diff --git a/.gitignore b/.gitignore index 83a414d1e..404b3156c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,19 +1,9 @@ -.project +target .classpath -.settings/ -.bpmn/ -target/ -bin/ -components-file/bin/ -core/bin/ +.project +.settings .checkstyle -transaction.log +*.sw? *.iml *.ipr -*.iws -.xml -.DS_Store -.metadata/ -.idea -.fbExcludeFilterFile -.factorypath +*.iws \ No newline at end of file diff --git a/LICENSE-2.0.txt b/LICENSE-2.0.txt new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/LICENSE-2.0.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/README b/README new file mode 100644 index 000000000..d19ad69ba --- /dev/null +++ b/README @@ -0,0 +1,2 @@ +This is the SwitchYard parent POM that SwitchYard projects like core and +component inherit from. diff --git a/assembly/pom.xml b/assembly/pom.xml deleted file mode 100644 index b1177cc57..000000000 --- a/assembly/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-quickstart-parent - 2.0.0.Final - - switchyard-quickstart-distro - jar - SwitchYard : Quickstarts Distribution Assembly - SwitchYard Quickstarts Distribution Assembly - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - - org.apache.maven.plugins - maven-assembly-plugin - - - make-assembly - package - - single - - - false - SwitchYard-Quickstarts - - ${basedir}/assembly.xml - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - - diff --git a/bean-service/Readme.md b/bean-service/Readme.md deleted file mode 100644 index d54ad207e..000000000 --- a/bean-service/Readme.md +++ /dev/null @@ -1,112 +0,0 @@ - -Introduction -============ -This quickstart demonstrates the usage of the bean component. This example shows a bean component -service, OrderService, which is provided through the OrderServiceBean, and an InventoryService which -is provided through the InventoryServiceBean implementation. Orders are submitted through the -OrderService, and the OrderService then looks items up in the InventoryService to see if they are -in stock and the order can be processed. - -This example is invoked through a SOAP gateway binding. - -![Bean Service Quickstart](https://github.com/jboss-switchyard/quickstarts/raw/master/bean-service/bean-service.jpg) - -Running the quickstart -====================== - -EAP ----------- -1. Start EAP in standalone mode: - - ${AS}/bin/standalone.sh - -2. Build and deploy the Quickstart : - - mvn install -Pdeploy - -3. Submit a webservice request to invoke the SOAP gateway. There are a number of ways to do this : - - Submit a request with your preferred SOAP client - src/test/resources/xml contains sample - requests and the responses that you should see - - Use the simple bundled SOAP client and the sample request XML e.g. -
-``` - mvn exec:java -``` -
- - SOAP-UI : Use the wsdl for this project (src/main/resources/wsdl/OrderService.wsdl) to create - a soap-ui project. Use the sample request (src/test/resources/xml/soap-request.xml) as an - example of a sample request. See the "Expected Output" heading for the expected results. - -4. Undeploy the quickstart: - mvn clean -Pdeploy - - -Wildfly ----------- -1. Start Wildfly in standalone mode : - - ${WILDFLY}/bin/standalone.sh - -2. Build and deploy the Quickstart : - - mvn install -Pdeploy -Pwildfly - -3. To submit a webservice request to invoke the SOAP gateway : -
-``` - mvn exec:java -``` -
- -4. Undeploy the quickstart: - mvn clean -Pdeploy -Pwildfly - - -Karaf ----------- -1. Start the Karaf server : - - ${KARAF_HOME}/bin/karaf - -2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} -with the version of SwitchYard that you are using (ex. 2.0.0): - -karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features - -3. Install the feature for the bean-service quickstart : - -karaf@root> features:install switchyard-quickstart-bean-service - -4. To submit a webservice request to invoke the SOAP gateway, run the quickstart client : -
-``` -mvn exec:java -Pkaraf -``` -
- -5. Undeploy the quickstart: - -karaf@root> features:uninstall switchyard-quickstart-bean-service - - -Expected Output -=============== -``` - - - - - -PO-19838-XYZ -true -Order Accepted - - - - -``` - - -## Further Reading - -1. [Bean Service Documentation](https://docs.jboss.org/author/display/SWITCHYARD/Bean) diff --git a/bean-service/pom.xml b/bean-service/pom.xml deleted file mode 100644 index 08495d9bc..000000000 --- a/bean-service/pom.xml +++ /dev/null @@ -1,263 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-bean-service - 2.0.0.Final - bundle - SwitchYard Quickstart: bean-service - Quickstart : Bean Service - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.bean.service - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - org.switchyard.validate.config.model.ValidateSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.bean.service.BeanClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/bom/pom.xml b/bom/pom.xml new file mode 100644 index 000000000..b49437270 --- /dev/null +++ b/bom/pom.xml @@ -0,0 +1,295 @@ + + + + 4.0.0 + + org.jboss.integration-platform + jboss-integration-platform-parent + 6.0.0.CR24 + + org.switchyard + switchyard-bom + 2.1.0-SNAPSHOT + pom + SwitchYard BOM + The BOM for SwitchYard application development + http://switchyard.org + + 6.0.0.CR24 + 7.4.0.Final-redhat-19 + 6.3.0.GA + + 6.2.0.CR3 + 6.2.0.CR3 + 6.2.0.CR3 + + + + + org.jboss.integration-platform + jboss-integration-platform-bom + ${version.ip.bom} + pom + import + + + org.kie + kie-bom + ${version.org.kie} + pom + import + + + org.drools + drools-bom + ${version.org.drools} + pom + import + + + org.jbpm + jbpm-bom + ${version.org.jbpm} + pom + import + + + org.jboss.bom + eap6-supported-artifacts + ${version.redhat.eap6.bom} + pom + import + + + org.jboss.as + jboss-as-parent + ${version.org.jboss.as} + pom + import + + + + + + org.switchyard + switchyard-api + ${project.version} + + + org.switchyard + switchyard-deploy-webapp + ${project.version} + + + org.switchyard + switchyard-remote + ${project.version} + + + org.switchyard + switchyard-test + ${project.version} + + + org.switchyard + switchyard-transform + ${project.version} + + + org.switchyard + switchyard-validate + ${project.version} + + + + + + org.switchyard.components + switchyard-component-bean + ${project.version} + + + org.switchyard.components + switchyard-component-bpel + ${project.version} + + + org.switchyard.components + switchyard-component-bpm + ${project.version} + + + org.switchyard.components + switchyard-component-camel + ${project.version} + + + org.switchyard.components + switchyard-component-camel-amqp + ${project.version} + + + org.switchyard.components + switchyard-component-camel-atom + ${project.version} + + + org.switchyard.components + switchyard-component-camel-core + ${project.version} + + + org.switchyard.components + switchyard-component-camel-cxf + ${project.version} + + + org.switchyard.components + switchyard-component-camel-file + ${project.version} + + + org.switchyard.components + switchyard-component-camel-ftp + ${project.version} + + + org.switchyard.components + switchyard-component-camel-jms + ${project.version} + + + org.switchyard.components + switchyard-component-camel-jpa + ${project.version} + + + org.switchyard.components + switchyard-component-camel-mail + ${project.version} + + + org.switchyard.components + switchyard-component-camel-mqtt + ${project.version} + + + org.switchyard.components + switchyard-component-camel-netty + ${project.version} + + + org.switchyard.components + switchyard-component-camel-quartz + ${project.version} + + + org.switchyard.components + switchyard-component-camel-rss + ${project.version} + + + org.switchyard.components + switchyard-component-camel-sap + ${project.version} + + + org.switchyard.components + switchyard-component-camel-sql + ${project.version} + + + org.switchyard.components + switchyard-component-clojure + ${project.version} + + + org.switchyard.components + switchyard-component-http + ${project.version} + + + org.switchyard.components + switchyard-component-jca + ${project.version} + + + org.switchyard.components + switchyard-component-resteasy + ${project.version} + + + org.switchyard.components + switchyard-component-rules + ${project.version} + + + org.switchyard.components + switchyard-component-sca + ${project.version} + + + org.switchyard.components + switchyard-component-soap + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-activemq + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-amqp + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-cdi + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-http + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-jca + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-naming + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-smooks + ${project.version} + + + org.switchyard.quickstarts + switchyard-quickstart-testutil + ${project.version} + + + + diff --git a/bpel-jms-binding/Readme.md b/bpel-jms-binding/Readme.md deleted file mode 100644 index fda982176..000000000 --- a/bpel-jms-binding/Readme.md +++ /dev/null @@ -1,98 +0,0 @@ -Introduction -============ -This quickstart demonstrates the use of a JMS binding for a BPEL service. Also of -note : the Camel JMS binding in the quickstart uses WSDL as it's interface type -instead of Java. - - -![BPEL JMS Binding Quickstart](https://github.com/jboss-switchyard/quickstarts/raw/master/bpel-service/jms_binding/bpel-jms-binding.jpg) - - -Running the quickstart -====================== - -EAP ----------- -1. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy - -4. Execute HornetQClient. See the "Expected Output" heading for the expected results. - - mvn exec:java - -5. Undeploy the quickstart: - mvn clean -Pdeploy - - -Wildfly ----------- -1. Start Wildfly in standalone-full mode: - - ${WILDFLY}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${WILDFLY}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pwildfly -Pdeploy - -4. Execute HornetQClient. See the "Expected Output" heading for the expected results. - - mvn exec:java -Pwildfly - -5. Undeploy the quickstart: - - mvn clean -Pdeploy -Pwildfly - - -Karaf ----------- -1. Start the Karaf server : - -${KARAF_HOME}/bin/karaf - -2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} -with the version of SwitchYard that you are using (ex. 2.0.0): - -karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features - -3. Install the feature for the bpel-jms-binding quickstart : - -karaf@root> features:install switchyard-quickstart-bpel-jms-binding - -4. To submit a webservice request to invoke the SOAP gateway, run the quickstart client : -
-``` -mvn exec:java -Pkaraf -``` -
- -5. Undeploy the quickstart: - -karaf@root> features:uninstall switchyard-quickstart-bpel-jms-binding - - - -Expected Output -=============== -``` -Message sent. Waiting for reply ... -REPLY: - -Hello Skippy - -``` diff --git a/bpel-jms-binding/pom.xml b/bpel-jms-binding/pom.xml deleted file mode 100644 index b6a20e722..000000000 --- a/bpel-jms-binding/pom.xml +++ /dev/null @@ -1,326 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-bpel-jms-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: bpel-jms-binding - Quickstart : BPEL Service : JMS Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.bpel.jms.binding - true - 9999 - 1.6 - 1.6 - * - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - 2.4.1.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bpel - - - org.switchyard.components - switchyard-component-camel-jms - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-hornetq - test - - - org.apache.activemq - activemq-client - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.bpel.service.hello.JMSClient - - Skippy - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - true - 8080 - - - - org.hornetq - hornetq-core-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-commons - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-journal - ${version.wildfly.hornetq} - test - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - hornetqmixin.port - 8080 - - - hornetqmixin.http.upgrade.enabled - true - - - - - - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - activemq - Skippy - - - - - - - - diff --git a/bpel-loan-approval/pom.xml b/bpel-loan-approval/pom.xml deleted file mode 100644 index 9b9c36534..000000000 --- a/bpel-loan-approval/pom.xml +++ /dev/null @@ -1,249 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-bpel-loan-approval - 2.0.0.Final - bundle - SwitchYard Quickstart: bpel-loan-approval - Quickstart : BPEL Service : Loan Approval - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.bpel.loan.approval - true - 9999 - 1.6 - 1.6 - * - - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bpel - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.bpel.service.BPELLoanClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/bpel-say-hello/pom.xml b/bpel-say-hello/pom.xml deleted file mode 100644 index 9c1752063..000000000 --- a/bpel-say-hello/pom.xml +++ /dev/null @@ -1,252 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-bpel-say-hello - 2.0.0.Final - bundle - SwitchYard Quickstart: bpel-say-hello - Quickstart : BPEL Service : Say Hello - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.bpel.say.hello - true - 9999 - 1.6 - 1.6 - 1.3.1 - * - - - org.switchyard,org.switchyard.* - - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bpel - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.bpel.service.BPELHelloClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/bpel-simple-correlation/pom.xml b/bpel-simple-correlation/pom.xml deleted file mode 100644 index 1e565f0da..000000000 --- a/bpel-simple-correlation/pom.xml +++ /dev/null @@ -1,248 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-bpel-simple-correlation - 2.0.0.Final - bundle - SwitchYard Quickstart: bpel-simple-correlation - Quickstart : BPEL Service : Simple Correlation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.bpel.simple.correlation - true - 9999 - 1.6 - 1.6 - * - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bpel - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - clean - - enforce - - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.bpel.service.BPELCorrelationClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/bpel-xts-subordinate-wsba/bpel/pom.xml b/bpel-xts-subordinate-wsba/bpel/pom.xml deleted file mode 100644 index c6feaf41a..000000000 --- a/bpel-xts-subordinate-wsba/bpel/pom.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-bpel-xts-subordinate-wsba - 2.0.0.Final - - switchyard-bpel-xts-subordinate-wsba-bpel - jar - SwitchYard Quickstart: bpel-xts-subordinate-wsba - bpel - Quickstart : BPEL Service : XTS Subordinate WSBA : Business Travel Process - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - - - - org.switchyard.components - switchyard-component-bpel - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.bpel.service.BPELClient - - ${project.build.directory}/test-classes/xml - - false - - - - - diff --git a/bpel-xts-subordinate-wsba/pom.xml b/bpel-xts-subordinate-wsba/pom.xml deleted file mode 100644 index 23cd668d5..000000000 --- a/bpel-xts-subordinate-wsba/pom.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-bpel-xts-subordinate-wsba - 2.0.0.Final - pom - SwitchYard Quickstart: bpel-xts-subordinate-wsba - Quickstart : BPEL Service : XTS Subordinate WSBA - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 9999 - 1.6 - 1.6 - 1.3.1 - 1.0.2.Final - - - bpel - ws - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - clean - - enforce - - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/bpel-xts-subordinate-wsba/ws/pom.xml b/bpel-xts-subordinate-wsba/ws/pom.xml deleted file mode 100644 index 44319930d..000000000 --- a/bpel-xts-subordinate-wsba/ws/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-bpel-xts-subordinate-wsba - 2.0.0.Final - - switchyard-bpel-xts-subordinate-wsba-ws - ejb - SwitchYard Quickstart: bpel-xts-subordinate-wsba - ws - Quickstart : BPEL Service : XTS Subordinate WSBA : Airport Web Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - - - - org.jboss.jbossts.xts - jbossxts - api - provided - - - org.jboss.spec.javax.ejb - jboss-ejb-api_3.1_spec - - - - ${project.artifactId} - - - org.apache.maven.plugins - maven-ejb-plugin - - 3.1 - - - true - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - ${project.build.finalName}.jar - - - - deploy - install - - deploy-only - - - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - diff --git a/bpel-xts-wsat/bpel/pom.xml b/bpel-xts-wsat/bpel/pom.xml deleted file mode 100644 index 7715f56ba..000000000 --- a/bpel-xts-wsat/bpel/pom.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-bpel-xts-wsat - 2.0.0.Final - - switchyard-bpel-xts-wsat-bpel - jar - SwitchYard Quickstart: bpel-xts-wsat - bpel - Quickstart : BPEL Service : XTS WSAT : Business Travel Process - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - - - ${project.artifactId} - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.bpel.service.BPELClient - - ${project.build.directory}/test-classes/xml - - false - - - - - - - org.switchyard.quickstarts - switchyard-bpel-xts-wsat-ws - ${project.version} - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bpel - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - diff --git a/bpel-xts-wsat/pom.xml b/bpel-xts-wsat/pom.xml deleted file mode 100644 index 15e09324d..000000000 --- a/bpel-xts-wsat/pom.xml +++ /dev/null @@ -1,139 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-bpel-xts-wsat - 2.0.0.Final - pom - SwitchYard Quickstart: bpel-xts-wsat - Quickstart : BPEL Service : XTS WSAT - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 9999 - 1.6 - 1.6 - 1.3.1 - 1.0.2.Final - - - bpel - ws - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - clean - - enforce - - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/bpel-xts-wsat/ws/pom.xml b/bpel-xts-wsat/ws/pom.xml deleted file mode 100644 index 75db290f7..000000000 --- a/bpel-xts-wsat/ws/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-bpel-xts-wsat - 2.0.0.Final - - switchyard-bpel-xts-wsat-ws - ejb - SwitchYard Quickstart: bpel-xts-wsat - ws - Quickstart : BPEL Service : XTS WSAT : Airport Web Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - - - - org.jboss.jbossts.xts - jbossxts - api - provided - - - org.jboss.spec.javax.ejb - jboss-ejb-api_3.1_spec - - - - ${project.artifactId} - - - org.apache.maven.plugins - maven-ejb-plugin - - 3.1 - - - true - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - ${project.build.finalName}.jar - - - - deploy - install - - deploy-only - - - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - diff --git a/bpm-service/pom.xml b/bpm-service/pom.xml deleted file mode 100644 index 5dfb90051..000000000 --- a/bpm-service/pom.xml +++ /dev/null @@ -1,260 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-bpm-service - 2.0.0.Final - bundle - SwitchYard Quickstart: bpm-service - Quickstart : BPM Service - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.bpm.service - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bpm - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-versions - clean - - enforce - - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.bpm.service.BPMClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/camel-amqp-binding/pom.xml b/camel-amqp-binding/pom.xml deleted file mode 100644 index c930ac880..000000000 --- a/camel-amqp-binding/pom.xml +++ /dev/null @@ -1,218 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-amqp-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-amqp-binding - Quickstart : Camel AMQP Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.amqp.binding - true - org.switchyard.quickstarts.camel.amqp.binding.QpidServer - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.apache.qpid - qpid-client - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-amqp - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-test-mixin-amqp - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - test - - - - ${project.artifactId} - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - org.apache.qpid - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - ${maven.exec.mainClass} - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - client - - org.switchyard.quickstarts.camel.amqp.binding.QpidClient - - - - diff --git a/camel-atom-binding/pom.xml b/camel-atom-binding/pom.xml deleted file mode 100644 index 2c58d5cf9..000000000 --- a/camel-atom-binding/pom.xml +++ /dev/null @@ -1,234 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-atom-binding - 2.0.0.Final - SwitchYard Quickstart: camel-atom-binding - Quickstart : Camel RSS Binding - bundle - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.atom.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-atom - - - org.switchyard.components - switchyard-component-bean - - - org.apache.ws.commons.axiom - axiom-api - - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.apache.abdera - abdera-core - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - org.apache.abdera.abdera-parser, org.apache.abdera.abdera-i18n, org.apache.abdera.abdera-core, org.apache.ws.commons.axiom.axiom-impl - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-bindy/Readme.md b/camel-bindy/Readme.md deleted file mode 100644 index 7825fbdc7..000000000 --- a/camel-bindy/Readme.md +++ /dev/null @@ -1,103 +0,0 @@ -Introduction -============ -This quickstart demonstrates the usage of the Camel Bindy component within a -SwitchYard service. The service unmarshals a delimited String into Order -objects, and then makes two changes to the Orders - it sets the -price of any "Lucky Charms" order to 17, and it changes any "Grape Nuts" -orders to "Cheerios". - -This example is invoked through a File gateway binding. - -Running the quickstart -====================== - - -EAP ----------- -1. Start EAP in standalone mode: - - ${AS}/bin/standalone.sh - -2. Build and deploy the Quickstart : - - mvn install -Pdeploy - -3. -
-``` - Copy src/test/resources/file.txt to /tmp/inbox/file.txt -``` -
-* (If on Windows, change the file binding in switchyard.xml to a Windows directory path) - -4. Undeploy the quickstart: - - mvn clean -Pdeploy - - -Wildfly ----------- -1. Start EAP in standalone mode: - - ${AS}/bin/standalone.sh - -2. Build and deploy the Quickstart : - - mvn install -Pdeploy -Pwildfly - -3. -
-``` - Copy src/test/resources/file.txt to /tmp/inbox/file.txt -``` -
-* (If on Windows, change the file binding in switchyard.xml to a Windows directory path) - -4. Undeploy the quickstart: - - mvn clean -Pdeploy -Pwildfly - - -Karaf ----------- -1. Start the Karaf server : - -${KARAF_HOME}/bin/karaf - -2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} -with the version of SwitchYard that you are using (ex. 2.0.0): - -karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features - -3. Install the feature for the camel-bindy quickstart : - -karaf@root> features:install switchyard-quickstart-camel-bindy - -4. -
-``` -Copy src/test/resources/file.txt to /tmp/inbox/file.txt -``` -
- -5. Undeploy the quickstart: - -karaf@root> features:uninstall switchyard-quickstart-camel-bindy - - -Expected Output -=============== -``` -[FileProcessorBean] 1|Fruit Loops|3.99 -2|Lucky Charms|4.99 -3|Grape Nuts|2.33 - -Processed Message : 1|Fruit Loops|3.99 -2|Lucky Charms|17 -3|Cheerios|2.33 -``` - - -## Further Reading - -1. [Camel Bindy](http://camel.apache.org/bindy.html) diff --git a/camel-bindy/pom.xml b/camel-bindy/pom.xml deleted file mode 100644 index c3e4103fb..000000000 --- a/camel-bindy/pom.xml +++ /dev/null @@ -1,262 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-bindy - 2.0.0.Final - SwitchYard Quickstart: camel-bindy - bundle - Quickstart : Camel Bindy - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.bindy - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-camel-file - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-bean - - - org.apache.camel - camel-bindy - - - - - jboss-public-repository - JBoss Public Maven Repository - http://repository.jboss.org/nexus/content/groups/public - - - - - jboss-public-repository - JBoss Public Maven Repository - http://repository.jboss.org/nexus/content/groups/public - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - false - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - org.apache.camel.bindy - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - clean - - enforce - - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-bus-cdi/pom.xml b/camel-bus-cdi/pom.xml deleted file mode 100644 index a65ff1329..000000000 --- a/camel-bus-cdi/pom.xml +++ /dev/null @@ -1,257 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-bus-cdi - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-bus-cdi - Quickstart : Camel Exchange Bus CDI - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.bus.cdi - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.camel.bus.CDIBusClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/camel-cxf-binding/pom.xml b/camel-cxf-binding/pom.xml deleted file mode 100644 index 06a599137..000000000 --- a/camel-cxf-binding/pom.xml +++ /dev/null @@ -1,239 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-cxf-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: CXF consumer - Quickstart : CXF based Webservice consumer - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.cxf.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-camel-cxf - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-soap - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.camel.cxf.CamelCxfClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-file-binding/pom.xml b/camel-file-binding/pom.xml deleted file mode 100644 index 4711f4aa9..000000000 --- a/camel-file-binding/pom.xml +++ /dev/null @@ -1,224 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-file-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-file-binding - Quickstart : Camel Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.file.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-file - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - - ${project.artifactId} - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-ftp-binding/pom.xml b/camel-ftp-binding/pom.xml deleted file mode 100644 index 621edfad7..000000000 --- a/camel-ftp-binding/pom.xml +++ /dev/null @@ -1,291 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-ftp-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-ftp-binding - Quickstart : Camel FTP Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.ftp.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - org.apache.sshd - sshd-core - 0.9.0 - - - org.apache.sshd - sshd-sftp - 0.9.0 - - - com.jcraft - jsch - 0.1.51 - - - org.bouncycastle - bcpg-jdk15on - 1.49 - - - org.bouncycastle - bcpkix-jdk15on - 1.49 - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-ftp - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.apache.ftpserver - ftpserver-core - test - - - commons-io - commons-io - test - - - org.hamcrest - hamcrest-core - test - - - org.apache.sshd - sshd-core - test - - - org.apache.sshd - sshd-sftp - test - - - com.jcraft - jsch - test - - - org.bouncycastle - bcpg-jdk15on - test - - - org.bouncycastle - bcpkix-jdk15on - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - false - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-hl7/pom.xml b/camel-hl7/pom.xml deleted file mode 100644 index ae602d068..000000000 --- a/camel-hl7/pom.xml +++ /dev/null @@ -1,252 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-hl7 - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-hl7 - Quickstart : Camel HL7 - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.hl7 - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-camel-core - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.apache.camel - camel-hl7 - - - org.apache.camel - camel-mina2 - - - - ca.uhn.hapi - hapi-osgi-base - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - org.apache.mina, org.apache.camel.mina2, org.apache.camel.hl7, ca.uhn.hapi-osgi-base - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.camel.hl7example.HL7Client - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-jaxb/pom.xml b/camel-jaxb/pom.xml deleted file mode 100644 index e060b0161..000000000 --- a/camel-jaxb/pom.xml +++ /dev/null @@ -1,258 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-jaxb - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-jaxb - Quickstart : Camel JAXB - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.jaxb - true - 9999 - 1.6 - 1.6 - * - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.apache.camel - camel-jaxb - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-http - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - commons-io - commons-io - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.camel.jaxb.JAXBClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.http.client.port - 8181 - - - - - - - - - wildfly - - 9990 - - - - diff --git a/camel-jms-binding/Readme.md b/camel-jms-binding/Readme.md deleted file mode 100644 index be54f53bb..000000000 --- a/camel-jms-binding/Readme.md +++ /dev/null @@ -1,95 +0,0 @@ -Introduction -============ -This quickstart demonstrates the usage of the Camel Component and it's binding feature, by binding -to a JMS Queue. When a message arrives in this queue the service will be invoked. - -![Camel JMS Binding Quickstart](https://github.com/jboss-switchyard/quickstarts/raw/master/camel-jms-binding/camel-jms-binding.jpg) - - -Running the quickstart -====================== - - -EAP ----------- -1. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm UserName=guest Password=guestp.1 Group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy - -4. Execute HornetQClient - - mvn exec:java - -5. Check the server console for output from the service. - -6. Undeploy the quickstart: - - mvn clean -Pdeploy - - -Wildfly ----------- -1. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm UserName=guest Password=guestp.1 Group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy -Pwildfly - -4. Execute HornetQClient - - mvn exec:java -Pwildfly - -5. Check the server console for output from the service. - -6. Undeploy the quickstart: - - mvn clean -Pdeploy -Pwildfly - - -Karaf ----------- -1. Start the Karaf server : - - ${KARAF_HOME}/bin/karaf - -2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} -with the version of SwitchYard that you are using (ex. 2.0.0): - -karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features - -3. Install the feature for the camel-jms-binding quickstart : - -karaf@root> features:install switchyard-quickstart-camel-jms-binding - -4. To submit a jms request, run the quickstart client : -
-``` - mvn exec:java -Pkaraf -``` -
- -5. Undeploy the quickstart: - -karaf@root> features:uninstall switchyard-quickstart-camel-jms-binding - - - -## Further Reading - -1. [JMS Binding Documentation](https://docs.jboss.org/author/display/SWITCHYARD/JMS) diff --git a/camel-jms-binding/pom.xml b/camel-jms-binding/pom.xml deleted file mode 100644 index 5c850b122..000000000 --- a/camel-jms-binding/pom.xml +++ /dev/null @@ -1,342 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-jms-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-jms-binding - Quickstart : Camel JMS Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.jms.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - 2.4.1.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-jms - - - org.switchyard.components - switchyard-component-bean - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - - - org.apache.activemq - activemq-client - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-hornetq - test - - - org.mockito - mockito-all - test - - - org.hamcrest - hamcrest-core - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.camel.jms.binding.JMSClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - true - 8080 - - - - org.hornetq - hornetq-core-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-commons - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-journal - ${version.wildfly.hornetq} - test - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - hornetqmixin.port - 8080 - - - hornetqmixin.http.upgrade.enabled - true - - - - - - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - activemq - - - - - - - diff --git a/camel-jpa-binding/pom.xml b/camel-jpa-binding/pom.xml deleted file mode 100644 index 3ebedef80..000000000 --- a/camel-jpa-binding/pom.xml +++ /dev/null @@ -1,306 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-jpa-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-jpa-binding - Quickstart : Camel JPA Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.jpa.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - java:jboss/datasources/ExampleDS - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-camel-jpa - - - org.switchyard.components - switchyard-component-camel-quartz - - - org.hibernate - hibernate-entitymanager - - - org.switchyard - switchyard-test - test - - - org.hamcrest - hamcrest-core - test - - - com.h2database - h2 - test - - - org.mockito - mockito-all - test - - - org.switchyard.components - switchyard-component-test-mixin-jca - test - - - - ${project.artifactId} - - - true - src/main/resources - - - false - src/main/resources - - **/switchyard.xml - - - - - - org.apache.maven.plugins - maven-resources-plugin - - - resources - process-resources - - resources - - - - ${*} - - false - - - - test-resources - process-test-resources - - testResources - - - - ${*} - - false - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - ${jpa.persistence.datasource.name} - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - META-INF/persistence.xml - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - karaf - - osgi:service/jboss/datasources/ExampleDS - - - - diff --git a/camel-mail-binding/pom.xml b/camel-mail-binding/pom.xml deleted file mode 100644 index 718432090..000000000 --- a/camel-mail-binding/pom.xml +++ /dev/null @@ -1,235 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-mail-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-mail-binding - Quickstart : Camel Mail Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.mail.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-mail - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.hamcrest - hamcrest-core - test - - - org.jvnet.mock-javamail - mock-javamail - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-mqtt-binding/pom.xml b/camel-mqtt-binding/pom.xml deleted file mode 100644 index ddb28b997..000000000 --- a/camel-mqtt-binding/pom.xml +++ /dev/null @@ -1,255 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-mqtt-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-mqtt-binding - Quickstart : Camel MQTT Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.mqtt.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - 1.6 - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-mqtt - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.apache.activemq - activemq-broker - test - - - org.apache.activemq - activemq-mqtt - test - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - test - - - org.fusesource.mqtt-client - mqtt-client - ${version.org.fusesource.mqtt-client} - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.camel.mqtt.binding.MQTTClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-netty-binding/pom.xml b/camel-netty-binding/pom.xml deleted file mode 100644 index fede56e68..000000000 --- a/camel-netty-binding/pom.xml +++ /dev/null @@ -1,256 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-netty-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-netty-binding - Quickstart : Camel Netty Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.netty.binding - true - 9999 - org.switchyard.quickstarts.camel.netty.binding.TCPClient - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-netty - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.hamcrest - hamcrest-core - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - ${maven.exec.mainClass} - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - udp - - org.switchyard.quickstarts.camel.netty.binding.UDPClient - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-quartz-binding/pom.xml b/camel-quartz-binding/pom.xml deleted file mode 100644 index 6d0ec701c..000000000 --- a/camel-quartz-binding/pom.xml +++ /dev/null @@ -1,226 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-quartz-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-quartz-binding - Quickstart : Camel Quartz Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.quartz.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-camel-quartz - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.hamcrest - hamcrest-core - test - - - org.hamcrest - hamcrest-library - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-rss-binding/pom.xml b/camel-rss-binding/pom.xml deleted file mode 100644 index aee418f8a..000000000 --- a/camel-rss-binding/pom.xml +++ /dev/null @@ -1,239 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-rss-binding - 2.0.0.Final - SwitchYard Quickstart: camel-rss-binding - Quickstart : Camel RSS Binding - bundle - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.rss.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-rss - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - rome - rome - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - rome.rome:1.0 - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.camel.rss.binding.RSSClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-sap-binding/pom.xml b/camel-sap-binding/pom.xml deleted file mode 100644 index 9b97b9fb1..000000000 --- a/camel-sap-binding/pom.xml +++ /dev/null @@ -1,237 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-sap-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-sap-binding - Quickstart : Camel SAP Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.sap.binding - 1.6 - 1.6 - true - 9999 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-sap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard.components - switchyard-component-bean - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-saxon/pom.xml b/camel-saxon/pom.xml deleted file mode 100644 index e07e04b6d..000000000 --- a/camel-saxon/pom.xml +++ /dev/null @@ -1,264 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-saxon - 2.0.0.Final - bundle - org.switchyard.quickstarts:switchyard-camel-saxon - Quickstart : Camel Saxon - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.saxon - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-soap - - - org.apache.camel - camel-saxon - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - org.switchyard.quickstarts.camel.saxon.CamelSaxonClient - test - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/camel-service/pom.xml b/camel-service/pom.xml deleted file mode 100644 index 951065382..000000000 --- a/camel-service/pom.xml +++ /dev/null @@ -1,265 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-service - 2.0.0.Final - bundle - SwitchYard Quickstart: camel-service - Quickstart : Camel Service - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.service - true - 9999 - 1.6 - 1.6 - * - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard - switchyard-remote - test - - - org.codehaus.groovy - groovy-all - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-sca - - - org.apache.camel - camel-ognl - - - org.apache.camel - camel-mvel - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - org.switchyard.quickstarts.camel.service.CamelServiceClient - test - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.sca.client.port - 8181 - - - - - - - - - wildfly - - 9990 - - - - diff --git a/camel-soap-proxy/pom.xml b/camel-soap-proxy/pom.xml deleted file mode 100644 index 1111c1b6d..000000000 --- a/camel-soap-proxy/pom.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-soap-proxy-parent - 2.0.0.Final - pom - SwitchYard Quickstart: camel-soap-proxy parent - Quickstart : Camel SOAP Proxy Parent - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 9999 - 1.6 - 1.6 - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - org.switchyard.quickstarts - switchyard-camel-soap-proxy-reverse - ${project.version} - - - org.switchyard.quickstarts - switchyard-camel-soap-proxy-reverse-service - ${project.version} - - - org.switchyard.quickstarts - switchyard-camel-soap-proxy - ${project.version} - - - - - reverse - reverse-service - soap-proxy - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/camel-soap-proxy/reverse-service/pom.xml b/camel-soap-proxy/reverse-service/pom.xml deleted file mode 100644 index f72067ed2..000000000 --- a/camel-soap-proxy/reverse-service/pom.xml +++ /dev/null @@ -1,128 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-camel-soap-proxy-parent - 2.0.0.Final - ../pom.xml - - switchyard-camel-soap-proxy-reverse-service - war - SwitchYard Quickstart: camel-soap-proxy-reverse-service - Quickstart : Camel SOAP Proxy Reverse Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 1.6 - 1.6 - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.quickstarts - switchyard-camel-soap-proxy-reverse - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - maven-war-plugin - - - false - WEB-INF/jboss-web.xml,WEB-INF/lib/switchyard-camel-soap-proxy-reverse-**.jar - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.war - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.war - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - diff --git a/camel-soap-proxy/reverse/pom.xml b/camel-soap-proxy/reverse/pom.xml deleted file mode 100644 index 27fd2cd1b..000000000 --- a/camel-soap-proxy/reverse/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-camel-soap-proxy-parent - 2.0.0.Final - ../pom.xml - - switchyard-camel-soap-proxy-reverse - bundle - SwitchYard Quickstart: camel-soap-proxy reverse - Quickstart : Camel SOAP Proxy Reverse - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - - org.switchyard.quickstarts.camel.soap.proxy - - - javax.xml.ws.soap, - javax.ws.rs.*;version="[1.1,3)", - org.apache.cxf.*;version="[2,4)", - org.switchyard.quickstarts.camel.soap.proxy - - - - - - org.apache.cxf - cxf-rt-frontend-jaxrs - - - org.apache.cxf - cxf-rt-frontend-jaxws - - - - ${project.artifactId} - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${project.name} - ${project.groupId}.${project.artifactId} - ${switchyard.osgi.import} - {maven-resources} - ${switchyard.osgi.dynamic} - <_failok>true - !* - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - diff --git a/camel-soap-proxy/soap-proxy/pom.xml b/camel-soap-proxy/soap-proxy/pom.xml deleted file mode 100644 index d9528caa7..000000000 --- a/camel-soap-proxy/soap-proxy/pom.xml +++ /dev/null @@ -1,208 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-camel-soap-proxy-parent - 2.0.0.Final - ../pom.xml - - switchyard-camel-soap-proxy - bundle - SwitchYard Quickstart: camel-soap-proxy - Quickstart : Camel SOAP Proxy - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.soap.proxy - true - 1.6 - 1.6 - - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; - filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.quickstarts - switchyard-camel-soap-proxy-reverse - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.camel.soap.proxy.CamelClient - false - - ${project.build.directory}/test-classes/xml/soap-request.xml - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${project.name} - ${bundle.symbolic.name} - ${switchyard.osgi.import} - {maven-resources}, - META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.dynamic} - <_failok>true - !* - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - org.switchyard.component.soap.standalone.dir - cxf/reverseService - - - - - - - - - diff --git a/camel-sql-binding/pom.xml b/camel-sql-binding/pom.xml deleted file mode 100644 index ed88eed99..000000000 --- a/camel-sql-binding/pom.xml +++ /dev/null @@ -1,316 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-camel-sql-binding - 2.0.0.Final - SwitchYard Quickstart: camel-sql-binding - Quickstart : Camel SQL Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.camel.sql.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.168 - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel-sql - - - org.switchyard.components - switchyard-component-camel-quartz - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-naming - test - - - com.h2database - h2 - test - - - org.hamcrest - hamcrest-core - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - db - - - - com.edugility - h2-maven-plugin - 1.0 - false - - ${project.build.directory} - - - - Spawn a new H2 TCP server - package - - spawn - - - - Stop a spawned H2 TCP server - pre-clean - - stop - - - - - - org.codehaus.mojo - sql-maven-plugin - 1.5 - - - com.h2database - h2 - ${version.com.h2database} - - - - org.h2.Driver - jdbc:h2:tcp://localhost/h2db - sa - - - - create - package - - execute - - - CREATE TABLE IF NOT EXISTS greetings ( id INT PRIMARY KEY AUTO_INCREMENT, receiver VARCHAR(255), sender VARCHAR(255) ) - - - - - - - - - wildfly - - 9990 - - - - bundle - diff --git a/components/.gitignore b/components/.gitignore new file mode 100644 index 000000000..9cc08abad --- /dev/null +++ b/components/.gitignore @@ -0,0 +1,17 @@ +.project +.classpath +.settings/ +.bpmn/ +target/ +bin/ +.checkstyle +*.iml +*.ipr +*.iws +.DS_Store +jca/transaction.log +transaction.log.* +itests/transaction.log +.idea +.fbExcludeFilterFile +.factorypath diff --git a/components/README b/components/README new file mode 100644 index 000000000..4f035e59e --- /dev/null +++ b/components/README @@ -0,0 +1 @@ +Repository for components which can be used with SwitchYard core. diff --git a/components/bean/pom.xml b/components/bean/pom.xml new file mode 100644 index 000000000..0b4af0daa --- /dev/null +++ b/components/bean/pom.xml @@ -0,0 +1,93 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-bean + bundle + SwitchYard: Bean Component + http://switchyard.org + + + org.switchyard.component.bean.* + + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + * + + + org.ops4j.pax.cdi.extension; extension=switchyard-component-bean; version:Version=${switchyard.osgi.version} + + + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + org.jboss.weld.se + weld-se-core + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-cdi + + + org.switchyard + switchyard-extensions-java + + + org.switchyard + switchyard-transform + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + diff --git a/components/bean/src/main/java/org/switchyard/component/bean/BeanComponentException.java b/components/bean/src/main/java/org/switchyard/component/bean/BeanComponentException.java new file mode 100644 index 000000000..ead976399 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/BeanComponentException.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import org.switchyard.Exchange; +import org.switchyard.HandlerException; + +/** + * Bean Component Exception. + * + * @author tom.fennelly@gmail.com + */ +public class BeanComponentException extends HandlerException { + + /** + * Fault exchange instance associated with the exception. + */ + private Exchange _faultExchange; + + /** + * Public constructor. + * @param message Exception message. + */ + public BeanComponentException(final String message) { + super(message); + } + + /** + * Create a new BeanComponentException with the specified cause. + * @param cause underlying error + */ + public BeanComponentException(final Throwable cause) { + super(cause); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause The parent/cause exception. + */ + public BeanComponentException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Set the fault {@link Exchange} instance on the exception. + * @param faultExchange The fault exchange instance. + * @return {@code this} exception instance. + */ + public BeanComponentException setFaultExchange(Exchange faultExchange) { + this._faultExchange = faultExchange; + return this; + } + + /** + * Get the fault {@link Exchange} instance associated with this exception instance. + * @return The fault exchange instance. + */ + public Exchange getFaultExchange() { + return _faultExchange; + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/BeanLogger.java b/components/bean/src/main/java/org/switchyard/component/bean/BeanLogger.java new file mode 100644 index 000000000..02d6ef7b1 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/BeanLogger.java @@ -0,0 +1,33 @@ +package org.switchyard.component.bean; + +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 30000-30399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface BeanLogger { + /** + * A root logger with the category of the package name. + */ + BeanLogger ROOT_LOGGER = Logger.getMessageLogger(BeanLogger.class, BeanLogger.class.getPackage().getName()); + + /** + * propertyHasIncompatibleTypeBean method definition. + * @param propAnnoName propAnnoName + * @param serviceMetadataClassName the serviceMetadataClassName + * @param fieldTypeName the fieldTypeName + * @param propertyClassName the propertyClassName + */ + @LogMessage(level = Level.WARN) + @Message(id = 30000, value = "Property '%s' has incompatible type: Bean '%s' is expecting '%s', but was '%s'. ignoring...") + void propertyHasIncompatibleTypeBean(String propAnnoName, String serviceMetadataClassName, String fieldTypeName, String propertyClassName); + +} + diff --git a/components/bean/src/main/java/org/switchyard/component/bean/BeanMessages.java b/components/bean/src/main/java/org/switchyard/component/bean/BeanMessages.java new file mode 100644 index 000000000..63256f587 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/BeanMessages.java @@ -0,0 +1,248 @@ +package org.switchyard.component.bean; + +import java.io.IOException; + +import javax.naming.NameNotFoundException; +import javax.naming.NamingException; +import javax.xml.namespace.QName; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 30400-30799 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface BeanMessages { + /** + * The default messages. + */ + BeanMessages MESSAGES = Messages.getBundle(BeanMessages.class); + + /** + * operationNameMustResolveToExactlyOneBeanMethodOnBeanType method definition. + * @param operationName the operationName + * @param serviceClassName serviceClassName + * @return BeanComponentException + */ + @Message(id = 30400, value = "Operation name '%s' must resolve to exactly one bean method on bean type '%s'.") + BeanComponentException operationNameMustResolveToExactlyOneBeanMethodOnBeanType(String operationName, String serviceClassName); + + /** + * operationNameNotSpecifiedOnExchange method definition. + * @return BeanComponentException + */ + @Message(id = 30401, value = "Operation name not specified on exchange.") + BeanComponentException operationNameNotSpecifiedOnExchange(); + + /** + * aServiceReferenceToServiceIsNotBoundInto method definition. + * @param serviceName the serviceName + * @return BeanComponentException + */ + @Message(id = 30402, value = "A service reference to service '%s' is not bound into this client proxy instance. A reference configuration to the service may be required in the application configuration.") + BeanComponentException aServiceReferenceToServiceIsNotBoundInto(String serviceName); + + /** + * beanComponentInvocationFailureServiceOperation method definition. + * @param serviceName serviceName + * @param methodName methodName + * @return BeanComponentException + */ + @Message(id = 30403, value = "Bean Component invocation failure. Service '%s', operation '%s'.") + BeanComponentException beanComponentInvocationFailureServiceOperation(String serviceName, String methodName); + + /** + * beanComponentInvocationFailureOperationIsNotDefinedOnService method definition. + * @param operationName the operationName + * @param serviceName serviceName + * @return BeanComponentException + */ + @Message(id = 30404, value = "Bean Component invocation failure. Operation '%s' is not defined on Service '%s'.") + BeanComponentException beanComponentInvocationFailureOperationIsNotDefinedOnService(String operationName, String serviceName); + + /** + * unknownPolicy method definition. + * @param secPolicy the secPolicy + * @return IOException + */ + @Message(id = 30405, value = "Unknown policy: %s") + IOException unknownPolicy(String secPolicy); + + /** + * null method definition. + * @param ptx the ptx + * @param stx the stx + * @param name the name + * @return IOException + */ + @Message(id = 30407, value = "TransactionPolicies %s and %s cannot co-exist on service %s") + IOException transactionPoliciesCannotCoexistService(QName ptx, QName stx, String name); + + /** + * null method definition. + * @param gtx the gtx + * @param ltx the ltx + * @param ntx the ntx + * @param name the name + * @return IOException + */ + @Message(id = 30408, value = "TransactionPolicies %s, %s and %s cannot co-exist on implementation %s") + IOException transactionPoliciesCannotCoexistImplementation(QName gtx, QName ltx, QName ntx, String name); + + /** + * stringFormatReferenceOnlyCouldBeMarkedWithInteractionPolicyBut%sIsNotTheOne method definition. + * @param policy policy + * @return IOException + */ + @Message(id = 30409, value = "Reference only could be marked with Interaction policy, but %s is not the one.") + IOException referenceOnlyCouldBeMarkedWithInteractionPolicyButIsNotTheOne(String policy); + + /** + * unknownServiceName method definition. + * @param serviceName the serviceName + * @return SwitchYardException + */ + @Message(id = 30412, value = "Unknown Service name '%s'.") + SwitchYardException unknownServiceName(String serviceName); + + /** + * failedToLookupBeanDeploymentMetaDataFromBeanManagerMustBeBoundIntoBeanManagerPerhapsSwitchYardCDIExtensionsNotProperlyInstalledInContainer method definition. + * @return SwitchYardException + */ + @Message(id = 30414, value = "Failed to lookup BeanDeploymentMetaData from BeanManager. Must be bound into BeanManager. Perhaps SwitchYard CDI Extensions not properly installed in container.") + SwitchYardException failedToLookupBeanDeploymentMetaDataFromBeanManagerMustBeBoundIntoBeanManagerPerhapsSwitchYardCDIExtensionsNotProperlyInstalledInContainer(); + + /** + * failedToLookupBeanDeploymentMetaDataFromBeanManagerMultipleBeansResolvedForType method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id = 30415, value = "Failed to lookup BeanDeploymentMetaData from BeanManager. Multiple beans resolved for type '%s'.") + SwitchYardException failedToLookupBeanDeploymentMetaDataFromBeanManagerMultipleBeansResolvedForType(String className); + + /** + * failedToLookupBeanManagerMustBeBoundIntoJavaCompAsPerCDISpecification method definition. + * @return SwitchYardException + */ + @Message(id = 30416, value = "Failed to lookup BeanManager. Must be bound into java:comp as per CDI specification.") + SwitchYardException failedToLookupBeanManagerMustBeBoundIntoJavaCompAsPerCDISpecification(); + + /** + * nameBeanManagerIsNotBoundInThisContext method definition. + * @return NameNotFoundException + */ + @Message(id = 30417, value = "Name BeanManager is not bound in this Context") + NameNotFoundException nameBeanManagerIsNotBoundInThisContext(); + + /** + * unexpectedExceptionRetrieving method definition. + * @param jndiName the jndiName + * @param e the e + * @return SwitchYardException + */ + @Message(id = 30418, value = "Unexpected Exception retrieving '%s' from JNDI namespace.") + SwitchYardException unexpectedExceptionRetrieving(String jndiName, @Cause Exception e); + + /** + * unexpectedErrorClosingInitialContext method definition. + * @param e the e + * @return SwitchYardException + */ + @Message(id = 30419, value = "Unexpected error closing InitialContext.") + SwitchYardException unexpectedErrorClosingInitialContext(@Cause NamingException e); + + /** + * unexpectedExceptionThe@ServiceAnnotationRequiresAServiceInterfaceClassValueToBeDefinedYetTheAnnotationHasNoValue method definition. + * @return SwitchYardException + */ + @Message(id = 30420, value = "Unexpected exception. The @Service annotation has no value. It cannot be ommitted unless the bean implements exactly one interface.") + SwitchYardException unexpectedExceptionTheServiceAnnotationHasNoValueItCannotBeOmmittedUnlessTheBeanImplementsExactlyOneInterface(); + + /** + * invalid@ServiceSpecification@Service method definition. + * @param serviceInterfaceName serviceInterfaceName + * @return SwitchYardException + */ + @Message(id = 30421, value = "Invalid @Service specification @Service(%s.class). @Service interface Class must be a Java Interface. Cannot be a concrete implementation.") + SwitchYardException invalidServiceSpecificationService(String serviceInterfaceName); + + /** + * illegalCallToGetTheSwitchYardContext;MustBeCalledWithinTheExecutionOfAnExchangeHandlerChain method definition. + * @return IllegalStateException + */ + @Message(id = 30422, value = "Illegal call to get the SwitchYard Context; must be called within the execution of an ExchangeHandler chain.") + IllegalStateException illegalCallToGetTheSwitchYardContextMustBeCalledWithinTheExecutionOfAnExchangeHandlerChain(); + + /** + * failedToLookupBeanDeploymentMetaDataFromNamingContext method definition. + * @return SwitchYardException + */ + @Message(id = 30424, value = "Failed to lookup BeanDeploymentMetaData from Naming Context.") + SwitchYardException failedToLookupBeanDeploymentMetaDataFromNamingContext(); + + /** + * beanServiceOperation method definition. + * @param operationName operationName + * @return BeanComponentException + */ + @Message(id = 30425, value = "Bean service operation '%s' has more than 1 argument. Bean component currently only supports single argument operations.") + BeanComponentException beanServiceOperationMoreThanOne(String operationName); + + /** + * beanServiceOperation method definition. + * @param operationName operationName + * @return BeanComponentException + */ + @Message(id = 30426, value = "Bean service operation '%s' requires a single argument. Exchange payload specifies no payload.") + BeanComponentException beanServiceOperationRequiresSingle(String operationName); + + /** + * beanServiceOperation method definition. + * @param operationName operationName + * @param argsLength argsLength + * @return BeanComponentException + */ + @Message(id = 30427, value = "Bean service operation '%s' only supports a single argument. Exchange payload specifies %s args.") + BeanComponentException beanServiceOperationSupportsSingle(String operationName, String argsLength); + + /** + * beanServiceOperationRequiresAPayloadTypeOf method definition. + * @param operationName operationName + * @param argTypeName argTypeName + * @param className className + * @return BeanComponentException + */ + @Message(id = 30428, value = "Bean service operation '%s' requires a payload type of '%s'. Actual payload type is '%s'. You must define and register a Transformer.") + BeanComponentException beanServiceOperationRequiresAPayloadTypeOf(String operationName, String argTypeName, String className); + + /** + * unexpectedErrorBeanServiceMetadataShouldReturnAnInvocationInstanceOrThrowABeanComponentException method definition. + * @return SwitchYardException + */ + @Message(id = 30430, value = "Unexpected error. BeanServiceMetadata should return an Invocation instance, or throw a BeanComponentException.") + SwitchYardException unexpectedErrorBeanServiceMetadataShouldReturnAnInvocationInstanceOrThrowABeanComponentException(); + + /** + * invocationOfOperationFailed method definition. + * @param invocationMethodName invocationMethodName + * @param serviceBeanClassName serviceBeanClassName + * @return String + */ + @Message(id = 30431, value = "Invocation of operation '%s' on bean component '%s' failed.") + String invocationOfOperationFailed(String invocationMethodName, String serviceBeanClassName); + + /** + * illegalExchangeAccessOutsideHandlerChain method definition. + * @return String + */ + @Message(id = 30432, value = "Illegal call to get the SwitchYard Exchange; must be called within the execution of an ExchangeHandler chain.") + IllegalStateException illegalExchangeAccessOutsideHandlerChain(); + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/BeanServiceMetadata.java b/components/bean/src/main/java/org/switchyard/component/bean/BeanServiceMetadata.java new file mode 100644 index 000000000..24ea52cac --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/BeanServiceMetadata.java @@ -0,0 +1,110 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import org.switchyard.Exchange; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +/** + * Bean Service meta data. + *

+ * Provides access to Bean Service operation invocation information. + * + * @author tom.fennelly@gmail.com + */ +public class BeanServiceMetadata { + + /** + * Service bean component runtime class. + */ + private Class _serviceClass; + /** + * List of service methods/operations. + */ + private List _serviceMethods = new ArrayList(); + + /** + * Public constructor. + * + * @param serviceClass The service bean class. + */ + public BeanServiceMetadata(Class serviceClass) { + Method[] serviceMethods = serviceClass.getMethods(); + for (Method serviceMethod : serviceMethods) { + if (serviceMethod.getDeclaringClass() != Object.class) { + this._serviceMethods.add(serviceMethod); + } + } + this._serviceClass = serviceClass; + } + + /** + * Get the Service Interface runtime class. + * @return The Service Interface runtime class. + */ + public Class getServiceClass() { + return _serviceClass; + } + + /** + * Get the Bean Service operation {@link Invocation} for the specified + * {@link Exchange}. + * + * @param exchange The Exchange instance. + * @return The operation {@link Invocation} instance. + * @throws BeanComponentException Error invoking Bean component operation. + */ + public Invocation getInvocation(Exchange exchange) throws BeanComponentException { + + String operationName = exchange.getContract().getProviderOperation().getName(); + + if (operationName != null) { + List candidateMethods = getCandidateMethods(operationName); + + // Operation name must resolve to exactly one bean method... + if (candidateMethods.size() != 1) { + throw BeanMessages.MESSAGES.operationNameMustResolveToExactlyOneBeanMethodOnBeanType(operationName, _serviceClass.getName()); + } + + Method operationMethod = candidateMethods.get(0); + return new Invocation(operationMethod, exchange); + } else { + throw BeanMessages.MESSAGES.operationNameNotSpecifiedOnExchange(); + } + } + + /** + * Get the list of candidate service {@link Method methods/operations} for the specified + * operation name. + * + * @param operationName The operation name. + * @return The list of possible matching operation methods. + */ + public List getCandidateMethods(String operationName) { + List candidateMethods = new ArrayList(); + + for (Method serviceMethod : _serviceMethods) { + if (serviceMethod.getName().equals(operationName)) { + candidateMethods.add(serviceMethod); + } + } + + return candidateMethods; + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/ClientProxyBean.java b/components/bean/src/main/java/org/switchyard/component/bean/ClientProxyBean.java new file mode 100644 index 000000000..41225cbe5 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/ClientProxyBean.java @@ -0,0 +1,351 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.lang.reflect.Type; +import java.text.MessageFormat; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.Any; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.enterprise.util.AnnotationLiteral; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangeState; +import org.switchyard.ServiceReference; +import org.switchyard.component.bean.deploy.BeanDeploymentMetaData; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.extensions.java.JavaService; + +/** + * Client Proxy CDI Bean. + *

+ * CDI bean for injecting into consumer beans where the {@link org.switchyard.component.bean.Reference @Reference} + * is used. + * + * @author tom.fennelly@gmail.com + */ +public class ClientProxyBean implements Bean { + + /** + * The target Service. + */ + private String _serviceName; + + /** + * Target service reference. + */ + private ServiceReference _service; + + /** + * The bean proxy Interface {@link Class} of the bean being proxied. This class + * must be one of the {@link org.switchyard.component.bean.Service @Service} + * interfaces implemented by the actual Service bean component. + */ + private Class _serviceInterface; + + /** + * CDI bean qualifiers. See CDI Specification. + */ + private Set _qualifiers; + + /** + * The dynamic proxy bean instance created from the supplied {@link #_serviceInterface}. + */ + private Object _proxyBean; + + /** + * Public constructor. + * + * @param serviceName The name of the ESB Service being proxied to. + * @param proxyInterface The proxy Interface. + * @param qualifiers The CDI bean qualifiers. Copied from the injection point. + * @param beanDeploymentMetaData Deployment metadata. + */ + public ClientProxyBean(String serviceName, Class proxyInterface, Set qualifiers, BeanDeploymentMetaData beanDeploymentMetaData) { + this._serviceName = serviceName; + this._serviceInterface = proxyInterface; + + if (qualifiers != null) { + this._qualifiers = qualifiers; + } else { + this._qualifiers = new HashSet(); + this._qualifiers.add(new AnnotationLiteral() { + }); + this._qualifiers.add(new AnnotationLiteral() { + }); + } + + _proxyBean = Proxy.newProxyInstance(beanDeploymentMetaData.getDeploymentClassLoader(), + new Class[]{_serviceInterface}, + new ClientProxyInvocationHandler(_serviceInterface)); + } + + /** + * Get the name of the ESB Service being proxied to. + * + * @return The Service name. + */ + public String getServiceName() { + return _serviceName; + } + + /** + * Get the Service interface. + * @return The service interface. + */ + public Class getServiceInterface() { + return _serviceInterface; + } + + /** + * Set the service reference for the target Service. + * @param service The target service. + */ + public void setService(ServiceReference service) { + this._service = service; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject bean types} of the bean. + * + * @return the {@linkplain javax.enterprise.inject bean types} + */ + public Set getTypes() { + Set types = new HashSet(); + types.add(_serviceInterface); + types.add(Object.class); + return types; + } + + /** + * Obtains the {@linkplain javax.inject.Qualifier qualifiers} of the bean. + * + * @return the {@linkplain javax.inject.Qualifier qualifiers} + */ + public Set getQualifiers() { + return _qualifiers; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject EL name} of a bean, if it has one. + * + * @return the {@linkplain javax.enterprise.inject EL name} + */ + public String getName() { + return null; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject.Stereotype stereotypes} + * of the bean. + * + * @return the set of {@linkplain javax.enterprise.inject.Stereotype stereotypes} + */ + public Set> getStereotypes() { + return Collections.emptySet(); + } + + /** + * The bean {@linkplain Class class} of the managed bean or session bean or + * of the bean that declares the producer method or field. + * + * @return the bean {@linkplain Class class} + */ + public Class getBeanClass() { + return _serviceInterface; + } + + /** + * Determines if the bean is an + * {@linkplain javax.enterprise.inject.Alternative alternative}. + * + * @return true if the bean is an + * {@linkplain javax.enterprise.inject.Alternative alternative}, + * and false otherwise. + */ + public boolean isAlternative() { + return false; + } + + /** + * Determines if + * {@link javax.enterprise.context.spi.Contextual#create(CreationalContext)} + * sometimes return a null value. + * + * @return true if the {@code create()} method may return a null + * value, and false otherwise + */ + public boolean isNullable() { + return false; + } + + /** + * Obtains the {@link javax.enterprise.inject.spi.InjectionPoint} objects + * representing injection points of the bean, that will be validated by the + * container at initialization time. + * + * @return the set of {@linkplain javax.enterprise.inject.spi.InjectionPoint injection points} of the bean + */ + public Set getInjectionPoints() { + return Collections.emptySet(); + } + + /** + * Obtains the {@linkplain javax.enterprise.context scope} of the bean. + * + * @return the {@linkplain javax.enterprise.context scope} + */ + public Class getScope() { + return ApplicationScoped.class; + } + + /** + * Create a new instance of the contextual type. Instances should + * use the given {@link javax.enterprise.context.spi.CreationalContext} + * when obtaining contextual references to inject, in order to ensure + * that any dependent objects are associated with the contextual instance + * that is being created. An implementation may call + * {@link javax.enterprise.context.spi.CreationalContext#push(Object)} + * between instantiation and injection to help the container minimize the + * use of client proxy objects. + * + * @param creationalContext the context in which this instance is being created + * @return the contextual instance + */ + public Object create(CreationalContext creationalContext) { + return _proxyBean; + } + + /** + * Destroy an instance of the contextual type. Implementations should + * call {@link javax.enterprise.context.spi.CreationalContext#release()} + * to allow the container to destroy dependent objects of the contextual + * instance. + * + * @param instance the contextual instance to destroy + * @param creationalContext the context in which this instance was created + */ + public void destroy(Object instance, CreationalContext creationalContext) { + + } + + /** + * Dynamic proxy {@link InvocationHandler}. + */ + private class ClientProxyInvocationHandler implements InvocationHandler { + + private JavaService _invokerInterface; + + public ClientProxyInvocationHandler(Class invokerInterface) { + _invokerInterface = JavaService.fromClass(invokerInterface); + } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (_service == null) { + throw BeanMessages.MESSAGES.aServiceReferenceToServiceIsNotBoundInto(_serviceName); + } + + // Handle basic Object methods. + if (method.getDeclaringClass() == Object.class) { + final String methodName = method.getName(); + final int paramCount = method.getParameterTypes().length; + if ("toString".equals(methodName) && paramCount == 0) { + return MessageFormat.format("SwitchYard proxy for {0} [{1}]", _invokerInterface.getJavaInterface(), _invokerInterface); + } else if ("equals".equals(methodName) && paramCount == 1) { + return this.equals(args[0]); + } else if ("hashCode".equals(methodName) && paramCount == 0) { + return this.hashCode(); + } + } + + if (method.getReturnType() != null && !Void.TYPE.isAssignableFrom(method.getReturnType())) { + SynchronousInOutHandler inOutHandler = new SynchronousInOutHandler(); + + Exchange exchangeIn = createExchange(_service, method, inOutHandler); + // Don't set the message content as an array unless there are multiple arguments + if (args != null && args.length == 1) { + exchangeIn.send(exchangeIn.createMessage().setContent(args[0])); + } else { + exchangeIn.send(exchangeIn.createMessage().setContent(args)); + } + + Exchange exchangeOut = inOutHandler.waitForOut(); + if (exchangeOut.getState() == ExchangeState.OK) { + return exchangeOut.getMessage().getContent(method.getReturnType()); + } else { + return handleException(exchangeOut, method); + } + } else { + Exchange exchange = createExchange(_service, method, null); + // Don't set the message content as an array unless there are multiple arguments + if (args == null) { + exchange.send(exchange.createMessage()); + } else if (args.length == 1) { + exchange.send(exchange.createMessage().setContent(args[0])); + } else { + exchange.send(exchange.createMessage().setContent(args)); + } + + Object propagateException = _service.getDomain().getProperty(Exchange.PROPAGATE_EXCEPTION_ON_IN_ONLY); + if ((propagateException == null || Boolean.parseBoolean(propagateException.toString())) + && exchange.getState().equals(ExchangeState.FAULT)) { + handleException(exchange, method); + } + return null; + } + } + + private Exchange createExchange(ServiceReference service, Method method, ExchangeHandler responseExchangeHandler) throws BeanComponentException { + String operationName = method.getName(); + if (service.getInterface().getOperation(operationName) == null) { + throw BeanMessages.MESSAGES.beanComponentInvocationFailureOperationIsNotDefinedOnService(operationName, _serviceName); + } + + return service.createExchange(operationName, responseExchangeHandler); + } + + private Throwable handleException(Exchange exchange, Method method) throws Throwable { + Object exceptionObj = exchange.getMessage().getContent(); + if (exceptionObj instanceof Throwable) { + if (exceptionObj instanceof BeanComponentException) { + BeanComponentException beanCompException = (BeanComponentException) exceptionObj; + Throwable cause = beanCompException.getCause(); + if (cause instanceof InvocationTargetException) { + throw cause.getCause(); + } else { + throw cause; + } + } + throw (Throwable) exceptionObj; + } else { + throw BeanMessages.MESSAGES.beanComponentInvocationFailureServiceOperation(_serviceName, method.getName()).setFaultExchange(exchange); + } + } + + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/Invocation.java b/components/bean/src/main/java/org/switchyard/component/bean/Invocation.java new file mode 100644 index 000000000..faeaa739d --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/Invocation.java @@ -0,0 +1,123 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import org.switchyard.Exchange; +import org.switchyard.Message; + +import java.lang.reflect.Method; + +/** + * Bean component invocation details. + * + * @author tom.fennelly@gmail.com + */ +public class Invocation { + + /** + * The method/operation being invoked. + */ + private Method _method; + /** + * The exchange instance. + */ + private Exchange _exchange; + + /** + * The invocation arguments. + */ + private Object[] _args; + + /** + * Constructor. + * + * @param method The method/operation being invoked. + * @param exchange The exchange instance. + * @throws BeanComponentException Unsupported method structure, or type mismatch. + */ + Invocation(Method method, Exchange exchange) throws BeanComponentException { + this._method = method; + this._exchange = exchange; + this._args = castArg(method, exchange.getMessage()); + assertOK(); + } + + /** + * Assert that the exchange payload type(s) and the bean method + * argument type(s) match. + */ + private void assertOK() throws BeanComponentException { + assertMethodStructureSupported(); + assertTypesMatch(); + } + + /** + * Get the invocation arguments. + * + * @return The invocation arguments. + */ + public Object[] getArgs() { + return _args; + } + + /** + * Get the method/operation being invoked. + * + * @return The method/operation being invoked. + */ + public Method getMethod() { + return _method; + } + + private static Object[] castArg(Method method, Message message) { + if (method.getParameterTypes().length == 1 && message != null) { + return new Object[]{message.getContent(method.getParameterTypes()[0])}; + } + return null; + } + + private void assertMethodStructureSupported() throws BeanComponentException { + Class[] parameterTypes = _method.getParameterTypes(); + + // TODO: Only supports 0 or 1 arg operations for now... + if (parameterTypes.length > 1) { + throw BeanMessages.MESSAGES.beanServiceOperationMoreThanOne(operationName()); + } + } + + private void assertTypesMatch() throws BeanComponentException { + if (_args == null) { + if (_method.getParameterTypes().length != 0) { + throw BeanMessages.MESSAGES.beanServiceOperationRequiresSingle(operationName()); + } + } else { + if (_args.length > 1) { + throw BeanMessages.MESSAGES.beanServiceOperationSupportsSingle(operationName(), Integer.toString(_args.length)); + } + + if (_args[0] != null) { + Class argType = _method.getParameterTypes()[0]; + + if (!argType.isInstance(_args[0])) { + throw BeanMessages.MESSAGES.beanServiceOperationRequiresAPayloadTypeOf(operationName(), argType.getName(), _args[0].getClass().getName()); + } + } + } + } + + private String operationName() { + return _exchange.getProvider().getName() + "#" + _method.getName(); + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/Property.java b/components/bean/src/main/java/org/switchyard/component/bean/Property.java new file mode 100644 index 000000000..03337b94d --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/Property.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Property Annotation. + * Use this annotation to inject a Property into service bean component. + */ +@Target(FIELD) +@Retention(RUNTIME) +@Documented +public @interface Property { + + /** + * name of the property. + */ + String name() default ""; +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/Reference.java b/components/bean/src/main/java/org/switchyard/component/bean/Reference.java new file mode 100644 index 000000000..19f5ee61f --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/Reference.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import javax.inject.Qualifier; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Service reference. + *

+ * Use this annotation, in conjunction with the {@link javax.inject.Inject} + * annotation, to inject a reference to a Service bean component. + * + * @author tom.fennelly@gmail.com + */ +@Qualifier +@Target({TYPE, FIELD }) +@Retention(RUNTIME) +@Documented +public @interface Reference { + + /** + * Get the name of the Service to which a reference + * is to be injected. + */ + String value() default ""; +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/ReferenceInvocation.java b/components/bean/src/main/java/org/switchyard/component/bean/ReferenceInvocation.java new file mode 100644 index 000000000..7cb9349d8 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/ReferenceInvocation.java @@ -0,0 +1,58 @@ +package org.switchyard.component.bean; + +import org.switchyard.Context; +import org.switchyard.Message; + +/** + * An instance of an invocation for an @Reference. A single instance of + * ReferenceInvocation cannot be used for multiple invocations of a service. + * Message content and context properties for an invocation can be accessed + * through this interface. + */ +public interface ReferenceInvocation { + + /** + * Access the context for a reference. + * @return context + */ + Context getContext(); + + /** + * Access the current message for a reference. Before invoke() is called + * this will return the IN message. After invoke() is called, this will + * return the OUT message for IN_OUT MEPs. + * @return current message. + */ + Message getMessage(); + + /** + * Invoke the target service. + * @return a reference to this ReferenceInvocation for chaining calls + * @throws Exception fault encountered during the invocation + */ + ReferenceInvocation invoke() throws Exception; + + /** + * Invoke the target service using the specified object as the message content. + * @param content message content + * @return a reference to this ReferenceInvocation for chaining calls + * @throws Exception fault encountered during the invocation + */ + ReferenceInvocation invoke(Object content) throws Exception; + + /** + * Convenience method for setting a message-scoped context property for the + * invocation. + * @param name property name + * @param value property value + * @return a reference to this ReferenceInvocation for chaining calls + */ + ReferenceInvocation setProperty(String name, String value); + + /** + * Convenience method to retrieve a context property. + * @param name property name + * @return property value + */ + Object getProperty(String name); +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/ReferenceInvoker.java b/components/bean/src/main/java/org/switchyard/component/bean/ReferenceInvoker.java new file mode 100644 index 000000000..8d1c655ec --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/ReferenceInvoker.java @@ -0,0 +1,34 @@ +package org.switchyard.component.bean; + +import org.switchyard.metadata.ServiceInterface; + +/** + * Used to create invocation instances for @Reference injection points in + * a bean service. A new ReferenceInvocation should be created for each + * invocation of the target reference. + *

+ * If the contract associated with the reference has + * multiple operations, the overloaded version of newInvocation() must be + * used to specify the operation name. + */ +public interface ReferenceInvoker { + /** + * Create a new instance of an invocation when the reference contract + * only has one operation. + * @return new instance of ReferenceInvocation + */ + ReferenceInvocation newInvocation(); + + /** + * Create a new instance of an invocation for the specified operation. + * @param operation name of the operation to invoke + * @return new instance of ReferenceInvocation + */ + ReferenceInvocation newInvocation(String operation); + + /** + * Get the service contract for the reference. + * @return service contract used by the reference + */ + ServiceInterface getContract(); +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/Service.java b/components/bean/src/main/java/org/switchyard/component/bean/Service.java new file mode 100644 index 000000000..4d1c2612e --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/Service.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Bean Service Annotation. + * + * @author tom.fennelly@gmail.com + * @author jpechane@redhat.com + * @see org.switchyard.component.bean.Reference + */ +@Target({TYPE, FIELD }) +@Retention(RUNTIME) +@Documented +public @interface Service { + + /** + * Get the Service Interface for the Service. + */ + // Class field couldn't be declared so using a literal anyway + Class value() default Service.class; + + /** + * Optional Service name. + */ + String name() default EMPTY; + + /** + * Optional name of the component that implements the service. + */ + String componentName() default EMPTY; + + /** + * Constant representing a null (i.e. unassigned) value. + * Annotations are not allowed to have empty values, so a default + * representation for an empty value is used. + */ + public static final String EMPTY = ""; +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/ServiceProxyHandler.java b/components/bean/src/main/java/org/switchyard/component/bean/ServiceProxyHandler.java new file mode 100644 index 000000000..5653f48c7 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/ServiceProxyHandler.java @@ -0,0 +1,230 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.ServiceReference; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.common.type.reflect.FieldAccess; +import org.switchyard.component.bean.deploy.BeanDeploymentMetaData; +import org.switchyard.component.bean.internal.ReferenceInvokerBean; +import org.switchyard.component.bean.internal.context.ContextProxy; +import org.switchyard.component.bean.internal.exchange.ExchangeProxy; +import org.switchyard.component.bean.internal.message.MessageProxy; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.deploy.ComponentNames; +import org.switchyard.deploy.ServiceHandler; + +/** + * Service/Provider proxy handler. + *

+ * Handler for converting extracting Service operation invocation details from + * an ESB {@link Exchange}, making the invocation and then mapping the invocation + * return/result onto the {@link Message Exchange Message} (if the Exchange pattern + * is {@link ExchangePattern#IN_OUT IN_OUT}). + * + * @author tom.fennelly@gmail.com + */ +public class ServiceProxyHandler extends BaseServiceHandler implements ServiceHandler { + + private static Logger _logger = Logger.getLogger(ServiceProxyHandler.class); + + /** + * The Service bean instance being proxied to. + */ + private Object _serviceBean; + /** + * The Service bean metadata. + */ + private BeanServiceMetadata _serviceMetadata; + /** + * Deployment metadata. + */ + private BeanDeploymentMetaData _beanDeploymentMetaData; + + private Map _references = + new HashMap(); + + /** + * Public constructor. + * + * @param serviceBean The Service bean instance being proxied to. + * @param serviceMetadata The Service bean metadata. + * @param beanDeploymentMetaData Deployment metadata. + */ + public ServiceProxyHandler(Object serviceBean, + BeanServiceMetadata serviceMetadata, + BeanDeploymentMetaData beanDeploymentMetaData) { + _serviceBean = serviceBean; + _serviceMetadata = serviceMetadata; + _beanDeploymentMetaData = beanDeploymentMetaData; + } + + /** + * Called when a message is sent through an exchange. + * + * @param exchange an {@code Exchange} instance containing a message to be processed. + * @throws HandlerException when handling of the message event fails (e.g. invalid request message). + */ + public void handleMessage(Exchange exchange) throws HandlerException { + handle(exchange); + } + + /** + * Called when a fault is generated while processing an exchange. + * + * @param exchange an {@code Exchange} instance containing a message to be processed. + */ + public void handleFault(Exchange exchange) { + } + + /** + * Add the specified reference to the handler. + * @param reference service reference + */ + public void addReference(ServiceReference reference) { + QName refName = ComponentNames.unqualify(reference); + _references.put(refName.getLocalPart(), reference); + } + + /** + * Inject Implementation Properties into Bean component. + * @param resolver property resolver + */ + public void injectImplementationProperties(PropertyResolver resolver) { + for (Field field : _serviceBean.getClass().getDeclaredFields()) { + Property propAnno = field.getAnnotation(Property.class); + if (propAnno != null) { + String propertyName = propAnno.name(); + if (propertyName.equals("")) { + propertyName = field.getName(); + } + Object property = resolver.resolveProperty(propertyName); + if (property != null) { + if (field.getType().isAssignableFrom(property.getClass())) { + new FieldAccess(field).write(_serviceBean, property); + } else { + BeanLogger.ROOT_LOGGER.propertyHasIncompatibleTypeBean(propAnno.name(), _serviceMetadata.getServiceClass().getName(), field.getType().getName(), property.getClass().getName()); + } + } + + } + } + } + + protected ClassLoader getDeploymentClassLoader() { + return _beanDeploymentMetaData.getDeploymentClassLoader(); + } + + /** + * Handle the Service bean invocation. + * + * @param exchange The Exchange instance. + * @throws HandlerException Error invoking Bean component operation. + */ + private void handle(Exchange exchange) throws HandlerException { + Invocation invocation = _serviceMetadata.getInvocation(exchange); + + if (invocation != null) { + ExchangePattern exchangePattern = exchange.getContract().getProviderOperation().getExchangePattern(); + try { + + if (_logger.isDebugEnabled()) { + _logger.debug("CDI Bean Service ExchangeHandler proxy class received " + exchangePattern + " Exchange (" + + System.identityHashCode(exchange) + ") for Bean Service '" + + exchange.getProvider().getName() + "'. Invoking bean method '" + invocation.getMethod().getName() + "'."); + } + + Object responseObject; + ContextProxy.setContext(exchange.getContext()); + MessageProxy.setMessage(exchange.getMessage()); + ExchangeProxy.setExchange(exchange); + try { + responseObject = invocation.getMethod().invoke(_serviceBean, invocation.getArgs()); + } finally { + ContextProxy.setContext(null); + MessageProxy.setMessage(null); + ExchangeProxy.setExchange(null); + } + + if (exchangePattern == ExchangePattern.IN_OUT + && exchange.getPhase() != ExchangePhase.OUT) { + Message message = exchange.createMessage(); + message.setContent(responseObject); + exchange.send(message); + } + } catch (Exception ex) { + String errMsg = BeanMessages.MESSAGES.invocationOfOperationFailed(invocation.getMethod().getName(), + _serviceBean.getClass().getName()); + // write error details to log + if (_logger.isDebugEnabled()) { + _logger.debug(errMsg, ex); + } + + // if the exception is declared on service interface, use sendFault, otherwise throw an exception + Throwable faultContent = ex; + if (faultContent instanceof InvocationTargetException) { + faultContent = ((InvocationTargetException)ex).getTargetException(); + } + if (exchangePattern == ExchangePattern.IN_OUT) { + for (Class expectedFault : invocation.getMethod().getExceptionTypes()) { + if (expectedFault.isAssignableFrom(faultContent.getClass())) { + exchange.sendFault(exchange.createMessage().setContent(faultContent)); + return; + } + } + } + throw new HandlerException(faultContent); + } + } else { + throw BeanMessages.MESSAGES.unexpectedErrorBeanServiceMetadataShouldReturnAnInvocationInstanceOrThrowABeanComponentException(); + } + } + + @Override + protected void doStart() { + // Initialise any client proxies to the started service... + for (ClientProxyBean proxyBean : _beanDeploymentMetaData.getClientProxies()) { + if (_references.containsKey(proxyBean.getServiceName())) { + proxyBean.setService(_references.get(proxyBean.getServiceName())); + } + } + + // Initialise ReferenceInvokers + for (ReferenceInvokerBean invokerBean : _beanDeploymentMetaData.getReferenceInvokers()) { + if (_references.containsKey(invokerBean.getServiceName())) { + invokerBean.setReference(_references.get(invokerBean.getServiceName())); + } + } + } + + @Override + public void stop() { + // NOP + // leave state alone + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/SwitchYardCDIServiceDiscovery.java b/components/bean/src/main/java/org/switchyard/component/bean/SwitchYardCDIServiceDiscovery.java new file mode 100644 index 000000000..0b2834a20 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/SwitchYardCDIServiceDiscovery.java @@ -0,0 +1,202 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.spi.AfterBeanDiscovery; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.BeforeBeanDiscovery; +import javax.enterprise.inject.spi.Extension; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.enterprise.inject.spi.ProcessBean; + +import org.jboss.logging.Logger; +import org.switchyard.common.type.Classes; +import org.switchyard.component.bean.deploy.BeanDeploymentMetaData; +import org.switchyard.component.bean.deploy.BeanDeploymentMetaDataCDIBean; +import org.switchyard.component.bean.deploy.CDIBean; +import org.switchyard.component.bean.deploy.CDIBeanServiceDescriptor; +import org.switchyard.component.bean.internal.ReferenceInvokerBean; +import org.switchyard.component.bean.internal.context.ContextBean; +import org.switchyard.component.bean.internal.exchange.ExchangeBean; +import org.switchyard.component.bean.internal.message.MessageBean; + +/** + * Portable CDI extension for SwitchYard. + * + * @author tom.fennelly@gmail.com + */ +@ApplicationScoped +public class SwitchYardCDIServiceDiscovery implements Extension { + + /** + * Logger + */ + private static Logger _logger = Logger.getLogger(SwitchYardCDIServiceDiscovery.class); + /** + * Bean deployment metadata. + */ + private BeanDeploymentMetaData _beanDeploymentMetaData; + /** + * List of created {@link ClientProxyBean} instances. + */ + private List _createdProxyBeans = new ArrayList(); + + /** + * List of created ReferenceInvokerBean instances. + */ + private List _createdInvokerBeans = new ArrayList(); + + /** + * {@link javax.enterprise.inject.spi.BeforeBeanDiscovery} CDI event observer. + * + * @param beforeEvent CDI Event instance. + * @param beanManager CDI Bean Manager instance. + */ + public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery beforeEvent, BeanManager beanManager) { + _logger.debug("CDI Bean discovery process started."); + + _beanDeploymentMetaData = new BeanDeploymentMetaData(); + _beanDeploymentMetaData.setBeanManager(beanManager); + _beanDeploymentMetaData.setDeploymentClassLoader(Classes.getTCCL()); + } + + /** + * {@link javax.enterprise.inject.spi.ProcessBean} CDI event observer. + * + * @param processBean CDI Event instance. + * @param beanManager CDI Bean Manager instance. + */ + public void processBean(@Observes ProcessBean processBean, BeanManager beanManager) { + Bean bean = processBean.getBean(); + Set injectionPoints = bean.getInjectionPoints(); + + // Create proxies for the relevant injection points... + for (InjectionPoint injectionPoint : injectionPoints) { + for (Annotation qualifier : injectionPoint.getQualifiers()) { + if (Reference.class.isAssignableFrom(qualifier.annotationType())) { + Member member = injectionPoint.getMember(); + if (member instanceof Field) { + Class memberType = ((Field) member).getType(); + if (memberType.isInterface()) { + if (memberType.equals(ReferenceInvoker.class)) { + addInvokerBean((Reference)qualifier, injectionPoint.getQualifiers()); + } else { + addInjectableClientProxyBean((Field) member, (Reference) qualifier, injectionPoint.getQualifiers(), beanManager); + } + } + } + } + } + } + + CDIBean cdiBean = new CDIBean(bean, beanManager); + + // Create Service Proxy ExchangeHandlers and register them as Services, for all @Service beans... + if (isServiceBean(bean)) { + _logger.debug("Adding ServiceDescriptor for bean " + bean.getBeanClass().getName()); + _beanDeploymentMetaData.addServiceDescriptor(new CDIBeanServiceDescriptor(cdiBean, _beanDeploymentMetaData)); + } + + // Register all beans in the deployment... + _beanDeploymentMetaData.addDeploymentBean(cdiBean); + } + + /** + * {@link javax.enterprise.inject.spi.ProcessBean} CDI event observer. + * + * @param afterEvent CDI Event instance. + */ + public void afterBeanDiscovery(@Observes AfterBeanDiscovery afterEvent) { + for (ClientProxyBean proxyBean : _createdProxyBeans) { + _logger.debug("Adding ClientProxyBean for bean Service " + proxyBean.getServiceName() + ". Service Interface type is " + proxyBean.getServiceInterface().getName()); + afterEvent.addBean(proxyBean); + _beanDeploymentMetaData.addClientProxy(proxyBean); + } + + for (ReferenceInvokerBean invokerBean : _createdInvokerBeans) { + _logger.debug("Adding ReferenceInvokerBean for bean Service " + invokerBean.getServiceName()); + afterEvent.addBean(invokerBean); + _beanDeploymentMetaData.addReferenceInvoker(invokerBean); + } + + afterEvent.addBean(new BeanDeploymentMetaDataCDIBean(_beanDeploymentMetaData)); + afterEvent.addBean(new ContextBean()); + afterEvent.addBean(new MessageBean()); + afterEvent.addBean(new ExchangeBean()); + + _logger.debug("CDI Bean discovery process completed."); + } + + private void addInjectableClientProxyBean(Field injectionPointField, Reference serviceReference, Set qualifiers, BeanManager beanManager) { + final String serviceName; + + if (serviceReference.value().length() > 0) { + serviceName = serviceReference.value(); + } else { + serviceName = injectionPointField.getType().getSimpleName(); + } + + addClientProxyBean(serviceName, injectionPointField.getType(), qualifiers); + } + + private void addClientProxyBean(String serviceName, Class beanClass, Set qualifiers) { + // Check do we already have a proxy for this service interface... + for (ClientProxyBean clientProxyBean : _createdProxyBeans) { + if (serviceName.equals(clientProxyBean.getServiceName()) && beanClass == clientProxyBean.getBeanClass()) { + // ignore... we already have a proxy ... + return; + } + } + + ClientProxyBean clientProxyBean = new ClientProxyBean(serviceName, beanClass, qualifiers, _beanDeploymentMetaData); + _createdProxyBeans.add(clientProxyBean); + } + + private void addInvokerBean(Reference serviceReference, Set qualifiers) { + // Value of Reference annotation is required for ReferenceInvoker + if (serviceReference.value().length() == 0) { + _logger.debug("Unable to create reference invoker for @Reference with missing value"); + } + + String serviceName = serviceReference.value(); + // Check do we already have an invoker for this service reference ... + for (ReferenceInvokerBean invokerBean : _createdInvokerBeans) { + if (serviceName.equals(invokerBean.getServiceName())) { + // ignore... we already have a proxy ... + return; + } + } + + ReferenceInvokerBean invokerBean = new ReferenceInvokerBean(serviceName, qualifiers); + _createdInvokerBeans.add(invokerBean); + } + + private boolean isServiceBean(Bean bean) { + Class beanClass = bean.getBeanClass(); + return (Modifier.isPublic(beanClass.getModifiers()) && beanClass.isAnnotationPresent(Service.class)); + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanComponentImplementationModel.java b/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanComponentImplementationModel.java new file mode 100644 index 000000000..78b36d184 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanComponentImplementationModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.config.model; + +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * A "bean" ComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface BeanComponentImplementationModel extends ComponentImplementationModel { + + /** + * The "bean" implementation type. + */ + public static final String BEAN = "bean"; + + /** + * The "class" attribute. + */ + public static final String CLASS = "class"; + + /** + * Gets the "class" attribute. + * + * @return the "class" attribute + */ + public String getClazz(); + + /** + * Sets the "class" attribute. + * + * @param clazz the "class" attribute + * @return this instance (useful for chaining) + */ + public BeanComponentImplementationModel setClazz(String clazz); + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanNamespace.java b/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanNamespace.java new file mode 100644 index 000000000..840bfadd5 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.config.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Bean config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum BeanNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new BeanNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + BeanNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the BeanNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the BeanNamespace + */ + public static BeanNamespace fromUri(String uri) { + return Util.fromUri(BeanNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(BeanNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-bean:config", version); + } + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanSwitchYardScanner.java b/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanSwitchYardScanner.java new file mode 100644 index 000000000..70749f9ad --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/config/model/BeanSwitchYardScanner.java @@ -0,0 +1,265 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.config.model; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.annotations.Requires; +import org.switchyard.common.type.classpath.ClasspathScanner; +import org.switchyard.common.type.classpath.CompositeFilter; +import org.switchyard.common.type.classpath.IsAnnotationPresentFilter; +import org.switchyard.common.type.classpath.PackageFilter; +import org.switchyard.component.bean.BeanMessages; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; +import org.switchyard.component.bean.config.model.v1.V1BeanComponentImplementationModel; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.v1.V1ComponentModel; +import org.switchyard.config.model.composite.v1.V1ComponentReferenceModel; +import org.switchyard.config.model.composite.v1.V1ComponentServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeModel; +import org.switchyard.config.model.composite.v1.V1InterfaceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.policy.Policy.PolicyType; +import org.switchyard.policy.SecurityPolicy; +import org.switchyard.policy.TransactionPolicy; + +/** + * Bean Scanner. + * + * @author tom.fennelly@gmail.com + */ +public class BeanSwitchYardScanner implements Scanner { + + /** + * {@inheritDoc} + */ + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + SwitchYardNamespace switchyardNamespace = input.getSwitchyardNamespace(); + SwitchYardModel switchyardModel = new V1SwitchYardModel(switchyardNamespace.uri()); + CompositeModel compositeModel = new V1CompositeModel(); + compositeModel.setName(input.getCompositeName()); + + BeanNamespace beanNamespace = BeanNamespace.DEFAULT; + for (BeanNamespace value : BeanNamespace.values()) { + if (value.versionMatches(switchyardNamespace)) { + beanNamespace = value; + break; + } + } + + List> serviceClasses = scanForServiceBeans(input); + + for (Class serviceClass : serviceClasses) { + if (serviceClass.isInterface()) { + continue; + } + if (Modifier.isAbstract(serviceClass.getModifiers())) { + continue; + } + + ComponentModel componentModel = new V1ComponentModel(); + ComponentServiceModel serviceModel = new V1ComponentServiceModel(switchyardNamespace.uri()); + String name = serviceClass.getSimpleName(); + + BeanComponentImplementationModel beanModel = new V1BeanComponentImplementationModel(beanNamespace.uri()); + beanModel.setClazz(serviceClass.getName()); + componentModel.setImplementation(beanModel); + + Service service = serviceClass.getAnnotation(Service.class); + if (service != null) { + Class iface = service.value(); + if (iface == Service.class) { + Class[] interfaces = serviceClass.getInterfaces(); + if (interfaces.length == 1) { + iface = interfaces[0]; + } else { + throw BeanMessages.MESSAGES.unexpectedExceptionTheServiceAnnotationHasNoValueItCannotBeOmmittedUnlessTheBeanImplementsExactlyOneInterface(); + } + } + InterfaceModel csiModel = new V1InterfaceModel(InterfaceModel.JAVA); + + if (service.name().equals(Service.EMPTY)) { + name = iface.getSimpleName(); + } else { + name = service.name(); + } + + serviceModel.setName(name); + serviceModel.setInterface(csiModel); + csiModel.setInterface(iface.getName()); + + componentModel.addService(serviceModel); + } + + // Check to see if a policy requirements have been defined + Requires requires = serviceClass.getAnnotation(Requires.class); + if (requires != null) { + for (SecurityPolicy secPolicy : requires.security()) { + if (secPolicy == SecurityPolicy.AUTHORIZATION) { + // authorization supports both interaction and implementation, + // and we want to add it as implementation to be more correct. + beanModel.addPolicyRequirement(secPolicy.getQName()); + } else if (secPolicy.supports(PolicyType.INTERACTION)) { + serviceModel.addPolicyRequirement(secPolicy.getQName()); + } else if (secPolicy.supports(PolicyType.IMPLEMENTATION)) { + beanModel.addPolicyRequirement(secPolicy.getQName()); + } else { + throw BeanMessages.MESSAGES.unknownPolicy(secPolicy.toString()); + } + } + for (TransactionPolicy txPolicy : requires.transaction()) { + if (txPolicy.supports(PolicyType.INTERACTION)) { + serviceModel.addPolicyRequirement(txPolicy.getQName()); + } else if (txPolicy.supports(PolicyType.IMPLEMENTATION)) { + beanModel.addPolicyRequirement(txPolicy.getQName()); + } else { + throw BeanMessages.MESSAGES.unknownPolicy(txPolicy.toString()); + } + } + // Make sure we don't have conflicting policies + QName ptx = TransactionPolicy.PROPAGATES_TRANSACTION.getQName(); + QName stx = TransactionPolicy.SUSPENDS_TRANSACTION.getQName(); + if (serviceModel.hasPolicyRequirement(ptx) && serviceModel.hasPolicyRequirement(stx)) { + throw BeanMessages.MESSAGES.transactionPoliciesCannotCoexistService(ptx, stx, name); + } + QName gtx = TransactionPolicy.MANAGED_TRANSACTION_GLOBAL.getQName(); + QName ltx = TransactionPolicy.MANAGED_TRANSACTION_LOCAL.getQName(); + QName ntx = TransactionPolicy.NO_MANAGED_TRANSACTION.getQName(); + if (beanModel.hasPolicyRequirement(gtx) && beanModel.hasPolicyRequirement(ltx) + || beanModel.hasPolicyRequirement(gtx) && beanModel.hasPolicyRequirement(ntx) + || beanModel.hasPolicyRequirement(ltx) && beanModel.hasPolicyRequirement(ntx)) { + throw BeanMessages.MESSAGES.transactionPoliciesCannotCoexistImplementation(gtx, ltx, ntx, name); + } + } + + // Add any references + for (ComponentReferenceModel reference : getReferences(switchyardNamespace, serviceClass, name)) { + componentModel.addReference(reference); + } + + compositeModel.addComponent(componentModel); + componentModel.setName(getComponentName(name, service)); + compositeModel.addComponent(componentModel); + } + + if (!compositeModel.getModelChildren().isEmpty()) { + switchyardModel.setComposite(compositeModel); + } + + return new ScannerOutput().setModel(switchyardModel); + } + + private String getComponentName(String serviceName, Service service) { + if (service == null) { + return serviceName; + } + String componentName = service.componentName(); + return Service.EMPTY.equals(componentName) ? serviceName : componentName; + } + private List> scanForServiceBeans(ScannerInput input) throws IOException { + IsAnnotationPresentFilter annoFilter = new IsAnnotationPresentFilter(Service.class); + annoFilter.addType(Reference.class); + PackageFilter pkgFilter = new PackageFilter(input.getIncludePackages().toArray(new Package[0])); + for (Package pkg : input.getExcludePackages()) { + pkgFilter.addExclude(pkg); + } + CompositeFilter filter = new CompositeFilter(annoFilter, pkgFilter); + ClasspathScanner serviceScanner = new ClasspathScanner(filter); + + for (URL url : input.getURLs()) { + serviceScanner.scan(url); + } + + return filter.getMatchedTypes(); + } + + /** + * Pick up @Reference fields in the specified class and + * create corresponding ComponentReferenceModel + */ + private Set getReferences( + SwitchYardNamespace switchyardNamespace, + Class serviceClass, + String name) throws IOException { + HashSet references = new HashSet(); + for (Field field : serviceClass.getDeclaredFields()) { + if (!field.isAnnotationPresent(Reference.class)) { + continue; + } + + Class reference = field.getType(); + ComponentReferenceModel referenceModel = new V1ComponentReferenceModel(switchyardNamespace.uri()); + InterfaceModel interfaceModel = new V1InterfaceModel(InterfaceModel.JAVA); + + if (field.getAnnotation(Reference.class) != null) { + Reference ref = field.getAnnotation(Reference.class); + if (ref.value() == null || "".equals(ref.value())) { + referenceModel.setName(reference.getSimpleName()); + } else { + QName qname = QName.valueOf(ref.value()); + referenceModel.setName(qname.getLocalPart()); + } + } else { + referenceModel.setName(reference.getSimpleName()); + } + + referenceModel.setInterface(interfaceModel); + interfaceModel.setInterface(reference.getCanonicalName()); + // Add policy requirements to reference if specified + Requires refRequires = field.getAnnotation(Requires.class); + if (refRequires != null) { + for (SecurityPolicy secPolicy : refRequires.security()) { + if (!secPolicy.supports(PolicyType.INTERACTION)) { + throw BeanMessages.MESSAGES.referenceOnlyCouldBeMarkedWithInteractionPolicyButIsNotTheOne(secPolicy.toString()); + } + referenceModel.addPolicyRequirement(secPolicy.getQName()); + } + for (TransactionPolicy txPolicy : refRequires.transaction()) { + if (!txPolicy.supports(PolicyType.INTERACTION)) { + throw BeanMessages.MESSAGES.referenceOnlyCouldBeMarkedWithInteractionPolicyButIsNotTheOne(txPolicy.toString()); + } + referenceModel.addPolicyRequirement(txPolicy.getQName()); + } + // Make sure we don't have conflicting policies + QName ptx = TransactionPolicy.PROPAGATES_TRANSACTION.getQName(); + QName stx = TransactionPolicy.SUSPENDS_TRANSACTION.getQName(); + if (referenceModel.hasPolicyRequirement(ptx) && referenceModel.hasPolicyRequirement(stx)) { + throw BeanMessages.MESSAGES.transactionPoliciesCannotCoexistService(ptx, stx, name); + } + } + references.add(referenceModel); + } + return references; + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/config/model/v1/V1BeanComponentImplementationModel.java b/components/bean/src/main/java/org/switchyard/component/bean/config/model/v1/V1BeanComponentImplementationModel.java new file mode 100644 index 000000000..f17c6a094 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/config/model/v1/V1BeanComponentImplementationModel.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.config.model.v1; + +import org.switchyard.component.bean.config.model.BeanComponentImplementationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1ComponentImplementationModel; + +/** + * A "bean" implementation of the BeanComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1BeanComponentImplementationModel extends V1ComponentImplementationModel implements BeanComponentImplementationModel { + + /** + * Default constructor for application use. + * @param namespace namespace + */ + public V1BeanComponentImplementationModel(String namespace) { + super(BEAN, namespace); + } + + /** + * Constructor for Marshaller use (ie: V1BeanMarshaller). + * + * @param config the Configuration + * @param desc the Descriptor + */ + public V1BeanComponentImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getClazz() { + return getModelAttribute(CLASS); + } + + @Override + public BeanComponentImplementationModel setClazz(String clazz) { + setModelAttribute(CLASS, clazz); + return this; + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/config/model/v1/V1BeanMarshaller.java b/components/bean/src/main/java/org/switchyard/component/bean/config/model/v1/V1BeanMarshaller.java new file mode 100644 index 000000000..7c7bde668 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/config/model/v1/V1BeanMarshaller.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.config.model.v1; + +import org.switchyard.component.bean.config.model.BeanComponentImplementationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.v1.V1CompositeMarshaller; + +/** + * A CompositeMarshaller which can also create BeanComponentImplementationModels. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1BeanMarshaller extends V1CompositeMarshaller { + + /** + * The complete local name ("implementation.bean"). + */ + private static final String IMPLEMENTATION_BEAN = ComponentImplementationModel.IMPLEMENTATION + "." + BeanComponentImplementationModel.BEAN; + + /** + * Required constructor called via reflection. + * + * @param desc the Descriptor + */ + public V1BeanMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for "implementation.bean". + * If not found, it falls back to the super class (V1CompositeMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + if (config.getName().equals(IMPLEMENTATION_BEAN)) { + return new V1BeanComponentImplementationModel(config, getDescriptor()); + } + return super.read(config); + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanComponent.java b/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanComponent.java new file mode 100644 index 000000000..be25c285b --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanComponent.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.deploy; + +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * An implementation of Bean component. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class BeanComponent extends BaseComponent { + + /** + * Default constructor. + */ + public BeanComponent() { + super(BeanComponentActivator.BEAN_TYPE); + setName("BeanComponent"); + } + + /* (non-Javadoc) + * @see org.switchyard.deploy.Component#createActivator(org.switchyard.ServiceDomain) + */ + @Override + public Activator createActivator(ServiceDomain domain) { + BeanComponentActivator activator = new BeanComponentActivator(); + activator.setServiceDomain(domain); + return activator; + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanComponentActivator.java b/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanComponentActivator.java new file mode 100644 index 000000000..4d3496c39 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanComponentActivator.java @@ -0,0 +1,120 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.component.bean.ClientProxyBean; +import org.switchyard.component.bean.ServiceProxyHandler; +import org.switchyard.component.bean.internal.ReferenceInvokerBean; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ComponentNames; +import org.switchyard.deploy.ServiceHandler; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.component.bean.BeanMessages; + +/** + * The Bean Component Activator. + * + * @author tom.fennelly@gmail.com + */ +public class BeanComponentActivator extends BaseActivator { + + /** + * Bean component activator type name. + */ + public static final String BEAN_TYPE = "bean"; + + private BeanDeploymentMetaData _beanDeploymentMetaData; + + /** + * Public constructor. + */ + public BeanComponentActivator() { + super(BEAN_TYPE); + } + + + @Override + public ServiceHandler activateService(QName serviceName, ComponentModel config) { + lookupBeanMetaData(); + + // This is a bit of a kludge - catches cases where an implementation + // does not provide a service, only a reference + if (serviceName == null) { + for (ComponentReferenceModel reference : config.getReferences()) { + for (ClientProxyBean proxyBean : _beanDeploymentMetaData.getClientProxies()) { + if (reference.getQName().getLocalPart().equals(proxyBean.getServiceName())) { + QName refName = ComponentNames.qualify(config.getQName(), reference.getQName()); + proxyBean.setService(getServiceDomain().getServiceReference(refName)); + } + } + for (ReferenceInvokerBean invokerBean : _beanDeploymentMetaData.getReferenceInvokers()) { + if (reference.getQName().getLocalPart().equals(invokerBean.getServiceName())) { + QName refName = ComponentNames.qualify(config.getQName(), reference.getQName()); + invokerBean.setReference(getServiceDomain().getServiceReference(refName)); + } + } + } + return null; + } + + PropertyResolver resolver = config.getModelConfiguration().getPropertyResolver(); + for (ServiceDescriptor descriptor : _beanDeploymentMetaData.getServiceDescriptors()) { + if (descriptor.getServiceName().equals(serviceName.getLocalPart())) { + ServiceProxyHandler handler = descriptor.getHandler(); + for (ComponentReferenceModel reference : config.getReferences()) { + QName refName = ComponentNames.qualify(config.getQName(), reference.getQName()); + handler.addReference(getServiceDomain().getServiceReference(refName)); + } + handler.injectImplementationProperties(resolver); + return handler; + } + } + // bean discovery did not find a bean providing this service + throw BeanMessages.MESSAGES.unknownServiceName(serviceName.toString()); + } + + @Override + public void deactivateService(QName name, ServiceHandler handler) { + // NOP - CDI subsystem will pull down the CDI bits and pieces + } + + /** + * Looks up Bean meta data. + */ + public void lookupBeanMetaData() { + _beanDeploymentMetaData = BeanDeploymentMetaData.lookupBeanDeploymentMetaData(); + } + + /** + * Create a ServiceInterface instance for the named Service. + * @param name The Service Name. + * @return The ServiceInterface instance. + */ + public ServiceInterface buildServiceInterface(String name) { + for (ServiceDescriptor descriptor : _beanDeploymentMetaData.getServiceDescriptors()) { + if (descriptor.getServiceName().equals(name)) { + return descriptor.getInterface(); + } + } + // bean discovery did not find a bean providing this service + throw BeanMessages.MESSAGES.unknownServiceName(name); + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanDeploymentMetaData.java b/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanDeploymentMetaData.java new file mode 100644 index 000000000..e9a0b6ce5 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanDeploymentMetaData.java @@ -0,0 +1,176 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.deploy; + + +import javax.enterprise.inject.Alternative; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.BeanManager; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.switchyard.common.cdi.CDIUtil; +import org.switchyard.component.bean.ClientProxyBean; +import org.switchyard.component.bean.BeanMessages; +import org.switchyard.component.bean.internal.ReferenceInvokerBean; + +/** + * Bean Deployment Meta Data. + *

+ * All the CDI bean info for a specific deployment. This bean is actually + * managed by BeanDeploymentMetaDataCDIBean. + * + * @author tom.fennelly@gmail.com + */ +@Alternative +public class BeanDeploymentMetaData { + + private BeanManager _beanManager; + private ClassLoader _deploymentClassLoader; + private List _serviceDescriptors = new ArrayList(); + private List _clientProxies = new ArrayList(); + private List _referenceInvokers = new ArrayList(); + private List _deploymentBeans = new ArrayList(); + + /** + * Default no-arg constructor. + */ + public BeanDeploymentMetaData() {} + + /** + * Set the deployment CDI BeanManager. + * @param beanManager The bean manager. + * @return this instance. + */ + public BeanDeploymentMetaData setBeanManager(BeanManager beanManager) { + _beanManager = beanManager; + return this; + } + + /** + * Get the deployment CDI BeanManager. + * @return The bean manager. + */ + public BeanManager getBeanManager() { + return _beanManager; + } + + /** + * Set the deployment ClassLoader. + * @param deploymentClassLoader The deployment ClassLoader. + * @return this instance. + */ + public BeanDeploymentMetaData setDeploymentClassLoader(ClassLoader deploymentClassLoader) { + _deploymentClassLoader = deploymentClassLoader; + return this; + } + + /** + * Get the deployment ClassLoader. + * @return The deployment ClassLoader. + */ + public ClassLoader getDeploymentClassLoader() { + return _deploymentClassLoader; + } + + /** + * Add a {@link ServiceDescriptor}. + * @param serviceDescriptor The descriptor instance. + */ + public void addServiceDescriptor(ServiceDescriptor serviceDescriptor) { + _serviceDescriptors.add(serviceDescriptor); + } + + /** + * Add a {@link ClientProxyBean}. + * @param proxy The proxy instance. + */ + public void addClientProxy(ClientProxyBean proxy) { + _clientProxies.add(proxy); + } + + /** + * Add a ReferenceInvokerBean. + * @param invoker The invoker bean. + */ + public void addReferenceInvoker(ReferenceInvokerBean invoker) { + _referenceInvokers.add(invoker); + } + + /** + * Add a deployment CDI bean. + * @param bean The CDI bean instance. + */ + public void addDeploymentBean(CDIBean bean) { + _deploymentBeans.add(bean); + } + + /** + * Add a list of all the {@link ServiceDescriptor ServiceDescriptors}. + * @return The list of all the {@link ServiceDescriptor ServiceDescriptors}. + */ + public List getServiceDescriptors() { + return Collections.unmodifiableList(_serviceDescriptors); + } + + /** + * Get a list of all the {@link ClientProxyBean ClientProxyBeans}. + * @return The list of all the {@link ClientProxyBean ClientProxyBeans}. + */ + public List getClientProxies() { + return Collections.unmodifiableList(_clientProxies); + } + + /** + * Get a list of all the ReferenceInvokerBeans. + * @return The list of all the ReferenceInvokerBeans. + */ + public List getReferenceInvokers() { + return Collections.unmodifiableList(_referenceInvokers); + } + + /** + * Get a list of all beans in the deployment. + * @return The list of all beans in the deployment. + */ + public List getDeploymentBeans() { + return Collections.unmodifiableList(_deploymentBeans); + } + + /** + * Lookup the BeanDeploymentMetaData for the current deployment. + * @return The BeanDeploymentMetaData. + */ + public static BeanDeploymentMetaData lookupBeanDeploymentMetaData() { + BeanManager beanManager = CDIUtil.lookupBeanManager(); + if (beanManager == null) { + throw BeanMessages.MESSAGES.failedToLookupBeanManagerMustBeBoundIntoJavaCompAsPerCDISpecification(); + } + + Set> beans = beanManager.getBeans(BeanDeploymentMetaData.class); + if (beans.isEmpty()) { + throw BeanMessages.MESSAGES.failedToLookupBeanDeploymentMetaDataFromBeanManagerMustBeBoundIntoBeanManagerPerhapsSwitchYardCDIExtensionsNotProperlyInstalledInContainer(); + } + if (beans.size() > 1) { + throw BeanMessages.MESSAGES.failedToLookupBeanDeploymentMetaDataFromBeanManagerMultipleBeansResolvedForType(BeanDeploymentMetaData.class.getName()); + } + + BeanDeploymentMetaDataCDIBean bean = (BeanDeploymentMetaDataCDIBean) beans.iterator().next(); + return bean.getBeanMetaData(); + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanDeploymentMetaDataCDIBean.java b/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanDeploymentMetaDataCDIBean.java new file mode 100644 index 000000000..3ac855c6a --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/deploy/BeanDeploymentMetaDataCDIBean.java @@ -0,0 +1,187 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.deploy; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.Any; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.enterprise.util.AnnotationLiteral; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +/** + * BeanDeploymentMetaData CDI Bean. + * + * @author tom.fennelly@gmail.com + */ +public class BeanDeploymentMetaDataCDIBean implements Bean { + + /** + * Bean deployment metadata. + */ + private BeanDeploymentMetaData _beanMetaData; + /** + * CDI bean qualifiers. See CDI Specification. + */ + private Set _qualifiers; + + /** + * Public constructor. + * @param beanDeploymentMetaData Bean metadata. + */ + public BeanDeploymentMetaDataCDIBean(BeanDeploymentMetaData beanDeploymentMetaData) { + _beanMetaData = beanDeploymentMetaData; + this._qualifiers = new HashSet(); + this._qualifiers.add(new AnnotationLiteral() {}); + this._qualifiers.add(new AnnotationLiteral() {}); + } + + /** + * Get the BeanDeploymentMetaData. + * @return The BeanDeploymentMetaData. + */ + public BeanDeploymentMetaData getBeanMetaData() { + return _beanMetaData; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject bean types} of the bean. + * + * @return the {@linkplain javax.enterprise.inject bean types} + */ + public Set getTypes() { + Set types = new HashSet(); + types.add(BeanDeploymentMetaData.class); + types.add(Object.class); + return types; + } + + /** + * Obtains the {@linkplain javax.inject.Qualifier qualifiers} of the bean. + * + * @return the {@linkplain javax.inject.Qualifier qualifiers} + */ + public Set getQualifiers() { + return _qualifiers; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject EL name} of a bean, if it has one. + * + * @return the {@linkplain javax.enterprise.inject EL name} + */ + public String getName() { + return null; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject.Stereotype stereotypes} + * of the bean. + * + * @return the set of {@linkplain javax.enterprise.inject.Stereotype stereotypes} + */ + public Set> getStereotypes() { + return Collections.emptySet(); + } + + /** + * The bean {@linkplain Class class} of the managed bean or session bean or + * of the bean that declares the producer method or field. + * + * @return the bean {@linkplain Class class} + */ + public Class getBeanClass() { + return BeanDeploymentMetaData.class; + } + + /** + * Determines if the bean is an + * {@linkplain javax.enterprise.inject.Alternative alternative}. + * + * @return true if the bean is an + * {@linkplain javax.enterprise.inject.Alternative alternative}, + * and false otherwise. + */ + public boolean isAlternative() { + return false; + } + + /** + * Determines if + * {@link javax.enterprise.context.spi.Contextual#create(javax.enterprise.context.spi.CreationalContext)} + * sometimes return a null value. + * + * @return true if the {@code create()} method may return a null + * value, and false otherwise + */ + public boolean isNullable() { + return false; + } + + /** + * Obtains the {@link javax.enterprise.inject.spi.InjectionPoint} objects + * representing injection points of the bean, that will be validated by the + * container at initialization time. + * + * @return the set of {@linkplain javax.enterprise.inject.spi.InjectionPoint injection points} of the bean + */ + public Set getInjectionPoints() { + return Collections.emptySet(); + } + + /** + * Obtains the {@linkplain javax.enterprise.context scope} of the bean. + * + * @return the {@linkplain javax.enterprise.context scope} + */ + public Class getScope() { + return ApplicationScoped.class; + } + + /** + * Create a new instance of the contextual type. Instances should + * use the given {@link javax.enterprise.context.spi.CreationalContext} + * when obtaining contextual references to inject, in order to ensure + * that any dependent objects are associated with the contextual instance + * that is being created. An implementation may call + * {@link javax.enterprise.context.spi.CreationalContext#push(Object)} + * between instantiation and injection to help the container minimize the + * use of client proxy objects. + * + * @param creationalContext the context in which this instance is being created + * @return the contextual instance + */ + public Object create(CreationalContext creationalContext) { + return _beanMetaData; + } + + /** + * Destroy an instance of the contextual type. Implementations should + * call {@link javax.enterprise.context.spi.CreationalContext#release()} + * to allow the container to destroy dependent objects of the contextual + * instance. + * + * @param instance the contextual instance to destroy + * @param creationalContext the context in which this instance was created + */ + public void destroy(Object instance, CreationalContext creationalContext) { + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/deploy/CDIBean.java b/components/bean/src/main/java/org/switchyard/component/bean/deploy/CDIBean.java new file mode 100644 index 000000000..35c02d50d --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/deploy/CDIBean.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.deploy; + +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.BeanManager; + +/** + * CDI Bean instance. + * + * @author tom.fennelly@gmail.com + */ +public class CDIBean { + + private Bean _bean; + private BeanManager _beanManager; + + /** + * Public constructor. + * @param bean The bean isntance. + * @param beanManager The bean manager. + */ + public CDIBean(Bean bean, BeanManager beanManager) { + this._bean = bean; + this._beanManager = beanManager; + } + + /** + * Get the CDI Bean instance. + * @return The CDI bean instance. + */ + public Bean getBean() { + return _bean; + } + + /** + * Get the CDI BeanManager instance. + * @return The CDI BeanManager instance. + */ + public BeanManager getBeanManager() { + return _beanManager; + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/deploy/CDIBeanServiceDescriptor.java b/components/bean/src/main/java/org/switchyard/component/bean/deploy/CDIBeanServiceDescriptor.java new file mode 100644 index 000000000..8aef040e1 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/deploy/CDIBeanServiceDescriptor.java @@ -0,0 +1,125 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.deploy; + +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.BeanManager; + +import org.switchyard.common.lang.Strings; +import org.switchyard.component.bean.BeanServiceMetadata; +import org.switchyard.component.bean.BeanMessages; +import org.switchyard.component.bean.Service; +import org.switchyard.component.bean.ServiceProxyHandler; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.metadata.ServiceInterface; + +/** + * SwitchYard CDI bean Service Descriptor. + * + * @author tom.fennelly@gmail.com + */ +public class CDIBeanServiceDescriptor implements ServiceDescriptor { + + private final CDIBean _cdiBean; + private final BeanDeploymentMetaData _beanDeploymentMetaData; + private final String _serviceName; + private final BeanServiceMetadata _serviceMetadata; + + /** + * Public constructor. + * @param cdiBean The CDI bean instance. + * @param beanDeploymentMetaData bean deployment info + */ + public CDIBeanServiceDescriptor(CDIBean cdiBean, BeanDeploymentMetaData beanDeploymentMetaData) { + this._cdiBean = cdiBean; + this._beanDeploymentMetaData = beanDeploymentMetaData; + final Class beanClass = cdiBean.getBean().getBeanClass(); + this._serviceName = getServiceName(beanClass); + this._serviceMetadata = new BeanServiceMetadata(getServiceInterface(beanClass)); + } + + /** + * Get the CDI bean. + * @return The CDI bean. + */ + public CDIBean getCDIBean() { + return _cdiBean; + } + + @Override + public String getServiceName() { + return _serviceName; + } + + /** + * Get the service metadata. + * @return The service metadata. + */ + public BeanServiceMetadata getServiceMetadata() { + return _serviceMetadata; + } + + @Override + public ServiceProxyHandler getHandler() { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(_beanDeploymentMetaData.getDeploymentClassLoader()); + + BeanManager beanManager = _cdiBean.getBeanManager(); + CreationalContext creationalContext = beanManager.createCreationalContext(_cdiBean.getBean()); + Object beanRef = beanManager.getReference(_cdiBean.getBean(), Object.class, creationalContext); + + return new ServiceProxyHandler(beanRef, _serviceMetadata, _beanDeploymentMetaData); + } finally { + Thread.currentThread().setContextClassLoader(tccl); + } + } + + @Override + public ServiceInterface getInterface() { + return JavaService.fromClass(_serviceMetadata.getServiceClass()); + } + + private String getServiceName(Class beanClass) { + Service service = beanClass.getAnnotation(Service.class); + String name = Strings.trimToNull(service.name()); + if (name == null) { + name = getServiceInterface(beanClass).getSimpleName(); + } + return name; + } + + /** + * Get the service interface defined by a service bean class. + * @param beanClass The bean class. + * @return The Service Interface type. + */ + protected static Class getServiceInterface(Class beanClass) { + Service serviceAnnotation = beanClass.getAnnotation(Service.class); + Class serviceInterface = serviceAnnotation.value(); + + if (serviceInterface == Service.class) { + Class[] interfaces = beanClass.getInterfaces(); + if (interfaces.length == 1) { + serviceInterface = interfaces[0]; + } else { + throw BeanMessages.MESSAGES.unexpectedExceptionTheServiceAnnotationHasNoValueItCannotBeOmmittedUnlessTheBeanImplementsExactlyOneInterface(); + } + } else if (!serviceInterface.isInterface()) { + throw BeanMessages.MESSAGES.invalidServiceSpecificationService(serviceInterface.getName()); + } + + return serviceInterface; + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/deploy/ServiceDescriptor.java b/components/bean/src/main/java/org/switchyard/component/bean/deploy/ServiceDescriptor.java new file mode 100644 index 000000000..fc9895972 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/deploy/ServiceDescriptor.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.deploy; + +import java.io.Serializable; + +import org.switchyard.component.bean.ServiceProxyHandler; +import org.switchyard.metadata.ServiceInterface; + +/** + * Service Descriptor. + * + * @author tom.fennelly@gmail.com + */ +public interface ServiceDescriptor extends Serializable { + + /** + * Get the Service name. + * @return The Service Name. + */ + String getServiceName(); + + /** + * Get the ServiceHandler. + * @return The ServiceHandler. + */ + ServiceProxyHandler getHandler(); + + /** + * Get the ServiceInterface. + * @return The ServiceInterface. + */ + ServiceInterface getInterface(); +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/ExchangeInvocation.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/ExchangeInvocation.java new file mode 100644 index 000000000..d79d9745f --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/ExchangeInvocation.java @@ -0,0 +1,109 @@ +package org.switchyard.component.bean.internal; + +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.component.bean.ReferenceInvocation; + +/** + * Implements ReferenceInvocation backed by an exchange. + */ +public class ExchangeInvocation implements ReferenceInvocation { + + private Exchange _exchange; + private Message _inMessage; + private InvocationResponseHandler _replyHandler; + + /** + * Create a new instance of ExchangeInvocation. + * @param exchange exchange to be used for the invocation + * @param replyHandler takes care of replies/faults for the exchange + */ + public ExchangeInvocation(Exchange exchange, InvocationResponseHandler replyHandler) { + _exchange = exchange; + _inMessage = _exchange.createMessage(); + _replyHandler = replyHandler; + } + + @Override + public Context getContext() { + return _exchange.getContext(); + } + + @Override + public Message getMessage() { + return isNew() ? _inMessage : _exchange.getMessage(); + } + + @Override + public ReferenceInvocation invoke() throws Exception { + if (!isNew()) { + throw new IllegalStateException( + "Repeated calls to invoke() on ExchangeInvocation are not permitted"); + } + _exchange.send(_inMessage); + if (_replyHandler.isFault()) { + Object error = _replyHandler.getExchange().getMessage().getContent(); + + // Handling case where fault content is not an exception + if (!Throwable.class.isAssignableFrom(error.getClass())) { + throw createException(_replyHandler.getExchange()); + } + + // Unwrap HandlerException instances if appropriate + if (error instanceof HandlerException) { + HandlerException haEx = (HandlerException)error; + error = haEx.isWrapper() ? haEx.getCause() : haEx; + } + + // Time to throw up! + if (error instanceof Exception) { + throw (Exception)error; + } else { + throw new Exception((Throwable)error); + } + } + return this; + } + + @Override + public ReferenceInvocation invoke(Object content) throws Exception { + _inMessage.setContent(content); + return invoke(); + } + + @Override + public ReferenceInvocation setProperty(String name, String value) { + _exchange.getContext(_inMessage).setProperty(name, value); + return this; + } + + @Override + public Object getProperty(String name) { + return _exchange.getContext().getPropertyValue(name); + } + + boolean isNew() { + return _exchange.getPhase() == null; + } + + /** + * Utility method to create consistent exceptions for invocations. + */ + Exception createException(Exchange exchange) { + String exMsg = null; + try { + // Attempt to convert to String + exMsg = exchange.getMessage().getContent(String.class); + } catch (Exception ex) { + // No luck converting, go with toString + Object content = exchange.getMessage().getContent(); + if (content != null) { + exMsg = content.toString(); + } + } + return new Exception(exMsg); + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/InternalBean.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/InternalBean.java new file mode 100644 index 000000000..0642e4062 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/InternalBean.java @@ -0,0 +1,201 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.internal; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.Any; +import javax.enterprise.inject.Default; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.enterprise.util.AnnotationLiteral; + +/** + * Internal Bean. + *

+ * CDI bean for injecting a SwitchYard Object into consumer beans. + * + * @author tom.fennelly@gmail.com + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public abstract class InternalBean implements Bean { + + /** + * CDI bean qualifiers. See CDI Specification. + */ + private Set _qualifiers; + + /** + * Proxy object. + */ + private Object _proxyObject; + + /** + * Bean class. + */ + private final Class _beanClass; + + /** + * Used when the proxy object is created/managed by extensions of this class. + */ + protected InternalBean(Class beanClass, Set qualifiers) { + _qualifiers = qualifiers; + _beanClass = beanClass; + } + + /** + * Protected constructor. + */ + protected InternalBean(Object proxyObject, Class beanClass) { + _qualifiers = new HashSet(); + _qualifiers.add(new AnnotationLiteral() {}); + _qualifiers.add(new AnnotationLiteral() {}); + _proxyObject = proxyObject; + _beanClass = beanClass; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject bean types} of the bean. + * + * @return the {@linkplain javax.enterprise.inject bean types} + */ + public Set getTypes() { + Set types = new HashSet(); + types.add(_beanClass); + types.add(Object.class); + return types; + } + + /** + * Obtains the {@linkplain javax.inject.Qualifier qualifiers} of the bean. + * + * @return the {@linkplain javax.inject.Qualifier qualifiers} + */ + public Set getQualifiers() { + return _qualifiers; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject EL name} of a bean, if it has one. + * + * @return the {@linkplain javax.enterprise.inject EL name} + */ + public String getName() { + return null; + } + + protected void setProxyObject(Object proxyObject) { + _proxyObject = proxyObject; + } + + /** + * Obtains the {@linkplain javax.enterprise.inject.Stereotype stereotypes} + * of the bean. + * + * @return the set of {@linkplain javax.enterprise.inject.Stereotype stereotypes} + */ + public Set> getStereotypes() { + return Collections.emptySet(); + } + + /** + * The bean {@linkplain Class class} of the managed bean or session bean or + * of the bean that declares the producer method or field. + * + * @return the bean {@linkplain Class class} + */ + public Class getBeanClass() { + return _beanClass; + } + + /** + * Determines if the bean is an + * {@linkplain javax.enterprise.inject.Alternative alternative}. + * + * @return true if the bean is an + * {@linkplain javax.enterprise.inject.Alternative alternative}, + * and false otherwise. + */ + public boolean isAlternative() { + return false; + } + + /** + * Determines if + * {@link javax.enterprise.context.spi.Contextual#create(javax.enterprise.context.spi.CreationalContext)} + * sometimes return a null value. + * + * @return true if the {@code create()} method may return a null + * value, and false otherwise + */ + public boolean isNullable() { + return false; + } + + /** + * Obtains the {@link javax.enterprise.inject.spi.InjectionPoint} objects + * representing injection points of the bean, that will be validated by the + * container at initialization time. + * + * @return the set of {@linkplain javax.enterprise.inject.spi.InjectionPoint injection points} of the bean + */ + public Set getInjectionPoints() { + return Collections.emptySet(); + } + + /** + * Obtains the {@linkplain javax.enterprise.context scope} of the bean. + * + * @return the {@linkplain javax.enterprise.context scope} + */ + public Class getScope() { + return ApplicationScoped.class; + } + + /** + * Create a new instance of the contextual type. Instances should + * use the given {@link javax.enterprise.context.spi.CreationalContext} + * when obtaining contextual references to inject, in order to ensure + * that any dependent objects are associated with the contextual instance + * that is being created. An implementation may call + * {@link javax.enterprise.context.spi.CreationalContext#push(Object)} + * between instantiation and injection to help the container minimize the + * use of client proxy objects. + * + * @param creationalContext the context in which this instance is being created + * @return the contextual instance + */ + public Object create(CreationalContext creationalContext) { + return _proxyObject; + } + + /** + * Destroy an instance of the contextual type. Implementations should + * call {@link javax.enterprise.context.spi.CreationalContext#release()} + * to allow the container to destroy dependent objects of the contextual + * instance. + * + * @param instance the contextual instance to destroy + * @param creationalContext the context in which this instance was created + */ + public void destroy(Object instance, CreationalContext creationalContext) { + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/InvocationResponseHandler.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/InvocationResponseHandler.java new file mode 100644 index 000000000..12343259f --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/InvocationResponseHandler.java @@ -0,0 +1,43 @@ +package org.switchyard.component.bean.internal; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.HandlerException; + +/** + * Used to handle responses and faults for exchanges used by an + * ExchangeInvoker. + */ +public class InvocationResponseHandler implements ExchangeHandler { + + private Exchange _exchange; + private boolean _isFault; + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + _exchange = exchange; + } + + @Override + public void handleFault(Exchange exchange) { + _isFault = true; + _exchange = exchange; + } + + /** + * Reports whether the exchange is in fault state. + * @return true if the exchange resulted in a fault, false otherwise + */ + public boolean isFault() { + return _isFault; + } + + /** + * Gets the Exchange object received with a fault/reply message. + * @return exchange + */ + public Exchange getExchange() { + return _exchange; + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/ReferenceInvokerBean.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/ReferenceInvokerBean.java new file mode 100644 index 000000000..629ac1f25 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/ReferenceInvokerBean.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.internal; + +import java.lang.annotation.Annotation; +import java.util.Set; + +import org.switchyard.Exchange; +import org.switchyard.ServiceReference; +import org.switchyard.component.bean.ReferenceInvocation; +import org.switchyard.component.bean.ReferenceInvoker; +import org.switchyard.metadata.ServiceInterface; + +/** + * Bean class used to inject a ReferenceInvoker for an @Reference in a bean class. + */ +public class ReferenceInvokerBean extends InternalBean implements ReferenceInvoker { + + private final String _serviceName; + private ServiceReference _reference; + + /** + * Creates a new ReferenceInvokerBean. + * @param serviceName name of the service reference + * @param qualifiers any qualifiers associated with the injection point + */ + public ReferenceInvokerBean(String serviceName, Set qualifiers) { + super(ReferenceInvoker.class, qualifiers); + setProxyObject(this); + _serviceName = serviceName; + } + + /** + * Get the name of the service used by the invoker. + * @return service name + */ + public String getServiceName() { + return _serviceName; + } + + /** + * Set the service reference for the target service. + * @param reference The target service. + */ + public void setReference(ServiceReference reference) { + _reference = reference; + } + + /** + * Returns the service reference used by this invoker. + * @return target reference + */ + public ServiceReference getReference() { + return _reference; + } + + @Override + public ReferenceInvocation newInvocation() { + assertReference(); + ServiceInterface intf = _reference.getInterface(); + if (intf.getOperations().size() != 1) { + throw new IllegalStateException("Operation name is required to create ReferenceInvocation for " + _serviceName); + } + + return newInvocation(intf.getOperations().iterator().next().getName()); + } + + @Override + public ReferenceInvocation newInvocation(String operation) { + assertReference(); + InvocationResponseHandler handler = new InvocationResponseHandler(); + Exchange exchange = _reference.createExchange(operation, handler); + return new ExchangeInvocation(exchange, handler); + } + + @Override + public ServiceInterface getContract() { + return _reference.getInterface(); + } + + private void assertReference() throws IllegalStateException { + if (_reference == null) { + throw new IllegalStateException("Reference does not exist for service: " + _serviceName); + } + } + +} + diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/SimpleCDIDeployment.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/SimpleCDIDeployment.java new file mode 100644 index 000000000..a550bc280 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/SimpleCDIDeployment.java @@ -0,0 +1,129 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.internal; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.bean.BeanMessages; +import org.switchyard.component.bean.ServiceProxyHandler; +import org.switchyard.component.bean.deploy.BeanComponentActivator; +import org.switchyard.component.bean.deploy.BeanDeploymentMetaData; +import org.switchyard.component.bean.deploy.CDIBean; +import org.switchyard.component.bean.deploy.ServiceDescriptor; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.Lifecycle; +import org.switchyard.deploy.internal.AbstractDeployment; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.transform.internal.TransformerTypes; +import org.switchyard.transform.internal.TransformerUtil; + +/** + * Simple CDI deployment. + *

+ * For internal use only with tests etc. Does not initialize/deploy the CDI container. + * + * @author tom.fennelly@gmail.com + */ +public class SimpleCDIDeployment extends AbstractDeployment { + + private boolean _activateBeans = false; + + /** + * Creates a new CDI deployment with no configuration. + */ + public SimpleCDIDeployment() { + super(null); + } + + @Override + protected void doInit(List activators) { + for (Activator activator : activators) { + if (activator.getActivationTypes().contains(BeanComponentActivator.BEAN_TYPE)) { + _activateBeans = true; + return; + } + } + } + + @Override + public void start() { + BeanDeploymentMetaData beanDeploymentMetaData = BeanDeploymentMetaData.lookupBeanDeploymentMetaData(); + deployTransformers(beanDeploymentMetaData, getDomain()); + deployServicesAndProxies(beanDeploymentMetaData, getDomain()); + } + + @Override + public void stop() { + } + + @Override + public void destroy() { + } + + private void deployTransformers(BeanDeploymentMetaData beanDeploymentMetaData, ServiceDomain domain) { + TransformerRegistry transformerRegistry = domain.getTransformerRegistry(); + + for (CDIBean deploymentBean : beanDeploymentMetaData.getDeploymentBeans()) { + Class beanClass = deploymentBean.getBean().getBeanClass(); + + if (TransformerUtil.isTransformer(beanClass)) { + List transformers = TransformerUtil.listTransformations(beanClass); + for (TransformerTypes transformer : transformers) { + transformerRegistry.addTransformer(TransformerUtil.newTransformer(beanClass, + transformer.getFrom(), transformer.getTo())); + } + } + } + } + + private void deployServicesAndProxies(BeanDeploymentMetaData beanDeploymentMetaData, ServiceDomain domain) { + if (!_activateBeans) { + return; + } + + if (beanDeploymentMetaData == null) { + throw BeanMessages.MESSAGES.failedToLookupBeanDeploymentMetaDataFromNamingContext(); + } + + BeanComponentActivator activator = new BeanComponentActivator(); + + for (ServiceDescriptor serviceDescriptor : beanDeploymentMetaData.getServiceDescriptors()) { + String serviceName = serviceDescriptor.getServiceName(); + ServiceProxyHandler handler = serviceDescriptor.getHandler(); + ServiceInterface serviceInterface; + ServiceReference service; + + activator.lookupBeanMetaData(); + serviceInterface = activator.buildServiceInterface(serviceName); + QName serviceQName = XMLHelper.createQName(domain.getName().getNamespaceURI(), serviceName); + domain.registerService(serviceQName, serviceInterface, handler); + service = domain.registerServiceReference(serviceQName, serviceInterface); + handler.addReference(service); + handler.start(); + + } + } + + @Override + public Lifecycle getGatwayLifecycle(QName serviceName, String bindingName) { + return null; + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/context/ContextBean.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/context/ContextBean.java new file mode 100644 index 000000000..767693b05 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/context/ContextBean.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.internal.context; + +import org.switchyard.Context; +import org.switchyard.component.bean.internal.InternalBean; + +/** + * Context Bean. + *

+ * CDI bean for injecting the SwitchYard Context into consumer beans. + * + * @author tom.fennelly@gmail.com + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class ContextBean extends InternalBean { + + /** + * Public constructor. + */ + public ContextBean() { + super(new ContextProxy(), Context.class); + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/context/ContextProxy.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/context/ContextProxy.java new file mode 100644 index 000000000..86f56429f --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/context/ContextProxy.java @@ -0,0 +1,176 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.internal.context; + +import java.util.Set; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Alternative; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.component.bean.BeanMessages; + +/** + * SwitchYard Context proxy. + *

+ * Injection is managed through ContextBean. + * + * @author tom.fennelly@gmail.com + */ +@ApplicationScoped +@Alternative +public class ContextProxy implements Context { + + private static final ThreadLocal CONTEXT = new ThreadLocal(); + + /** + * {@inheritDoc} + */ + @Override + public Property getProperty(String name) { + return getContext().getProperty(name); + } + + /** + * {@inheritDoc} + */ + @Override + public Property getProperty(String name, Scope scope) { + return getContext().getProperty(name, scope); + } + + /** + * {@inheritDoc} + */ + @Override + public T getPropertyValue(String name) { + return getContext().getPropertyValue(name); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getProperties() { + return getContext().getProperties(); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getProperties(Scope scope) { + return getContext().getProperties(scope); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperty(Property property) { + getContext().removeProperty(property); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperties() { + getContext().removeProperties(); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperties(Scope scope) { + getContext().removeProperties(scope); + } + + /** + * {@inheritDoc} + */ + @Override + public Property setProperty(String name, Object val) { + return getContext().setProperty(name, val); + } + + /** + * {@inheritDoc} + */ + @Override + public Property setProperty(String name, Object val, Scope scope) { + return getContext().setProperty(name, val, scope); + } + + /** + * {@inheritDoc} + */ + @Override + public Context setProperties(Set properties) { + return getContext().setProperties(properties); + } + + /** + * {@inheritDoc} + */ + @Override + public void mergeInto(Context context) { + getContext().mergeInto(context); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getProperties(String label) { + return getContext().getProperties(label); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperties(String label) { + getContext().removeProperties(label); + } + + /** + * Gets the {@link Context} for the current thread. + * @return the context + */ + private static Context getContext() { + Context context = CONTEXT.get(); + if (context == null) { + throw BeanMessages.MESSAGES.illegalCallToGetTheSwitchYardContextMustBeCalledWithinTheExecutionOfAnExchangeHandlerChain(); + } + return context; + } + + /** + * Sets the {@link Context} for the current thread. + * @param context the context + */ + public static void setContext(Context context) { + if (context != null) { + CONTEXT.set(context); + } else { + CONTEXT.remove(); + } + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/exchange/ExchangeBean.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/exchange/ExchangeBean.java new file mode 100644 index 000000000..979a76ad2 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/exchange/ExchangeBean.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.internal.exchange; + +import org.switchyard.Exchange; +import org.switchyard.component.bean.internal.InternalBean; + +/** + * Exchange Bean. + *

+ * CDI bean for injecting the SwitchYard Exchange into service beans. + */ +public class ExchangeBean extends InternalBean { + + /** + * Public constructor. + */ + public ExchangeBean() { + super(new ExchangeProxy(), Exchange.class); + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/exchange/ExchangeProxy.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/exchange/ExchangeProxy.java new file mode 100644 index 000000000..e53fecaae --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/exchange/ExchangeProxy.java @@ -0,0 +1,149 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.internal.exchange; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Alternative; + +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangePhase; +import org.switchyard.ExchangeSecurity; +import org.switchyard.ExchangeState; +import org.switchyard.Message; +import org.switchyard.Service; +import org.switchyard.ServiceReference; +import org.switchyard.component.bean.BeanMessages; +import org.switchyard.metadata.ExchangeContract; +import org.switchyard.metadata.ServiceOperation; + +/** + * SwitchYard Exchange proxy. + *

+ * Injection is managed through ExchangeBean + */ +@ApplicationScoped +@Alternative +public class ExchangeProxy implements Exchange { + + private static final ThreadLocal EXCHANGE = new ThreadLocal(); + + /** + * Gets the {@link Exchange} for the current thread. + * @return the message + */ + private static Exchange getExchange() { + Exchange exchange = EXCHANGE.get(); + if (exchange == null) { + throw BeanMessages.MESSAGES.illegalExchangeAccessOutsideHandlerChain(); + } + return exchange; + } + + /** + * Sets the {@link Exchange} for the current thread. + * @param exchange the exchange + */ + public static void setExchange(Exchange exchange) { + if (exchange != null) { + EXCHANGE.set(exchange); + } else { + EXCHANGE.remove(); + } + } + + @Override + public Context getContext() { + return getExchange().getContext(); + } + + @Override + public Context getContext(Message message) { + return getExchange().getContext(message); + } + + @Override + public ServiceReference getConsumer() { + return getExchange().getConsumer(); + } + + @Override + public Service getProvider() { + return getExchange().getProvider(); + } + + @Override + public ExchangeContract getContract() { + return getExchange().getContract(); + } + + @Override + public Exchange consumer(ServiceReference consumer, ServiceOperation operation) { + // ignore calls to consumer() as this is not supported after an exchange has been sent + return this; + } + + @Override + public Exchange provider(Service provider, ServiceOperation operation) { + // ignore calls to provider() as this is not supported after an exchange has been sent + return this; + } + + @Override + public Message getMessage() { + return getExchange().getMessage(); + } + + @Override + public Message createMessage() { + return getExchange().createMessage(); + } + + @Override + public void send(Message message) { + getExchange().send(message); + } + + @Override + public void sendFault(Message message) { + getExchange().sendFault(message); + } + + @Override + public ExchangeState getState() { + return getExchange().getState(); + } + + @Override + public ExchangePhase getPhase() { + return getExchange().getPhase(); + } + + @Override + public ExchangeHandler getReplyHandler() { + return null; + } + + @Override + public ExchangePattern getPattern() { + return getExchange().getPattern(); + } + + @Override + public ExchangeSecurity getSecurity() { + return getExchange().getSecurity(); + } +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/message/MessageBean.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/message/MessageBean.java new file mode 100644 index 000000000..6f8c2d400 --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/message/MessageBean.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.internal.message; + +import org.switchyard.Message; +import org.switchyard.component.bean.internal.InternalBean; + +/** + * Message Bean. + *

+ * CDI bean for injecting the SwitchYard Message into consumer beans. + * + * @author tom.fennelly@gmail.com + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class MessageBean extends InternalBean { + + /** + * Public constructor. + */ + public MessageBean() { + super(new MessageProxy(), Message.class); + } + +} diff --git a/components/bean/src/main/java/org/switchyard/component/bean/internal/message/MessageProxy.java b/components/bean/src/main/java/org/switchyard/component/bean/internal/message/MessageProxy.java new file mode 100644 index 000000000..9b9de06ad --- /dev/null +++ b/components/bean/src/main/java/org/switchyard/component/bean/internal/message/MessageProxy.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.internal.message; + +import java.util.Map; + +import javax.activation.DataSource; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Alternative; + +import org.switchyard.Context; +import org.switchyard.Message; +import org.switchyard.component.bean.BeanMessages; + +/** + * SwitchYard Message proxy. + *

+ * Injection is managed through MessageBean. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@ApplicationScoped +@Alternative +public class MessageProxy implements Message { + + private static final ThreadLocal MESSAGE = new ThreadLocal(); + + /** + * {@inheritDoc} + */ + @Override + public Context getContext() { + return getMessage().getContext(); + } + + /** + * {@inheritDoc} + */ + @Override + public Message setContent(Object content) { + return getMessage().setContent(content); + } + + /** + * {@inheritDoc} + */ + @Override + public Object getContent() { + return getMessage().getContent(); + } + + /** + * {@inheritDoc} + */ + @Override + public T getContent(Class type) { + return getMessage().getContent(type); + } + + /** + * {@inheritDoc} + */ + @Override + public Message addAttachment(String name, DataSource attachment) { + return getMessage().addAttachment(name, attachment); + } + + /** + * {@inheritDoc} + */ + @Override + public DataSource getAttachment(String name) { + return getMessage().getAttachment(name); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeAttachment(String name) { + getMessage().removeAttachment(name); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getAttachmentMap() { + return getMessage().getAttachmentMap(); + } + + /** + * {@inheritDoc} + */ + @Override + public Message copy() { + return getMessage().copy(); + } + + /** + * Gets the {@link Message} for the current thread. + * @return the message + */ + private static Message getMessage() { + Message message = MESSAGE.get(); + if (message == null) { + throw BeanMessages.MESSAGES.illegalCallToGetTheSwitchYardContextMustBeCalledWithinTheExecutionOfAnExchangeHandlerChain(); + } + return message; + } + + /** + * Sets the {@link Message} for the current thread. + * @param message the message + */ + public static void setMessage(Message message) { + if (message != null) { + MESSAGE.set(message); + } else { + MESSAGE.remove(); + } + } + +} diff --git a/components/bean/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/components/bean/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 000000000..5362de103 --- /dev/null +++ b/components/bean/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1 @@ +org.switchyard.component.bean.SwitchYardCDIServiceDiscovery \ No newline at end of file diff --git a/components/bean/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/bean/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..35b2296c9 --- /dev/null +++ b/components/bean/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.bean.deploy.BeanComponent diff --git a/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v1/bean_1_0.xsd b/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v1/bean_1_0.xsd new file mode 100644 index 000000000..5cf09cc7d --- /dev/null +++ b/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v1/bean_1_0.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v1/bean_1_1.xsd b/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v1/bean_1_1.xsd new file mode 100644 index 000000000..b2f0fda53 --- /dev/null +++ b/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v1/bean_1_1.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v2/bean_2_0.xsd b/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v2/bean_2_0.xsd new file mode 100644 index 000000000..b7e282a13 --- /dev/null +++ b/components/bean/src/main/resources/org/switchyard/component/bean/config/model/v2/bean_2_0.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/components/bean/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/bean/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..4c3f36111 --- /dev/null +++ b/components/bean/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +bean_1_0.section=urn:switchyard-component-bean:config +bean_1_0.version=1.0 +bean_1_0.namespace=urn:switchyard-component-bean:config:1.0 +bean_1_0.schema=bean_1_0.xsd +bean_1_0.location=/org/switchyard/component/bean/config/model/v1/ +bean_1_0.marshaller=org.switchyard.component.bean.config.model.v1.V1BeanMarshaller + +bean_1_1.section=urn:switchyard-component-bean:config +bean_1_1.version=1.1 +bean_1_1.namespace=urn:switchyard-component-bean:config:1.1 +bean_1_1.schema=bean_1_1.xsd +bean_1_1.location=/org/switchyard/component/bean/config/model/v1/ +bean_1_1.marshaller=org.switchyard.component.bean.config.model.v1.V1BeanMarshaller + +bean_2_0.section=urn:switchyard-component-bean:config +bean_2_0.version=2.0 +bean_2_0.namespace=urn:switchyard-component-bean:config:2.0 +bean_2_0.schema=bean_2_0.xsd +bean_2_0.location=/org/switchyard/component/bean/config/model/v2/ +bean_2_0.marshaller=org.switchyard.component.bean.config.model.v1.V1BeanMarshaller diff --git a/components/bean/src/test/java/org/switchyard/component/bean/config/model/BeanModelTests.java b/components/bean/src/test/java/org/switchyard/component/bean/config/model/BeanModelTests.java new file mode 100644 index 000000000..1a96ae9f9 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/config/model/BeanModelTests.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.config.model; + +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * BeanModelTests. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class BeanModelTests { + + private static final String COMPLETE_XML = "/org/switchyard/component/bean/config/model/BeanModelTests-Complete.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void testReadComplete() throws Exception { + SwitchYardModel switchyard = _puller.pull(COMPLETE_XML, getClass()); + CompositeModel composite = switchyard.getComposite(); + ComponentModel component = composite.getComponents().get(0); + ComponentImplementationModel implementation = component.getImplementation(); + Assert.assertTrue(implementation instanceof BeanComponentImplementationModel); + BeanComponentImplementationModel bci = (BeanComponentImplementationModel)implementation; + Assert.assertEquals("bean", bci.getType()); + Assert.assertEquals("org.switchyard.example.m1app.SimpleBean", bci.getClazz()); + Configuration config = bci.getModelConfiguration(); + Assert.assertEquals("implementation.bean", config.getName()); + QName qname = config.getQName(); + Assert.assertEquals("urn:switchyard-component-bean:config:1.0", qname.getNamespaceURI()); + Assert.assertEquals("implementation.bean", qname.getLocalPart()); + } + + @Test + public void testWriteComplete() throws Exception { + String old_xml = new StringPuller().pull(COMPLETE_XML, getClass()); + SwitchYardModel switchyard = _puller.pull(new StringReader(old_xml)); + String new_xml = switchyard.toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testValidation() throws Exception { + SwitchYardModel switchyard = _puller.pull(COMPLETE_XML, getClass()); + switchyard.assertModelValid(); + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/config/model/BeanSwitchYardScannerTest.java b/components/bean/src/test/java/org/switchyard/component/bean/config/model/BeanSwitchYardScannerTest.java new file mode 100644 index 000000000..5f04b78e3 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/config/model/BeanSwitchYardScannerTest.java @@ -0,0 +1,134 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.config.model; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; +import org.switchyard.component.bean.deploy.CDIBeanServiceDescriptorTest; +import org.switchyard.component.bean.tests.BeanUTConstants; +import org.switchyard.component.bean.tests.OneWay; +import org.switchyard.component.bean.tests.ServiceWithReferenceBean; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * @author tom.fennelly@gmail.com + */ +public class BeanSwitchYardScannerTest { + + private SwitchYardModel _scannedModel; + private BeanSwitchYardScanner _scanner; + private List _scannedURLs; + + @Before + public void setUp() throws Exception { + _scanner = new BeanSwitchYardScanner(); + + // If running this test inside your IDE... you need to set the cwd to be the + // root of the bean module !! + _scannedURLs = new ArrayList(); + _scannedURLs.add(new File("./target/test-classes").toURI().toURL()); + } + + @Test + public void test() throws Exception { + scan(new File("./target/test-classes").toURI().toURL()); + List components = _scannedModel.getComposite().getComponents(); + for(ComponentModel component : components) { + ComponentImplementationModel implementation = component.getImplementation(); + Assert.assertTrue(implementation instanceof BeanComponentImplementationModel); + checkBeanModel((BeanComponentImplementationModel)implementation); + } + } + + // Verify that the ConsumerBean reference is picked up by the scanner + @Test + public void checkReference() throws Exception { + scan(new File("./target/test-classes").toURI().toURL()); + ComponentModel consumerBeanModel = null; + ComponentReferenceModel oneWayReference = null; + + for (ComponentModel component : _scannedModel.getComposite().getComponents()) { + BeanComponentImplementationModel beanImp = + (BeanComponentImplementationModel)component.getImplementation(); + if (ServiceWithReferenceBean.class.getName().equals(beanImp.getClazz())) { + consumerBeanModel = component; + break; + } + } + // If the bean wasn't found, then something is screwed up + Assert.assertNotNull(consumerBeanModel); + for (ComponentReferenceModel reference : consumerBeanModel.getReferences()) { + if (reference.getName().equals(OneWay.class.getSimpleName())) { + oneWayReference = reference; + } + } + // OneWay reference should have been picked up by scanner + Assert.assertNotNull(oneWayReference); + } + + // verify an empty model is created + @Test + public void testEmptyScan() throws Exception { + scan(); + Assert.assertNull("Composite element should not be created if no components were found.", + _scannedModel.getComposite()); + } + + private void checkBeanModel(BeanComponentImplementationModel model) throws ClassNotFoundException { + Class serviceClass = Classes.forName(model.getClazz(), getClass()); + + Assert.assertFalse(serviceClass.isInterface()); + Assert.assertFalse(Modifier.isAbstract(serviceClass.getModifiers())); + if (!serviceClass.isAnnotationPresent(Service.class)) { + boolean referencePresent = false; + for (Field f : serviceClass.getDeclaredFields()) { + if (f.isAnnotationPresent(Reference.class)) { + referencePresent = true; + break; + } + } + Assert.assertTrue("Bean classes without an @Service must have at least one @Reference", referencePresent); + } + + } + + // Takes a list of URLs to scan *instead* of what's defined in @Before. + private void scan(URL ... urls) throws Exception { + _scannedURLs.clear(); + if (urls != null && urls.length > 0) { + _scannedURLs.addAll(Arrays.asList(urls)); + } + ScannerInput input = new ScannerInput() + .setURLs(_scannedURLs) + .setExcludePackages(BeanUTConstants.BEAN_SCANNER_BLACK_LIST); + _scannedModel = _scanner.scan(input).getModel(); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/deploy/CDIBeanServiceDescriptorTest.java b/components/bean/src/test/java/org/switchyard/component/bean/deploy/CDIBeanServiceDescriptorTest.java new file mode 100644 index 000000000..409554b92 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/deploy/CDIBeanServiceDescriptorTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.deploy; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.component.bean.Service; + +/** + * @author tom.fennelly@gmail.com + */ +public class CDIBeanServiceDescriptorTest { + + @Test + public void test_IsInterface_OK() { + CDIBeanServiceDescriptor.getServiceInterface(XImpl.class); + } + + @Test + public void test_OmmitInterface_OK() { + CDIBeanServiceDescriptor.getServiceInterface(ZImpl.class); + } + + @Test + public void test_OmmitInterface_Fail_noInterface() { + try { + CDIBeanServiceDescriptor.getServiceInterface(TImpl.class); + } catch (RuntimeException e) { + String message = e.getMessage(); + Assert.assertTrue(message.contains("SWITCHYARD030420")); + } + } + + @Test + public void test_OmmitInterface_Fail_multipleInterfaces() { + try { + CDIBeanServiceDescriptor.getServiceInterface(UImpl.class); + } catch (RuntimeException e) { + String message = e.getMessage(); + Assert.assertTrue(message.contains("SWITCHYARD030420")); + } + } + + @Test + public void test_IsInterface_Fail() { + try { + CDIBeanServiceDescriptor.getServiceInterface(YImpl.class); + } catch (RuntimeException e) { + String message = e.getMessage(); + Assert.assertTrue(message.contains("SWITCHYARD030421")); + } + } + + @Service(X.class) + private class XImpl { + } + private interface X { + } + @Service(String.class) + private class YImpl { + } + @Service + private class ZImpl implements Z { + } + private interface Z { + } + @Service + private class TImpl { + } + @Service + private class UImpl implements U, Z { + } + private interface U { + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjection.java b/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjection.java new file mode 100644 index 000000000..918c65137 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjection.java @@ -0,0 +1,9 @@ +package org.switchyard.component.bean.exchange; + +public interface ExchangeInjection { + + String injectionNotNull(String msg); + String correctMessage(String msg); + String sendReply(String msg); + String attachments(String msg); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjectionBean.java b/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjectionBean.java new file mode 100644 index 000000000..0673760b1 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjectionBean.java @@ -0,0 +1,56 @@ +package org.switchyard.component.bean.exchange; + +import javax.activation.DataSource; +import javax.inject.Inject; + +import org.junit.Assert; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.bean.Service; + +@Service(value = ExchangeInjection.class, name = "ExchangeInjectionService") +public class ExchangeInjectionBean implements ExchangeInjection { + + @Inject + private Exchange exchange; + + @Override + public String injectionNotNull(String msg) { + Assert.assertNotNull(exchange); + return msg; + } + + @Override + public String correctMessage(String msg) { + Assert.assertEquals(ExchangeInjectionTest.TEST_IN_CONTENT, msg); + Assert.assertEquals(ExchangeInjectionTest.TEST_IN_PROPERTY, + exchange.getContext().getPropertyValue(ExchangeInjectionTest.TEST_IN_PROPERTY)); + return ""; + } + + @Override + public String sendReply(String msg) { + Message message = exchange.createMessage(); + message.setContent(ExchangeInjectionTest.TEST_OUT_CONTENT); + message.getContext().setProperty(ExchangeInjectionTest.TEST_OUT_PROPERTY, + ExchangeInjectionTest.TEST_OUT_PROPERTY); + exchange.send(message); + return "THIS SHOULD NOT BE RETURNED AS MESSAGE CONTENT"; + } + + @Override + public String attachments(String msg) { + DataSource attachIn = exchange.getMessage().getAttachment( + ExchangeInjectionTest.TEST_IN_ATTACHMENT); + Assert.assertNotNull(attachIn); + Assert.assertEquals(ExchangeInjectionTest.TEST_IN_ATTACHMENT, attachIn.getName()); + Message message = exchange.createMessage(); + message.setContent(ExchangeInjectionTest.TEST_OUT_CONTENT); + message.addAttachment(ExchangeInjectionTest.TEST_OUT_ATTACHMENT, + new DummyDataSource(ExchangeInjectionTest.TEST_OUT_ATTACHMENT)); + exchange.send(message); + return ""; + } + + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjectionTest.java b/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjectionTest.java new file mode 100644 index 000000000..42dae3375 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/exchange/ExchangeInjectionTest.java @@ -0,0 +1,124 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.exchange; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.activation.DataSource; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class ExchangeInjectionTest { + + public static final String TEST_IN_ATTACHMENT = "TestInAttachment"; + public static final String TEST_OUT_ATTACHMENT = "TestOutAttachment"; + public static final String TEST_IN_CONTENT = "TestInContent"; + public static final String TEST_OUT_CONTENT = "TestOutContent"; + public static final String TEST_IN_PROPERTY = "TestInProperty"; + public static final String TEST_OUT_PROPERTY = "TestOutProperty"; + + @ServiceOperation("ExchangeInjectionService") + private Invoker invokerService; + + @ServiceOperation("ExchangeInjectionService.sendReply") + private Invoker sendReply; + + @ServiceOperation("ExchangeInjectionService.attachments") + private Invoker attachments; + + @Test + public void injectionNotNull() { + invokerService.operation("injectionNotNull").sendInOnly("injectionNotNull"); + } + + @Test + public void correctMessage() { + invokerService + .property(TEST_IN_PROPERTY, TEST_IN_PROPERTY) + .operation("correctMessage") + .sendInOut(TEST_IN_CONTENT); + } + + @Test + public void sendReply() throws Exception { + MockHandler handler = new MockHandler(); + handler.setWaitTimeout(3000); + Exchange ex = sendReply.createExchange(handler); + ex.send(ex.createMessage().setContent(TEST_IN_CONTENT)); + Assert.assertEquals(1, handler.waitForOKMessage().getMessages().size()); + Assert.assertEquals(TEST_OUT_CONTENT, + handler.getMessages().poll().getMessage().getContent()); + } + + @Test + public void attachments() throws Exception { + MockHandler handler = new MockHandler(); + handler.setWaitTimeout(3000); + Exchange ex = attachments.createExchange(handler); + ex.send(ex.createMessage() + .setContent(TEST_IN_CONTENT) + .addAttachment(TEST_IN_ATTACHMENT, new DummyDataSource(TEST_IN_ATTACHMENT))); + Assert.assertEquals(1, handler.waitForOKMessage().getMessages().size()); + Message reply = handler.getMessages().poll().getMessage(); + DataSource attachOut = reply.getAttachment(TEST_OUT_ATTACHMENT); + Assert.assertNotNull(attachOut); + Assert.assertEquals(TEST_OUT_ATTACHMENT, attachOut.getName()); + } +} + +class DummyDataSource implements DataSource { + + private String _name; + + public DummyDataSource(String name) { + _name = name; + } + + @Override + public String getContentType() { + return ""; + } + + @Override + public InputStream getInputStream() throws IOException { + return null; + } + + @Override + public String getName() { + return _name; + } + + @Override + public OutputStream getOutputStream() throws IOException { + return null; + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/includeexclude/BeanActivatorWithoutConfigExcludeTest.java b/components/bean/src/test/java/org/switchyard/component/bean/includeexclude/BeanActivatorWithoutConfigExcludeTest.java new file mode 100644 index 000000000..055c88cb5 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/includeexclude/BeanActivatorWithoutConfigExcludeTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.includeexclude; + +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.component.bean.deploy.BeanComponentActivator; +import org.switchyard.internal.DomainImpl; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +import javax.xml.namespace.QName; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class, exclude = BeanComponentActivator.BEAN_TYPE) +public class BeanActivatorWithoutConfigExcludeTest { + + private ServiceDomain domain; + + @Test + public void test() { + List services = ((DomainImpl)domain).getServiceRegistry().getServices( + QName.valueOf("ConsumerService")); + Assert.assertEquals(0, services.size()); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/includeexclude/BeanActivatorWithoutConfigIncludeTest.java b/components/bean/src/test/java/org/switchyard/component/bean/includeexclude/BeanActivatorWithoutConfigIncludeTest.java new file mode 100644 index 000000000..331ca9ca6 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/includeexclude/BeanActivatorWithoutConfigIncludeTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.includeexclude; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.component.bean.deploy.BeanComponentActivator; +import org.switchyard.internal.DomainImpl; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class, include = BeanComponentActivator.BEAN_TYPE) +public class BeanActivatorWithoutConfigIncludeTest { + + private ServiceDomain domain; + + @Test + public void test() { + List services = ((DomainImpl)domain).getServiceRegistry().getServices( + QName.valueOf("ConsumerService")); + Assert.assertEquals(1, services.size()); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectService.java b/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectService.java new file mode 100644 index 000000000..138ab1ee8 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectService.java @@ -0,0 +1,20 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.inject; + +public interface InjectService { + + public String doSomething(String in); + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectServiceImpl.java b/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectServiceImpl.java new file mode 100644 index 000000000..198f2741d --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectServiceImpl.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.inject; + +import java.io.IOException; + +import javax.activation.DataSource; +import javax.inject.Inject; + +import org.switchyard.Context; +import org.switchyard.Message; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.bean.Service; + +@Service(InjectService.class) +public class InjectServiceImpl implements InjectService { + + @Inject + private Context context; + + @Inject + private Message message; + + @Override + public String doSomething(String in) { + String propC = (String)context.getProperty("someProp").getValue(); + String propM = (String)message.getContext().getProperty("someProp").getValue(); + boolean propertyMatch = propC.equals(propM); + boolean contentMatch = in.equals(message.getContent(String.class)); + DataSource attach = message.getAttachment("someAttach"); + String attachData; + try { + attachData = new StringPuller().pull(attach.getInputStream()); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + boolean attachMatch = "someAttach".equals(attach.getName()) && "text/plain".equals(attach.getContentType()) && "someAttachData".equals(attachData); + return propertyMatch + ", " + contentMatch + ", " + attachMatch; + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectTest.java b/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectTest.java new file mode 100644 index 000000000..4eb127738 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/inject/InjectTest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bean.inject; + +import javax.activation.DataSource; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.test.TestDataSource; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class InjectTest { + + private SwitchYardTestKit _testKit; + + @Test + public void testInject() { + Invoker invoker = _testKit.newInvoker("InjectService.doSomething"); + SynchronousInOutHandler handler = new SynchronousInOutHandler(); + Exchange exchange = invoker.createExchange(handler); + Message message = exchange.createMessage(); + Context context = exchange.getContext(message); + context.setProperty("someProp", "somePropVal"); + message.setContent("blah"); + DataSource attach = new TestDataSource("someAttach", "text/plain", "someAttachData"); + message.addAttachment(attach.getName(), attach); + exchange.send(message); + Exchange outExchange = handler.waitForOut(); + Assert.assertEquals("true, true, true", outExchange.getMessage().getContent()); + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/invoker/DummyException.java b/components/bean/src/test/java/org/switchyard/component/bean/invoker/DummyException.java new file mode 100644 index 000000000..d7db703ba --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/invoker/DummyException.java @@ -0,0 +1,10 @@ +package org.switchyard.component.bean.invoker; + +public class DummyException extends Exception { + + private static final long serialVersionUID = 1L; + + public DummyException(String msg) { + super(msg); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/invoker/InvokerReferenceContract.java b/components/bean/src/test/java/org/switchyard/component/bean/invoker/InvokerReferenceContract.java new file mode 100644 index 000000000..5410206c4 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/invoker/InvokerReferenceContract.java @@ -0,0 +1,9 @@ +package org.switchyard.component.bean.invoker; + +public interface InvokerReferenceContract { + + void inOnly(String msg); + String inOut(String msg); + String declaredException(String msg) throws DummyException; + String undeclaredException(String msg); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/invoker/InvokerServiceContract.java b/components/bean/src/test/java/org/switchyard/component/bean/invoker/InvokerServiceContract.java new file mode 100644 index 000000000..966f3187e --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/invoker/InvokerServiceContract.java @@ -0,0 +1,15 @@ +package org.switchyard.component.bean.invoker; + +public interface InvokerServiceContract { + + void testA(String msg); + void testB(String msg); + void testZ(String msg); + void propertyTest(String msg); + void noOperation(String msg); + void getContract(String msg); + void invokeWithContent(String msg); + void messageTest(String msg); + void declaredException(String msg); + void undeclaredException(String msg); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/invoker/ReferenceInvokerBean.java b/components/bean/src/test/java/org/switchyard/component/bean/invoker/ReferenceInvokerBean.java new file mode 100644 index 000000000..0f6b1ecdd --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/invoker/ReferenceInvokerBean.java @@ -0,0 +1,136 @@ +package org.switchyard.component.bean.invoker; + +import javax.inject.Inject; + +import org.junit.Assert; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.ReferenceInvocation; +import org.switchyard.component.bean.ReferenceInvoker; +import org.switchyard.component.bean.Service; +import org.switchyard.extensions.java.JavaService; + +@Service(value = InvokerServiceContract.class, name = "InvokerService") +public class ReferenceInvokerBean implements InvokerServiceContract { + + @Inject @Reference(ReferenceInvokerTest.REFERENCE_A) + private ReferenceInvoker invokerA; + + @Inject @Reference(ReferenceInvokerTest.REFERENCE_B) + private ReferenceInvoker invokerB; + + @Inject @Reference("ThisReferenceDoesNotExist") + private ReferenceInvoker invokerZ; + + @Override + public void testA(String msg) { + try { + invokerA.newInvocation("inOnly").invoke(); + } catch (Exception ex) { + ex.printStackTrace(); + Assert.fail(); + } + } + + @Override + public void testB(String msg) { + try { + invokerB.newInvocation("inOnly").invoke(); + } catch (Exception ex) { + ex.printStackTrace(); + Assert.fail(); + } + } + + @Override + public void testZ(String msg) { + try { + invokerZ.newInvocation("inOnly").invoke(); + Assert.fail("Should not be able to invoke a service without a component reference"); + } catch (Exception ex) { + Assert.assertTrue(ex instanceof IllegalStateException); + System.out.println("Expected exception caught with missing reference:\n\t" + ex.getMessage()); + } + } + + @Override + public void propertyTest(String msg) { + try { + ReferenceInvocation invoke = invokerA.newInvocation("inOut") + .setProperty(ReferenceInvokerTest.TEST_IN_PROPERTY, ReferenceInvokerTest.TEST_IN_PROPERTY) + .invoke(); + + // check that the out property can be read from the context + Object outProp = invoke.getProperty(ReferenceInvokerTest.TEST_OUT_PROPERTY); + Assert.assertNotNull(outProp); + Assert.assertEquals(ReferenceInvokerTest.TEST_OUT_PROPERTY, outProp); + } catch (Exception ex) { + ex.printStackTrace(); + Assert.fail(); + } + } + + @Override + public void messageTest(String msg) { + try { + ReferenceInvocation invoker = invokerA.newInvocation("inOut"); + invoker.getMessage().setContent("message-test-in"); + invoker.invoke(); + + // check that the correct message reference is returned from invoke + Assert.assertNotNull(invoker.getMessage().getContent()); + Assert.assertEquals("message-test-out", invoker.getMessage().getContent()); + } catch (Exception ex) { + ex.printStackTrace(); + Assert.fail(); + } + } + + @Override + public void invokeWithContent(String msg) { + try { + invokerA.newInvocation("inOnly").invoke("content-test-in"); + } catch (Exception ex) { + ex.printStackTrace(); + Assert.fail(); + } + } + + @Override + public void noOperation(String msg) { + try { + invokerA.newInvocation().invoke(); + Assert.fail("Should not be able to invoke a service with multiple operations without specifying op name"); + } catch (Exception ex) { + Assert.assertTrue(ex instanceof IllegalStateException); + System.out.println("Expected exception caught when operation name not specified:\n\t" + ex.getMessage()); + } + } + + @Override + public void getContract(String msg) { + Assert.assertEquals(invokerA.getContract().getType(), JavaService.TYPE); + Assert.assertEquals(((JavaService)invokerA.getContract()).getJavaInterface(), InvokerReferenceContract.class); + } + + @Override + public void declaredException(String msg) { + try { + invokerA.newInvocation("declaredException").invoke(); + Assert.fail("Fault returned on reference invocation not thrown as exception"); + } catch (Exception ex) { + Assert.assertTrue(ex instanceof DummyException); + } + } + + @Override + public void undeclaredException(String msg) { + try { + invokerA.newInvocation("undeclaredException").invoke(); + Assert.fail(); + } catch (Exception ex) { + Assert.assertTrue(ex instanceof DummyException); + } + } + + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/invoker/ReferenceInvokerTest.java b/components/bean/src/test/java/org/switchyard/component/bean/invoker/ReferenceInvokerTest.java new file mode 100644 index 000000000..a7c3eaece --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/invoker/ReferenceInvokerTest.java @@ -0,0 +1,156 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.invoker; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardTestKit; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "ReferenceInvokerTest.xml", mixins = CDIMixIn.class) +public class ReferenceInvokerTest { + + public static final String REFERENCE_A = "ReferenceA"; + public static final String REFERENCE_B = "ReferenceB"; + public static final String TEST_IN_PROPERTY = "TestInProperty"; + public static final String TEST_OUT_PROPERTY = "TestOutProperty"; + private SwitchYardTestKit testKit; + + @ServiceOperation("InvokerService") + private Invoker invokerService; + + @Test + public void invokeReferenceA() { + MockHandler handlerA = testKit.registerInOnlyService(REFERENCE_A); + MockHandler handlerB = testKit.registerInOnlyService(REFERENCE_B); + invokerService.operation("testA").sendInOut("testA"); + Assert.assertEquals(1, handlerA.getMessages().size()); + Assert.assertEquals(0, handlerB.getMessages().size()); + } + + @Test + public void invokeReferenceB() { + MockHandler handlerA = testKit.registerInOnlyService(REFERENCE_A); + MockHandler handlerB = testKit.registerInOnlyService(REFERENCE_B); + invokerService.operation("testB").sendInOut("testB"); + Assert.assertEquals(0, handlerA.getMessages().size()); + Assert.assertEquals(1, handlerB.getMessages().size()); + } + + @Test + public void invokeNonexistentReference() { + invokerService.operation("testZ").sendInOut("testZ"); + } + + @Test + public void invokeWithoutOperationName() { + invokerService.operation("noOperation").sendInOut("noOperation"); + } + + @Test + public void getContract() { + invokerService.operation("getContract").sendInOut("getContract"); + } + + @Test + public void messageTest() { + testKit.registerInOutService(REFERENCE_A, new BaseHandler() { + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // Verify that the content was set on the request message by the invoker + Assert.assertNotNull(exchange.getMessage().getContent()); + Assert.assertEquals("message-test-in", exchange.getMessage().getContent()); + + // Set out content to be returned through invoker + Message reply = exchange.createMessage(); + reply.setContent("message-test-out"); + exchange.send(reply); + } + }); + invokerService.operation("messageTest").sendInOut("messageTest"); + } + + @Test + public void invokeWithContent() { + testKit.registerInOutService(REFERENCE_A, new BaseHandler() { + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // Verify that the content was set on the request message by the invoker + Assert.assertNotNull(exchange.getMessage().getContent()); + Assert.assertEquals("content-test-in", exchange.getMessage().getContent()); + } + }); + invokerService.operation("invokeWithContent").sendInOut("invokeWithContent"); + } + + @Test + public void setProperty() { + testKit.registerInOutService(REFERENCE_A, new BaseHandler() { + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // Verify that a property was set on the request message by the invoker + Property inProp = exchange.getContext(exchange.getMessage()) + .getProperty(TEST_IN_PROPERTY, Scope.MESSAGE); + Assert.assertNotNull(inProp); + Assert.assertEquals(TEST_IN_PROPERTY, inProp.getValue()); + + // Set an out property which will be verified in the test bean class + Message reply = exchange.createMessage(); + exchange.getContext(reply) + .setProperty(TEST_OUT_PROPERTY, TEST_OUT_PROPERTY, Scope.MESSAGE); + exchange.send(reply); + } + }); + invokerService.operation("propertyTest").sendInOut("propertyTest"); + } + + @Test + public void declaredException() { + testKit.registerInOutService(REFERENCE_A, new BaseHandler() { + public void handleMessage(Exchange exchange) throws HandlerException { + Message reply = exchange.createMessage(); + reply.setContent(new DummyException( + exchange.getMessage().getContent(String.class))); + exchange.sendFault(reply); + } + }); + invokerService.operation("declaredException").sendInOut("declaredException"); + } + + @Test + public void undeclaredException() { + testKit.registerInOutService(REFERENCE_A, new BaseHandler() { + public void handleMessage(Exchange exchange) throws HandlerException { + throw new HandlerException(new DummyException( + exchange.getMessage().getContent(String.class))); + } + }); + invokerService.operation("undeclaredException").sendInOut("undeclaredException"); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService1.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService1.java new file mode 100644 index 000000000..8132db25c --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService1.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref; + +/** + * @author tom.fennelly@gmail.com + */ +public interface InventoryClientService1 { + + String doStuff(String input); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService1Bean.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService1Bean.java new file mode 100644 index 000000000..51a1e733e --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService1Bean.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref; + +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; +import org.switchyard.component.bean.multiversionref.oldinvservice.A; +import org.switchyard.component.bean.multiversionref.oldinvservice.OldInventoryService; + +import javax.inject.Inject; + +/** + * @author tom.fennelly@gmail.com + */ +@Service(InventoryClientService1.class) +public class InventoryClientService1Bean implements InventoryClientService1 { + + @Inject @Reference("InventoryService") + private OldInventoryService oldInventoryService; + + @Override + public String doStuff(String input) { + A result = oldInventoryService.getInventory(new A()); + return "old"; + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService2.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService2.java new file mode 100644 index 000000000..100ece759 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService2.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref; + +/** + * @author tom.fennelly@gmail.com + */ +public interface InventoryClientService2 { + + String doStuff(String input); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService2Bean.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService2Bean.java new file mode 100644 index 000000000..c94b59ac8 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/InventoryClientService2Bean.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref; + +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; +import org.switchyard.component.bean.multiversionref.newinvservice.B; +import org.switchyard.component.bean.multiversionref.newinvservice.InventoryService; + +import javax.inject.Inject; + +/** + * @author tom.fennelly@gmail.com + */ +@Service(InventoryClientService2.class) +public class InventoryClientService2Bean implements InventoryClientService2 { + + @Inject @Reference("InventoryService") + private InventoryService newInventoryService; + + @Override + public String doStuff(String input) { + B result = newInventoryService.getInventory(new B()); + return "new"; + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/MultiVersionServiceTest.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/MultiVersionServiceTest.java new file mode 100644 index 000000000..4e73723c3 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/MultiVersionServiceTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/** + * This test is testing checking that @Referenced services can be invoked + * through old and new interfaces and that the appropriate input/output + * parameter transformations are automatically applied based on the ExchangeContract + * information specified in the ClientBeanProxyHandler. + *

+ * InventoryClientService1 uses the old inventory interface to invoke the inventory service, + * while InventoryClientService2 uses the new inventory interface. In both cases, they are + * invoking the same backend service (the new version). SwitchYard ensures that the appropriate + * type transformation happen for InventoryClientService1. + * + * @author tom.fennelly@gmail.com + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class MultiVersionServiceTest { + + @ServiceOperation("InventoryClientService1.doStuff") + private Invoker doStuffOp1; + + @ServiceOperation("InventoryClientService2.doStuff") + private Invoker doStuffOp2; + + @Test + public void test_InventoryClientService1() { + String response = doStuffOp1.sendInOut("hello").getContent(String.class); + + Assert.assertEquals("old", response); + } + + @Test + public void test_InventoryClientService2() { + String response = doStuffOp2.sendInOut("hello").getContent(String.class); + + Assert.assertEquals("new", response); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/B.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/B.java new file mode 100644 index 000000000..2da41af98 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/B.java @@ -0,0 +1,21 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref.newinvservice; + +/** + * @author tom.fennelly@gmail.com + */ +public class B { +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/InventoryService.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/InventoryService.java new file mode 100644 index 000000000..55ba4d15f --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/InventoryService.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref.newinvservice; + +/** + * @author tom.fennelly@gmail.com + */ +public interface InventoryService { + + B getInventory(B b); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/NewInventoryServiceBean.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/NewInventoryServiceBean.java new file mode 100644 index 000000000..69ce758af --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/NewInventoryServiceBean.java @@ -0,0 +1,29 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref.newinvservice; + +import org.switchyard.component.bean.Service; + +/** + * @author tom.fennelly@gmail.com + */ +@Service(InventoryService.class) +public class NewInventoryServiceBean implements InventoryService { + + @Override + public B getInventory(B b) { + return b; + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/Transformers.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/Transformers.java new file mode 100644 index 000000000..57b600872 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/newinvservice/Transformers.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref.newinvservice; + +import org.switchyard.annotations.Transformer; +import org.switchyard.component.bean.multiversionref.oldinvservice.A; + +/** + * @author tom.fennelly@gmail.com + */ +public class Transformers { + + @Transformer + public B transformA2B(A a) { + return new B(); + } + + @Transformer + public A transformB2A(B b) { + return new A(); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/oldinvservice/A.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/oldinvservice/A.java new file mode 100644 index 000000000..51123eb7f --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/oldinvservice/A.java @@ -0,0 +1,21 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref.oldinvservice; + +/** + * @author tom.fennelly@gmail.com + */ +public class A { +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/oldinvservice/OldInventoryService.java b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/oldinvservice/OldInventoryService.java new file mode 100644 index 000000000..6d73d7776 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/multiversionref/oldinvservice/OldInventoryService.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.multiversionref.oldinvservice; + +/** + * @author tom.fennelly@gmail.com + */ +public interface OldInventoryService { + + A getInventory(A a); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicInOutTest.java b/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicInOutTest.java new file mode 100644 index 000000000..a778df2b9 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicInOutTest.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.omservice.basic; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.component.bean.omservice.model.OrderRequest; +import org.switchyard.component.bean.omservice.model.OrderResponse; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/** + * @author tom.fennelly@gmail.com + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class BasicInOutTest { + + private SwitchYardTestKit _testKit; + + @Test + public void test_New_Way() { + + Message responseMsg = _testKit.newInvoker("BasicOrderManagementService.createOrder"). + sendInOut(new OrderRequest("D123", "ABCD")); + + OrderResponse response = (OrderResponse) responseMsg.getContent(); + + Assert.assertEquals("D123", response.orderId); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicOrderManagementService.java b/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicOrderManagementService.java new file mode 100644 index 000000000..d36e88aec --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicOrderManagementService.java @@ -0,0 +1,11 @@ +package org.switchyard.component.bean.omservice.basic; + +import org.switchyard.component.bean.omservice.model.OrderRequest; +import org.switchyard.component.bean.omservice.model.OrderResponse; + +/** + * @author tom.fennelly@gmail.com + */ +public interface BasicOrderManagementService { + OrderResponse createOrder(OrderRequest request); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicOrderManagementServiceImpl.java b/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicOrderManagementServiceImpl.java new file mode 100644 index 000000000..213496b9d --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/omservice/basic/BasicOrderManagementServiceImpl.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.omservice.basic; + +import org.switchyard.component.bean.Service; +import org.switchyard.component.bean.omservice.model.OrderRequest; +import org.switchyard.component.bean.omservice.model.OrderResponse; + +/** + * @author tom.fennelly@gmail.com + */ +@Service(BasicOrderManagementService.class) +public class BasicOrderManagementServiceImpl implements BasicOrderManagementService { + + @Override + public OrderResponse createOrder(OrderRequest request) { + + return new OrderResponse(request.orderId); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/omservice/model/OrderRequest.java b/components/bean/src/test/java/org/switchyard/component/bean/omservice/model/OrderRequest.java new file mode 100644 index 000000000..5bdca2603 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/omservice/model/OrderRequest.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.omservice.model; + +/** + * @author tom.fennelly@gmail.com + */ +public class OrderRequest { + + public String orderId; + public String productId; + + public OrderRequest() { + } + + public OrderRequest(String orderId, String productId) { + this.orderId = orderId; + this.productId = productId; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/omservice/model/OrderResponse.java b/components/bean/src/test/java/org/switchyard/component/bean/omservice/model/OrderResponse.java new file mode 100644 index 000000000..c2cd044e8 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/omservice/model/OrderResponse.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.omservice.model; + +import org.switchyard.component.bean.prodservice.Product; + +/** + * @author tom.fennelly@gmail.com + */ +public class OrderResponse { + + public String orderId; + public Product product; + + public OrderResponse() { + } + + public OrderResponse(String orderId) { + this.orderId = orderId; + } + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/prodservice/Product.java b/components/bean/src/test/java/org/switchyard/component/bean/prodservice/Product.java new file mode 100644 index 000000000..7884deb08 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/prodservice/Product.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.prodservice; + +/** + * @author tom.fennelly@gmail.com + */ +public class Product { + + public String id; + public String name; + + public Product() { + } + + public Product(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/prodservice/ProductService.java b/components/bean/src/test/java/org/switchyard/component/bean/prodservice/ProductService.java new file mode 100644 index 000000000..d0109c3d4 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/prodservice/ProductService.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.prodservice; + +/** + * @author tom.fennelly@gmail.com + */ +public interface ProductService { + + Product getProduct(String productId); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/prodservice/ProductServiceImpl.java b/components/bean/src/test/java/org/switchyard/component/bean/prodservice/ProductServiceImpl.java new file mode 100644 index 000000000..0f981bcda --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/prodservice/ProductServiceImpl.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.prodservice; + +import org.switchyard.component.bean.Service; + +/** + * @author tom.fennelly@gmail.com + */ +@Service(ProductService.class) +public class ProductServiceImpl implements ProductService { + + public Product getProduct(String productId) { + return new Product(productId, "MacBook Pro"); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanConsumerTest.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanConsumerTest.java new file mode 100644 index 000000000..3f3aeacef --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanConsumerTest.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.component.bean.BeanComponentException; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.InvocationFaultException; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/* + * Assorted methods for testing a CDI bean consuming a service in SwitchYard. + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class BeanConsumerTest { + + @ServiceOperation("ConsumerService.consumeInOnlyNoArgsService") + private Invoker inOnlyNoArgs; + @ServiceOperation("ConsumerService.consumeInOnlyService") + private Invoker inOnly; + @ServiceOperation("ConsumerService.consumeInOutService") + private Invoker inOut; + @ServiceOperation("ConsumerService.consumeInOutServiceThrowsRuntimeException") + private Invoker inOutRuntimeEx; + @ServiceOperation("ConsumerService.unknownXOp") + private Invoker unknownXOp; + + @Test + public void consumeInOnlyServiceFromBean_without_args() { + inOnlyNoArgs.sendInOnly(null); + } + + @Test + public void consumeInOnlyServiceFromBean_new_way() { + inOnly.sendInOnly("hello"); + } + + @Test + public void consumeInOutServiceFromBean_new_way() { + Message responseMsg = inOut.sendInOut("hello"); + + Assert.assertEquals("hello", responseMsg.getContent()); + } + + @Test + public void consumeInOnlyServiceFromBean_Fault_invalid_operation() { + try { + // this should result in a fault + unknownXOp.sendInOut("hello"); + // if we got here, then our negative test failed + Assert.fail("Invalid operation allowed!"); + } catch (InvocationFaultException ifEx) { + String msg = ifEx.getFaultMessage().getContent(Exception.class).getMessage(); + Assert.assertTrue(msg.contains("SWITCHYARD014013")); + } + } + + @Test + public void consumeInOutServiceFromBean_Fault_service_exception() { + try { + // this should result in a fault + inOut.sendInOut(new ConsumerException("throw me a remote exception please!!")); + // if we got here, then our negative test failed + Assert.fail("Exception thrown by bean but not turned into fault!"); + } catch (InvocationFaultException infEx) { + System.out.println(infEx.getFaultMessage().getContent()); + Message faultMsg = infEx.getFaultMessage(); + Assert.assertTrue(faultMsg.getContent() instanceof ConsumerException); + Assert.assertEquals("remote-exception-received", faultMsg.getContent(ConsumerException.class).getMessage()); + } + } + + @Test + public void consumeInOutServiceFromBean_throws_runtime_exception() { + try { + // this should result in a fault + inOutRuntimeEx.sendInOut(new ConsumerException("throw me a remote exception please!!")); + // if we got here, then our negative test failed + Assert.fail("Exception thrown by bean but not turned into fault!"); + } catch (InvocationFaultException infEx) { + System.out.println(infEx.getFaultMessage().getContent()); + Message faultMsg = infEx.getFaultMessage(); + Assert.assertTrue(faultMsg.getContent() instanceof HandlerException); + Assert.assertEquals("throw me a remote exception please!!", faultMsg.getContent(HandlerException.class).getCause().getCause().getMessage()); + } + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanPropertyTest.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanPropertyTest.java new file mode 100644 index 000000000..e8f2e7879 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanPropertyTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import java.util.Map; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/* + * Assorted methods for testing a CDI bean consuming a service in SwitchYard. + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "BeanPropertyTests.xml", mixins = CDIMixIn.class) +public class BeanPropertyTest { + + @ServiceOperation("PropertyService.getProperties") + private Invoker _invoker; + + @Test + public void testBeanProperty() { + Map response = _invoker.sendInOut(null).getContent(Map.class); + Assert.assertEquals("bar", response.get("foo")); + Assert.assertEquals("composite.bar", response.get("composite.foo")); + Assert.assertEquals("component.bar", response.get("component.foo")); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanProviderTest.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanProviderTest.java new file mode 100644 index 000000000..6110b9688 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanProviderTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/* + * Assorted methods for testing a CDI bean providing a service in SwitchYard. + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class BeanProviderTest { + + @ServiceOperation("OneWay.oneWay") + private Invoker oneWay; + @ServiceOperation("RequestResponse.reply") + private Invoker reply; + + @Test + public void invokeOneWayProviderWithInOnly() { + oneWay.sendInOnly("hello"); + } + + @Test + public void invokeRequestResponseProviderWithInOut() { + String ECHO_MSG = "hello"; + Message response = reply.sendInOut(ECHO_MSG); + + Assert.assertEquals(ECHO_MSG, response.getContent()); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanUTConstants.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanUTConstants.java new file mode 100644 index 000000000..6cd0275bb --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/BeanUTConstants.java @@ -0,0 +1,13 @@ +package org.switchyard.component.bean.tests; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.switchyard.component.bean.deploy.CDIBeanServiceDescriptorTest; + +public final class BeanUTConstants { + public static final List BEAN_SCANNER_BLACK_LIST = + Collections.unmodifiableList( + Arrays.asList(new Package[] {CDIBeanServiceDescriptorTest.class.getPackage()})); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerBean.java new file mode 100644 index 000000000..df0917a26 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerBean.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import javax.inject.Inject; + +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +import java.io.StringReader; + +@Service(ConsumerService.class) +public class ConsumerBean implements ConsumerService { + + @Inject @Reference + private OneWay oneWay; + + @Inject @Reference + private RequestResponse requestResponse; + + @Override + public void consumeInOnlyNoArgsService() { + oneWay.oneWayNoArgs(); + } + + @Override + public void consumeInOnlyService(Object message) { + oneWay.oneWay(message); + } + + @Override + public Object consumeInOutService(Object message) throws ConsumerException { + try { + Object reply = null; + reply = requestResponse.reply(message); + Assert.assertEquals(message, reply); + + // SWITCHYARD-1688 + System.out.println(oneWay.toString()); + Assert.assertTrue(oneWay.hashCode() == oneWay.hashCode()); + Assert.assertTrue(oneWay.equals(oneWay)); + Assert.assertFalse(oneWay.equals(requestResponse)); + + return reply; + } catch (ConsumerException e) { + Assert.assertEquals(message, e); + // OK... this validates that the remote exception was transported through the + // Exchange fault mechanism and then rethrown by the client proxy. Create + // and throw a new exception... + throw new ConsumerException("remote-exception-received"); + } + } + + @Override + public Object consumeInOutServiceThrowsRuntimeException(Object message) { + try { + Object reply = null; + reply = requestResponse.reply(message); + Assert.assertEquals(message, reply); + return reply; + } catch (ConsumerException e) { + Assert.assertEquals(message, e); + throw new RuntimeException(e); + } + } + + @Override + public String domOperation(Document message) { + try { + XMLUnit.compareXML(XMLHelper.getDocument(new InputSource(new StringReader(""))), message); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + + return ""; + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerException.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerException.java new file mode 100644 index 000000000..cf18bfe6d --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerException.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +/** + * @author tom.fennelly@gmail.com + */ +public class ConsumerException extends Exception { + + public ConsumerException(String message) { + super(message); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerService.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerService.java new file mode 100644 index 000000000..2150d8548 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ConsumerService.java @@ -0,0 +1,18 @@ +package org.switchyard.component.bean.tests; + +import org.w3c.dom.Document; + +/** + * @author tom.fennelly@gmail.com + */ +public interface ConsumerService { + void consumeInOnlyNoArgsService(); + + void consumeInOnlyService(Object message); + + Object consumeInOutService(Object message) throws ConsumerException; + + Object consumeInOutServiceThrowsRuntimeException(Object message); + + String domOperation(Document message); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/InputTypeMismatchTest.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/InputTypeMismatchTest.java new file mode 100644 index 000000000..0d2d919a2 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/InputTypeMismatchTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class InputTypeMismatchTest { + + @ServiceOperation("ConsumerService.domOperation") + private Invoker domOperation; + + @Test + public void test_invokeWithWrongInputParameterType() { + // A basic type conversion should happen automatically... + Message response = domOperation.sendInOut(""); + + Assert.assertEquals("", response.getContent()); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/LocalTransactionBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/LocalTransactionBean.java new file mode 100644 index 000000000..4eb4b06ca --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/LocalTransactionBean.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import javax.inject.Inject; + +import org.switchyard.annotations.Requires; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; +import org.switchyard.policy.TransactionPolicy; + +@Requires(transaction = TransactionPolicy.SUSPENDS_TRANSACTION) +@Service(value = OneWay.class, name = "LocalTransactionService") +public class LocalTransactionBean implements OneWay { + + @Inject @Reference @Requires(transaction = TransactionPolicy.SUSPENDS_TRANSACTION) + private OneWay oneWay; + + @Override + public void oneWay(Object message) { + // TODO Auto-generated method stub + + } + + @Override + public void oneWayNoArgs() { + // TODO Auto-generated method stub + + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/NoServiceReferenceBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/NoServiceReferenceBean.java new file mode 100644 index 000000000..417143a86 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/NoServiceReferenceBean.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.switchyard.component.bean.Reference; + +// A Bean class which includes an @Reference but does not declare a service +public class NoServiceReferenceBean { + @Reference + private OneWay oneWay; + + public void process(String data) { + // NOP + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/OneWay.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/OneWay.java new file mode 100644 index 000000000..b6f95be19 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/OneWay.java @@ -0,0 +1,22 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +public interface OneWay { + + void oneWayNoArgs(); + + void oneWay(Object message); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/OneWayBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/OneWayBean.java new file mode 100644 index 000000000..243f94f2a --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/OneWayBean.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.switchyard.component.bean.Service; + +@Service(OneWay.class) +public class OneWayBean implements OneWay { + + public void oneWay(Object message) { + System.out.println("Received message in OneWayBean: " + message); + } + + @Override + public void oneWayNoArgs() { + System.out.println("OneWayNoArgsBean successfully invoked with zero arguments"); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/PropertyService.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/PropertyService.java new file mode 100644 index 000000000..0ad9a8f8b --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/PropertyService.java @@ -0,0 +1,7 @@ +package org.switchyard.component.bean.tests; + +import java.util.Map; + +public interface PropertyService { + Map getProperties(); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/PropertyServiceBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/PropertyServiceBean.java new file mode 100644 index 000000000..244248263 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/PropertyServiceBean.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import java.util.HashMap; +import java.util.Map; + +import org.switchyard.component.bean.Property; +import org.switchyard.component.bean.Service; + +@Service(PropertyService.class) +public class PropertyServiceBean implements PropertyService { + + @Property(name="foo") + String _foo; + + @Property(name="composite.foo") + String _compositeFoo; + + @Property(name="component.foo") + String _componentFoo; + + @Override + public Map getProperties() { + Map response = new HashMap(); + response.put("foo", _foo); + response.put("composite.foo", _compositeFoo); + response.put("component.foo", _componentFoo); + return response; + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ReferenceAnnoationTest.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ReferenceAnnoationTest.java new file mode 100644 index 000000000..1cc0fa535 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ReferenceAnnoationTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.component.bean.config.model.BeanSwitchYardScanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +public class ReferenceAnnoationTest { + + private SwitchYardModel _scannedModel; + + @Before + public void setUp() throws Exception { + BeanSwitchYardScanner scanner = new BeanSwitchYardScanner(); + List urls = new ArrayList(); + urls.add(new File("./target/test-classes").toURI().toURL()); + + ScannerInput input = new ScannerInput() + .setURLs(urls) + .setExcludePackages(BeanUTConstants.BEAN_SCANNER_BLACK_LIST); + _scannedModel = scanner.scan(input).getModel(); + } + + @Test + public void testAnnotationRenameService() throws IOException, ClassNotFoundException { + List components = _scannedModel.getComposite().getComponents(); + boolean customReferenceNameFound = false; + for(ComponentModel component : components) { + if(component.getName().equals("ServiceWithReference")){ + for (ComponentReferenceModel reference : component.getReferences()) { + if (reference.getName().equals(ServiceWithReferenceBean.RENAMED_REFERENCE)) { + customReferenceNameFound = true; + } + } + } + } + Assert.assertTrue(customReferenceNameFound); + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ReferenceTest.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ReferenceTest.java new file mode 100644 index 000000000..5da6a79d2 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ReferenceTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.ServiceDomain; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class ReferenceTest { + + private ServiceDomain domain; + + @Test + public void verifyReferenceIsRegistered() { + Assert.assertNotNull(domain.getServiceReference(new QName("ConsumerService"))); + } +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/RequestResponse.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/RequestResponse.java new file mode 100644 index 000000000..414106fc6 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/RequestResponse.java @@ -0,0 +1,20 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +public interface RequestResponse { + + Object reply(Object message) throws ConsumerException; +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/RequestResponseBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/RequestResponseBean.java new file mode 100644 index 000000000..6e4c8019b --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/RequestResponseBean.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.switchyard.component.bean.Service; + +@Service(RequestResponse.class) +public class RequestResponseBean implements RequestResponse { + + public Object reply(Object message) throws ConsumerException { + if(message instanceof ConsumerException) { + throw (ConsumerException) message; + } + + return message; + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/RequiredPoliciesTest.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/RequiredPoliciesTest.java new file mode 100644 index 000000000..373b06c51 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/RequiredPoliciesTest.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import java.io.File; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.component.bean.config.model.BeanSwitchYardScanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.policy.SecurityPolicy; +import org.switchyard.policy.TransactionPolicy; + +/** + * @author tom.fennelly@gmail.com + */ +public class RequiredPoliciesTest { + + private SwitchYardModel _scannedModel; + + @Before + public void setUp() throws Exception { + BeanSwitchYardScanner scanner = new BeanSwitchYardScanner(); + List urls = new ArrayList(); + + // If running this test inside your IDE... you need to set the cwd to be the + // root of the bean module !! + urls.add(new File("./target/test-classes").toURI().toURL()); + + ScannerInput input = new ScannerInput() + .setURLs(urls) + .setExcludePackages(BeanUTConstants.BEAN_SCANNER_BLACK_LIST); + _scannedModel = scanner.scan(input).getModel(); + } + + @Test + public void verifyPolicyGenerated() throws Exception { + List components = _scannedModel.getComposite().getComponents(); + + boolean ssFound = false; + boolean ltsFound = false; + boolean stsFound = false; + + for(ComponentModel component : components) { + if(component.getName().equals("SecureService")) { + ComponentImplementationModel impl = component.getImplementation(); + Assert.assertTrue(impl.hasPolicyRequirement(SecurityPolicy.AUTHORIZATION.getQName())); + ComponentServiceModel svc = component.getServices().get(0); + Assert.assertTrue(svc.hasPolicyRequirement(SecurityPolicy.CLIENT_AUTHENTICATION.getQName())); + Assert.assertTrue(svc.hasPolicyRequirement(SecurityPolicy.CONFIDENTIALITY.getQName())); + ComponentReferenceModel ref = component.getReferences().get(0); + Assert.assertTrue(ref.hasPolicyRequirement(SecurityPolicy.AUTHORIZATION.getQName())); + Assert.assertTrue(ref.hasPolicyRequirement(SecurityPolicy.CLIENT_AUTHENTICATION.getQName())); + Assert.assertTrue(ref.hasPolicyRequirement(SecurityPolicy.CONFIDENTIALITY.getQName())); + ssFound = true; + continue; + } + + if(component.getName().equals("LocalTransactionService")) { + ComponentServiceModel svc = component.getServices().get(0); + Assert.assertTrue(svc.hasPolicyRequirement(TransactionPolicy.SUSPENDS_TRANSACTION.getQName())); + ComponentReferenceModel ref = component.getReferences().get(0); + Assert.assertTrue(ref.hasPolicyRequirement(TransactionPolicy.SUSPENDS_TRANSACTION.getQName())); + ltsFound = true; + continue; + } + + if(component.getName().equals("SharedTransactionService")) { + ComponentServiceModel svc = component.getServices().get(0); + Assert.assertTrue(svc.hasPolicyRequirement(TransactionPolicy.PROPAGATES_TRANSACTION.getQName())); + ComponentReferenceModel ref = component.getReferences().get(0); + Assert.assertTrue(ref.hasPolicyRequirement(TransactionPolicy.PROPAGATES_TRANSACTION.getQName())); + stsFound = true; + continue; + } + } + + Assert.assertTrue("SecureService not discovered!", ssFound); + Assert.assertTrue("LocalTransactionService not discovered!", ltsFound); + Assert.assertTrue("SharedTransactionService not discovered!", stsFound); + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/SecureBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/SecureBean.java new file mode 100644 index 000000000..71bafead3 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/SecureBean.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import static org.switchyard.policy.SecurityPolicy.AUTHORIZATION; +import static org.switchyard.policy.SecurityPolicy.CLIENT_AUTHENTICATION; +import static org.switchyard.policy.SecurityPolicy.CONFIDENTIALITY; + +import javax.inject.Inject; + +import org.switchyard.annotations.Requires; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; + +@Requires(security = {AUTHORIZATION, CLIENT_AUTHENTICATION, CONFIDENTIALITY}) +@Service(value = OneWay.class, name = "SecureService") +public class SecureBean implements OneWay { + + @Inject @Reference @Requires(security = {AUTHORIZATION, CLIENT_AUTHENTICATION, CONFIDENTIALITY}) + private OneWay oneWay; + + @Override + public void oneWay(Object message) { + // TODO Auto-generated method stub + + } + + @Override + public void oneWayNoArgs() { + // TODO Auto-generated method stub + + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationCustomComponentNameBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationCustomComponentNameBean.java new file mode 100644 index 000000000..4eff74186 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationCustomComponentNameBean.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.switchyard.component.bean.Service; + +@Service(value = ServiceAnnotationService.class, componentName = "CustomServiceAnnotationComponentName") +public class ServiceAnnotationCustomComponentNameBean implements ServiceAnnotationService { + + @Override + public void noOp(String ignored) { + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationCustomNameBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationCustomNameBean.java new file mode 100644 index 000000000..31e1e7403 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationCustomNameBean.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.switchyard.component.bean.Service; + +@Service(value = ServiceAnnotationService.class, name = "CustomServiceAnnotationServiceName") +public class ServiceAnnotationCustomNameBean implements ServiceAnnotationService { + + @Override + public void noOp(String ignored) { + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationEmptyNameBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationEmptyNameBean.java new file mode 100644 index 000000000..8d248f1a7 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationEmptyNameBean.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import org.switchyard.component.bean.Service; + +@Service(value = ServiceAnnotationService.class, name = "") +public class ServiceAnnotationEmptyNameBean implements ServiceAnnotationService { + + @Override + public void noOp(String ignored) { + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationService.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationService.java new file mode 100644 index 000000000..9428b07ce --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationService.java @@ -0,0 +1,20 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +public interface ServiceAnnotationService { + + public void noOp(String ignored); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationTest.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationTest.java new file mode 100644 index 000000000..8eaf1fbd8 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceAnnotationTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.component.bean.config.model.BeanSwitchYardScanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * @author tom.fennelly@gmail.com + */ +public class ServiceAnnotationTest { + + private SwitchYardModel _scannedModel; + + @Before + public void setUp() throws Exception { + BeanSwitchYardScanner scanner = new BeanSwitchYardScanner(); + List urls = new ArrayList(); + + // If running this test inside your IDE... you need to set the cwd to be the + // root of the bean module !! + urls.add(new File("./target/test-classes").toURI().toURL()); + + ScannerInput input = new ScannerInput() + .setURLs(urls) + .setExcludePackages(BeanUTConstants.BEAN_SCANNER_BLACK_LIST); + _scannedModel = scanner.scan(input).getModel(); + } + + @Test + public void test() throws IOException, ClassNotFoundException { + List components = _scannedModel.getComposite().getComponents(); + boolean customServiceNameFound = false; + boolean emptyServiceNameFound = false; + boolean customComponentNameFound = false; + for(ComponentModel component : components) { + if(component.getName().equals("CustomServiceAnnotationServiceName")){ + customServiceNameFound = true; + } + if(component.getName().equals("")){ + emptyServiceNameFound = true; + } + if(component.getName().equals("CustomServiceAnnotationComponentName")){ + customComponentNameFound = true; + } + } + Assert.assertTrue(customServiceNameFound); + Assert.assertFalse(emptyServiceNameFound); + Assert.assertTrue(customComponentNameFound); + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceWithReference.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceWithReference.java new file mode 100644 index 000000000..16dab3e5d --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceWithReference.java @@ -0,0 +1,20 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +public interface ServiceWithReference { + + public void noOp(String ignored); +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceWithReferenceBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceWithReferenceBean.java new file mode 100644 index 000000000..6bf215533 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/ServiceWithReferenceBean.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import javax.inject.Inject; + +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; + +@Service(ServiceWithReference.class) +public class ServiceWithReferenceBean implements ServiceWithReference { + + public static final String RENAMED_REFERENCE = "RenamedServiceReference"; + + @Inject @Reference + private OneWay _reference; + + @Inject @Reference(RENAMED_REFERENCE) + private OneWay _renamedReference; + + @Override + public void noOp(String ignored) { + } + +} diff --git a/components/bean/src/test/java/org/switchyard/component/bean/tests/SharedTransactionBean.java b/components/bean/src/test/java/org/switchyard/component/bean/tests/SharedTransactionBean.java new file mode 100644 index 000000000..570b6c983 --- /dev/null +++ b/components/bean/src/test/java/org/switchyard/component/bean/tests/SharedTransactionBean.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.bean.tests; + +import javax.inject.Inject; + +import org.switchyard.annotations.Requires; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; +import org.switchyard.policy.TransactionPolicy; + +@Requires(transaction = TransactionPolicy.PROPAGATES_TRANSACTION) +@Service(value = OneWay.class, name = "SharedTransactionService") +public class SharedTransactionBean implements OneWay { + + @Inject @Reference @Requires(transaction = TransactionPolicy.PROPAGATES_TRANSACTION) + private OneWay oneWay; + + @Override + public void oneWay(Object message) { + // TODO Auto-generated method stub + + } + + @Override + public void oneWayNoArgs() { + // TODO Auto-generated method stub + + } + +} diff --git a/components/bean/src/test/resources/META-INF/beans.xml b/components/bean/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/bean/src/test/resources/jaxbautoregister/switchyard-config-01.xml b/components/bean/src/test/resources/jaxbautoregister/switchyard-config-01.xml new file mode 100644 index 000000000..9b436c0a7 --- /dev/null +++ b/components/bean/src/test/resources/jaxbautoregister/switchyard-config-01.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/components/bean/src/test/resources/jaxbautoregister/switchyard-config-02.xml b/components/bean/src/test/resources/jaxbautoregister/switchyard-config-02.xml new file mode 100644 index 000000000..ce4eea010 --- /dev/null +++ b/components/bean/src/test/resources/jaxbautoregister/switchyard-config-02.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + diff --git a/components/bean/src/test/resources/log4j.xml b/components/bean/src/test/resources/log4j.xml new file mode 100644 index 000000000..cc45d1fd9 --- /dev/null +++ b/components/bean/src/test/resources/log4j.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bean/src/test/resources/org/switchyard/component/bean/config/model/BeanModelTests-Complete.xml b/components/bean/src/test/resources/org/switchyard/component/bean/config/model/BeanModelTests-Complete.xml new file mode 100644 index 000000000..a28b5e6af --- /dev/null +++ b/components/bean/src/test/resources/org/switchyard/component/bean/config/model/BeanModelTests-Complete.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + diff --git a/components/bean/src/test/resources/org/switchyard/component/bean/invoker/ReferenceInvokerTest.xml b/components/bean/src/test/resources/org/switchyard/component/bean/invoker/ReferenceInvokerTest.xml new file mode 100644 index 000000000..cdafa117d --- /dev/null +++ b/components/bean/src/test/resources/org/switchyard/component/bean/invoker/ReferenceInvokerTest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + diff --git a/components/bean/src/test/resources/org/switchyard/component/bean/tests/BeanPropertyTests.xml b/components/bean/src/test/resources/org/switchyard/component/bean/tests/BeanPropertyTests.xml new file mode 100644 index 000000000..c26187d72 --- /dev/null +++ b/components/bean/src/test/resources/org/switchyard/component/bean/tests/BeanPropertyTests.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpel/pom.xml b/components/bpel/pom.xml new file mode 100644 index 000000000..420d20c68 --- /dev/null +++ b/components/bpel/pom.xml @@ -0,0 +1,132 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-bpel + jar + SwitchYard: BPEL Component + http://switchyard.org + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-transform + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard.components + switchyard-component-soap + test + + + org.riftsaw + engine + + + org.jboss.soa.bpel + riftsaw-bpel-api + + + org.hibernate.common + hibernate-commons-annotations + + + org.hibernate + hibernate-core + + + org.hibernate + hibernate-entitymanager + + + org.jboss.soa.bpel + riftsaw-bpel-compiler + + + org.codehaus.woodstox + wstx-asl + + + + + org.jboss.soa.bpel + riftsaw-dao-jpa + + + org.jboss + jboss-vfs + provided + + + org.jboss.as + jboss-as-naming + provided + + + org.jboss.as + jboss-as-server + provided + + + diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/BPELFault.java b/components/bpel/src/main/java/org/switchyard/component/bpel/BPELFault.java new file mode 100644 index 000000000..c3e570643 --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/BPELFault.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel; + +import org.switchyard.HandlerException; +import org.switchyard.annotations.DefaultType; + +/** + * This class represents a thin wrapper around a SOAP Fault + * generated when a BPEL process returns a fault response. + * + */ +@Deprecated +@DefaultType(BPELFault.MESSAGE_TYPE) +public class BPELFault extends HandlerException { + + /** + * The message type for the BPEL fault. + */ + public static final String MESSAGE_TYPE = + "java:org.switchyard.component.bpel.BPELFault"; + + /** + * Serialization id. + */ + private static final long serialVersionUID = 1L; + + private javax.xml.soap.SOAPFault _fault=null; + + /** + * This is the constructor for the BPEL fault. + * + * @param fault The SOAP fault being wrapped + */ + public BPELFault(javax.xml.soap.SOAPFault fault) { + super("BPEL Fault ["+ fault.getFaultCode()+ "]"); + _fault = fault; + } + + /** + * This method returns the SOAP fault. + * + * @return The SOAP fault + */ + public javax.xml.soap.SOAPFault getSOAPFault() { + return (_fault); + } +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/BPELLogger.java b/components/bpel/src/main/java/org/switchyard/component/bpel/BPELLogger.java new file mode 100644 index 000000000..55ae49bc1 --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/BPELLogger.java @@ -0,0 +1,120 @@ +package org.switchyard.component.bpel; + +import javax.xml.namespace.QName; +import org.jboss.logging.Cause; +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 30800-31199 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface BPELLogger { + /** + * A root logger with the category of the package name. + */ + BPELLogger ROOT_LOGGER = Logger.getMessageLogger(BPELLogger.class, BPELLogger.class.getPackage().getName()); + + /** + * initBPELComponent method definition. + */ + @LogMessage(level = Level.INFO) + @Message(id = 30800, value = "Init BPEL component") + void initBPELComponent(); + + /** + * destroyBPELComponent method definition. + */ + @LogMessage(level = Level.INFO) + @Message(id = 30801, value = "Destroy BPEL component") + void destroyBPELComponent(); + + /** + * failedToCloseBPELEngine method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30802, value = "Failed to close BPEL engine") + void failedToCloseBPELEngine(@Cause Exception e); + + /** + * failedToObtainDeploymentNameFromURL method definition. + * @param urlpath the urlpath + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30803, value = "Failed to obtain deployment name from URL: %s") + void failedToObtainDeploymentNameFromURL(String urlpath); + + /** + * unableToLocateDeploymentDescriptorDeployXmlToDeriveDeploymentName method definition. + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30804, value = "Unable to locate deployment descriptor (deploy.xml) to derive deployment name") + void unableToLocateDeploymentDescriptorDeployXmlToDeriveDeploymentName(); + + /** + * deploymentNameIs method definition. + * @param ret the ret + */ + @LogMessage(level = Level.INFO) + @Message(id = 30805, value = "Deployment name is: %s") + void deploymentNameIs(String ret); + + /** + * unableToResolveTheDeploymentURL method definition. + * @param t the t + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30806, value = "Unable to resolve the deployment URL") + void unableToResolveTheDeploymentURL(@Cause java.lang.NoClassDefFoundError t); + + /** + * unableToTransformPropertyValueIntoUndeployDelayValue method definition. + * @param e the e + * @param delayValue delayValue + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30807, value = "Unable to transform property value '%s' into undeploy delay value") + void unableToTransformPropertyValueIntoUndeployDelayValue(@Cause Exception e, String delayValue); + + /** + * failedToUndeploy method definition. + * @param serviceName the serviceName + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30808, value = "Failed to undeploy '%s'") + void failedToUndeploy(QName serviceName, @Cause Exception e); + + /** + * noServiceReferencesFoundForProcess method definition. + * @param localProcessName the localProcessName + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30809, value = "No service references found for process '%s'") + void noServiceReferencesFoundForProcess(String localProcessName); + + /** + * noServiceFoundFor method definition. + * @param serviceName the serviceName + * @param portName the portName + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30810, value = "No service found for '%s' (port %s)") + void noServiceFoundFor(String serviceName, String portName); + + /** + * noServiceFoundFor method definition. + * @param serviceName the serviceName + */ + @LogMessage(level = Level.ERROR) + @Message(id = 30811, value = "No service found for '%s") + void noServiceFoundFor(String serviceName); + +} + diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/BPELMessages.java b/components/bpel/src/main/java/org/switchyard/component/bpel/BPELMessages.java new file mode 100644 index 000000000..210896d90 --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/BPELMessages.java @@ -0,0 +1,119 @@ +package org.switchyard.component.bpel; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; +/** + *

+ * This file is using the subset 31200-31599 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface BPELMessages { + /** + * The default messages. + */ + BPELMessages MESSAGES = Messages.getBundle(BPELMessages.class); + + /** + * interfaceNotDefinedForComponentWithBPELImplementation method definition. + * @return SwitchYardException + */ + @Message(id = 31200, value = "Interface not defined for component with BPEL implementation") + SwitchYardException interfaceNotDefinedForComponentWithBPELImplementation(); + + /** + * failedToLoadDefaultProperties method definition. + * @param e the e + * @return SwitchYardException + */ + @Message(id = 31201, value = "Failed to load default properties") + SwitchYardException failedToLoadDefaultProperties(@Cause Exception e); + + /** + * failedToInitializeTheEngine method definition. + * @param e the e + * @return SwitchYardException + */ + @Message(id = 31202, value = "Failed to initialize the engine") + SwitchYardException failedToInitializeTheEngine(@Cause Exception e); + + /** + * unknownDeploymentEnvironment method definition. + * @return SwitchYardException + */ + @Message(id = 31203, value = "Unknown deployment environment") + SwitchYardException unknownDeploymentEnvironment(); + + /** + * couldNotFindBPELImplementationAssociatedWithReference method definition. + * @return SwitchYardException + */ + @Message(id = 31207, value = "Could not find BPEL implementation associated with reference") + SwitchYardException couldNotFindBPELImplementationAssociatedWithReference(); + + /** + * timedOutAfterMsWaitingOnSynchronousResponseFromTargetService method definition. + * @param waitTimeout the waitTimeout + * @param serviceReferenceName serviceReferenceName + * @return HandlerException + */ + @Message(id = 31208, value = "Timed out after %s ms waiting on synchronous response from target service '%s'.") + HandlerException timedOutAfterMsWaitingOnSynchronousResponseFromTargetService(long waitTimeout, String serviceReferenceName); + + /** + * responseNotReturnedFromOperationOnService method definition. + * @param operationName the operationName + * @param serviceReferenceName serviceReferenceName + * @return Exception + */ + @Message(id = 31209, value = "Response not returned from operation '%s' on service: %s") + Exception responseNotReturnedFromOperationOnService(String operationName, String serviceReferenceName); + + /** + * wSDLLocationHasNotBeenSpecified method definition. + * @return SwitchYardException + */ + @Message(id = 31211, value = "WSDL location has not been specified") + SwitchYardException wSDLLocationHasNotBeenSpecified(); + + /** + * failedToLoadWSDL method definition. + * @param location the location + * @param e the e + * @return SwitchYardException + */ + @Message(id = 31212, value = "Failed to load WSDL '%s'") + SwitchYardException failedToLoadWSDL(String location, @Cause Exception e); + + /** + * unableToFindFaultOn method definition. + * @param faultName the faultName + * @param operationName operationName + * @return SwitchYardException + */ + @Message(id = 31214, value = "Unable to find fault '%s' on operation '%s'") + SwitchYardException unableToFindFaultOn(String faultName, String operationName); + + /** + * onlyExpectingASingleMessagePartForOperation method definition. + * @param operationName operationName + * @return SwitchYardException + */ + @Message(id = 31215, value = "Only expecting a single message part for operation '%s'") + SwitchYardException onlyExpectingASingleMessagePartForOperation(String operationName); + + /** + * unableToFindPartNameFor method definition. + * @param operationName operationName + * @return SwitchYardException + */ + @Message(id = 31216, value = "Unable to find part name for operation '%s'") + SwitchYardException unableToFindPartNameFor(String operationName); + +} + diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/DefaultBPELFaultTransformer.java b/components/bpel/src/main/java/org/switchyard/component/bpel/DefaultBPELFaultTransformer.java new file mode 100644 index 000000000..f6e8830a8 --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/DefaultBPELFaultTransformer.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; +import org.w3c.dom.Node; + +/** + * This class provides the default transformation for a BPELFault into a DOM Node. + * + * @param The BPEL fault + * @param The DOM Node + */ +@Deprecated +@Scannable(false) +public class DefaultBPELFaultTransformer extends BaseTransformer { + + @Override + public QName getFrom() { + return toMessageType(BPELFault.class); + } + + @Override + public QName getTo() { + return toMessageType(Node.class); + } + + @SuppressWarnings("unchecked") + @Override + public org.w3c.dom.Node transform(BPELFault from) { + return (from.getSOAPFault()); + } +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/deploy/BPELActivator.java b/components/bpel/src/main/java/org/switchyard/component/bpel/deploy/BPELActivator.java new file mode 100644 index 000000000..149d717bf --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/deploy/BPELActivator.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.deploy; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.riftsaw.engine.BPELEngine; +import org.switchyard.config.model.implementation.bpel.BPELComponentImplementationModel; +import org.switchyard.component.bpel.BPELMessages; +import org.switchyard.component.bpel.exchange.BPELExchangeHandler; +import org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory; +import org.switchyard.component.bpel.riftsaw.RiftsawServiceLocator; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; + +/** + * Activator for the BPEL component. + * + */ +public class BPELActivator extends BaseActivator { + + /** + * BPEL component activator type name. + */ + public static final String BPEL_TYPE = "bpel"; + + private static final Logger LOG = Logger.getLogger(BPELActivator.class); + + private static Map _handlers = new HashMap(); + + private BPELEngine _engine = null; + private RiftsawServiceLocator _locator = null; + private java.util.Properties _config = null; + + + /** + * Constructs a new Activator of type "bpel". + * + * @param engine The BPEL engine + * @param locator The service locator + * @param config The properties + */ + public BPELActivator(BPELEngine engine, RiftsawServiceLocator locator, java.util.Properties config) { + super(BPEL_TYPE); + + _engine = engine; + _locator = locator; + _config = config; + } + + @Override + public ServiceHandler activateService(QName serviceName, ComponentModel config) { + + if (LOG.isDebugEnabled()) { + LOG.debug("Activate service: "+serviceName+" config="+config); + } + + BPELExchangeHandler handler = BPELExchangeHandlerFactory.instance().newBPELExchangeHandler(getServiceDomain()); + BPELComponentImplementationModel bciModel = (BPELComponentImplementationModel)config.getImplementation(); + ComponentServiceModel service = null; + for (ComponentServiceModel csm : config.getServices()) { + if (csm.getQName().equals(serviceName)) { + service = csm; + break; + } + } + + if ((service == null) || (service.getInterface() == null)) { + throw BPELMessages.MESSAGES.interfaceNotDefinedForComponentWithBPELImplementation(); + } + + // take care of references + for (ComponentReferenceModel crm : config.getReferences()) { + _locator.addServiceDomain(crm.getQName(), getServiceDomain()); + _locator.initialiseReference(crm); + } + + handler.init(serviceName, bciModel, + service.getInterface().getInterface(), _engine, _config); + + _handlers.put(serviceName, handler); + + return handler; + } + + @Override + public void deactivateService(QName name, ServiceHandler handler) { + if (LOG.isDebugEnabled()) { + LOG.debug("De-activate service: " + name + " handler=" + handler); + } + + _handlers.remove(name); + } + +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/deploy/BPELComponent.java b/components/bpel/src/main/java/org/switchyard/component/bpel/deploy/BPELComponent.java new file mode 100644 index 000000000..af1e73f2b --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/deploy/BPELComponent.java @@ -0,0 +1,237 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.deploy; + +import java.util.Properties; + +import org.jboss.logging.Logger; +import org.apache.ode.bpel.evt.BpelEvent; +import org.riftsaw.engine.BPELEngine; +import org.riftsaw.engine.BPELEngineListener; +import org.riftsaw.engine.ServiceLocator; +import org.switchyard.ServiceDomain; +import org.switchyard.component.bpel.riftsaw.RiftsawServiceLocator; +import org.switchyard.config.Configuration; +import org.switchyard.component.bpel.BPELLogger; +import org.switchyard.component.bpel.BPELMessages; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * An implementation of BPEL component. + */ +public class BPELComponent extends BaseComponent { + + private static final Logger LOG = Logger.getLogger(BPELComponent.class); + + private final BPELEngineInstance _bpelEngineInstance; + private static java.util.Properties _config; + private static BPELEngine _engine; + private static boolean _initialized; + + /** + * Default constructor. + */ + public BPELComponent() { + this(new BPELEngineInstanceImpl()); + } + + protected BPELComponent(BPELEngineInstance bpelEngineInstance) { + super(BPELActivator.BPEL_TYPE); + setName("BPELComponent"); + _bpelEngineInstance = bpelEngineInstance; + } + + /* (non-Javadoc) + * @see org.switchyard.deploy.Component#init(org.switchyard.config.Configuration) + */ + @Override + public void init(Configuration config) { + super.init(config); + + initConfig(); + } + + /** + * This method initializes the configuration information for use + * by the BPEL engine. + */ + protected void initConfig() { + synchronized (BPELComponent.class) { + if (_initialized) { + return; + } + + BPELLogger.ROOT_LOGGER.initBPELComponent(); + + ClassLoader current=Thread.currentThread().getContextClassLoader(); + + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + + try { + // Initialize the BPEL engine configuration + _config = new java.util.Properties(); + + // Load default properties + try { + java.io.InputStream is = getClass().getClassLoader().getResourceAsStream("bpel.properties"); + + _config.load(is); + } catch (Exception e) { + throw BPELMessages.MESSAGES.failedToLoadDefaultProperties(e); + } + + if (getConfig() != null) { + // Overwrite default properties with values from configuration + for (Configuration child : getConfig().getChildren()) { + if (LOG.isDebugEnabled()) { + if (_config.containsKey(child.getName())) { + LOG.debug("Overriding BPEL property: "+child.getName() + +" = "+child.getValue()); + } else { + LOG.debug("Setting BPEL property: "+child.getName() + +" = "+child.getValue()); + } + } + _config.put(child.getName(), child.getValue()); + } + } + _bpelEngineInstance.init(new RiftsawServiceLocator(), _config); + } finally { + Thread.currentThread().setContextClassLoader(current); + } + + _initialized = true; + } + } + + protected BPELEngine getEngine(final ServiceDomain domain) { + synchronized (BPELComponent.class) { + if (_engine == null) { + initConfig(); + try { + _engine = _bpelEngineInstance.getBPELEngine(); + } catch (Exception e) { + throw BPELMessages.MESSAGES.failedToInitializeTheEngine(e); + } + _engine.register(new BPELEngineListener() { + public void onEvent(BpelEvent bpelEvent) { + domain.getEventPublisher().publish(bpelEvent); + } + }); + } + } + return _engine; + } + + /** + * {@inheritDoc} + */ + @Override + public void destroy() { + super.destroy(); + + BPELLogger.ROOT_LOGGER.destroyBPELComponent(); + synchronized (BPELComponent.class) { + if (_engine != null) { + try { + synchronized (_engine) { + _bpelEngineInstance.dispose(); + _engine = null; + } + } catch (Exception e) { + BPELLogger.ROOT_LOGGER.failedToCloseBPELEngine(e); + } + } + } + } + + /* (non-Javadoc) + * @see org.switchyard.deploy.Component#createActivator(org.switchyard.ServiceDomain) + */ + @Override + public Activator createActivator(ServiceDomain domain) { + if (domain == null) { + throw new NullPointerException("domain cannot be null"); + } + + BPELEngine engine = getEngine(domain); + BPELActivator activator = new BPELActivator(engine, (RiftsawServiceLocator) engine.getServiceLocator(), _config); + activator.setServiceDomain(domain); + + return activator; + } + + /** + * Simple interface for managing the BPELEngine. + */ + protected static interface BPELEngineInstance { + + /** + * Initialize the factory. + * + * @param serviceLocator the service locator. + * @param config the configuration. + */ + public void init(ServiceLocator serviceLocator, java.util.Properties config); + + /** + * Returns the BPELEngine instance. + * + * @return the BPELEngine. + * @throws Exception if something goes awry. + */ + public BPELEngine getBPELEngine() throws Exception; + + /** + * Dispose any resources allocated by the factory. + * + * @throws Exception if something goes awry. + */ + public void dispose() throws Exception; + } + + private static final class BPELEngineInstanceImpl implements BPELEngineInstance { + + private BPELEngine _engine; + + @Override + public synchronized void init(ServiceLocator serviceLocator, Properties config) { + org.riftsaw.engine.BPELEngineFactory.setConfig(config); + org.riftsaw.engine.BPELEngineFactory.setServiceLocator(serviceLocator); + } + + @Override + public synchronized BPELEngine getBPELEngine() throws Exception { + if (_engine == null) { + final ClassLoader origTCCL = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + _engine = org.riftsaw.engine.BPELEngineFactory.getEngine(); + } finally { + Thread.currentThread().setContextClassLoader(origTCCL); + } + } + return _engine; + } + + @Override + public synchronized void dispose() throws Exception { + if (_engine != null) { + _engine.close(); + _engine = null; + } + } + } +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/exchange/BPELExchangeHandler.java b/components/bpel/src/main/java/org/switchyard/component/bpel/exchange/BPELExchangeHandler.java new file mode 100644 index 000000000..3b529a898 --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/exchange/BPELExchangeHandler.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.exchange; + +import javax.xml.namespace.QName; + +import org.riftsaw.engine.BPELEngine; +import org.switchyard.config.model.implementation.bpel.BPELComponentImplementationModel; +import org.switchyard.deploy.ServiceHandler; + +/** + * The ExchangeHandler for the BPEL component. + * + */ +public interface BPELExchangeHandler extends ServiceHandler { + + /** + * Initializes the BPELExchangeHandler. + * + * @param qname the qualified name + * @param model the configuration + * @param intf the WSDL interface details + * @param engine the BPEL engine + * @param config The configuration + */ + public void init(QName qname, BPELComponentImplementationModel model, + String intf, BPELEngine engine, java.util.Properties config); + +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/exchange/BPELExchangeHandlerFactory.java b/components/bpel/src/main/java/org/switchyard/component/bpel/exchange/BPELExchangeHandlerFactory.java new file mode 100644 index 000000000..07562674d --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/exchange/BPELExchangeHandlerFactory.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.exchange; + +import java.util.List; + +import org.switchyard.ServiceDomain; +import org.switchyard.common.util.ProviderRegistry; + +/** + * Creates BPELExchangeHandlers via the JDK ServiceLoader mechanism. + * + */ +public abstract class BPELExchangeHandlerFactory { + + private static final BPELExchangeHandlerFactory INSTANCE; + static { + List services = ProviderRegistry.getProviders(BPELExchangeHandlerFactory.class); + INSTANCE = services.iterator().next(); + } + + /** + * Creates a new BPELExchangeHandler in the specified ServiceDomain. + * + * @param serviceDomain the specified ServiceDomain + * @return the BPELExchangeHandler + */ + public abstract BPELExchangeHandler newBPELExchangeHandler(ServiceDomain serviceDomain); + + /** + * Returns the singleton instance of the BPELExchangeHandlerFactory. + * + * @return the singleton instance + */ + public static BPELExchangeHandlerFactory instance() { + return INSTANCE; + } + +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawBPELExchangeHandler.java b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawBPELExchangeHandler.java new file mode 100644 index 000000000..e40f923b6 --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawBPELExchangeHandler.java @@ -0,0 +1,385 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Timer; +import java.util.TimerTask; + +import javax.xml.namespace.QName; +import javax.xml.soap.Detail; +import javax.xml.soap.SOAPFault; + +import org.jboss.logging.Logger; +import org.riftsaw.engine.BPELEngine; +import org.riftsaw.engine.DeploymentRef; +import org.riftsaw.engine.Fault; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.ServiceDomain; +import org.switchyard.component.bpel.BPELMessages; +import org.switchyard.component.bpel.exchange.BPELExchangeHandler; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.component.bpel.BPELLogger; +import org.switchyard.config.model.implementation.bpel.BPELComponentImplementationModel; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.SwitchYardException; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * A Riftsaw implementation of a BPEL ExchangeHandler. + * + */ +public class RiftsawBPELExchangeHandler extends BaseServiceHandler implements BPELExchangeHandler { + + private static final int UNDEPLOY_DELAY = 10000; + + private static final String VFS_SCHEME = "vfs"; + + private static final String DEPLOY_XML = "deploy.xml"; + + private static final Logger LOG = + Logger.getLogger(RiftsawBPELExchangeHandler.class); + + private BPELEngine _engine = null; + private QName _serviceName = null; + private QName _processName = null; + private javax.wsdl.Definition _wsdl = null; + private javax.wsdl.PortType _portType = null; + private long _undeployDelay=UNDEPLOY_DELAY; + private BPELComponentImplementationModel _model; + private Properties _config; + + private static Map _serviceRefToCompositeMap= + new HashMap(); + private static Map _deployed= + new HashMap(); + private static Timer _timer=new Timer(); + private static List _undeployed=new ArrayList(); + + /** + * Constructs a new RiftSaw BPEL ExchangeHandler within the specified ServiceDomain. + * @param domain the service domain. + */ + public RiftsawBPELExchangeHandler(final ServiceDomain domain) { + super(domain); + } + + /** + * {@inheritDoc} + */ + public void init(QName qname, BPELComponentImplementationModel model, + String intf, BPELEngine engine, Properties config) { + + _engine = engine; + + _wsdl = WSDLHelper.getWSDLDefinition(intf); + + _portType = WSDLHelper.getPortType(intf, _wsdl); + + _serviceName = qname; + + _processName = model.getProcessQName(); + + _model = model; + + _config = config; + } + + /** + * This method returns the deployment name associated with the + * deployed app. + * + * @return The deployment name + * @throws Exception Failed to obtain the deployment name + */ + protected String getDeploymentName() throws Exception { + String ret=null; + + java.net.URL url = Thread.currentThread(). + getContextClassLoader().getResource(DEPLOY_XML); + + if (url != null) { + String urlpath=url.toString(); + + // Remove deploy.xml from end of path, removing an + // extra character for the path separator + urlpath = urlpath.substring(0, urlpath.length()-DEPLOY_XML.length()-1); + + int fileSeparatorIndex = urlpath.lastIndexOf('/'); + + if (fileSeparatorIndex != -1) { + ret = urlpath.substring(fileSeparatorIndex+1); + + int suffixIndex = ret.lastIndexOf('.'); + + if (suffixIndex != -1) { + ret = ret.substring(0, suffixIndex); + } + } else { + BPELLogger.ROOT_LOGGER.failedToObtainDeploymentNameFromURL(urlpath); + } + } else { + BPELLogger.ROOT_LOGGER.unableToLocateDeploymentDescriptorDeployXmlToDeriveDeploymentName(); + } + + if (LOG.isDebugEnabled()) { + BPELLogger.ROOT_LOGGER.deploymentNameIs(ret); + } + + return (ret); + } + + /** + * This method returns the file associated with the BPEL deployment + * archive or root folder. + * + * @return The deployment + * @throws Exception Failed to obtain deployment folder/archive + */ + protected java.io.File getDeployment() throws Exception { + java.io.File ret = null; + + java.net.URL url = Thread.currentThread(). + getContextClassLoader().getResource(DEPLOY_XML); + int index = url.toString().indexOf(".jar"); + + // Check if url contains a jar + if (index != -1) { + + if (url.getProtocol().equals(VFS_SCHEME)) { + // AS7 deployment + try { + org.jboss.vfs.VirtualFile vfile=org.jboss.vfs.VFS.getChild(url.toURI()); + + // Recursively get all files + List children=vfile.getParent().getChildrenRecursively(); + for (org.jboss.vfs.VirtualFile child : children) { + // Need to request the physical file to have it expanded + // on the file system + child.getPhysicalFile(); + } + + // Virtual file is for the deployment descriptor, so we need + // the parent file which represents the root of the deployment + ret = vfile.getPhysicalFile().getParentFile(); + + } catch (java.lang.NoClassDefFoundError t) { + BPELLogger.ROOT_LOGGER.unableToResolveTheDeploymentURL(t); + } + + } else { + throw BPELMessages.MESSAGES.unknownDeploymentEnvironment(); + } + } else { + // Retrieve parent folder of deployment descriptor + ret = new java.io.File(url.toURI()).getParentFile(); + } + + if (LOG.isDebugEnabled()) { + LOG.debug("Deployment=" + ret); + } + + return (ret); + } + + /** + * {@inheritDoc} + */ + protected void doStart() { + if (LOG.isDebugEnabled()) { + LOG.debug("START: " + _serviceName); + } + // Setup configuration + if (_config.containsKey("bpel.undeploy.delay")) { + try { + _undeployDelay = Long.parseLong(_config.getProperty("bpel.undeploy.delay")); + + } catch (Exception e) { + BPELLogger.ROOT_LOGGER.unableToTransformPropertyValueIntoUndeployDelayValue(e, _config.getProperty("bpel.undeploy.delay")); + } + } + + if (LOG.isDebugEnabled()) { + LOG.debug("Undeployment delay="+_undeployDelay+"ms"); + } + + // Check if composite is already been initialized for BPEL processes + QName compositeName = _model.getComponent().getComposite().getQName(); + + if (!_serviceRefToCompositeMap.containsValue(compositeName)) { + try { + java.io.File deployFile=getDeployment(); + + DeploymentRef ref=_engine.deploy(getDeploymentName(), deployFile); + + _deployed.put(_serviceName, ref); + + // Remove, in case marked for undeployment as part + // of replacing an existing deployed jar + _undeployed.remove(_serviceName); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + SwitchYardPropertyFunction.setPropertyResolver(_processName, _model.getModelConfiguration().getPropertyResolver()); + _serviceRefToCompositeMap.put(_serviceName, compositeName); + } + + /** + * {@inheritDoc} + */ + public void handleMessage(final Exchange exchange) throws HandlerException { + Message message = exchange.getMessage(); + Node request = message.getContent(Node.class); + + Map headers = new HashMap(); + for (Property p : exchange.getContext().getProperties()) { + if (p.hasLabel(EndpointLabel.SOAP.label())) { + headers.put(p.getName(), p.getValue()); + } + } + + try { + // Find part name associated with operation on port type + javax.wsdl.Operation operation = + _portType.getOperation(exchange.getContract(). + getProviderOperation().getName(), + null, null); + + Element newreq = + WSDLHelper.wrapRequestMessagePart((Element) request, + operation); + + // Invoke the operation on the BPEL process + Element response = _engine.invoke(_serviceName, null, + exchange.getContract(). + getProviderOperation().getName(), + newreq, headers); + + if (exchange.getContract().getProviderOperation(). + getExchangePattern().equals(ExchangePattern.IN_OUT)) { + + Message reply = exchange.createMessage(); + + // Strip off wrapper and part to just return + // the part contents + reply.setContent(WSDLHelper.unwrapMessagePart(response)); + + // Set header parts for a response message + for (Map.Entry e : headers.entrySet()) { + exchange.getContext(reply).setProperty(e.getKey(), + headers.get(e.getKey())).addLabels(EndpointLabel.SOAP.label()); + } + + exchange.send(reply); + } + } catch (Fault f) { + SOAPFault fault = null; + + try { + fault = javax.xml.soap.SOAPFactory.newInstance(). + createFault("", f.getFaultName()); + + Detail detail=fault.addDetail(); + Node cloned=detail.getOwnerDocument().importNode(WSDLHelper.unwrapMessagePart(f.getFaultMessage()), true); + detail.appendChild(cloned); + + } catch (Exception e) { + throw new HandlerException(e); + } + + Message msg = exchange.createMessage().setContent(fault); + exchange.sendFault(msg); + + } catch (Exception e) { + throw new HandlerException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + protected void doStop() { + if (LOG.isDebugEnabled()) { + LOG.debug("STOP: " + _serviceName); + } + + _undeployed.add(_serviceName); + + if (_undeployDelay > 0) { + _timer.schedule(new TimerTask() { + public void run() { + undeploy(); + } + + }, _undeployDelay); + } else { + undeploy(); + } + + _serviceRefToCompositeMap.remove(_serviceName); + } + + private void undeploy() { + synchronized (_undeployed) { + if (LOG.isDebugEnabled()) { + LOG.debug("Checking whether to undeploy '" + +_serviceName+"'"); + } + + if (_undeployed.contains(_serviceName) + && _deployed.containsKey(_serviceName)) { + DeploymentRef ref=_deployed.get(_serviceName); + + if (LOG.isDebugEnabled()) { + LOG.debug("Undeploy '" + +_serviceName+"' with ref: "+ref); + } + + if (ref != null) { + try { + _engine.undeploy(ref); + } catch (Exception e) { + BPELLogger.ROOT_LOGGER.failedToUndeploy(_serviceName, e); + } + } + + _deployed.remove(_serviceName); + _undeployed.remove(_serviceName); + } + SwitchYardPropertyFunction.removePropertyResolver(_processName); + } + } + + /** + * {@inheritDoc} + */ + public void destroy() { + if (LOG.isDebugEnabled()) { + LOG.debug("DESTROY: " + _serviceName); + } + } + +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawBPELExchangeHandlerFactory.java b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawBPELExchangeHandlerFactory.java new file mode 100644 index 000000000..a08f2b44f --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawBPELExchangeHandlerFactory.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.bpel.exchange.BPELExchangeHandler; +import org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory; + +/** + * The factory for RiftsawBPELExchangeHandler. + */ +public class RiftsawBPELExchangeHandlerFactory extends BPELExchangeHandlerFactory { + + /** + * {@inheritDoc} + */ + @Override + public BPELExchangeHandler newBPELExchangeHandler(ServiceDomain serviceDomain) { + return new RiftsawBPELExchangeHandler(serviceDomain); + } + +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawServiceLocator.java b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawServiceLocator.java new file mode 100644 index 000000000..e0b84f759 --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/RiftsawServiceLocator.java @@ -0,0 +1,324 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPFault; + +import org.jboss.logging.Logger; +import org.riftsaw.engine.Fault; +import org.riftsaw.engine.Service; +import org.riftsaw.engine.ServiceLocator; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangeState; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.component.bpel.BPELFault; +import org.switchyard.config.model.implementation.bpel.BPELComponentImplementationModel; +import org.switchyard.component.bpel.BPELLogger; +import org.switchyard.component.bpel.BPELMessages; +import org.switchyard.component.common.DeliveryException; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.deploy.ComponentNames; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * This class implements the service locator interface to retrieve a + * reference to an external service (provided by switchyard) for use + * by a BPEL process instance. + * + */ +public class RiftsawServiceLocator implements ServiceLocator { + + private static final Logger LOG = Logger.getLogger(RiftsawServiceLocator.class); + + private static final long DEFAULT_TIMEOUT = 120000; + + private Map _serviceDomains = new HashMap(); + private java.util.Map _registry=new java.util.HashMap(); + private long _waitTimeout = DEFAULT_TIMEOUT; + + /** + * This is the constructor for the riftsaw service locator. + * + */ + public RiftsawServiceLocator() { + } + + /** + * Add a service -> service domain mapping. + * @param serviceName service name + * @param serviceDomain The service domain + */ + public void addServiceDomain(QName serviceName, ServiceDomain serviceDomain) { + _serviceDomains.put(serviceName, serviceDomain); + } + + /** + * Remove a service -> service domain mapping. + * @param serviceName the service name + */ + public void removeServiceDomain(QName serviceName) { + _serviceDomains.remove(serviceName); + } + + /** + * This method returns the service domain for a given service. + * @param serviceName service name + * @return The service domain + */ + public ServiceDomain getServiceDomain(QName serviceName) { + return _serviceDomains.get(serviceName); + } + + /** + * This method returns the service associated with the supplied + * process, service and port. + * + * @param processName The process name + * @param serviceName The service name + * @param portName The port name + * @return The service or null if not found + */ + public Service getService(QName processName, QName serviceName, String portName) { + // Currently need to just use the local part, without the version number, to + // lookup the registry entry + int index=processName.getLocalPart().indexOf('-'); + QName localProcessName=new QName(processName.getNamespaceURI(), + processName.getLocalPart().substring(0, index)); + + RegistryEntry re=_registry.get(localProcessName); + + if (re == null) { + BPELLogger.ROOT_LOGGER.noServiceReferencesFoundForProcess(localProcessName.toString()); + return (null); + } + + Service ret=re.getService(serviceName, portName, _serviceDomains.get(serviceName)); + + if (ret == null) { + BPELLogger.ROOT_LOGGER.noServiceFoundFor(serviceName.toString(), portName); + } + + return (ret); + } + + /** + * This method registers a component reference against the service BPEL + * process, for use when it calls out to the external service. + * + * @param crm The component reference + */ + public void initialiseReference(ComponentReferenceModel crm) { + + // Find the BPEL implementation associated with the reference + if (crm.getComponent() != null + && crm.getComponent().getImplementation() instanceof BPELComponentImplementationModel) { + BPELComponentImplementationModel impl= + (BPELComponentImplementationModel)crm.getComponent().getImplementation(); + + QName processName=impl.getProcessQName(); + + if (LOG.isDebugEnabled()) { + LOG.debug("Register reference "+crm.getName()+" ("+crm.getQName()+") for process "+processName); + } + + RegistryEntry re=_registry.get(processName); + + if (re == null) { + re = new RegistryEntry(); + _registry.put(processName, re); + } + + javax.wsdl.Definition wsdl=WSDLHelper.getWSDLDefinition(crm.getInterface().getInterface()); + javax.wsdl.PortType portType=WSDLHelper.getPortType(crm.getInterface().getInterface(), wsdl); + + re.register(portType, crm.getQName(), crm.getComponent().getQName()); + + } else { + throw BPELMessages.MESSAGES.couldNotFindBPELImplementationAssociatedWithReference(); + } + + } + + /** + * This class provides a registry entry for use in looking up the + * appropriate service to use for an external BPEL invoke. + * + */ + public class RegistryEntry { + + private java.util.List _portTypes= + new java.util.Vector(); + private java.util.List _services= + new java.util.Vector(); + + private QName _componentName; + + /** + * This method registers the wsdl, port type and service details. + * + * @param portType The port type + * @param service The SwitchYard service + * @param componentName the service component name for this registry entry + */ + public void register(javax.wsdl.PortType portType, QName service, QName componentName) { + _portTypes.add(portType); + _services.add(service); + _componentName = componentName; + } + + /** + * This method returns the service associated with the supplied service and + * port names. + * + * @param serviceName The service name + * @param portName The port name + * @param serviceDomain The service domain + * @return The service or null if not found + */ + public Service getService(QName serviceName, String portName, ServiceDomain serviceDomain) { + Service ret = null; + for (int index = 0, count = _services.size(); index < count; ++index) { + if (serviceName.equals(_services.get(index))) { + QName refName = ComponentNames.qualify(_componentName, serviceName); + ServiceReference sref = serviceDomain.getServiceReference(refName); + if (sref != null) { + ret = new ServiceProxy(sref, _portTypes.get(index)); + } + break; + } + } + if (ret == null) { + BPELLogger.ROOT_LOGGER.noServiceFoundFor(serviceName.toString()); + } + return ret; + } + } + + /** + * This class represents a service proxy, used by the BPEL engine to invoke + * and external service. The proxy intercepts the request and applies + * it to the appropriate switchyard service. + * + */ + public class ServiceProxy implements Service { + + private ServiceReference _serviceReference=null; + private javax.wsdl.PortType _portType=null; + + /** + * The constructor for the service proxy. + * + * @param sref The service reference + * @param portType The port type + */ + public ServiceProxy(ServiceReference sref, javax.wsdl.PortType portType) { + _serviceReference = sref; + _portType = portType; + } + + /** + * {@inheritDoc} + */ + public Element invoke(String operationName, Element mesg, + Map headers) throws Exception { + + // Unwrap the first two levels, to remove the part wrapper + Node node=WSDLHelper.unwrapMessagePart(mesg); + + // Need to create an exchange + SynchronousInOutHandler rh = new SynchronousInOutHandler(); + Exchange exchange=_serviceReference.createExchange(operationName, rh); + + Message req = exchange.createMessage(); + req.setContent(node); + if (headers != null) { + + for (Map.Entry e : headers.entrySet()) { + exchange.getContext(req).setProperty(e.getKey(), headers.get(e.getKey())).addLabels(EndpointLabel.SOAP.label()); + + } + + // Clear the headers in preparation for response headers + headers.clear(); + } + + exchange.send(req); + + javax.wsdl.Operation operation=_portType.getOperation(operationName, null, null); + Element newresp = null; + Element respelem = null; + if (ExchangePattern.IN_OUT.equals(exchange.getContract().getConsumerOperation().getExchangePattern())) { + try { + exchange = rh.waitForOut(_waitTimeout); + } catch (DeliveryException e) { + throw BPELMessages.MESSAGES.timedOutAfterMsWaitingOnSynchronousResponseFromTargetService(_waitTimeout, _serviceReference.getName().toString()); + } + + Message resp=exchange.getMessage(); + + if (resp == null) { + throw BPELMessages.MESSAGES.responseNotReturnedFromOperationOnService(operationName, _serviceReference.getName().toString()); + } + + // Process header values associated with the response + for (org.switchyard.Property p : exchange.getContext().getProperties(Scope.MESSAGE)) { + if (p.hasLabel(EndpointLabel.SOAP.label())) { + headers.put(p.getName(), p.getValue()); + } + } + + // Check for exception - but don't rethrow a BPEL + // fault as it will be converted to a message + // response + if (resp.getContent() instanceof Exception + && !(resp.getContent() instanceof BPELFault)) { + throw (Exception)resp.getContent(); + } + + respelem = (Element)resp.getContent(Node.class); + newresp=WSDLHelper.wrapResponseMessagePart(respelem, operation); + + } + + if (exchange.getState() == ExchangeState.FAULT) { + QName faultCode=null; + + if ((respelem != null) && (respelem instanceof SOAPFault)) { + SOAPFault fault=(SOAPFault)respelem; + + respelem = (Element)fault.getDetail().getFirstChild(); + + faultCode = fault.getFaultCodeAsQName(); + } + + Element newfault=WSDLHelper.wrapFaultMessagePart(respelem, operation, null); + throw new Fault(faultCode, newfault); + } + + return ((Element)newresp); + } + } + +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/SwitchYardPropertyFunction.java b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/SwitchYardPropertyFunction.java new file mode 100644 index 000000000..b3a5a9959 --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/SwitchYardPropertyFunction.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import java.util.HashMap; +import java.util.Map; +import javax.xml.namespace.QName; + +import org.switchyard.common.property.PropertyResolver; + +/** + * The custom XPath function which resolves SwitchYard properties referenced from BPEL process definition. + */ +public final class SwitchYardPropertyFunction { + + private static final Map PROPERTY_RESOLVERS = new HashMap(); + + private SwitchYardPropertyFunction() {} + + /** + * Sets PropertyResolver instance. + * @param processName BPEL process QName + * @param resolver PropertyResolver instance + */ + public static final void setPropertyResolver(QName processName, PropertyResolver resolver) { + PROPERTY_RESOLVERS.put(processName, resolver); + } + + /** + * Removes a PropertyResolver for the specified process. + * @param processName BPEL process QName + */ + public static final void removePropertyResolver(QName processName) { + PROPERTY_RESOLVERS.remove(processName); + } + + /** + * Resolves a property. + * @param processName BPEL process QName + * @param key property name + * @return property value + */ + public static final Object resolveProperty(QName processName, Object key) { + PropertyResolver resolver = PROPERTY_RESOLVERS.get(processName); + if (resolver == null) { + return null; + } + return resolver.resolveProperty(key.toString()); + } +} diff --git a/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/WSDLHelper.java b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/WSDLHelper.java new file mode 100644 index 000000000..f925a4b1d --- /dev/null +++ b/components/bpel/src/main/java/org/switchyard/component/bpel/riftsaw/WSDLHelper.java @@ -0,0 +1,277 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.SwitchYardException; +import org.switchyard.component.bpel.BPELMessages; +import org.w3c.dom.Element; + +/** + * WSDL Helper. + * + */ +public final class WSDLHelper { + + private static final Logger LOG = Logger.getLogger(WSDLHelper.class); + + private static final String WSDL_PORTTYPE_PREFIX = "#wsdl.porttype("; + + private WSDLHelper() { + } + + /** + * This method returns the WSDL definition defined by the location. + * + * @param location the location + * @return The WSDL definition or null if not found + * @throws SwitchYardException Failed to locate WSDL + */ + public static javax.wsdl.Definition getWSDLDefinition(String location) throws SwitchYardException { + javax.wsdl.Definition ret=null; + + if (location == null) { + throw BPELMessages.MESSAGES.wSDLLocationHasNotBeenSpecified(); + } else { + try { + int index=location.indexOf('#'); + + if (index != -1) { + location = location.substring(0, index); + } + + java.net.URL url=Thread.currentThread().getContextClassLoader().getResource(location); + + ret = javax.wsdl.factory.WSDLFactory.newInstance().newWSDLReader().readWSDL(url.toString()); + + } catch (Exception e) { + throw BPELMessages.MESSAGES.failedToLoadWSDL(location, e); + } + } + + return (ret); + } + + /** + * This method returns the port type associated with the supplied wsdl and location. + * + * @param location The location + * @param wsdl The wsdl + * @return The port type + * @throws SwitchYardException Failed to get port type + */ + public static javax.wsdl.PortType getPortType(String location, javax.wsdl.Definition wsdl) + throws SwitchYardException { + javax.wsdl.PortType ret=null; + + if (location == null) { + throw BPELMessages.MESSAGES.wSDLLocationHasNotBeenSpecified(); + } else { + int index=location.indexOf(WSDL_PORTTYPE_PREFIX); + + if (index != -1) { + String portTypeName = location.substring(index+WSDL_PORTTYPE_PREFIX.length(), location.length() - 1); + + ret = wsdl.getPortType(new QName(wsdl.getTargetNamespace(), portTypeName)); + } + } + + return (ret); + } + + /** + * This method returns the service associated with the supplied port type from the + * supplied WSDL. + * + * @param portType The port type + * @param wsdl The wsdl + * @return The service, or null if not found + */ + public static javax.wsdl.Service getServiceForPortType(javax.wsdl.PortType portType, + javax.wsdl.Definition wsdl) { + javax.wsdl.Service ret=null; + + java.util.Iterator iter=wsdl.getServices().values().iterator(); + while (ret == null && iter.hasNext()) { + ret = (javax.wsdl.Service)iter.next(); + + java.util.Iterator ports=ret.getPorts().values().iterator(); + boolean f_found=false; + + while (!f_found && ports.hasNext()) { + javax.wsdl.Port port=(javax.wsdl.Port)ports.next(); + + if (port.getBinding().getPortType() == portType) { + f_found = true; + } + } + + if (!f_found) { + ret = null; + } + } + + return (ret); + } + + /** + * This method removes the message content from its part wrapper. + * + * @param content The wrapped part + * @return The unwrapped content + */ + public static org.w3c.dom.Node unwrapMessagePart(org.w3c.dom.Element content) { + + org.w3c.dom.NodeList nl=content.getChildNodes(); + + for (int i=0; i < nl.getLength(); i++) { + + if (nl.item(i) instanceof org.w3c.dom.Element) { + + org.w3c.dom.NodeList nl2=((org.w3c.dom.Element)nl.item(i)).getChildNodes(); + + for (int j=0; j < nl2.getLength(); j++) { + + if (nl2.item(j) instanceof org.w3c.dom.Element) { + return ((org.w3c.dom.Node)nl2.item(j)); + } + } + + if (nl2.getLength() > 0) { + return (nl2.item(0)); + } + + return (null); + } + } + + return (null); + } + + /** + * This method wraps a request message content in a part wrapper. + * + * @param content The message + * @param operation The operation + * @return The part wrapper associated with the operation + */ + public static org.w3c.dom.Element wrapRequestMessagePart(org.w3c.dom.Element content, + javax.wsdl.Operation operation) { + return (wrapMessagePart(content, operation, operation.getInput().getMessage().getParts(), false)); + } + + /** + * This method wraps a response message content in a part wrapper. + * + * @param content The message + * @param operation The operation + * @return The part wrapper associated with the operation + */ + public static org.w3c.dom.Element wrapResponseMessagePart(org.w3c.dom.Element content, + javax.wsdl.Operation operation) { + return (wrapMessagePart(content, operation, operation.getOutput().getMessage().getParts(), false)); + } + + /** + * This method wraps a fault message content in a part wrapper. + * + * @param content The message + * @param operation The operation + * @param faultName The fault + * @return The part wrapper associated with the operation and fault + */ + public static org.w3c.dom.Element wrapFaultMessagePart(org.w3c.dom.Element content, + javax.wsdl.Operation operation, String faultName) { + java.util.Map parts=null; + + if (faultName != null) { + javax.wsdl.Fault fault=operation.getFault(faultName); + + if (fault == null) { + throw BPELMessages.MESSAGES.unableToFindFaultOn(faultName, operation.getName()); + } + + parts = fault.getMessage().getParts(); + } else { + // Need to iterate through faults to determine which has a part with the + // appropriate element type + @SuppressWarnings({ "unchecked" }) + java.util.Iterator iter= + (java.util.Iterator)operation.getFaults().values().iterator(); + + while (parts == null && iter.hasNext()) { + javax.wsdl.Fault fault=iter.next(); + + if (fault.getMessage().getParts().size() == 1) { + javax.wsdl.Part part=(javax.wsdl.Part)fault.getMessage().getParts().values().iterator().next(); + + if (part.getElementName() != null + && content.getLocalName().equals(part.getElementName().getLocalPart()) + && content.getNamespaceURI().equals(part.getElementName().getNamespaceURI())) { + + parts = fault.getMessage().getParts(); + } + } + } + } + + return (wrapMessagePart(content, operation, parts, true)); + } + + /** + * This method wraps a message content in a part wrapper. + * + * @param content The message + * @param operation The operation + * @param parts The parts map + * @param fault Whether dealing with a fault + * @return The part wrapper associated with the operation + */ + protected static org.w3c.dom.Element wrapMessagePart(org.w3c.dom.Element content, + javax.wsdl.Operation operation, java.util.Map parts, boolean fault) { + org.w3c.dom.Element ret=content.getOwnerDocument().createElement("message"); + String partName=null; + + // Find part name from content type for the operation + if (parts != null) { + if (parts.size() != 1) { + throw BPELMessages.MESSAGES.onlyExpectingASingleMessagePartForOperation(operation.getName()); + } + + partName = (String)parts.keySet().iterator().next(); + } + + if (partName == null) { + if (LOG.isDebugEnabled()) { + LOG.debug("No part found for operation: "+operation+" and content: "+content); + } + + if (!fault) { + throw BPELMessages.MESSAGES.unableToFindPartNameFor(operation.getName()); + } + + // Assume that this represents an undeclared fault, and therefore return as an + // element instead of a message (RIFTSAW-516) + return (content); + } + + Element part=ret.getOwnerDocument().createElement(partName); + ret.appendChild(part); + part.appendChild(content); + + return (ret); + } +} diff --git a/components/bpel/src/main/resources/META-INF/services/org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory b/components/bpel/src/main/resources/META-INF/services/org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory new file mode 100644 index 000000000..f4687b9a6 --- /dev/null +++ b/components/bpel/src/main/resources/META-INF/services/org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.bpel.riftsaw.RiftsawBPELExchangeHandlerFactory diff --git a/components/bpel/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/bpel/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..64eba2563 --- /dev/null +++ b/components/bpel/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.bpel.deploy.BPELComponent diff --git a/components/bpel/src/main/resources/META-INF/switchyard/transforms.xml b/components/bpel/src/main/resources/META-INF/switchyard/transforms.xml new file mode 100644 index 000000000..a3e5d0d00 --- /dev/null +++ b/components/bpel/src/main/resources/META-INF/switchyard/transforms.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + diff --git a/components/bpel/src/main/resources/bpel.properties b/components/bpel/src/main/resources/bpel.properties new file mode 100644 index 000000000..d3776d401 --- /dev/null +++ b/components/bpel/src/main/resources/bpel.properties @@ -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. +# + +## bpel Configuration Properties + +bpel.dao.factory=org.apache.ode.dao.jpa.hibernate.BpelDAOConnectionFactoryImpl +bpel.dao.factory.store=org.apache.ode.dao.jpa.hibernate.ConfStoreDAOConnectionFactoryImpl +bpel.dao.factory.scheduler=org.apache.ode.dao.jpa.hibernate.SchedulerDAOConnectionFactoryImpl +bpel.cache.provider=org.riftsaw.engine.internal.InfinispanCacheProvider + +bpel.tx.factory.class = org.riftsaw.engine.jboss.JBossTransactionFactory + +bpel.db.mode=EMBEDDED +db.emb.create=false +bpel.db.ext.dataSource=java:BPELDB + +# all hibernate specific properties + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.hbm2ddl.auto=none +hibernate.current_session_context_class=jta +hibernate.show_sql=false +hibernate.connection.isolation=2 +hibernate.jdbc.batch_size=20 + +jta.UserTransaction=UserTransaction + +ode.persistence=hibernate + +# +# Comma separated list of BPEL event listeners. +# BPAFLogAdapter is used to store BPEL events for historic analysis. +# +bpel.event.listeners=org.jboss.soa.bpel.console.bpaf.BPAFLogAdapter +#bpel.event.listeners= + +# Property used to configure whether ODE should store the BPEL events in its default location +# (Set to false, as RiftSaw uses the BPEL events stored by the BPAFLogAdapter) +persist.bpel.events = false + +# Determines if even top level transaction based ODE invokes should bypass the scheduler +# If false, then top level invokes will be scheduled, but subsequent nested invokes (to +# external services in same thread) will be directly invoked instead of via the scheduler. +# NOTE: Currently disabled, as the mechanism bypasses the mex.timeout guard and also has +# issues when dealing with correlation, where messages are received out of order. +#bpel.invoke.immediate=false + +#Configure the scheduler node name +bpel.riftsaw.node.name=riftsaw-scheduler-node + +#Configure the cache name from the infinispan module for the ProcessConf cache +bpel.cache-name=cluster diff --git a/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELInOnlyLocatorTest.java b/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELInOnlyLocatorTest.java new file mode 100644 index 000000000..8671f694b --- /dev/null +++ b/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELInOnlyLocatorTest.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.transform.config.model.TransformSwitchYardScanner; + +/* + * This test is in response to SWITCHYARD-2311. It uses a modified version + * of the loan approval / risk assessment processes which do not return a response, + * and triggers the creation of an IN_ONLY exchange in RiftsawServiceLocator. + */ +@SwitchYardTestCaseConfig( + config = "/loan2_approval/switchyard.xml", + scanners = {TransformSwitchYardScanner.class }, + mixins = {CDIMixIn.class, HTTPMixIn.class }) +public class BPELInOnlyLocatorTest { + + private SwitchYardTestKit _testKit; + + @org.junit.Before + public void init() { + try { + _testKit = new SwitchYardTestKit(this); + _testKit.start(); + } catch(Exception e) { + e.printStackTrace(); + fail("Unable to initialize testkit: "+ e); + } + } + + @org.junit.After + public void close() { + if (_testKit != null) { + try { + _testKit.cleanup(); + } catch(Exception e) { + e.printStackTrace(); + fail("Unable to cleanup testkit: "+ e); + } + } + } + + @Test + public void sendLoanRequest1() throws Exception { + String msg = "" + + "" + + "" + + "Fred" + + "Bloggs" + + "100" + + "" + + ""; + + String result = _testKit.getMixIn(HTTPMixIn.class). + postResourceAndTestXML("http://localhost:18001/loan2Service", + "/loan2_approval/soap-loanreq1.xml", "/loan2_approval/soap-loanresp1.xml"); + } + +} diff --git a/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELLoanApprovalTest.java b/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELLoanApprovalTest.java new file mode 100644 index 000000000..7d72a603d --- /dev/null +++ b/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELLoanApprovalTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.transform.config.model.TransformSwitchYardScanner; + +@SwitchYardTestCaseConfig( + config = "/loan_approval/switchyard.xml", + scanners = {TransformSwitchYardScanner.class }, + mixins = {CDIMixIn.class, HTTPMixIn.class }) +public class BPELLoanApprovalTest { + + private SwitchYardTestKit _testKit; + + @org.junit.Before + public void init() { + try { + _testKit = new SwitchYardTestKit(this); + _testKit.start(); + } catch(Exception e) { + e.printStackTrace(); + fail("Unable to initialize testkit: "+ e); + } + } + + @org.junit.After + public void close() { + if (_testKit != null) { + try { + _testKit.cleanup(); + } catch(Exception e) { + e.printStackTrace(); + fail("Unable to cleanup testkit: "+ e); + } + } + } + + @Test + public void sendLoanRequest1() throws Exception { + _testKit.getMixIn(HTTPMixIn.class). + postResourceAndTestXML("http://localhost:18001/loanService", + "/loan_approval/soap-loanreq1.xml", "/loan_approval/soap-loanresp1.xml"); + } + + + @Test + public void sendLoanRequest2() throws Exception { + _testKit.getMixIn(HTTPMixIn.class). + postResourceAndTestXML("http://localhost:18001/loanService", + "/loan_approval/soap-loanreq2.xml", "/loan_approval/soap-loanresp2.xml"); + } +} diff --git a/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELSayHelloTest.java b/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELSayHelloTest.java new file mode 100644 index 000000000..3ae67d13b --- /dev/null +++ b/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/BPELSayHelloTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import org.junit.Test; +import org.switchyard.test.SwitchYardTestKit; + +import static org.junit.Assert.*; + +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.transform.config.model.TransformSwitchYardScanner; + +@SwitchYardTestCaseConfig( + config = "/say_hello/switchyard.xml", + scanners = {TransformSwitchYardScanner.class }, + mixins = {CDIMixIn.class, HTTPMixIn.class }) +public class BPELSayHelloTest { + + private SwitchYardTestKit _testKit; + + @org.junit.Before + public void init() { + try { + _testKit = new SwitchYardTestKit(this); + _testKit.start(); + } catch(Exception e) { + fail("Unable to initialize testkit"); + } + } + + @org.junit.After + public void close() { + if (_testKit != null) { + try { + _testKit.cleanup(); + } catch(Exception e) { + e.printStackTrace(); + fail("Unable to cleanup testkit: "+ e); + } + } + } + + @Test + public void invokeSayHelloService() throws Exception { + _testKit.getMixIn(HTTPMixIn.class). + postResourceAndTestXML("http://localhost:18001/SayHelloService", + "/say_hello/soap-request.xml", "/say_hello/soap-response.xml"); + } +} diff --git a/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/WSDLHelperTest.java b/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/WSDLHelperTest.java new file mode 100644 index 000000000..b73cabead --- /dev/null +++ b/components/bpel/src/test/java/org/switchyard/component/bpel/riftsaw/WSDLHelperTest.java @@ -0,0 +1,262 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.riftsaw; + +import static org.junit.Assert.*; + +import javax.xml.namespace.QName; + +import org.apache.ode.utils.DOMUtils; +import org.junit.Test; +import org.w3c.dom.Text; + +public class WSDLHelperTest { + + @Test + public void testUnwrapMessagePart() { + String content="content"; + String xml="<"+content+"/>"; + + try { + org.w3c.dom.Element elem=DOMUtils.stringToDOM(xml); + + org.w3c.dom.Node unwrapped=WSDLHelper.unwrapMessagePart(elem); + + if (unwrapped == null) { + fail("Result is null"); + } + + if (unwrapped.getNodeName().equals(content) == false) { + fail("Unexpected unwrapped content: "+unwrapped.getNodeName()); + } + } catch(Exception e) { + fail("Failed: "+e); + } + } + + @Test + public void testUnwrapMessagePartText() { + String content="content"; + String xml=""+content+""; + + try { + org.w3c.dom.Element elem=DOMUtils.stringToDOM(xml); + + org.w3c.dom.Node unwrapped=WSDLHelper.unwrapMessagePart(elem); + + if (unwrapped == null) { + fail("Result is null"); + } + + if (!(unwrapped instanceof Text)) { + fail("Context was not Text"); + } + + if (((Text)unwrapped).getTextContent().equals(content) == false) { + fail("Unexpected unwrapped content: "+((Text)unwrapped).getTextContent()); + } + } catch(Exception e) { + fail("Failed: "+e); + } + } + + @Test + public void testUnwrapMessagePartWhitespace() { + String content="content"; + String xml="\r\n <"+content+"/>\r\n"; + + try { + org.w3c.dom.Element elem=DOMUtils.stringToDOM(xml); + + org.w3c.dom.Node unwrapped=WSDLHelper.unwrapMessagePart(elem); + + if (unwrapped == null) { + fail("Result is null"); + } + + if (unwrapped.getNodeName().equals(content) == false) { + fail("Unexpected unwrapped content: "+unwrapped.getNodeName()); + } + } catch(Exception e) { + fail("Failed: "+e); + } + } + + @Test + public void testWrapRequestMessagePart() { + try { + java.net.URL url=WSDLHelperTest.class.getResource("/tests/wsdl/LoanService.wsdl"); + + javax.wsdl.Definition wsdl=javax.wsdl.factory.WSDLFactory.newInstance().newWSDLReader().readWSDL(url.getFile()); + + javax.wsdl.PortType portType= + wsdl.getPortType(QName.valueOf("{http://example.com/loan-approval/loanService/}loanServicePT")); + if (portType == null) { + fail("Unable to get port type"); + } + + javax.wsdl.Operation op=portType.getOperation("request", null, null); + + if (op == null) { + fail("Unable to get operation 'request'"); + } + + String content="content"; + String xml="<"+content+"/>"; + + org.w3c.dom.Element elem=DOMUtils.stringToDOM(xml); + + org.w3c.dom.Element wrapped=WSDLHelper.wrapRequestMessagePart(elem, op); + + if (wrapped == null) { + fail("Result is null"); + } + + if (wrapped.getFirstChild().getNodeName().equals("reqpart") == false) { + fail("Part name was not 'reqpart': "+wrapped.getFirstChild().getNodeName()); + } + + if (wrapped.getFirstChild().getFirstChild().getNodeName().equals(content) == false) { + fail("Content was not '"+content+"': "+wrapped.getFirstChild().getFirstChild().getNodeName()); + } + } catch(Exception e) { + fail("Failed: "+e); + } + } + + @Test + public void testWrapResponseMessagePart() { + try { + java.net.URL url=WSDLHelperTest.class.getResource("/tests/wsdl/LoanService.wsdl"); + + javax.wsdl.Definition wsdl=javax.wsdl.factory.WSDLFactory.newInstance().newWSDLReader().readWSDL(url.getFile()); + + javax.wsdl.PortType portType= + wsdl.getPortType(QName.valueOf("{http://example.com/loan-approval/loanService/}loanServicePT")); + if (portType == null) { + fail("Unable to get port type"); + } + + javax.wsdl.Operation op=portType.getOperation("request", null, null); + + if (op == null) { + fail("Unable to get operation 'request'"); + } + + String content="content"; + String xml="<"+content+"/>"; + + org.w3c.dom.Element elem=DOMUtils.stringToDOM(xml); + + org.w3c.dom.Element wrapped=WSDLHelper.wrapResponseMessagePart(elem, op); + + if (wrapped == null) { + fail("Result is null"); + } + + if (wrapped.getFirstChild().getNodeName().equals("resppart") == false) { + fail("Part name was not 'resppart': "+wrapped.getFirstChild().getNodeName()); + } + + if (wrapped.getFirstChild().getFirstChild().getNodeName().equals(content) == false) { + fail("Content was not '"+content+"': "+wrapped.getFirstChild().getFirstChild().getNodeName()); + } + } catch(Exception e) { + fail("Failed: "+e); + } + } + + @Test + public void testWrapFaultMessagePartWithName() { + try { + java.net.URL url=WSDLHelperTest.class.getResource("/tests/wsdl/LoanService.wsdl"); + + javax.wsdl.Definition wsdl=javax.wsdl.factory.WSDLFactory.newInstance().newWSDLReader().readWSDL(url.getFile()); + + javax.wsdl.PortType portType= + wsdl.getPortType(QName.valueOf("{http://example.com/loan-approval/loanService/}loanServicePT")); + if (portType == null) { + fail("Unable to get port type"); + } + + javax.wsdl.Operation op=portType.getOperation("request", null, null); + + if (op == null) { + fail("Unable to get operation 'request'"); + } + + String content="content"; + String xml="<"+content+"/>"; + + org.w3c.dom.Element elem=DOMUtils.stringToDOM(xml); + + org.w3c.dom.Element wrapped=WSDLHelper.wrapFaultMessagePart(elem, op, "unableToHandleRequest"); + + if (wrapped == null) { + fail("Result is null"); + } + + if (wrapped.getFirstChild().getNodeName().equals("errorCode") == false) { + fail("Part name was not 'errorCode': "+wrapped.getFirstChild().getNodeName()); + } + + if (wrapped.getFirstChild().getFirstChild().getNodeName().equals(content) == false) { + fail("Content was not '"+content+"': "+wrapped.getFirstChild().getFirstChild().getNodeName()); + } + } catch(Exception e) { + fail("Failed: "+e); + } + } + + @Test + public void testWrapFaultMessagePartWithoutName() { + try { + java.net.URL url=WSDLHelperTest.class.getResource("/tests/wsdl/LoanService.wsdl"); + + javax.wsdl.Definition wsdl=javax.wsdl.factory.WSDLFactory.newInstance().newWSDLReader().readWSDL(url.getFile()); + + javax.wsdl.PortType portType= + wsdl.getPortType(QName.valueOf("{http://example.com/loan-approval/loanService/}loanServicePT")); + if (portType == null) { + fail("Unable to get port type"); + } + + javax.wsdl.Operation op=portType.getOperation("request", null, null); + + if (op == null) { + fail("Unable to get operation 'request'"); + } + + String xml=""; + + org.w3c.dom.Element elem=DOMUtils.stringToDOM(xml); + + org.w3c.dom.Element wrapped=WSDLHelper.wrapFaultMessagePart(elem, op, null); + + if (wrapped == null) { + fail("Result is null"); + } + + if (wrapped.getFirstChild().getNodeName().equals("errorCode") == false) { + fail("Part name was not 'errorCode': "+wrapped.getFirstChild().getNodeName()); + } + + if (wrapped.getFirstChild().getFirstChild().getNodeName().equals(elem.getNodeName()) == false) { + fail("Content was not '"+elem.getNodeName()+"': "+wrapped.getFirstChild().getFirstChild().getNodeName()); + } + } catch(Exception e) { + fail("Failed: "+e); + } + } +} diff --git a/components/bpel/src/test/resources/META-INF/beans.xml b/components/bpel/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/bpel/src/test/resources/SayHello.bpel b/components/bpel/src/test/resources/SayHello.bpel new file mode 100644 index 000000000..a33559194 --- /dev/null +++ b/components/bpel/src/test/resources/SayHello.bpel @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpel-say-hello/src/main/resources/SayHelloArtifacts.wsdl b/components/bpel/src/test/resources/SayHelloArtifacts.wsdl similarity index 100% rename from bpel-say-hello/src/main/resources/SayHelloArtifacts.wsdl rename to components/bpel/src/test/resources/SayHelloArtifacts.wsdl diff --git a/components/bpel/src/test/resources/bpel.properties b/components/bpel/src/test/resources/bpel.properties new file mode 100644 index 000000000..a84b49a9a --- /dev/null +++ b/components/bpel/src/test/resources/bpel.properties @@ -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. +# + +## bpel Configuration Properties + +bpel.dao.factory=org.apache.ode.dao.jpa.hibernate.BpelDAOConnectionFactoryImpl +bpel.dao.factory.store=org.apache.ode.dao.jpa.hibernate.ConfStoreDAOConnectionFactoryImpl +bpel.dao.factory.scheduler=org.apache.ode.dao.jpa.hibernate.SchedulerDAOConnectionFactoryImpl +bpel.cache.provider=org.apache.ode.il.cache.DefaultCacheProvider + +bpel.tx.factory.class = org.apache.ode.il.EmbeddedGeronimoFactory + +bpel.db.mode=EMBEDDED +db.emb.create=false +bpel.db.ext.dataSource=java:BPELDB + +# all hibernate specific properties + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.hbm2ddl.auto=none +hibernate.current_session_context_class=jta +hibernate.show_sql=false +hibernate.connection.isolation=2 +hibernate.jdbc.batch_size=20 + +jta.UserTransaction=UserTransaction + +ode.persistence=hibernate + +# +# Comma separated list of BPEL event listeners. +# BPAFLogAdapter is used to store BPEL events for historic analysis. +# +#bpel.event.listeners=org.jboss.soa.bpel.console.bpaf.BPAFLogAdapter +#bpel.event.listeners= + +# Property used to configure whether ODE should store the BPEL events in its default location +# (Set to false, as RiftSaw uses the BPEL events stored by the BPAFLogAdapter) +persist.bpel.events = false + +# Determines if even top level transaction based ODE invokes should bypass the scheduler +# If false, then top level invokes will be scheduled, but subsequent nested invokes (to +# external services in same thread) will be directly invoked instead of via the scheduler. +bpel.invoke.immediate=false + +# Delay not set during testing +bpel.undeploy.delay = 0 diff --git a/components/bpel/src/test/resources/deploy.xml b/components/bpel/src/test/resources/deploy.xml new file mode 100644 index 000000000..19cfc88b4 --- /dev/null +++ b/components/bpel/src/test/resources/deploy.xml @@ -0,0 +1,74 @@ + + + + + + true + + + + + + + + + + + + true + + + + + + + + + true + false + + + + + + + + true + + + + + + + + + + + true + + + + + + + diff --git a/components/bpel/src/test/resources/loan2ServicePT.wsdl b/components/bpel/src/test/resources/loan2ServicePT.wsdl new file mode 100644 index 000000000..308f7f97d --- /dev/null +++ b/components/bpel/src/test/resources/loan2ServicePT.wsdl @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpel/src/test/resources/loan2_approval.bpel b/components/bpel/src/test/resources/loan2_approval.bpel new file mode 100644 index 000000000..89272a42c --- /dev/null +++ b/components/bpel/src/test/resources/loan2_approval.bpel @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1000 + + + + + + + + + + + + + + + + + yes + + + + + + + + + + diff --git a/components/bpel/src/test/resources/loan2_approval/soap-loanreq1.xml b/components/bpel/src/test/resources/loan2_approval/soap-loanreq1.xml new file mode 100644 index 000000000..d135edf63 --- /dev/null +++ b/components/bpel/src/test/resources/loan2_approval/soap-loanreq1.xml @@ -0,0 +1,10 @@ + + + + + Fred + Bloggs + 100 + + + diff --git a/components/bpel/src/test/resources/loan2_approval/soap-loanresp1.xml b/components/bpel/src/test/resources/loan2_approval/soap-loanresp1.xml new file mode 100644 index 000000000..263b70a4f --- /dev/null +++ b/components/bpel/src/test/resources/loan2_approval/soap-loanresp1.xml @@ -0,0 +1,3 @@ + + yes + diff --git a/components/bpel/src/test/resources/loan2_approval/switchyard.xml b/components/bpel/src/test/resources/loan2_approval/switchyard.xml new file mode 100644 index 000000000..c1efacc81 --- /dev/null +++ b/components/bpel/src/test/resources/loan2_approval/switchyard.xml @@ -0,0 +1,39 @@ + + + + + + loan2ServicePT.wsdl + localhost:18001 + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpel-loan-approval/src/main/resources/loanServicePT.wsdl b/components/bpel/src/test/resources/loanServicePT.wsdl similarity index 100% rename from bpel-loan-approval/src/main/resources/loanServicePT.wsdl rename to components/bpel/src/test/resources/loanServicePT.wsdl diff --git a/components/bpel/src/test/resources/loan_approval.bpel b/components/bpel/src/test/resources/loan_approval.bpel new file mode 100644 index 000000000..7a87556e6 --- /dev/null +++ b/components/bpel/src/test/resources/loan_approval.bpel @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1000 + + + + + + + + + + + + + + + + + yes + + + + + + + + + + diff --git a/components/bpel/src/test/resources/loan_approval/soap-loanreq1.xml b/components/bpel/src/test/resources/loan_approval/soap-loanreq1.xml new file mode 100644 index 000000000..4be1ad5ee --- /dev/null +++ b/components/bpel/src/test/resources/loan_approval/soap-loanreq1.xml @@ -0,0 +1,10 @@ + + + + + Fred + Bloggs + 100 + + + \ No newline at end of file diff --git a/components/bpel/src/test/resources/loan_approval/soap-loanreq2.xml b/components/bpel/src/test/resources/loan_approval/soap-loanreq2.xml new file mode 100644 index 000000000..fddd084d3 --- /dev/null +++ b/components/bpel/src/test/resources/loan_approval/soap-loanreq2.xml @@ -0,0 +1,10 @@ + + + + + Fred + Bloggs + 11000 + + + diff --git a/components/bpel/src/test/resources/loan_approval/soap-loanresp1.xml b/components/bpel/src/test/resources/loan_approval/soap-loanresp1.xml new file mode 100644 index 000000000..a9bc361d7 --- /dev/null +++ b/components/bpel/src/test/resources/loan_approval/soap-loanresp1.xml @@ -0,0 +1,3 @@ + + yes + \ No newline at end of file diff --git a/components/bpel/src/test/resources/loan_approval/soap-loanresp2.xml b/components/bpel/src/test/resources/loan_approval/soap-loanresp2.xml new file mode 100644 index 000000000..c85f1cd22 --- /dev/null +++ b/components/bpel/src/test/resources/loan_approval/soap-loanresp2.xml @@ -0,0 +1,13 @@ + + + + + + ns0:unableToHandleRequest + + + 1 + + + + \ No newline at end of file diff --git a/components/bpel/src/test/resources/loan_approval/switchyard.xml b/components/bpel/src/test/resources/loan_approval/switchyard.xml new file mode 100644 index 000000000..1cc0eef74 --- /dev/null +++ b/components/bpel/src/test/resources/loan_approval/switchyard.xml @@ -0,0 +1,39 @@ + + + + + + loanServicePT.wsdl + localhost:18001 + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpel/src/test/resources/log4j.properties b/components/bpel/src/test/resources/log4j.properties new file mode 100644 index 000000000..104be7601 --- /dev/null +++ b/components/bpel/src/test/resources/log4j.properties @@ -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. +# + +# Set root logger level to WARN and its only appender to CONSOLE +log4j.rootLogger=INFO, CONSOLE + +log4j.category.org.apache.ode=INFO +log4j.category.org.jboss.soa.bpel=INFO +log4j.category.org.switchyard=INFO + +# Console appender +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%p - %C{1}.%M(%L) | %m%n diff --git a/components/bpel/src/test/resources/risk2AssessmentPT.wsdl b/components/bpel/src/test/resources/risk2AssessmentPT.wsdl new file mode 100644 index 000000000..eaea87df4 --- /dev/null +++ b/components/bpel/src/test/resources/risk2AssessmentPT.wsdl @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpel/src/test/resources/risk2_assessment.bpel b/components/bpel/src/test/resources/risk2_assessment.bpel new file mode 100644 index 000000000..1966d8f1c --- /dev/null +++ b/components/bpel/src/test/resources/risk2_assessment.bpel @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + = 1000]]> + + + + + + 1 + + + + + + + + + + + + + + low + + + + + + + + + + + + diff --git a/components/bpel/src/test/resources/riskAssessmentPT.wsdl b/components/bpel/src/test/resources/riskAssessmentPT.wsdl new file mode 100644 index 000000000..69d905ab7 --- /dev/null +++ b/components/bpel/src/test/resources/riskAssessmentPT.wsdl @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpel/src/test/resources/risk_assessment.bpel b/components/bpel/src/test/resources/risk_assessment.bpel new file mode 100644 index 000000000..7fd5e64ff --- /dev/null +++ b/components/bpel/src/test/resources/risk_assessment.bpel @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = 1000]]> + + + + + + 1 + + + + + + + + + + + + + + + + + low + + + + + + + + + + + + + + + + diff --git a/bpel-say-hello/src/test/resources/xml/soap-request.xml b/components/bpel/src/test/resources/say_hello/soap-request.xml similarity index 100% rename from bpel-say-hello/src/test/resources/xml/soap-request.xml rename to components/bpel/src/test/resources/say_hello/soap-request.xml diff --git a/bpel-say-hello/src/test/resources/xml/soap-response.xml b/components/bpel/src/test/resources/say_hello/soap-response.xml similarity index 100% rename from bpel-say-hello/src/test/resources/xml/soap-response.xml rename to components/bpel/src/test/resources/say_hello/soap-response.xml diff --git a/components/bpel/src/test/resources/say_hello/switchyard.xml b/components/bpel/src/test/resources/say_hello/switchyard.xml new file mode 100644 index 000000000..1e890cb71 --- /dev/null +++ b/components/bpel/src/test/resources/say_hello/switchyard.xml @@ -0,0 +1,28 @@ + + + + + + SayHelloArtifacts.wsdl + :18001 + + + + + + + + + + + + + diff --git a/components/bpel/src/test/resources/tests/wsdl/LoanService.wsdl b/components/bpel/src/test/resources/tests/wsdl/LoanService.wsdl new file mode 100644 index 000000000..1ad1c0551 --- /dev/null +++ b/components/bpel/src/test/resources/tests/wsdl/LoanService.wsdl @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/pom.xml b/components/bpm/pom.xml new file mode 100644 index 000000000..93296d2e3 --- /dev/null +++ b/components/bpm/pom.xml @@ -0,0 +1,108 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-bpm + bundle + SwitchYard: BPM Component + http://switchyard.org + + org.switchyard.component.common.knowledge.deploy.OSGiKnowledgeBundleActivator + + org.switchyard.component.bpm.* + + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + * + + + org.jbpm.bpmn2, + org.jbpm.flow.core, + org.jbpm.persistence.jpa, + org.jbpm.services.task.jpa + + + org.jbpm.*, + org.drools.*, + org.kie.* + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-extensions-java + + + org.switchyard.components + switchyard-component-common-knowledge + + + + org.hibernate + hibernate-core + + + org.jbpm + jbpm-flow + + + org.jbpm + jbpm-human-task-core + + + org.jbpm + jbpm-human-task-workitems + + + org.kie + kie-api + + + org.kie + kie-internal + + + diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/BPMConstants.java b/components/bpm/src/main/java/org/switchyard/component/bpm/BPMConstants.java new file mode 100644 index 000000000..d0cb0c1f6 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/BPMConstants.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm; + +import javax.xml.namespace.QName; + +/** + * BPM constants. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class BPMConstants { + + /** urn:switchyard-component-bpm:bpm:1.0 . */ + public static final String BPM_NAMESPACE = "urn:switchyard-component-bpm:bpm:1.0"; + + /** + * sessionId is not used anymore. + * @deprecated + */ + @Deprecated + public static final String SESSION_ID = "sessionId"; + /** + * {urn:switchyard-component-bpm:bpm:1.0}sessionId is not used anymore. + * @deprecated + */ + @Deprecated + public static final String SESSION_ID_PROPERTY = new QName(BPM_NAMESPACE, SESSION_ID).toString(); + + /** processInstanceId . */ + public static final String PROCESS_INSTANCE_ID = "processInstanceId"; + /** {urn:switchyard-component-bpm:bpm:1.0}processInstanceId . */ + public static final String PROCESSS_INSTANCE_ID_PROPERTY = new QName(BPM_NAMESPACE, PROCESS_INSTANCE_ID).toString(); + + /** correlationKey . */ + public static final String CORRELATION_KEY = "correlationKey"; + /** {urn:switchyard-component-bpm:bpm:1.0}correlationKey . */ + public static final String CORRELATION_KEY_PROPERTY = new QName(BPM_NAMESPACE, CORRELATION_KEY).toString(); + + private BPMConstants() {} + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/BPMLogger.java b/components/bpm/src/main/java/org/switchyard/component/bpm/BPMLogger.java new file mode 100644 index 000000000..4385bfbd1 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/BPMLogger.java @@ -0,0 +1,18 @@ +package org.switchyard.component.bpm; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 31600-31999 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface BPMLogger { + /** + * A root logger with the category of the package name. + */ + BPMLogger ROOT_LOGGER = Logger.getMessageLogger(BPMLogger.class, BPMLogger.class.getPackage().getName()); + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/BPMMessages.java b/components/bpm/src/main/java/org/switchyard/component/bpm/BPMMessages.java new file mode 100644 index 000000000..aa0c62de9 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/BPMMessages.java @@ -0,0 +1,62 @@ +package org.switchyard.component.bpm; + +import java.io.IOException; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.component.bpm.operation.BPMOperationType; + +/** + *

+ * This file is using the subset 32000-32399 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface BPMMessages { + /** + * The default messages. + */ + BPMMessages MESSAGES = Messages.getBundle(BPMMessages.class); + + /** + * bpmClassGetNameIsMissingTheBPMAnnotation method definition. + * @param bpmClassName bpmClassName + * @return IOException + */ + @Message(id = 32000, value = "%s is missing the @BPM annotation.") + IOException bpmClassGetNameIsMissingTheBPMAnnotation(String bpmClassName); + + /** + * bpmInterfaceGetNameIsAClassBPMOnlyAllowedOnInterfaces method definition. + * @param bpmInterfaceName bpmInterfaceName + * @return IOException + */ + @Message(id = 32001, value = "%s is a class. @BPM only allowed on interfaces.") + IOException bpmInterfaceGetNameIsAClassBPMOnlyAllowedOnInterfaces(String bpmInterfaceName); + + /** + * cannotSignalEventUnknownProcessInstanceIdOrUnknown/unmatchedCorrelationKey method definition. + * @return HandlerException + */ + @Message(id = 32002, value = "Cannot signalEvent: unknown processInstanceId or unknown/unmatched correlationKey") + HandlerException cannotSignalEventUnknownProcessInstanceIdOrUnknownunmatchedCorrelationKey(); + + /** + * cannotAbortProcessInstanceUnknownProcessInstanceIdOrUnknown/unmatchedCorrelationKey method definition. + * @return HandlerException + */ + @Message(id = 32003, value = "Cannot abortProcessInstance: unknown processInstanceId or unknown/unmatched correlationKey") + HandlerException cannotAbortProcessInstance(); + + /** + * unsupportedOperationType method definition. + * @param operationType the operationType + * @return HandlerException + */ + @Message(id = 32004, value = "Unsupported operation type: %s") + HandlerException unsupportedOperationType(BPMOperationType operationType); +} + diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/AbortProcessInstance.java b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/AbortProcessInstance.java new file mode 100644 index 000000000..b70e5dca6 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/AbortProcessInstance.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Output; + +/** + * AbortProcessInstance. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(METHOD) +@Retention(RUNTIME) +@Documented +public @interface AbortProcessInstance { + + /** Outputs. */ + public Output[] outputs() default {}; + + /** Faults. */ + public Fault[] faults() default {}; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/BPM.java b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/BPM.java new file mode 100644 index 000000000..079c35d74 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/BPM.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Channel; +import org.switchyard.component.common.knowledge.annotation.Listener; +import org.switchyard.component.common.knowledge.annotation.Logger; +import org.switchyard.component.common.knowledge.annotation.Manifest; +import org.switchyard.component.common.knowledge.annotation.Property; + +/** + * BPM. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface BPM { + + /** Namespace. */ + public String namespace() default ""; + + /** Name. */ + public String name() default ""; + + /** Undefined interface class. */ + public Class value() default UndefinedBPMInterface.class; + + /** Persistent. */ + public boolean persistent() default false; + + /** Process id. */ + public String processId() default ""; + + /** Channels. */ + public Channel[] channels() default {}; + + /** Listeners. */ + public Listener[] listeners() default {}; + + /** Loggers. */ + public Logger[] loggers() default {}; + + /** Manifest. */ + public Manifest[] manifest() default {}; + + /** Properties. */ + public Property[] properties() default {}; + + /** UserGroupCallback. */ + public UserGroupCallback[] userGroupCallback() default {}; + + /** WorkItemHandlers. */ + public WorkItemHandler[] workItemHandlers() default {}; + + /** Undefined interface class. */ + public static interface UndefinedBPMInterface {}; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/SignalEvent.java b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/SignalEvent.java new file mode 100644 index 000000000..33c7aac55 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/SignalEvent.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; + +/** + * SignalEvent. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(METHOD) +@Retention(RUNTIME) +@Documented +public @interface SignalEvent { + + /** EventId. */ + public String eventId() default ""; + + /** Globals. */ + public Global[] globals() default {}; + + /** Inputs. */ + public Input[] inputs() default {}; + + /** Outputs. */ + public Output[] outputs() default {}; + + /** Faults. */ + public Fault[] faults() default {}; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/SignalEventAll.java b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/SignalEventAll.java new file mode 100644 index 000000000..ce2611bda --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/SignalEventAll.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; + +/** + * SignalEventAll. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(METHOD) +@Retention(RUNTIME) +@Documented +public @interface SignalEventAll { + + /** EventId. */ + public String eventId() default ""; + + /** Globals. */ + public Global[] globals() default {}; + + /** Inputs. */ + public Input[] inputs() default {}; + + /** Outputs. */ + public Output[] outputs() default {}; + + /** Faults. */ + public Fault[] faults() default {}; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/StartProcess.java b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/StartProcess.java new file mode 100644 index 000000000..db61ae45c --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/StartProcess.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; + +/** + * StartProcess. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(METHOD) +@Retention(RUNTIME) +@Documented +public @interface StartProcess { + + /** Globals. */ + public Global[] globals() default {}; + + /** Inputs. */ + public Input[] inputs() default {}; + + /** Outputs. */ + public Output[] outputs() default {}; + + /** Faults. */ + public Fault[] faults() default {}; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/UserGroupCallback.java b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/UserGroupCallback.java new file mode 100644 index 000000000..c35fc810d --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/UserGroupCallback.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Property; + +/** + * UserGroupCallback. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface UserGroupCallback { + + // SWITCHYARD-1755: internal api usage still required (public APIs insufficient) + /** Impl class. */ + public Class value(); + + /** Properties. */ + public Property[] properties() default {}; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/WorkItemHandler.java b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/WorkItemHandler.java new file mode 100644 index 000000000..c0256d663 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/annotation/WorkItemHandler.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * WorkItemHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface WorkItemHandler { + + /** Impl class. */ + public Class value(); + + /** Name. */ + public String name() default ""; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMComponentImplementationModel.java b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMComponentImplementationModel.java new file mode 100644 index 000000000..ba50bcd7d --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMComponentImplementationModel.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model; + +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; + +/** + * BPMComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface BPMComponentImplementationModel extends KnowledgeComponentImplementationModel { + + /** + * The "bpm" implementation type. + */ + public static final String BPM = "bpm"; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMNamespace.java b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMNamespace.java new file mode 100644 index 000000000..7a566f2fc --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMNamespace.java @@ -0,0 +1,112 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model; + +import org.switchyard.component.common.knowledge.config.model.KnowledgeNamespace; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A BPM config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum BPMNamespace implements KnowledgeNamespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new BPMNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + BPMNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the BPMNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the BPMNamespace + */ + public static BPMNamespace fromUri(String uri) { + return Util.fromUri(BPMNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(BPMNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-bpm:config", version); + } + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMSwitchYardScanner.java b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMSwitchYardScanner.java new file mode 100644 index 000000000..afff2d8df --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/BPMSwitchYardScanner.java @@ -0,0 +1,282 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.List; + +import org.jbpm.services.task.wih.AbstractHTWorkItemHandler; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.type.classpath.ClasspathScanner; +import org.switchyard.common.type.classpath.IsAnnotationPresentFilter; +import org.switchyard.component.bpm.BPMMessages; +import org.switchyard.component.bpm.annotation.AbortProcessInstance; +import org.switchyard.component.bpm.annotation.BPM; +import org.switchyard.component.bpm.annotation.SignalEvent; +import org.switchyard.component.bpm.annotation.SignalEventAll; +import org.switchyard.component.bpm.annotation.StartProcess; +import org.switchyard.component.bpm.annotation.UserGroupCallback; +import org.switchyard.component.bpm.annotation.WorkItemHandler; +import org.switchyard.component.bpm.config.model.v1.V1BPMComponentImplementationModel; +import org.switchyard.component.bpm.config.model.v1.V1BPMOperationModel; +import org.switchyard.component.bpm.operation.BPMOperationType; +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; +import org.switchyard.component.common.knowledge.config.model.KnowledgeSwitchYardScanner; +import org.switchyard.component.common.knowledge.config.model.OperationModel; +import org.switchyard.component.common.knowledge.config.model.OperationsModel; +import org.switchyard.component.common.knowledge.config.model.UserGroupCallbackModel; +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlerModel; +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlersModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1OperationsModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1UserGroupCallbackModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1WorkItemHandlerModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1WorkItemHandlersModel; +import org.switchyard.component.common.knowledge.service.StandardSwitchYardServiceTaskHandler; +import org.switchyard.component.common.knowledge.service.SwitchYardServiceTaskHandler; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.v1.V1ComponentModel; +import org.switchyard.config.model.composite.v1.V1ComponentServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeModel; +import org.switchyard.config.model.composite.v1.V1InterfaceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.metadata.ServiceOperation; + +/** + * BPMSwitchYardScanner. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class BPMSwitchYardScanner extends KnowledgeSwitchYardScanner { + + private static final IsAnnotationPresentFilter START_PROCESS_FILTER = new IsAnnotationPresentFilter(StartProcess.class); + private static final IsAnnotationPresentFilter SIGNAL_EVENT_FILTER = new IsAnnotationPresentFilter(SignalEvent.class); + private static final IsAnnotationPresentFilter SIGNAL_EVENT_ALL_FILTER = new IsAnnotationPresentFilter(SignalEventAll.class); + private static final IsAnnotationPresentFilter ABORT_PROCESS_INSTANCE_FILTER = new IsAnnotationPresentFilter(AbortProcessInstance.class); + + private final IsAnnotationPresentFilter _bpmFilter = new IsAnnotationPresentFilter(BPM.class); + + /** + * {@inheritDoc} + */ + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + SwitchYardNamespace switchyardNamespace = input.getSwitchyardNamespace(); + SwitchYardModel switchyardModel = new V1SwitchYardModel(switchyardNamespace.uri()); + CompositeModel compositeModel = new V1CompositeModel(); + compositeModel.setName(input.getCompositeName()); + ClasspathScanner bpmScanner = new ClasspathScanner(_bpmFilter); + for (URL url : input.getURLs()) { + bpmScanner.scan(url); + } + List> bpmClasses = _bpmFilter.getMatchedTypes(); + for (Class bpmClass : bpmClasses) { + compositeModel.addComponent(scan(bpmClass, switchyardNamespace)); + } + if (!compositeModel.getModelChildren().isEmpty()) { + switchyardModel.setComposite(compositeModel); + } + return new ScannerOutput().setModel(switchyardModel); + } + + /** + * Scans a class using the default switchyard namespace. + * @param bpmClass the class + * @return the component model + * @throws IOException oops + */ + public ComponentModel scan(Class bpmClass) throws IOException { + return scan(bpmClass, null); + } + + /** + * Scans a class using the specified switchyard namespace. + * @param bpmClass the class + * @param switchyardNamespace the switchyard namespace + * @return the component model + * @throws IOException oops + */ + public ComponentModel scan(Class bpmClass, SwitchYardNamespace switchyardNamespace) throws IOException { + if (switchyardNamespace == null) { + switchyardNamespace = SwitchYardNamespace.DEFAULT; + } + BPM bpm = bpmClass.getAnnotation(BPM.class); + if (bpm == null) { + throw BPMMessages.MESSAGES.bpmClassGetNameIsMissingTheBPMAnnotation(bpmClass.getName()); + } + Class bpmInterface = bpm.value(); + if (BPM.UndefinedBPMInterface.class.equals(bpmInterface)) { + bpmInterface = bpmClass; + } + if (!bpmInterface.isInterface()) { + throw BPMMessages.MESSAGES.bpmInterfaceGetNameIsAClassBPMOnlyAllowedOnInterfaces(bpmInterface.getName()); + } + String bpmName = Strings.trimToNull(bpm.name()); + if (bpmName == null) { + bpmName = bpmInterface.getSimpleName(); + } + ComponentModel componentModel = new V1ComponentModel(); + componentModel.setName(bpmName); + BPMNamespace bpmNamespace = BPMNamespace.fromUri(bpm.namespace()); + if (bpmNamespace == null) { + bpmNamespace = BPMNamespace.DEFAULT; + for (BPMNamespace value : BPMNamespace.values()) { + if (value.versionMatches(switchyardNamespace)) { + bpmNamespace = value; + break; + } + } + } + BPMComponentImplementationModel componentImplementationModel = new V1BPMComponentImplementationModel(bpmNamespace.uri()); + boolean persistent = bpm.persistent(); + if (persistent) { + componentImplementationModel.setPersistent(persistent); + } + String processId = bpm.processId(); + if (UNDEFINED.equals(processId)) { + processId = bpmName; + } + componentImplementationModel.setProcessId(processId); + OperationsModel operationsModel = new V1OperationsModel(bpmNamespace.uri()); + JavaService javaService = JavaService.fromClass(bpmInterface); + for (Method method : bpmClass.getDeclaredMethods()) { + BPMOperationType operationType = null; + String eventId = null; + Global[] globalMappingAnnotations = null; + Input[] inputMappingAnnotations = null; + Output[] outputMappingAnnotations = null; + Fault[] faultMappingAnnotations = null; + if (START_PROCESS_FILTER.matches(method)) { + operationType = BPMOperationType.START_PROCESS; + StartProcess startProcessAnnotation = method.getAnnotation(StartProcess.class); + globalMappingAnnotations = startProcessAnnotation.globals(); + inputMappingAnnotations = startProcessAnnotation.inputs(); + outputMappingAnnotations = startProcessAnnotation.outputs(); + faultMappingAnnotations = startProcessAnnotation.faults(); + } else if (SIGNAL_EVENT_FILTER.matches(method)) { + operationType = BPMOperationType.SIGNAL_EVENT; + SignalEvent signalEventAnnotation = method.getAnnotation(SignalEvent.class); + eventId = Strings.trimToNull(signalEventAnnotation.eventId()); + globalMappingAnnotations = signalEventAnnotation.globals(); + inputMappingAnnotations = signalEventAnnotation.inputs(); + outputMappingAnnotations = signalEventAnnotation.outputs(); + faultMappingAnnotations = signalEventAnnotation.faults(); + } else if (SIGNAL_EVENT_ALL_FILTER.matches(method)) { + operationType = BPMOperationType.SIGNAL_EVENT_ALL; + SignalEventAll signalEventAllAnnotation = method.getAnnotation(SignalEventAll.class); + eventId = Strings.trimToNull(signalEventAllAnnotation.eventId()); + globalMappingAnnotations = signalEventAllAnnotation.globals(); + inputMappingAnnotations = signalEventAllAnnotation.inputs(); + outputMappingAnnotations = signalEventAllAnnotation.outputs(); + faultMappingAnnotations = signalEventAllAnnotation.faults(); + } else if (ABORT_PROCESS_INSTANCE_FILTER.matches(method)) { + operationType = BPMOperationType.ABORT_PROCESS_INSTANCE; + AbortProcessInstance abortProcessInstanceAnnotation = method.getAnnotation(AbortProcessInstance.class); + globalMappingAnnotations = new Global[]{}; + inputMappingAnnotations = new Input[]{}; + outputMappingAnnotations = abortProcessInstanceAnnotation.outputs(); + faultMappingAnnotations = abortProcessInstanceAnnotation.faults(); + } + if (operationType != null) { + ServiceOperation serviceOperation = javaService.getOperation(method.getName()); + if (serviceOperation != null) { + OperationModel operationModel = new V1BPMOperationModel(bpmNamespace.uri()); + operationModel.setEventId(eventId); + operationModel.setName(serviceOperation.getName()); + operationModel.setType(operationType); + operationModel.setGlobals(toGlobalsModel(globalMappingAnnotations, bpmNamespace)); + operationModel.setInputs(toInputsModel(inputMappingAnnotations, bpmNamespace)); + operationModel.setOutputs(toOutputsModel(outputMappingAnnotations, bpmNamespace)); + operationModel.setFaults(toFaultsModel(faultMappingAnnotations, bpmNamespace)); + operationsModel.addOperation(operationModel); + } + } + } + if (!operationsModel.getOperations().isEmpty()) { + componentImplementationModel.setOperations(operationsModel); + } + componentImplementationModel.setChannels(toChannelsModel(bpm.channels(), bpmNamespace, componentModel, switchyardNamespace)); + componentImplementationModel.setListeners(toListenersModel(bpm.listeners(), bpmNamespace)); + componentImplementationModel.setLoggers(toLoggersModel(bpm.loggers(), bpmNamespace)); + componentImplementationModel.setManifest(toManifestModel(bpm.manifest(), bpmNamespace)); + componentImplementationModel.setProperties(toPropertiesModel(bpm.properties(), bpmNamespace)); + componentImplementationModel.setUserGroupCallback(toUserGroupCallbackModel(bpm.userGroupCallback(), bpmNamespace)); + componentImplementationModel.setWorkItemHandlers(toWorkItemHandlersModel(bpm.workItemHandlers(), bpmNamespace)); + componentModel.setImplementation(componentImplementationModel); + ComponentServiceModel componentServiceModel = new V1ComponentServiceModel(switchyardNamespace.uri()); + InterfaceModel interfaceModel = new V1InterfaceModel(InterfaceModel.JAVA); + interfaceModel.setInterface(bpmInterface.getName()); + componentServiceModel.setInterface(interfaceModel); + componentServiceModel.setName(bpmName); + componentModel.addService(componentServiceModel); + return componentModel; + } + + private UserGroupCallbackModel toUserGroupCallbackModel(UserGroupCallback[] userGroupCallbackAnnotations, BPMNamespace bpmNamespace) { + if (userGroupCallbackAnnotations == null || userGroupCallbackAnnotations.length == 0) { + return null; + } + UserGroupCallbackModel userGroupCallbackModel = null; + for (UserGroupCallback userGroupCallbackAnnotation : userGroupCallbackAnnotations) { + userGroupCallbackModel = new V1UserGroupCallbackModel(bpmNamespace.uri()); + // SWITCHYARD-1755: internal api usage still required (public APIs insufficient) + Class clazz = userGroupCallbackAnnotation.value(); + userGroupCallbackModel.setClazz(clazz); + userGroupCallbackModel.setProperties(toPropertiesModel(userGroupCallbackAnnotation.properties(), bpmNamespace)); + break; + } + return userGroupCallbackModel; + } + + private WorkItemHandlersModel toWorkItemHandlersModel(WorkItemHandler[] workItemHandlerAnnotations, BPMNamespace bpmNamespace) { + if (workItemHandlerAnnotations == null || workItemHandlerAnnotations.length == 0) { + return null; + } + WorkItemHandlersModel workItemHandlersModel = new V1WorkItemHandlersModel(bpmNamespace.uri()); + for (WorkItemHandler workItemHandlerAnnotation : workItemHandlerAnnotations) { + WorkItemHandlerModel workItemHandlerModel = new V1WorkItemHandlerModel(bpmNamespace.uri()); + Class clazz = workItemHandlerAnnotation.value(); + workItemHandlerModel.setClazz(clazz); + String name = workItemHandlerAnnotation.name(); + if (UNDEFINED.equals(name)) { + if (StandardSwitchYardServiceTaskHandler.class.isAssignableFrom(clazz)) { + name = StandardSwitchYardServiceTaskHandler.SERVICE_TASK; + } else if (SwitchYardServiceTaskHandler.class.isAssignableFrom(clazz)) { + name = SwitchYardServiceTaskHandler.SWITCHYARD_SERVICE_TASK; + } else if (AbstractHTWorkItemHandler.class.isAssignableFrom(clazz)) { + name = "Human Task"; + } + } + if (UNDEFINED.equals(name)) { + name = clazz.getSimpleName(); + } + workItemHandlerModel.setName(name); + workItemHandlersModel.addWorkItemHandler(workItemHandlerModel); + } + return workItemHandlersModel; + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMComponentImplementationModel.java b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMComponentImplementationModel.java new file mode 100644 index 000000000..45d1e90e6 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMComponentImplementationModel.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model.v1; + +import org.switchyard.component.bpm.config.model.BPMComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1KnowledgeComponentImplementationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A "bpm" implementation of a KnowledgeComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1BPMComponentImplementationModel extends V1KnowledgeComponentImplementationModel implements BPMComponentImplementationModel { + + /** + * Default constructor for application use. + * @param namespace namespace + */ + public V1BPMComponentImplementationModel(String namespace) { + super(BPM, namespace); + } + + /** + * Constructor for Marshaller use (ie: V1BPMMarshaller). + * + * @param config the Configuration + * @param desc the Descriptor + */ + public V1BPMComponentImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPersistent() { + String p = getModelAttribute("persistent"); + return p != null ? Boolean.parseBoolean(p) : false; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setPersistent(boolean persistent) { + setModelAttribute("persistent", String.valueOf(persistent)); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getProcessId() { + return getModelAttribute("processId"); + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setProcessId(String processId) { + setModelAttribute("processId", processId); + return this; + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMMarshaller.java b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMMarshaller.java new file mode 100644 index 000000000..dc2659d9d --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMMarshaller.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.OperationModel.OPERATION; + +import org.switchyard.component.bpm.config.model.BPMComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1KnowledgeMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * A CompositeMarshaller which can also create knowledge models. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1BPMMarshaller extends V1KnowledgeMarshaller { + + /** + * The complete local name ("implementation.bpm"). + */ + private static final String IMPLEMENTATION_BPM = ComponentImplementationModel.IMPLEMENTATION + "." + BPMComponentImplementationModel.BPM; + + /** + * Required constructor called via reflection. + * + * @param desc the Descriptor + */ + public V1BPMMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1CompositeMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (IMPLEMENTATION_BPM.equals(name)) { + return new V1BPMComponentImplementationModel(config, desc); + } else if (OPERATION.equals(name)) { + return new V1BPMOperationModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMOperationModel.java b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMOperationModel.java new file mode 100644 index 000000000..6f3bb74b9 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v1/V1BPMOperationModel.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model.v1; + +import org.switchyard.component.bpm.operation.BPMOperationType; +import org.switchyard.component.common.knowledge.config.model.v1.V1OperationModel; +import org.switchyard.component.common.knowledge.operation.KnowledgeOperationType; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version BPMOperationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1BPMOperationModel extends V1OperationModel { + + /** + * Creates a new V1BPMOperationModel. + * @param namespace namespace + */ + public V1BPMOperationModel(String namespace) { + super(namespace); + } + + /** + * Creates a new V1BPMOperationModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1BPMOperationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeOperationType getType() { + String type = getModelAttribute("type"); + return type != null ? BPMOperationType.valueOf(type) : null; + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v2/V2BPMMarshaller.java b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v2/V2BPMMarshaller.java new file mode 100644 index 000000000..60b402f24 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/config/model/v2/V2BPMMarshaller.java @@ -0,0 +1,67 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model.v2; + +import static org.switchyard.component.common.knowledge.config.model.OperationModel.OPERATION; + +import org.switchyard.component.bpm.config.model.BPMComponentImplementationModel; +import org.switchyard.component.bpm.config.model.v1.V1BPMComponentImplementationModel; +import org.switchyard.component.bpm.config.model.v1.V1BPMOperationModel; +import org.switchyard.component.common.knowledge.config.model.v2.V2KnowledgeMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * A CompositeMarshaller which can also create knowledge models. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2BPMMarshaller extends V2KnowledgeMarshaller { + + /** + * The complete local name ("implementation.bpm"). + */ + private static final String IMPLEMENTATION_BPM = ComponentImplementationModel.IMPLEMENTATION + "." + BPMComponentImplementationModel.BPM; + + /** + * Required constructor called via reflection. + * + * @param desc the Descriptor + */ + public V2BPMMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1CompositeMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (IMPLEMENTATION_BPM.equals(name)) { + return new V1BPMComponentImplementationModel(config, desc); + } else if (OPERATION.equals(name)) { + return new V1BPMOperationModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/deploy/BPMActivator.java b/components/bpm/src/main/java/org/switchyard/component/bpm/deploy/BPMActivator.java new file mode 100644 index 000000000..bdf7df40f --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/deploy/BPMActivator.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.component.bpm.config.model.BPMComponentImplementationModel; +import org.switchyard.component.bpm.exchange.BPMExchangeHandler; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; + +/** + * Activator for the BPM component. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class BPMActivator extends BaseActivator { + + /** + * BPM component activator type name. + */ + public static final String BPM_TYPE = "bpm"; + + /** + * Constructs a new Activator of type "bpm". + */ + public BPMActivator() { + super(BPM_TYPE); + } + + /** + * {@inheritDoc} + */ + @Override + public ServiceHandler activateService(QName name, ComponentModel config) { + return new BPMExchangeHandler((BPMComponentImplementationModel)config.getImplementation(), getServiceDomain(), name); + } + + /** + * {@inheritDoc} + */ + @Override + public void deactivateService(QName name, ServiceHandler handler) { + // no-op + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/deploy/BPMComponent.java b/components/bpm/src/main/java/org/switchyard/component/bpm/deploy/BPMComponent.java new file mode 100644 index 000000000..0fc1dd48f --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/deploy/BPMComponent.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.deploy; + +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * An implementation of BPM component. + * + * @author Magesh Kumar B © 2012 Red Hat Inc. + */ +public class BPMComponent extends BaseComponent { + + /** + * Default constructor. + */ + public BPMComponent() { + super(BPMActivator.BPM_TYPE); + setName("BPMComponent"); + } + + /** + * {@inheritDoc} + */ + @Override + public Activator createActivator(ServiceDomain domain) { + BPMActivator activator = new BPMActivator(); + activator.setServiceDomain(domain); + return activator; + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/exchange/BPMExchangeHandler.java b/components/bpm/src/main/java/org/switchyard/component/bpm/exchange/BPMExchangeHandler.java new file mode 100644 index 000000000..f995ecded --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/exchange/BPMExchangeHandler.java @@ -0,0 +1,319 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.exchange; + +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.getInput; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.getInputMap; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.setFaults; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.setGlobals; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.setOutputs; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.process.ProcessInstance; +import org.kie.internal.KieInternalServices; +import org.kie.internal.process.CorrelationAwareProcessRuntime; +import org.kie.internal.process.CorrelationKey; +import org.kie.internal.process.CorrelationKeyFactory; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.common.lang.Strings; +import org.switchyard.component.bpm.BPMConstants; +import org.switchyard.component.bpm.BPMMessages; +import org.switchyard.component.bpm.config.model.BPMComponentImplementationModel; +import org.switchyard.component.bpm.operation.BPMOperationType; +import org.switchyard.component.common.knowledge.exchange.KnowledgeExchangeHandler; +import org.switchyard.component.common.knowledge.operation.KnowledgeOperation; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeEngine; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManager; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerRegistry; +import org.switchyard.component.common.knowledge.transaction.TransactionHelper; + +/** + * A "bpm" implementation of a KnowledgeExchangeHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class BPMExchangeHandler extends KnowledgeExchangeHandler { + + private static final KnowledgeOperation DEFAULT_OPERATION = new KnowledgeOperation(BPMOperationType.START_PROCESS); + + private final boolean _persistent; + private final String _processId; + private final CorrelationKeyFactory _correlationKeyFactory; + private KnowledgeRuntimeManager _runtimeManager; + + /** + * Constructs a new BPMExchangeHandler with the specified model, service domain, and service name. + * @param model the specified model + * @param serviceDomain the specified service domain + * @param serviceName the specified service name + */ + public BPMExchangeHandler(BPMComponentImplementationModel model, ServiceDomain serviceDomain, QName serviceName) { + super(model, serviceDomain, serviceName); + _persistent = model.isPersistent(); + _processId = model.getProcessId(); + _correlationKeyFactory = KieInternalServices.Factory.get().newCorrelationKeyFactory(); + } + + /** + * {@inheritDoc} + */ + @Override + protected void doStart() { + super.doStart(); + _runtimeManager = newSingletonRuntimeManager(); + // TODO: SWITCHYARD-1584 + //_runtimeManager = newPerProcessInstanceRuntimeManager(); + //_runtimeManager = _persistent ? newPerProcessInstanceRuntimeManager() : newSingletonRuntimeManager(); + KnowledgeRuntimeManagerRegistry.putRuntimeManager(getServiceDomain().getName(), getServiceName(), _runtimeManager); + } + + /** + * {@inheritDoc} + */ + @Override + protected void doStop() { + KnowledgeRuntimeManagerRegistry.removeRuntimeManager(getServiceDomain().getName(), getServiceName()); + try { + _runtimeManager.close(); + } finally { + _runtimeManager = null; + super.doStop(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeOperation getDefaultOperation() { + return DEFAULT_OPERATION; + } + + /** + * {@inheritDoc} + */ + @Override + public void handleOperation(Exchange exchange, KnowledgeOperation operation) throws HandlerException { + //Long sessionIdentifier = null; + Long processInstanceId = null; + Message inputMessage = exchange.getMessage(); + ExchangePattern exchangePattern = exchange.getContract().getProviderOperation().getExchangePattern(); + Map expressionVariables = new HashMap(); + TransactionHelper txh = new TransactionHelper(_persistent); + BPMOperationType operationType = (BPMOperationType)operation.getType(); + switch (operationType) { + case START_PROCESS: { + try { + txh.begin(); + KnowledgeRuntimeEngine runtime = getRuntimeEngine(); + //sessionIdentifier = runtime.getSessionIdentifier(); + setGlobals(inputMessage, operation, runtime, true); + Map inputMap = getInputMap(inputMessage, operation, runtime); + ProcessInstance processInstance; + CorrelationKey correlationKey = getCorrelationKey(exchange, inputMessage); + if (correlationKey != null) { + processInstance = ((CorrelationAwareProcessRuntime)runtime.getKieSession()).startProcess(_processId, correlationKey, inputMap); + } else { + processInstance = runtime.getKieSession().startProcess(_processId, inputMap); + } + processInstanceId = Long.valueOf(processInstance.getId()); + if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + expressionVariables.putAll(getGlobalVariables(runtime)); + expressionVariables.putAll(getProcessInstanceVariables(processInstance)); + } + if (!_persistent) { + _runtimeManager.disposeRuntimeEngine(runtime); + } + txh.commit(); + } catch (RuntimeException re) { + txh.rollback(); + throw re; + } + break; + } + case SIGNAL_EVENT: + case SIGNAL_EVENT_ALL: { + try { + txh.begin(); + KnowledgeRuntimeEngine runtime; + if (BPMOperationType.SIGNAL_EVENT.equals(operationType)) { + runtime = getRuntimeEngine(exchange, inputMessage); + } else { //BPMOperationType.SIGNAL_EVENT_ALL + runtime = getRuntimeEngine(); + } + //sessionIdentifier = runtime.getSessionIdentifier(); + setGlobals(inputMessage, operation, runtime, true); + Object eventObject = getInput(inputMessage, operation, runtime); + String eventId = operation.getEventId(); + if (BPMOperationType.SIGNAL_EVENT.equals(operationType)) { + processInstanceId = getProcessInstanceId(exchange, inputMessage, runtime); + if (processInstanceId == null) { + throw BPMMessages.MESSAGES.cannotSignalEventUnknownProcessInstanceIdOrUnknownunmatchedCorrelationKey(); + } + if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + ProcessInstance processInstance = runtime.getKieSession().getProcessInstance(processInstanceId); + processInstance.signalEvent(eventId, eventObject); + expressionVariables.putAll(getGlobalVariables(runtime)); + expressionVariables.putAll(getProcessInstanceVariables(processInstance)); + } else { + runtime.getKieSession().signalEvent(eventId, eventObject, processInstanceId); + } + } else { //BPMOperationType.SIGNAL_EVENT_ALL + runtime.getKieSession().signalEvent(eventId, eventObject); + if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + expressionVariables.putAll(getGlobalVariables(runtime)); + } + } + if (!_persistent) { + _runtimeManager.disposeRuntimeEngine(runtime); + } + txh.commit(); + } catch (RuntimeException re) { + txh.rollback(); + throw re; + } + break; + } + case ABORT_PROCESS_INSTANCE: { + try { + txh.begin(); + KnowledgeRuntimeEngine runtime = getRuntimeEngine(exchange, inputMessage); + //sessionIdentifier = runtime.getSessionIdentifier(); + processInstanceId = getProcessInstanceId(exchange, inputMessage, runtime); + if (processInstanceId == null) { + throw BPMMessages.MESSAGES.cannotAbortProcessInstance(); + } + if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + expressionVariables.putAll(getGlobalVariables(runtime)); + ProcessInstance processInstance = runtime.getKieSession().getProcessInstance(processInstanceId); + expressionVariables.putAll(getProcessInstanceVariables(processInstance)); + } + runtime.getKieSession().abortProcessInstance(processInstanceId); + if (!_persistent) { + _runtimeManager.disposeRuntimeEngine(runtime); + } + txh.commit(); + } catch (RuntimeException re) { + txh.rollback(); + throw re; + } + break; + } + default: { + throw BPMMessages.MESSAGES.unsupportedOperationType(operationType); + } + } + if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + Message outputMessage = exchange.createMessage(); + Context outputContext = exchange.getContext(outputMessage); + /* + if (sessionIdentifier != null) { + outputContext.setProperty(BPMConstants.SESSION_ID_PROPERTY, sessionIdentifier); + } + */ + if (processInstanceId != null) { + outputContext.setProperty(BPMConstants.PROCESSS_INSTANCE_ID_PROPERTY, processInstanceId); + } + setFaults(outputMessage, operation, expressionVariables); + if (outputMessage.getContent() != null) { + exchange.sendFault(outputMessage); + } else { + setOutputs(outputMessage, operation, expressionVariables); + exchange.send(outputMessage); + } + } + } + + private KnowledgeRuntimeEngine getRuntimeEngine() { + return (KnowledgeRuntimeEngine)_runtimeManager.getRuntimeEngine(); + } + + private KnowledgeRuntimeEngine getRuntimeEngine(Exchange exchange, Message message) throws HandlerException { + RuntimeEngine runtimeEngine = null; + Long processInstanceId = getProcessInstanceId(exchange, message); + if (processInstanceId != null) { + runtimeEngine = _runtimeManager.getRuntimeEngine(processInstanceId); + } + if (runtimeEngine == null) { + CorrelationKey correlationKey = getCorrelationKey(exchange, message); + if (correlationKey != null) { + runtimeEngine = _runtimeManager.getRuntimeEngine(correlationKey); + } + } + if (runtimeEngine == null) { + throw new HandlerException("runtimeEngine == null"); + } + return (KnowledgeRuntimeEngine)runtimeEngine; + } + + private CorrelationKey getCorrelationKey(Exchange exchange, Message message) { + String ckp = getString(exchange, message, BPMConstants.CORRELATION_KEY_PROPERTY); + if (ckp != null) { + List properties = Strings.splitTrimToNull(ckp, " \t\n\r\f"); + if (properties.size() > 0) { + return _correlationKeyFactory.newCorrelationKey(properties); + } + } + return null; + } + + private Long getProcessInstanceId(Exchange exchange, Message message) { + return getLong(exchange, message, BPMConstants.PROCESSS_INSTANCE_ID_PROPERTY); + } + + private Long getProcessInstanceId(Exchange exchange, Message message, KnowledgeRuntimeEngine session) { + Long processInstanceId = getProcessInstanceId(exchange, message); + if (processInstanceId == null) { + CorrelationKey correlationKey = getCorrelationKey(exchange, message); + if (correlationKey != null) { + processInstanceId = getProcessInstanceId(correlationKey, session); + } + } + return processInstanceId; + } + + private Long getProcessInstanceId(CorrelationKey correlationKey, KnowledgeRuntimeEngine session) { + if (correlationKey != null) { + ProcessInstance processInstance = ((CorrelationAwareProcessRuntime)session.getKieSession()).getProcessInstance(correlationKey); + if (processInstance != null) { + return Long.valueOf(processInstance.getId()); + } + } + return null; + } + + private Map getProcessInstanceVariables(ProcessInstance processInstance) { + Map processInstanceVariables = new HashMap(); + if (processInstance instanceof WorkflowProcessInstanceImpl) { + Map var = ((WorkflowProcessInstanceImpl)processInstance).getVariables(); + if (var != null) { + processInstanceVariables.putAll(var); + } + } + return processInstanceVariables; + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/operation/BPMOperationType.java b/components/bpm/src/main/java/org/switchyard/component/bpm/operation/BPMOperationType.java new file mode 100644 index 000000000..1b77f2092 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/operation/BPMOperationType.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.operation; + +import org.switchyard.component.common.knowledge.operation.KnowledgeOperationType; + +/** + * Represents bpm operation types. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum BPMOperationType implements KnowledgeOperationType { + + /** The start process type. */ + START_PROCESS, + /** The signal event type. */ + SIGNAL_EVENT, + /** The signal event all type. */ + SIGNAL_EVENT_ALL, + /** The abort process instance type. */ + ABORT_PROCESS_INSTANCE; + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMTaskService.java b/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMTaskService.java new file mode 100644 index 000000000..1f1e9330b --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMTaskService.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.runtime; + +import org.jbpm.services.task.lifecycle.listeners.TaskLifeCycleEventListener; +import org.kie.internal.task.api.EventService; +import org.kie.internal.task.api.InternalTaskService; + +/** + * BPMTaskService is DEPRECATED. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + * @deprecated See {@link BPMTaskServiceRegistry} deprecation. + */ +@Deprecated +public interface BPMTaskService extends InternalTaskService, EventService {} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMTaskServiceRegistry.java b/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMTaskServiceRegistry.java new file mode 100644 index 000000000..2c2fbb28f --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMTaskServiceRegistry.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.runtime; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import javax.xml.namespace.QName; + +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.task.TaskService; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManager; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerRegistry; + +/** + * BPMTaskServiceRegistry is DEPRECATED. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + * @deprecated Use {@link KnowledgeRuntimeManagerRegistry} instead. + */ +@Deprecated +public final class BPMTaskServiceRegistry { + + /** + * Gets a task service. + * @param serviceDomainName the service domain name + * @param serviceName the service name + * @return the task service + */ + public static final synchronized BPMTaskService getTaskService(QName serviceDomainName, QName serviceName) { + KnowledgeRuntimeManager runtimeManager = KnowledgeRuntimeManagerRegistry.getRuntimeManager(serviceDomainName, serviceName); + if (runtimeManager != null) { + RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine(); + if (runtimeEngine != null) { + final TaskService taskService = runtimeEngine.getTaskService(); + if (taskService != null) { + InvocationHandler ih = new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return method.invoke(taskService, args); + } + }; + return (BPMTaskService)Proxy.newProxyInstance(BPMTaskService.class.getClassLoader(), new Class[]{BPMTaskService.class}, ih); + } + } + } + return null; + } + + /** + * Puts a task service. + * @param serviceDomainName the service domain name + * @param serviceName the service name + * @param taskService the task service + */ + public static final synchronized void putTaskService(QName serviceDomainName, QName serviceName, BPMTaskService taskService) { + // deprecated + } + + /** + * Removes a task service. + * @param serviceDomainName the service domain name + * @param serviceName the service name + */ + public static final synchronized void removeTaskService(QName serviceDomainName, QName serviceName) { + // deprecated + } + + private BPMTaskServiceRegistry() {} + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMUserGroupCallback.java b/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMUserGroupCallback.java new file mode 100644 index 000000000..9257fe501 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/runtime/BPMUserGroupCallback.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.runtime; + +import java.util.Properties; + +import org.switchyard.component.common.knowledge.task.PropertiesUserGroupCallback; + +/** + * BPMUserGroupCallback is DEPRECATED. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + * @deprecated Use {@link PropertiesUserGroupCallback} instead. + */ +@Deprecated +public class BPMUserGroupCallback extends PropertiesUserGroupCallback { + + /** + * Constructs a new BPMUserGroupCallback. + */ + public BPMUserGroupCallback() { + super(); + } + + /** + * Constructs a new BPMUserGroupCallback. + * @param location the location + */ + public BPMUserGroupCallback(String location) { + super(location); + } + + /** + * Constructs a new BPMUserGroupCallback. + * @param userGroups the userGroups + */ + public BPMUserGroupCallback(Properties userGroups) { + super(userGroups); + } + +} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/transaction/AS7JtaPlatform.java b/components/bpm/src/main/java/org/switchyard/component/bpm/transaction/AS7JtaPlatform.java new file mode 100644 index 000000000..30ac0d496 --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/transaction/AS7JtaPlatform.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.transaction; + +import org.switchyard.component.common.knowledge.transaction.KnowledgeJtaPlatform; + +/** + * AS7JtaPlatform is DEPRECATED. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + * @deprecated Use {@link KnowledgeJtaPlatform} instead. + */ +@Deprecated +@SuppressWarnings("serial") +public class AS7JtaPlatform extends KnowledgeJtaPlatform {} diff --git a/components/bpm/src/main/java/org/switchyard/component/bpm/transaction/AS7TransactionManagerLookup.java b/components/bpm/src/main/java/org/switchyard/component/bpm/transaction/AS7TransactionManagerLookup.java new file mode 100644 index 000000000..bf92f6f4d --- /dev/null +++ b/components/bpm/src/main/java/org/switchyard/component/bpm/transaction/AS7TransactionManagerLookup.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.transaction; + +import org.switchyard.component.common.knowledge.transaction.KnowledgeTransactionManagerLookup; + +/** + * AS7TransactionManagerLookup is DEPRECATED. + *

+ * See: jBPM5 on AS7: Lightning ! + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + * @deprecated Use {@link AS7JtaPlatform} instead + */ +@Deprecated +public class AS7TransactionManagerLookup extends KnowledgeTransactionManagerLookup {} diff --git a/components/bpm/src/main/resources/META-INF/SwitchYardWorkDefinitions.wid b/components/bpm/src/main/resources/META-INF/SwitchYardWorkDefinitions.wid new file mode 100644 index 000000000..8fa7d6e03 --- /dev/null +++ b/components/bpm/src/main/resources/META-INF/SwitchYardWorkDefinitions.wid @@ -0,0 +1,28 @@ +// Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 org.drools.process.core.datatype.impl.type.StringDataType; +[ + [ + "name" : "SwitchYard Service Task", + "parameters" : [ + "ServiceName" : new StringDataType(), + "OperationName" : new StringDataType(), + "ParameterName" : new StringDataType(), + "ResultName" : new StringDataType(), + "FaultName" : new StringDataType(), + "FaultEventId" : new StringDataType(), + "FaultAction" : new StringDataType() + ], + "displayName" : "SwitchYard Service Task", + "icon" : "org/switchyard/component/bpm/SwitchYard-16x16.gif" + ] +] diff --git a/components/bpm/src/main/resources/META-INF/drools.rulebase.conf b/components/bpm/src/main/resources/META-INF/drools.rulebase.conf new file mode 100644 index 000000000..300c267a7 --- /dev/null +++ b/components/bpm/src/main/resources/META-INF/drools.rulebase.conf @@ -0,0 +1,2 @@ +# Include both Drools' and jBPM's original work definitions, and add SwitchYard's. +drools.workDefinitions = WorkDefinitions.conf BPMNWorkDefinitions.conf SwitchYardWorkDefinitions.wid diff --git a/components/bpm/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/bpm/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..30d05c4be --- /dev/null +++ b/components/bpm/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.bpm.deploy.BPMComponent diff --git a/components/bpm/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/components/bpm/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 000000000..8e8d45676 --- /dev/null +++ b/components/bpm/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/components/bpm/src/main/resources/org/switchyard/component/bpm/SwitchYard-16x16.gif b/components/bpm/src/main/resources/org/switchyard/component/bpm/SwitchYard-16x16.gif new file mode 100644 index 000000000..ad5951b8a Binary files /dev/null and b/components/bpm/src/main/resources/org/switchyard/component/bpm/SwitchYard-16x16.gif differ diff --git a/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v1/bpm_1_0.xsd b/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v1/bpm_1_0.xsd new file mode 100644 index 000000000..0222f1c7f --- /dev/null +++ b/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v1/bpm_1_0.xsd @@ -0,0 +1,314 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v1/bpm_1_1.xsd b/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v1/bpm_1_1.xsd new file mode 100644 index 000000000..e8dbfd68f --- /dev/null +++ b/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v1/bpm_1_1.xsd @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v2/bpm_2_0.xsd b/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v2/bpm_2_0.xsd new file mode 100644 index 000000000..b008c2df2 --- /dev/null +++ b/components/bpm/src/main/resources/org/switchyard/component/bpm/config/model/v2/bpm_2_0.xsd @@ -0,0 +1,392 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/bpm/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..2d3337ecd --- /dev/null +++ b/components/bpm/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +bpm_1_0.section=urn:switchyard-component-bpm:config +bpm_1_0.version=1.0 +bpm_1_0.namespace=urn:switchyard-component-bpm:config:1.0 +bpm_1_0.schema=bpm_1_0.xsd +bpm_1_0.location=/org/switchyard/component/bpm/config/model/v1/ +bpm_1_0.marshaller=org.switchyard.component.bpm.config.model.v1.V1BPMMarshaller + +bpm_1_1.section=urn:switchyard-component-bpm:config +bpm_1_1.version=1.1 +bpm_1_1.namespace=urn:switchyard-component-bpm:config:1.1 +bpm_1_1.schema=bpm_1_1.xsd +bpm_1_1.location=/org/switchyard/component/bpm/config/model/v1/ +bpm_1_1.marshaller=org.switchyard.component.bpm.config.model.v1.V1BPMMarshaller + +bpm_2_0.section=urn:switchyard-component-bpm:config +bpm_2_0.version=2.0 +bpm_2_0.namespace=urn:switchyard-component-bpm:config:2.0 +bpm_2_0.schema=bpm_2_0.xsd +bpm_2_0.location=/org/switchyard/component/bpm/config/model/v2/ +bpm_2_0.marshaller=org.switchyard.component.bpm.config.model.v2.V2BPMMarshaller diff --git a/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/BPMModelTests.java b/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/BPMModelTests.java new file mode 100644 index 000000000..b2c3c7079 --- /dev/null +++ b/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/BPMModelTests.java @@ -0,0 +1,379 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model; + +import java.io.File; +import java.io.StringReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.drools.core.event.DebugProcessEventListener; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.kie.api.builder.ReleaseId; +import org.kie.api.runtime.Channel; +import org.kie.api.runtime.process.WorkItem; +import org.kie.api.runtime.process.WorkItemHandler; +import org.kie.api.runtime.process.WorkItemManager; +import org.kie.internal.task.api.UserGroupCallback; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.io.resource.ResourceDetail; +import org.switchyard.common.io.resource.ResourceType; +import org.switchyard.common.type.Classes; +import org.switchyard.component.bpm.operation.BPMOperationType; +import org.switchyard.component.common.knowledge.LoggerType; +import org.switchyard.component.common.knowledge.config.manifest.ContainerManifest; +import org.switchyard.component.common.knowledge.config.model.ChannelModel; +import org.switchyard.component.common.knowledge.config.model.ContainerModel; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel; +import org.switchyard.component.common.knowledge.config.model.FaultModel; +import org.switchyard.component.common.knowledge.config.model.GlobalModel; +import org.switchyard.component.common.knowledge.config.model.InputModel; +import org.switchyard.component.common.knowledge.config.model.ListenerModel; +import org.switchyard.component.common.knowledge.config.model.LoggerModel; +import org.switchyard.component.common.knowledge.config.model.ManifestModel; +import org.switchyard.component.common.knowledge.config.model.OperationModel; +import org.switchyard.component.common.knowledge.config.model.OutputModel; +import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel; +import org.switchyard.component.common.knowledge.config.model.RemoteModel; +import org.switchyard.component.common.knowledge.config.model.RemoteRestModel; +import org.switchyard.component.common.knowledge.config.model.UserGroupCallbackModel; +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlerModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.resource.ResourceModel; +import org.switchyard.config.model.resource.ResourcesModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Tests BPM models. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class BPMModelTests { + + private static final String CONTAINER_XML = "/org/switchyard/component/bpm/config/model/BPMModelTests-Container.xml"; + private static final String RESOURCES_XML = "/org/switchyard/component/bpm/config/model/BPMModelTests-Resources.xml"; + private static final String REMOTEJMS_XML = "/org/switchyard/component/bpm/config/model/BPMModelTests-RemoteJms.xml"; + private static final String REMOTEREST_XML = "/org/switchyard/component/bpm/config/model/BPMModelTests-RemoteRest.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @After + public void after() throws Exception { + _puller = null; + } + + @Test + public void testReadContainer() throws Exception { + doTestRead(CONTAINER_XML); + } + + @Test + public void testReadResources() throws Exception { + doTestRead(RESOURCES_XML); + } + + @Test + public void testReadRemoteJms() throws Exception { + doTestRead(REMOTEJMS_XML); + } + + @Test + public void testReadRemoteRest() throws Exception { + doTestRead(REMOTEREST_XML); + } + + private void doTestRead(String xml) throws Exception { + ClassLoader loader = getClass().getClassLoader(); + doTestModel(_puller.pull(xml, loader), xml, loader); + } + + private void doTestModel(SwitchYardModel switchyard, String xml, ClassLoader loader) throws Exception { + CompositeModel composite = switchyard.getComposite(); + ComponentModel component = null; + for (ComponentModel c : composite.getComponents()) { + if (DoStuffProcess.class.getSimpleName().equals(c.getName())) { + component = c; + break; + } + } + ComponentImplementationModel implementation = component.getImplementation(); + Assert.assertTrue(implementation instanceof BPMComponentImplementationModel); + BPMComponentImplementationModel bpm = (BPMComponentImplementationModel)implementation; + Assert.assertEquals("bpm", bpm.getType()); + Assert.assertTrue(bpm.isPersistent()); + Assert.assertEquals("theProcessId", bpm.getProcessId()); + OperationModel operation = bpm.getOperations().getOperations().get(0); + Assert.assertEquals("theEventId", operation.getEventId()); + Assert.assertEquals("process", operation.getName()); + Assert.assertEquals(BPMOperationType.SIGNAL_EVENT, operation.getType()); + GlobalModel globalModel = operation.getGlobals().getGlobals().get(0); + Assert.assertEquals("context['foobar']", globalModel.getFrom()); + Assert.assertEquals("globalVar", globalModel.getTo()); + InputModel inputModel = operation.getInputs().getInputs().get(0); + Assert.assertEquals("message.content.nested", inputModel.getFrom()); + Assert.assertEquals("inputVar", inputModel.getTo()); + OutputModel outputModel = operation.getOutputs().getOutputs().get(0); + Assert.assertEquals("outputVar", outputModel.getFrom()); + Assert.assertEquals("message.content", outputModel.getTo()); + FaultModel faultModel = operation.getFaults().getFaults().get(0); + Assert.assertEquals("faultVar", faultModel.getFrom()); + Assert.assertEquals("message.content", faultModel.getTo()); + ChannelModel channel = bpm.getChannels().getChannels().get(0); + Assert.assertEquals(TestChannel.class, channel.getClazz(loader)); + Assert.assertEquals("theName", channel.getName()); + Assert.assertEquals("theOperation", channel.getOperation()); + Assert.assertEquals("theReference", channel.getReference()); + ListenerModel listener = bpm.getListeners().getListeners().get(0); + Assert.assertEquals(DebugProcessEventListener.class, listener.getClazz(loader)); + LoggerModel logger = bpm.getLoggers().getLoggers().get(0); + Assert.assertEquals(Integer.valueOf(2000), logger.getInterval()); + Assert.assertEquals("theLog", logger.getLog()); + Assert.assertEquals(LoggerType.CONSOLE, logger.getType()); + ManifestModel manifest = bpm.getManifest(); + ContainerModel container = manifest.getContainer(); + ResourcesModel resources = manifest.getResources(); + RemoteModel remote = manifest.getRemote(); + if (CONTAINER_XML.equals(xml)) { + Assert.assertNull(resources); + Assert.assertNull(remote); + ReleaseId rid = ContainerManifest.toReleaseId(container.getReleaseId()); + Assert.assertEquals("theGroupId", rid.getGroupId()); + Assert.assertEquals("theArtifactId", rid.getArtifactId()); + Assert.assertEquals("theVersion", rid.getVersion()); + Assert.assertEquals("theBase", container.getBaseName()); + Assert.assertEquals("theSession", container.getSessionName()); + Assert.assertTrue(container.isScan()); + Assert.assertEquals(Long.valueOf(1000), container.getScanInterval()); + } else if (RESOURCES_XML.equals(xml)) { + Assert.assertNull(container); + Assert.assertNull(remote); + ResourceModel bpmn2Resource = resources.getResources().get(0); + Assert.assertEquals("foobar.bpmn", bpmn2Resource.getLocation()); + Assert.assertEquals(ResourceType.valueOf("BPMN2"), bpmn2Resource.getType()); + ResourceModel dtableResource = resources.getResources().get(1); + Assert.assertEquals("foobar.xls", dtableResource.getLocation()); + Assert.assertEquals(ResourceType.valueOf("DTABLE"), dtableResource.getType()); + ResourceDetail dtableDetail = dtableResource.getDetail(); + Assert.assertEquals("XLS", dtableDetail.getInputType()); + Assert.assertEquals("MySheet", dtableDetail.getWorksheetName()); + /* SWITCHYARD-1662 + Assert.assertEquals(true, dtableDetail.isUsingExternalTypes()); + */ + } else if (REMOTEJMS_XML.equals(xml) || REMOTEREST_XML.equals(xml)) { + Assert.assertNull(container); + Assert.assertNull(resources); + Assert.assertEquals("groupId:artifactId:0.0.1", remote.getDeploymentId()); + Assert.assertEquals("kermit", remote.getUserName()); + Assert.assertEquals("the-frog-1", remote.getPassword()); + Assert.assertEquals(5, remote.getTimeout().intValue()); + ExtraJaxbClassesModel extraJaxbClasses = remote.getExtraJaxbClasses(); + Assert.assertNotNull(extraJaxbClasses); + List extraJaxbClassList = extraJaxbClasses.getExtraJaxbClasses(); + Assert.assertEquals(2, extraJaxbClassList.size()); + Assert.assertEquals(Object.class, extraJaxbClassList.get(0).getClazz(loader)); + Assert.assertEquals(String.class, extraJaxbClassList.get(1).getClazz(loader)); + if (REMOTEJMS_XML.equals(xml)) { + RemoteJmsModel remoteJms = (RemoteJmsModel)remote; + Assert.assertEquals("remotehost", remoteJms.getHostName()); + Assert.assertEquals(4447, remoteJms.getRemotingPort().intValue()); + Assert.assertEquals(5455, remoteJms.getMessagingPort().intValue()); + Assert.assertEquals(true, remoteJms.isUseSsl()); + Assert.assertEquals("ksp", remoteJms.getKeystorePassword()); + Assert.assertEquals("/ksl", remoteJms.getKeystoreLocation()); + Assert.assertEquals("tsp", remoteJms.getTruststorePassword()); + Assert.assertEquals("/tsl", remoteJms.getTruststoreLocation()); + } else if (REMOTEREST_XML.equals(xml)) { + RemoteRestModel remoteRest = (RemoteRestModel)remote; + Assert.assertEquals("http://localhost:8080/kie-wb/", remoteRest.getUrl()); + } + } else { + Assert.fail("couldn't find container, resources, remoteJms, or remoteRest"); + } + PropertyModel bpm_property = bpm.getProperties().getProperties().get(0); + Assert.assertEquals("foo", bpm_property.getName()); + Assert.assertEquals("bar", bpm_property.getValue()); + UserGroupCallbackModel userGroupCallback = bpm.getUserGroupCallback(); + Assert.assertEquals(TestUserGroupCallback.class, userGroupCallback.getClazz(loader)); + PropertyModel ugc_property = userGroupCallback.getProperties().getProperties().get(0); + Assert.assertEquals("rab", ugc_property.getName()); + Assert.assertEquals("oof", ugc_property.getValue()); + WorkItemHandlerModel workItemHandler = bpm.getWorkItemHandlers().getWorkItemHandlers().get(0); + Assert.assertEquals(TestWorkItemHandler.class, workItemHandler.getClazz(loader)); + Assert.assertEquals("MyWIH", workItemHandler.getName()); + } + + @Test + public void testWriteContainer() throws Exception { + doTestWrite(CONTAINER_XML); + } + + @Test + public void testWriteResources() throws Exception { + doTestWrite(RESOURCES_XML); + } + + @Test + public void testWriteRemoteJms() throws Exception { + doTestWrite(REMOTEJMS_XML); + } + + @Test + public void testWriteRemoteRest() throws Exception { + doTestWrite(REMOTEREST_XML); + } + + private void doTestWrite(String xml) throws Exception { + String old_xml = new StringPuller().pull(xml, getClass()); + SwitchYardModel switchyard = _puller.pull(new StringReader(old_xml)); + String new_xml = switchyard.toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testValidateContainer() throws Exception { + doTestValidate(CONTAINER_XML); + } + + @Test + public void testValidateResources() throws Exception { + doTestValidate(RESOURCES_XML); + } + + @Test + public void testValidateRemoteJms() throws Exception { + doTestValidate(REMOTEJMS_XML); + } + + @Test + public void testValidateRemoteRest() throws Exception { + doTestValidate(REMOTEREST_XML); + } + + private void doTestValidate(String xml) throws Exception { + SwitchYardModel switchyard = _puller.pull(xml, getClass()); + switchyard.assertModelValid(); + } + + @Test + @Ignore + public void testScanContainer() throws Exception { + doTestScan(CONTAINER_XML); + } + + @Test + public void testScanResources() throws Exception { + doTestScan(RESOURCES_XML); + } + + @Test + @Ignore + public void testScanRemoteJms() throws Exception { + doTestScan(REMOTEJMS_XML); + } + + @Test + @Ignore + public void testScanRemoteRest() throws Exception { + doTestScan(REMOTEREST_XML); + } + + private void doTestScan(String xml) throws Exception { + ClassLoader loader = getClass().getClassLoader(); + Scanner scanner = new BPMSwitchYardScanner(); + ScannerInput input = new ScannerInput().setCompositeName(getClass().getSimpleName()); + List urls = new ArrayList(); + String resPath = getClass().getName().replaceAll("\\.", "/") + ".class"; + String urlPath = Classes.getResource(resPath).getPath(); + File file = new File(urlPath.substring(0, urlPath.length() - resPath.length())); + urls.add(file.toURI().toURL()); + input.setURLs(urls); + ScannerOutput output = scanner.scan(input); + SwitchYardModel model = output.getModel(); + CompositeModel composite = model.getComposite(); + Assert.assertEquals(getClass().getSimpleName(), composite.getName()); + doTestModel(model, xml, loader); + } + + @Test + public void testScanEmpty() throws Exception { + Scanner scanner = new BPMSwitchYardScanner(); + ScannerInput input = new ScannerInput(); + ScannerOutput output = scanner.scan(input); + Assert.assertNull("Composite element should not be created if no components were found.", output.getModel().getComposite()); + } + + public static final class TestChannel implements Channel { + @Override + public void send(Object object) { + System.out.println(object); + } + } + + public static final class TestUserGroupCallback implements UserGroupCallback { + @Override + public boolean existsUser(String userId) { + System.out.println(userId); + return false; + } + @Override + public boolean existsGroup(String groupId) { + System.out.println(groupId); + return false; + } + @Override + public List getGroupsForUser(String userId, List groupIds, List allExistingGroupIds) { + System.out.println(userId); + System.out.println(groupIds); + System.out.println(allExistingGroupIds); + return Collections.emptyList(); + } + } + + public static final class TestWorkItemHandler implements WorkItemHandler { + @Override + public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { + System.out.println(workItem); + System.out.println(manager); + } + @Override + public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { + System.out.println(workItem); + System.out.println(manager); + } + } + +} diff --git a/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/DoStuff.java b/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/DoStuff.java new file mode 100644 index 000000000..6a53acf59 --- /dev/null +++ b/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/DoStuff.java @@ -0,0 +1,7 @@ +package org.switchyard.component.bpm.config.model; + +public interface DoStuff { + + public void process(Object stuff); + +} diff --git a/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/DoStuffProcess.java b/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/DoStuffProcess.java new file mode 100644 index 000000000..430bd2f9a --- /dev/null +++ b/components/bpm/src/test/java/org/switchyard/component/bpm/config/model/DoStuffProcess.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.config.model; + +import org.drools.core.event.DebugProcessEventListener; +import org.switchyard.component.bpm.annotation.BPM; +import org.switchyard.component.bpm.annotation.SignalEvent; +import org.switchyard.component.bpm.annotation.UserGroupCallback; +import org.switchyard.component.bpm.annotation.WorkItemHandler; +import org.switchyard.component.common.knowledge.LoggerType; +import org.switchyard.component.common.knowledge.annotation.Channel; +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Listener; +import org.switchyard.component.common.knowledge.annotation.Logger; +import org.switchyard.component.common.knowledge.annotation.Manifest; +import org.switchyard.component.common.knowledge.annotation.Output; +import org.switchyard.component.common.knowledge.annotation.Property; +import org.switchyard.component.common.knowledge.annotation.Resource; +import org.switchyard.component.common.knowledge.annotation.ResourceDetail; + +/** + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@BPM( + persistent=true, + processId="theProcessId", + channels=@Channel(name="theName", operation="theOperation", reference="theReference", value=BPMModelTests.TestChannel.class), + listeners=@Listener(DebugProcessEventListener.class), + loggers=@Logger(interval=2000, log="theLog", type=LoggerType.CONSOLE), + manifest=@Manifest( + //container=@Container(baseName="theBase", scan=true, scanInterval=1000, releaseId="theGroupId:theArtifactId:theVersion", sessionName="theSession"), + resources={ + @Resource(location="foobar.bpmn", type="BPMN2"), + @Resource(location="foobar.xls", type="DTABLE", + detail=@ResourceDetail(inputType="XLS", worksheetName="MySheet")) // SWITCHYARD-1662, usingExternalTypes=true)) + }), + properties=@Property(name="foo", value="bar"), + userGroupCallback=@UserGroupCallback( + value=BPMModelTests.TestUserGroupCallback.class, + properties=@Property(name="rab", value="oof")), + workItemHandlers=@WorkItemHandler(name="MyWIH", value=BPMModelTests.TestWorkItemHandler.class) +) +public interface DoStuffProcess extends DoStuff { + + @Override + @SignalEvent( + eventId="theEventId", + globals=@Global(from="context['foobar']", to="globalVar"), + inputs=@Input(from="message.content.nested", to="inputVar"), + outputs=@Output(from="outputVar", to="message.content"), + faults=@Fault(from="faultVar", to="message.content") + ) + public void process(Object stuff); + +} diff --git a/components/bpm/src/test/java/org/switchyard/component/bpm/service/BPMServiceTests.java b/components/bpm/src/test/java/org/switchyard/component/bpm/service/BPMServiceTests.java new file mode 100644 index 000000000..7b8084651 --- /dev/null +++ b/components/bpm/src/test/java/org/switchyard/component/bpm/service/BPMServiceTests.java @@ -0,0 +1,466 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.service; + +import static org.switchyard.component.bpm.BPMConstants.CORRELATION_KEY_PROPERTY; +import static org.switchyard.component.bpm.BPMConstants.PROCESSS_INSTANCE_ID_PROPERTY; +import static org.switchyard.component.common.knowledge.service.SwitchYardServiceTaskHandler.SWITCHYARD_SERVICE_TASK; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.activation.DataSource; +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.kie.api.KieBase; +import org.kie.api.io.ResourceType; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.process.WorkflowProcessInstance; +import org.kie.internal.builder.KnowledgeBuilder; +import org.kie.internal.builder.KnowledgeBuilderFactory; +import org.kie.internal.io.ResourceFactory; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.component.bpm.annotation.BPM; +import org.switchyard.component.bpm.annotation.SignalEvent; +import org.switchyard.component.bpm.annotation.SignalEventAll; +import org.switchyard.component.bpm.annotation.StartProcess; +import org.switchyard.component.bpm.annotation.WorkItemHandler; +import org.switchyard.component.bpm.config.model.BPMComponentImplementationModel; +import org.switchyard.component.bpm.config.model.BPMSwitchYardScanner; +import org.switchyard.component.bpm.exchange.BPMExchangeHandler; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Manifest; +import org.switchyard.component.common.knowledge.annotation.Output; +import org.switchyard.component.common.knowledge.annotation.Resource; +import org.switchyard.component.common.knowledge.service.SwitchYardServiceInvoker; +import org.switchyard.component.common.knowledge.service.SwitchYardServiceTaskHandler; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutService; +import org.switchyard.test.InvocationFaultException; +import org.switchyard.test.Invoker; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.TestDataSource; + +/** + * Tests the BPM implementation. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class BPMServiceTests { + + private static final String ACCESS_ATTACHMENT_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-AccessAttachment.bpmn"; + private static final String CALL_SERVICE_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-CallService.bpmn"; + private static final String CONTROL_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-ControlProcess.bpmn"; + private static final String FAULT_RESULT_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-FaultResultProcess.bpmn"; + private static final String FAULT_EVENT_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-FaultEventProcess.bpmn"; + private static final String FAULT_BOUNDARY_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-FaultBoundaryProcess.bpmn"; + private static final String REUSE_HANDLER_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-ReuseHandler.bpmn"; + private static final String RULES_FIRED_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.bpmn"; + private static final String RULES_FIRED_DRL = "org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.drl"; + private static final String SIGNAL_PROCESS_BPMN = "org/switchyard/component/bpm/service/BPMServiceTests-SignalProcess.bpmn"; + + private ServiceDomain serviceDomain; + + @Test + public void testCallService() throws Exception { + final Holder holder = new Holder(); + serviceDomain.registerService(new QName("CallService"), new InOnlyService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + holder.setValue("message handled"); + } + }); + serviceDomain.registerServiceReference(new QName("CallService"), new InOnlyService()); + KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); + kbuilder.add(ResourceFactory.newClassPathResource(CALL_SERVICE_BPMN), ResourceType.BPMN2); + KieBase kbase = kbuilder.newKnowledgeBase(); + KieSession ksession = kbase.newKieSession(); + SwitchYardServiceTaskHandler ssth = new SwitchYardServiceTaskHandler(); + ssth.setProcessRuntime(ksession); + ssth.setInvoker(new SwitchYardServiceInvoker(serviceDomain)); + ksession.getWorkItemManager().registerWorkItemHandler(SWITCHYARD_SERVICE_TASK, ssth); + ksession.startProcess("CallService"); + ksession.halt(); + ksession.dispose(); + Assert.assertEquals("message handled", holder.getValue()); + } + + @BPM(processId="AccessAttachment", manifest=@Manifest(resources=@Resource(location=ACCESS_ATTACHMENT_BPMN, type="BPMN2"))) + public interface AccessAttachment { + @StartProcess(inputs={ + @Input(from="message.attachmentMap['someAttach']", to="attachment"), + @Input(from="message.content", to="holder") + }) + public Object process(Object content); + } + + @Test + public void testAccessAttachment() throws Exception { + final Holder holder = new Holder(); + BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel)new BPMSwitchYardScanner().scan(AccessAttachment.class).getImplementation(); + QName serviceName = new QName("AccessAttachment"); + BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName); + Service service = serviceDomain.registerService(serviceName, JavaService.fromClass(AccessAttachment.class), handler); + serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler()); + handler.start(); + DataSource attachment = new TestDataSource("someAttach", "text/plain", "someAttachData"); + new Invoker(serviceDomain, serviceName).operation("process").attachment(attachment.getName(), attachment).sendInOnly(holder); + handler.stop(); + Assert.assertEquals("someAttachData", holder.getValue()); + } + + @BPM(processId="ControlProcess", manifest=@Manifest(resources=@Resource(location=CONTROL_PROCESS_BPMN, type="BPMN2"))) + public interface ControlProcess { + @StartProcess + public Object process(Object content); + @SignalEvent(eventId="test") + public void signal(Object content); + } + + @Test + public void testControlProcess() throws Exception { + final Holder holder = new Holder(); + Service callService = serviceDomain.registerService(new QName("CallService"), new InOnlyService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + holder.setValue("message handled"); + } + }); + serviceDomain.registerServiceReference(callService.getName(), callService.getInterface(), callService.getProviderHandler()); + BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel)new BPMSwitchYardScanner().scan(ControlProcess.class).getImplementation(); + // setting the component name to null so that the service reference doesn't use the component-qualified name + bci_model.getComponent().setName(null); + QName serviceName = new QName("ControlProcess"); + BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName); + Service controlService = serviceDomain.registerService(serviceName, JavaService.fromClass(ControlProcess.class), handler); + serviceDomain.registerServiceReference(controlService.getName(), controlService.getInterface(), controlService.getProviderHandler()); + handler.start(); + Invoker processInvoker = new Invoker(serviceDomain, serviceName); + Message processResponse = processInvoker.operation("process").sendInOut(null); + Long processInstanceId = (Long)processResponse.getContext().getPropertyValue(PROCESSS_INSTANCE_ID_PROPERTY); + Invoker signalInvoker = new Invoker(serviceDomain, serviceName); + signalInvoker.operation("signal").property(PROCESSS_INSTANCE_ID_PROPERTY, processInstanceId).sendInOut(null); + handler.stop(); + Assert.assertEquals("message handled", holder.getValue()); + } + + @Test + public void testCorrelateProcessSuccess() throws Exception { + runCorrelateProcess(false); + } + + @Test + public void testCorrelateProcessFailure() throws Exception { + runCorrelateProcess(true); + } + + private void runCorrelateProcess(final boolean bomb) throws Exception { + final AtomicInteger counter = new AtomicInteger(); + final Holder holder = new Holder(); + Service callService = serviceDomain.registerService(new QName("CallService"), new InOnlyService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + int count = counter.incrementAndGet(); + holder.setValue(String.valueOf(count)); + } + }); + serviceDomain.registerServiceReference(callService.getName(), callService.getInterface(), callService.getProviderHandler()); + BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel)new BPMSwitchYardScanner().scan(ControlProcess.class).getImplementation(); + // setting the component name to null so that the service reference doesn't use the component-qualified name + bci_model.getComponent().setName(null); + QName serviceName = new QName("ControlProcess"); + BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName); + Service controlService = serviceDomain.registerService(serviceName, JavaService.fromClass(ControlProcess.class), handler); + serviceDomain.registerServiceReference(controlService.getName(), controlService.getInterface(), controlService.getProviderHandler()); + handler.start(); + new Invoker(serviceDomain, serviceName).operation("process").property(CORRELATION_KEY_PROPERTY, "A").sendInOnly(null); + new Invoker(serviceDomain, serviceName).operation("process").property(CORRELATION_KEY_PROPERTY, "B").sendInOnly(null); + new Invoker(serviceDomain, serviceName).operation("signal").property(CORRELATION_KEY_PROPERTY, "A").sendInOnly(null); + InvocationFaultException fault = null; + try { + new Invoker(serviceDomain, serviceName).operation("signal").property(CORRELATION_KEY_PROPERTY, bomb ? "A" : "B").sendInOut(null); + } catch (InvocationFaultException ife) { + fault = ife; + } + handler.stop(); + if (bomb) { + Assert.assertNotNull(fault); + Assert.assertEquals("1", holder.getValue()); + } else { + Assert.assertNull(fault); + Assert.assertEquals("2", holder.getValue()); + } + } + + @BPM(processId="ControlProcess", manifest=@Manifest(resources=@Resource(location=CONTROL_PROCESS_BPMN, type="BPMN2"))) + public interface SignalAllProcesses { + @StartProcess + public Object process(Object content); + @SignalEventAll(eventId="test") + public void signal(Object content); + } + + @Test + public void testSignalAllProcesses() throws Exception { + final AtomicInteger counter = new AtomicInteger(); + final Holder holder = new Holder(); + Service callService = serviceDomain.registerService(new QName("CallService"), new InOnlyService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + int count = counter.incrementAndGet(); + holder.setValue(String.valueOf(count)); + } + }); + serviceDomain.registerServiceReference(callService.getName(), callService.getInterface(), callService.getProviderHandler()); + BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel)new BPMSwitchYardScanner().scan(SignalAllProcesses.class).getImplementation(); + // setting the component name to null so that the service reference doesn't use the component-qualified name + bci_model.getComponent().setName(null); + QName serviceName = new QName("ControlProcess"); + BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName); + Service controlService = serviceDomain.registerService(serviceName, JavaService.fromClass(SignalAllProcesses.class), handler); + serviceDomain.registerServiceReference(controlService.getName(), controlService.getInterface(), controlService.getProviderHandler()); + handler.start(); + new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(null); + new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(null); + new Invoker(serviceDomain, serviceName).operation("signal").sendInOnly(null); + handler.stop(); + Assert.assertEquals("2", holder.getValue()); + } + + @Test + public void testFaultResultProcessSuccess() throws Exception { + runFaultResultProcess(false); + } + + @Test + public void testFaultResultProcessFailure() throws Exception { + runFaultResultProcess(true); + } + + private void runFaultResultProcess(final boolean bomb) throws Exception { + serviceDomain.registerService(new QName("TestService"), new InOnlyService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + if (bomb) { + throw new HandlerException("BOOM!"); + } + } + }); + serviceDomain.registerServiceReference(new QName("TestService"), new InOutService()); + KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); + kbuilder.add(ResourceFactory.newClassPathResource(FAULT_RESULT_PROCESS_BPMN), ResourceType.BPMN2); + KieBase kbase = kbuilder.newKnowledgeBase(); + KieSession ksession = kbase.newKieSession(); + SwitchYardServiceTaskHandler ssth = new SwitchYardServiceTaskHandler(); + ssth.setProcessRuntime(ksession); + ssth.setInvoker(new SwitchYardServiceInvoker(serviceDomain)); + ksession.getWorkItemManager().registerWorkItemHandler(SWITCHYARD_SERVICE_TASK, ssth); + WorkflowProcessInstance wpi = (WorkflowProcessInstance)ksession.startProcess("FaultResultProcess"); + HandlerException he = (HandlerException)wpi.getVariable("faultResult"); + if (bomb) { + Assert.assertNotNull(he); + Assert.assertEquals("BOOM!", he.getMessage()); + } else { + Assert.assertNull(he); + } + ksession.halt(); + ksession.dispose(); + } + + @Test + public void testFaultEventProcessSuccess() throws Exception { + runFaultEventProcess(false); + } + + @Test + public void testFaultEventProcessFailure() throws Exception { + runFaultEventProcess(true); + } + + private void runFaultEventProcess(final boolean bomb) throws Exception { + serviceDomain.registerService(new QName("TestService"), new InOnlyService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + if (bomb) { + throw new HandlerException("BOOM!"); + } + } + }); + serviceDomain.registerServiceReference(new QName("TestService"), new InOutService()); + KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); + kbuilder.add(ResourceFactory.newClassPathResource(FAULT_EVENT_PROCESS_BPMN), ResourceType.BPMN2); + KieBase kbase = kbuilder.newKnowledgeBase(); + KieSession ksession = kbase.newKieSession(); + SwitchYardServiceTaskHandler ssth = new SwitchYardServiceTaskHandler(); + ssth.setProcessRuntime(ksession); + ssth.setInvoker(new SwitchYardServiceInvoker(serviceDomain)); + ksession.getWorkItemManager().registerWorkItemHandler(SWITCHYARD_SERVICE_TASK, ssth); + WorkflowProcessInstance wpi = (WorkflowProcessInstance)ksession.startProcess("FaultEventProcess"); + HandlerException he = (HandlerException)wpi.getVariable("faultEvent"); + if (bomb) { + Assert.assertNotNull(he); + Assert.assertEquals("BOOM!", he.getMessage()); + } else { + Assert.assertNull(he); + } + ksession.halt(); + ksession.dispose(); + } + + @Test + public void testFaultBoundaryProcessSuccess() throws Exception { + runFaultBoundaryProcess(false); + } + + @Test + public void testFaultBoundaryProcessFailure() throws Exception { + runFaultBoundaryProcess(true); + } + + private void runFaultBoundaryProcess(final boolean bomb) throws Exception { + serviceDomain.registerService(new QName("TestService"), new InOnlyService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + if (bomb) { + throw new HandlerException("BOOM!"); + } + } + }); + serviceDomain.registerServiceReference(new QName("TestService"), new InOutService()); + KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); + kbuilder.add(ResourceFactory.newClassPathResource(FAULT_BOUNDARY_PROCESS_BPMN), ResourceType.BPMN2); + KieBase kbase = kbuilder.newKnowledgeBase(); + KieSession ksession = kbase.newKieSession(); + SwitchYardServiceTaskHandler ssth = new SwitchYardServiceTaskHandler(); + ssth.setProcessRuntime(ksession); + ssth.setInvoker(new SwitchYardServiceInvoker(serviceDomain)); + ksession.getWorkItemManager().registerWorkItemHandler(SWITCHYARD_SERVICE_TASK, ssth); + WorkflowProcessInstance wpi = (WorkflowProcessInstance)ksession.startProcess("FaultBoundaryProcess"); + String output = (String)wpi.getVariable("TestOutput"); + Assert.assertEquals(bomb ? "Failure" : "Success", output); + ksession.halt(); + ksession.dispose(); + } + + @BPM(processId="ReuseHandler", manifest=@Manifest(resources=@Resource(location=REUSE_HANDLER_BPMN, type="BPMN2")), + workItemHandlers=@WorkItemHandler(name="ReuseHandler", value=ReuseHandler.class)) + public interface ReuseHandlerProcess { + @StartProcess(inputs=@Input(from="message.content", to="holder")) + public void process(Object content); + } + + @Test + public void testReuseHandler() throws Exception { + BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel)new BPMSwitchYardScanner().scan(ReuseHandlerProcess.class).getImplementation(); + QName serviceName = new QName("ReuseHandler"); + BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName); + Service service = serviceDomain.registerService(serviceName, new InOnlyService("process"), handler); + serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler()); + handler.start(); + new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(null); + handler.stop(); + Assert.assertEquals("handler executed", ReuseHandler._holder.getValue()); + ReuseHandler._holder.setValue(null); + } + + @BPM(processId="RulesFired", manifest=@Manifest(resources={ + @Resource(location=RULES_FIRED_BPMN, type="BPMN2"), + @Resource(location=RULES_FIRED_DRL, type="DRL")})) + public interface RulesFiredProcess { + @StartProcess(inputs=@Input(from="message.content", to="holder")) + public void process(Object content); + } + + @Test + public void testRulesFired() throws Exception { + final Holder holder = new Holder(); + BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel)new BPMSwitchYardScanner().scan(RulesFiredProcess.class).getImplementation(); + QName serviceName = new QName("RulesFired"); + BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName); + Service service = serviceDomain.registerService(serviceName, new InOnlyService("process"), handler); + serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler()); + handler.start(); + new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(holder); + handler.stop(); + Assert.assertEquals("rules fired", holder.getValue()); + } + + @BPM(processId="SignalProcess", manifest=@Manifest(resources=@Resource(location=SIGNAL_PROCESS_BPMN, type="BPMN2"))) + public interface SignalProcess { + @StartProcess( + inputs={@Input(from="message.content", to="Parameter")}, + outputs={@Output(from="Result", to="message.content")} + ) + public Object process(Object content); + @SignalEvent( + eventId="TestSignal1", + inputs={@Input(from="message.content", to="Parameter")}, + outputs={@Output(from="Result", to="message.content")} + ) + public Object signal(Object content); + } + + @Test + public void testSignalProcess() throws Exception { + final Map testAssertionMap = new HashMap(); + Service serviceOne = serviceDomain.registerService(new QName("ServiceOne"), new InOutService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + Holder h = exchange.getMessage().getContent(Holder.class); + testAssertionMap.put("ServiceOne", h.getValue()); + } + }); + Service serviceTwo = serviceDomain.registerService(new QName("ServiceTwo"), new InOutService(), new BaseHandler(){ + public void handleMessage(Exchange exchange) throws HandlerException { + Holder h = exchange.getMessage().getContent(Holder.class); + testAssertionMap.put("ServiceTwo", h.getValue()); + } + }); + serviceDomain.registerServiceReference(serviceOne.getName(), serviceOne.getInterface(), serviceOne.getProviderHandler()); + serviceDomain.registerServiceReference(serviceTwo.getName(), serviceTwo.getInterface(), serviceTwo.getProviderHandler()); + BPMComponentImplementationModel bci_model = (BPMComponentImplementationModel)new BPMSwitchYardScanner().scan(SignalProcess.class).getImplementation(); + // setting the component name to null so that the service reference doesn't use the component-qualified name + bci_model.getComponent().setName(null); + QName serviceName = new QName("SignalProcess"); + BPMExchangeHandler handler = new BPMExchangeHandler(bci_model, serviceDomain, serviceName); + Service signalService = serviceDomain.registerService(serviceName, JavaService.fromClass(SignalProcess.class), handler); + serviceDomain.registerServiceReference(signalService.getName(), signalService.getInterface(), signalService.getProviderHandler()); + handler.start(); + Invoker processInvoker = new Invoker(serviceDomain, serviceName); + Holder holderOne = new Holder(); + holderOne.setValue("HolderOne"); + Message processResponse = processInvoker.operation("process").sendInOut(holderOne); + Long processInstanceId = (Long)processResponse.getContext().getPropertyValue(PROCESSS_INSTANCE_ID_PROPERTY); + Invoker signalInvoker = new Invoker(serviceDomain, serviceName); + Holder holderTwo = new Holder(); + holderTwo.setValue("HolderTwo"); + Message signalResponse = signalInvoker.operation("signal").property(PROCESSS_INSTANCE_ID_PROPERTY, processInstanceId).sendInOut(holderTwo); + Holder holderResponse = signalResponse.getContent(Holder.class); + handler.stop(); + Assert.assertEquals(holderOne.getValue(), testAssertionMap.get("ServiceOne")); + Assert.assertEquals(holderTwo.getValue(), testAssertionMap.get("ServiceTwo")); + Assert.assertEquals(holderTwo.getValue(), holderResponse.getValue()); + } + + public static final class Holder { + private String _value; + public String getValue() { return _value; } + public void setValue(String value) { _value = value; } + public String toString() { return _value; } + } + +} diff --git a/components/bpm/src/test/java/org/switchyard/component/bpm/service/ReuseHandler.java b/components/bpm/src/test/java/org/switchyard/component/bpm/service/ReuseHandler.java new file mode 100644 index 000000000..11a39730f --- /dev/null +++ b/components/bpm/src/test/java/org/switchyard/component/bpm/service/ReuseHandler.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.service; + +import org.kie.api.runtime.process.WorkItem; +import org.kie.api.runtime.process.WorkItemHandler; +import org.kie.api.runtime.process.WorkItemManager; +import org.switchyard.component.bpm.service.BPMServiceTests.Holder; + +/** + * An example handler being reused. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class ReuseHandler implements WorkItemHandler { + + static Holder _holder = new Holder(); + + @Override + public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { + _holder.setValue("handler executed"); + workItemManager.completeWorkItem(workItem.getId(), null); + } + + @Override + public void abortWorkItem(WorkItem workItem, WorkItemManager workItemManager) {} + +} diff --git a/components/bpm/src/test/java/org/switchyard/component/bpm/session/BPMSessionTests.java b/components/bpm/src/test/java/org/switchyard/component/bpm/session/BPMSessionTests.java new file mode 100644 index 000000000..44cc61f20 --- /dev/null +++ b/components/bpm/src/test/java/org/switchyard/component/bpm/session/BPMSessionTests.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm.session; + +import javax.xml.namespace.QName; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.switchyard.ServiceDomain; +import org.switchyard.component.bpm.config.model.BPMComponentImplementationModel; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManager; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerFactory; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerType; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.ServiceDomainManager; + +/** + * Tests BPM sessions. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class BPMSessionTests { + + private static final String GOOD_RESOURCES = "/org/switchyard/component/bpm/session/BPMSessionTests-GoodResources.xml"; + private static final String BAD_RESOURCES = "/org/switchyard/component/bpm/session/BPMSessionTests-BadResources.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @After + public void after() throws Exception { + _puller = null; + } + + @Test + public void testGoodResources() throws Exception { + Throwable t = doTestResources(GOOD_RESOURCES); + //t.printStackTrace(); + Assert.assertNull(t); + } + + @Test + public void testBadResources() throws Exception { + Throwable t = doTestResources(BAD_RESOURCES); + //t.printStackTrace(); + Assert.assertNotNull(t); + } + + private Throwable doTestResources(String xml) { + try { + ClassLoader loader = getClass().getClassLoader(); + SwitchYardModel switchyardModel = _puller.pull(xml, loader); + BPMComponentImplementationModel implementationModel = (BPMComponentImplementationModel)switchyardModel.getComposite().getComponents().get(0).getImplementation(); + ServiceDomain serviceDomain = new ServiceDomainManager().createDomain(); + QName serviceName = new QName("test"); + KnowledgeRuntimeManagerFactory runtimeManagerFactory = new KnowledgeRuntimeManagerFactory(loader, serviceDomain, serviceName, implementationModel); + KnowledgeRuntimeManager runtimeManager = runtimeManagerFactory.newRuntimeManager(KnowledgeRuntimeManagerType.SINGLETON); + RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine(); + KieSession session = runtimeEngine.getKieSession(); + session.startProcess("TestProcess"); + runtimeManager.disposeRuntimeEngine(runtimeEngine); + runtimeManager.close(); + return null; + } catch (Throwable t) { + return t; + } + } + +} diff --git a/components/bpm/src/test/resources/log4j.properties b/components/bpm/src/test/resources/log4j.properties new file mode 100644 index 000000000..c52adc99e --- /dev/null +++ b/components/bpm/src/test/resources/log4j.properties @@ -0,0 +1,15 @@ +# The logging properties used during tests +log4j.rootLogger=INFO, file, stdout +log4j.logger.org.switchyard.component.bpm=INFO + +# Console appender +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.file=org.apache.log4j.FileAppender +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n +log4j.appender.file.file=target/bpm-tests.log +log4j.appender.file.append=true diff --git a/components/bpm/src/test/resources/log4j.xml b/components/bpm/src/test/resources/log4j.xml new file mode 100644 index 000000000..2f567ba68 --- /dev/null +++ b/components/bpm/src/test/resources/log4j.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-Container.xml b/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-Container.xml new file mode 100644 index 000000000..f66c622db --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-Container.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-RemoteJms.xml b/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-RemoteJms.xml new file mode 100644 index 000000000..57dbb460c --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-RemoteJms.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + java.lang.Object + java.lang.String + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-RemoteRest.xml b/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-RemoteRest.xml new file mode 100644 index 000000000..86e7d7a62 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-RemoteRest.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + java.lang.Object + java.lang.String + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-Resources.xml b/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-Resources.xml new file mode 100644 index 000000000..0774ec592 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/config/model/BPMModelTests-Resources.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-AccessAttachment.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-AccessAttachment.bpmn new file mode 100644 index 000000000..dd442e9fb --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-AccessAttachment.bpmn @@ -0,0 +1,59 @@ + + + + + + + + + SequenceFlow_2 + + + SequenceFlow_3 + + + SequenceFlow_2 + SequenceFlow_3 + + + + + DataInput_1 + DataInput_2 + + + + Property_1 + DataInput_1 + + + Property_2 + DataInput_2 + + holder.setValue(new org.switchyard.common.io.pull.StringPuller().pull(attachment.getInputStream())); + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-CallService.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-CallService.bpmn new file mode 100644 index 000000000..d8cd63803 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-CallService.bpmn @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + _4_ServiceNameInput + + + + + + _4_ServiceNameInput + + CallService + _4_ServiceNameInput + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-ControlProcess.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-ControlProcess.bpmn new file mode 100644 index 000000000..2b026cd5d --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-ControlProcess.bpmn @@ -0,0 +1,66 @@ + + + + + _1-_5 + + + _4-_3 + + + + _5-_4 + _4-_3 + + + + _4_ServiceNameInput + + + + + _4_ServiceNameInput + + CallService + _4_ServiceNameInput + + + + + _1-_5 + _5-_4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultBoundaryProcess.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultBoundaryProcess.bpmn new file mode 100644 index 000000000..1c0e577a3 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultBoundaryProcess.bpmn @@ -0,0 +1,122 @@ + + + + + + + + + + + + + _1-_4 + + + SequenceFlow_4 + + + + + + + + + + + + _1-_4 + SequenceFlow_8 + + + + DataInput_ServiceName + + + + + DataInput_ServiceName + + TestService + DataInput_ServiceName + + + + + + SequenceFlow_1 + SequenceFlow_12 + System.out.println("********** FaultBoundaryProcess/TestFailureScript *******"); +kcontext.setVariable("TestOutput", "Failure"); + + + SequenceFlow_8 + SequenceFlow_6 + System.out.println("********** FaultBoundaryProcess/TestSuccessScript **********"); +kcontext.setVariable("TestOutput", "Success"); + + + SequenceFlow_6 + SequenceFlow_12 + SequenceFlow_4 + + + + + + + SequenceFlow_1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultEventProcess.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultEventProcess.bpmn new file mode 100644 index 000000000..544fa5bb2 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultEventProcess.bpmn @@ -0,0 +1,173 @@ + + + + + + + + + SequenceFlow_5 + SequenceFlow_12 + System.out.println("********** FaultEventProcess/TestFailureScript: " + faultEvent + " **********"); + + + + SequenceFlow_8 + SequenceFlow_6 + System.out.println("********** FaultEventProcess/TestSuccessScript **********"); + + + + SequenceFlow_4 + + + + + + + + + + + + SequenceFlow_1 + SequenceFlow_8 + + + + + + DataInput_ServiceName + DataInput_1 + DataInput_6 + + + + + DataInput_ServiceName + + TestService + DataInput_ServiceName + + + + DataInput_1 + + FaultSignal + DataInput_1 + + + + DataInput_6 + + SKIP + DataInput_6 + + + + + + SequenceFlow_12 + SequenceFlow_6 + SequenceFlow_4 + + + + SequenceFlow_2 + SequenceFlow_5 + + + DataOutput_FaultEvent + faultEvent + + + DataOutput_FaultEvent + + + + + + _1-_4 + SequenceFlow_1 + SequenceFlow_2 + + + + + _1-_4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultResultProcess.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultResultProcess.bpmn new file mode 100644 index 000000000..63e014c67 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-FaultResultProcess.bpmn @@ -0,0 +1,142 @@ + + + + + + + + _1-_4 + + + SequenceFlow_4 + + + + _1-_4 + SequenceFlow_1 + + + + + + + DataInput_ServiceName + DataInput_FaultName + DataInput_1 + + + DataOutput_FaultResult + + + + DataInput_ServiceName + + TestService + DataInput_ServiceName + + + + DataInput_FaultName + + faultResult + DataInput_FaultName + + + + DataInput_1 + + complete + DataInput_1 + + + + DataOutput_FaultResult + faultResult + + + + + SequenceFlow_2 + SequenceFlow_6 + + + + SequenceFlow_1 + SequenceFlow_2 + SequenceFlow_3 + + + + SequenceFlow_3 + SequenceFlow_7 + + + + return (faultResult == null); + + + return (faultResult != null); + + + SequenceFlow_6 + SequenceFlow_7 + SequenceFlow_4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-ReuseHandler.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-ReuseHandler.bpmn new file mode 100644 index 000000000..67981ec1e --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-ReuseHandler.bpmn @@ -0,0 +1,43 @@ + + + + + _1-_4 + + + _4-_3 + + + + _1-_4 + _4-_3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.bpmn new file mode 100644 index 000000000..3e8d83fe2 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.bpmn @@ -0,0 +1,53 @@ + + + + + + + SequenceFlow_8 + + + SequenceFlow_4 + SequenceFlow_5 + insert(((org.kie.api.runtime.process.WorkflowProcessInstance)kcontext.getProcessInstance()).getVariable("holder")); + + + + SequenceFlow_5 + SequenceFlow_8 + + + + SequenceFlow_4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.drl b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.drl new file mode 100644 index 000000000..705c288c8 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-RulesFired.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpm + +import org.switchyard.component.bpm.service.BPMServiceTests.Holder + +rule "RulesFired Rule" + ruleflow-group "RulesFired Group" + when + $holder : Holder() + then + $holder.setValue("rules fired"); +end diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-SignalProcess.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-SignalProcess.bpmn new file mode 100644 index 000000000..e3be023b6 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/service/BPMServiceTests-SignalProcess.bpmn @@ -0,0 +1,292 @@ + + + + + + + + + + + + + SequenceFlow_3 + SequenceFlow_7 + SequenceFlow_8 + + + + SequenceFlow_8 + SequenceFlow_2 + System.out.println("******* Process has completed ******** Parameter = " + Parameter); +System.out.println("******* Process has completed ******** Result = " + Result); + + + + SequenceFlow_2 + + + + + + + + + + + SequenceFlow_1 + SequenceFlow_7 + + + + + + + + + + + + _DataInput_9 + _DataInput_10 + _DataInput_11 + _DataInput_12 + _DataInput_13 + _DataInput_14 + _DataInput_15 + DataInput_2 + + + DataOutput_3 + + + + _DataInput_9 + + ServiceTwo + _DataInput_9 + + + + _DataInput_10 + + invoke + _DataInput_10 + + + + _DataInput_11 + + Parameter + _DataInput_11 + + + + _DataInput_12 + + Result + _DataInput_12 + + + + _DataInput_13 + + + _DataInput_14 + + + _DataInput_15 + + + Parameter + DataInput_2 + + + DataOutput_3 + Result + + + + + + + + + + + + + SequenceFlow_5 + SequenceFlow_3 + + + + + + + + + + + + _DataInput_2 + _DataInput_3 + _DataInput_4 + _DataInput_5 + _DataInput_6 + _DataInput_7 + _DataInput_8 + DataInput_1 + + + DataOutput_1 + + + + _DataInput_2 + + ServiceOne + _DataInput_2 + + + + _DataInput_3 + + invoke + _DataInput_3 + + + + _DataInput_4 + + Parameter + _DataInput_4 + + + + _DataInput_5 + + Result + _DataInput_5 + + + + _DataInput_6 + + + _DataInput_7 + + + _DataInput_8 + + + Parameter + DataInput_1 + + + DataOutput_1 + Result + + + + + SequenceFlow_6 + SequenceFlow_1 + + + DataOutput_2 + Parameter + + + DataOutput_2 + + + + + + SequenceFlow_4 + + + + SequenceFlow_4 + SequenceFlow_5 + SequenceFlow_6 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-BadProcess.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-BadProcess.bpmn new file mode 100644 index 000000000..7cf701385 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-BadProcess.bpmn @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-BadResources.xml b/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-BadResources.xml new file mode 100644 index 000000000..b92217af5 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-BadResources.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-GoodProcess.bpmn b/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-GoodProcess.bpmn new file mode 100644 index 000000000..ba787be53 --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-GoodProcess.bpmn @@ -0,0 +1,26 @@ + + + + + SequenceFlow_1 + + + + SequenceFlow_1 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-GoodResources.xml b/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-GoodResources.xml new file mode 100644 index 000000000..bc443314e --- /dev/null +++ b/components/bpm/src/test/resources/org/switchyard/component/bpm/session/BPMSessionTests-GoodResources.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/components/build/src/site/site.xml b/components/build/src/site/site.xml new file mode 100644 index 000000000..dfe033aa5 --- /dev/null +++ b/components/build/src/site/site.xml @@ -0,0 +1,11 @@ + + + + + org.apache.maven.skins + maven-default-skin + 1.0 + + + + diff --git a/components/camel/camel-amqp/pom.xml b/components/camel/camel-amqp/pom.xml new file mode 100644 index 000000000..fdfd990df --- /dev/null +++ b/components/camel/camel-amqp/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-amqp + bundle + SwitchYard: Camel Component :: AMQP Binding + + + org.switchyard.component.camel.amqp.* + + + org.apache.camel.component.amqp, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-jms + + + org.apache.camel + camel-amqp + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/deploy/CamelAmqpComponent.java b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/deploy/CamelAmqpComponent.java new file mode 100644 index 000000000..6a319aba1 --- /dev/null +++ b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/deploy/CamelAmqpComponent.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.amqp.deploy; + +import org.switchyard.component.camel.amqp.model.v1.V1CamelAmqpBindingModel; +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; + +/** + * AMQP binding component. + */ +public class CamelAmqpComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelAmqpComponent() { + super("CamelAmqpComponent", V1CamelAmqpBindingModel.AMQP); + } + +} diff --git a/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/CamelAmqpBindingModel.java b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/CamelAmqpBindingModel.java new file mode 100644 index 000000000..f7ccdd5e1 --- /dev/null +++ b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/CamelAmqpBindingModel.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.amqp.model; + +import org.switchyard.component.camel.jms.model.CamelJmsBindingModel; + +/** + * Represents the configuration settings for an Amqp endpoint in Camel. + * + * According to the Camel Documentation, Camel JMS and Camel AMQP configurations share + * all options, thus the reason to extend {@link GenericMqBindingModel}. + * + * @author: Eduardo de Vera + */ +public interface CamelAmqpBindingModel extends CamelJmsBindingModel { +} diff --git a/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/CamelAmqpNamespace.java b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/CamelAmqpNamespace.java new file mode 100644 index 000000000..3d1281830 --- /dev/null +++ b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/CamelAmqpNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.amqp.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Amqp config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelAmqpNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelAmqpNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelAmqpNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelAmqpNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelAmqpNamespace + */ + public static CamelAmqpNamespace fromUri(String uri) { + return Util.fromUri(CamelAmqpNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelAmqpNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-amqp:config", version); + } + } + +} diff --git a/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpBindingModel.java b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpBindingModel.java new file mode 100644 index 000000000..fd36f4eb0 --- /dev/null +++ b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpBindingModel.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.amqp.model.v1; + +import java.net.URI; + +import org.switchyard.component.camel.amqp.model.CamelAmqpBindingModel; +import org.switchyard.component.camel.jms.model.v1.V1CamelJmsBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + + +/** + * Implementation of {@link CamelAmqpBindingModel}. + * + * @author: Eduardo de Vera + */ +public class V1CamelAmqpBindingModel extends V1CamelJmsBindingModel + implements CamelAmqpBindingModel { + + /** + * Camel component prefix / binding prefix. + */ + public static final String AMQP = "amqp"; + + /** + * Default constructor, creates binding using only prefix. + * @param namespace namespace + */ + public V1CamelAmqpBindingModel(String namespace) { + super(AMQP, namespace); + } + + /** + * Create a binding from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param descriptor The switchyard descriptor instance. + */ + public V1CamelAmqpBindingModel(Configuration config, Descriptor descriptor) { + super(config, descriptor); + } + + @Override + public URI getComponentURI() { + return getComponentURI(AMQP); + } + +} diff --git a/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpModelMarshaller.java b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpModelMarshaller.java new file mode 100644 index 000000000..ca58054d7 --- /dev/null +++ b/components/camel/camel-amqp/src/main/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.amqp.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * AMQP model marshaller. + */ +public class V1CamelAmqpModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_AMQP = BindingModel.BINDING + '.' + V1CamelAmqpBindingModel.AMQP; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelAmqpModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_AMQP.equals(name)) { + return new V1CamelAmqpBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-amqp/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-amqp/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..6e31fe6d4 --- /dev/null +++ b/components/camel/camel-amqp/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.amqp.deploy.CamelAmqpComponent diff --git a/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v1/camel-amqp_1_0.xsd b/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v1/camel-amqp_1_0.xsd new file mode 100644 index 000000000..d27a150a4 --- /dev/null +++ b/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v1/camel-amqp_1_0.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v1/camel-amqp_1_1.xsd b/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v1/camel-amqp_1_1.xsd new file mode 100644 index 000000000..55cf796a2 --- /dev/null +++ b/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v1/camel-amqp_1_1.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v2/camel-amqp_2_0.xsd b/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v2/camel-amqp_2_0.xsd new file mode 100644 index 000000000..a021feb73 --- /dev/null +++ b/components/camel/camel-amqp/src/main/resources/org/switchyard/component/camel/amqp/model/v2/camel-amqp_2_0.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-amqp/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-amqp/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..45169fe52 --- /dev/null +++ b/components/camel/camel-amqp/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_amqp_1_0.section=urn:switchyard-component-camel-amqp:config +camel_amqp_1_0.version=1.0 +camel_amqp_1_0.namespace=urn:switchyard-component-camel-amqp:config:1.0 +camel_amqp_1_0.schema=camel-amqp_1_0.xsd +camel_amqp_1_0.location=/org/switchyard/component/camel/amqp/model/v1/ +camel_amqp_1_0.marshaller=org.switchyard.component.camel.amqp.model.v1.V1CamelAmqpModelMarshaller + +camel_amqp_1_1.section=urn:switchyard-component-camel-amqp:config +camel_amqp_1_1.version=1.1 +camel_amqp_1_1.namespace=urn:switchyard-component-camel-amqp:config:1.1 +camel_amqp_1_1.schema=camel-amqp_1_1.xsd +camel_amqp_1_1.location=/org/switchyard/component/camel/amqp/model/v1/ +camel_amqp_1_1.marshaller=org.switchyard.component.camel.amqp.model.v1.V1CamelAmqpModelMarshaller + +camel_amqp_2_0.section=urn:switchyard-component-camel-amqp:config +camel_amqp_2_0.version=2.0 +camel_amqp_2_0.namespace=urn:switchyard-component-camel-amqp:config:2.0 +camel_amqp_2_0.schema=camel-amqp_2_0.xsd +camel_amqp_2_0.location=/org/switchyard/component/camel/amqp/model/v2/ +camel_amqp_2_0.marshaller=org.switchyard.component.camel.amqp.model.v1.V1CamelAmqpModelMarshaller diff --git a/components/camel/camel-amqp/src/test/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpBindingModelTest.java b/components/camel/camel-amqp/src/test/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpBindingModelTest.java new file mode 100644 index 000000000..288402ee2 --- /dev/null +++ b/components/camel/camel-amqp/src/test/java/org/switchyard/component/camel/amqp/model/v1/V1CamelAmqpBindingModelTest.java @@ -0,0 +1,120 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.amqp.model.v1; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; + +import org.apache.camel.component.jms.JmsEndpoint; +import org.switchyard.component.camel.amqp.model.CamelAmqpNamespace; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; + +/** + * Test for amqp binding model. + * + * @author: Eduardo de Vera + */ +public class V1CamelAmqpBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-amqp-binding-beans.xml"; + + private static String TOPIC = "esb_in_topic"; + private static String CONNECTION_FACTORY = "connFactory"; + private static String USERNAME = "camel"; + private static String PASSWORD = "isMyFriend"; + private static String CLIENT_ID = "esb_in"; + private static String DURABLE_SUBSCRIPTION_NAME = "esb_in_sub"; + private static Integer CONCURRENT_CONSUMERS = 5; + private static Integer MAX_CONCURRENT_CONSUMERS = 15; + private static Boolean DISABLE_REPLY_TO = true; + private static Boolean PRESERVE_MESSAGE_QOS = true; + private static Boolean DELIVERY_PERSISTENT = false; + private static Integer PRIORITY = 9; + private static Boolean EXPLICIT_QOS_ENABLED = true; + private static String REPLY_TO = "esb_out"; + private static String REPLY_TO_TYPE= "Shared"; + private static Integer REQUEST_TIMEOUT = 300; + private static String SELECTOR = "DEST='ESB'"; + private static Integer TIME_TO_LIVE = 3600; + private static Boolean TRANSACTED = true; + + private static final String CAMEL_URI = "amqp:topic:esb_in_topic?connectionFactory=connFactory&" + + "username=camel&password=isMyFriend&clientId=esb_in&durableSubscriptionName=esb_in_sub&" + + "concurrentConsumers=5&maxConcurrentConsumers=15&disableReplyTo=true&preserveMessageQos=true&" + + "deliveryPersistent=false&priority=9&explicitQosEnabled=true&replyTo=esb_out&replyToType=Shared&" + + "requestTimeout=300&selector=DEST='ESB'&timeToLive=3600&transacted=true&dummy=test"; + + public V1CamelAmqpBindingModelTest() { + super(JmsEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelAmqpBindingModel createTestModel() { + final V1CamelAmqpBindingModel model = new V1CamelAmqpBindingModel(CamelAmqpNamespace.V_1_1.uri()); + model.setAdditionalUriParameters(createAdditionalUriParametersModel(CamelAmqpNamespace.V_1_1.uri(), Collections.singletonMap("dummy", "test"))); + model + .setTopic(TOPIC) + .setConnectionFactory(CONNECTION_FACTORY) + .setUsername(USERNAME) + .setPassword(PASSWORD) + .setClientId(CLIENT_ID) + .setDurableSubscriptionName(DURABLE_SUBSCRIPTION_NAME) + .setConcurrentConsumers(CONCURRENT_CONSUMERS) + .setMaxConcurrentConsumers(MAX_CONCURRENT_CONSUMERS) + .setDisableReplyTo(DISABLE_REPLY_TO) + .setPreserveMessageQos(PRESERVE_MESSAGE_QOS) + .setDeliveryPersistent(DELIVERY_PERSISTENT) + .setPriority(PRIORITY) + .setExplicitQosEnabled(EXPLICIT_QOS_ENABLED) + .setReplyTo(REPLY_TO) + .setReplyToType(REPLY_TO_TYPE) + .setRequestTimeout(REQUEST_TIMEOUT) + .setSelector(SELECTOR) + .setTimeToLive(TIME_TO_LIVE) + .setTransacted(TRANSACTED); + return model; + } + + @Override + protected void createModelAssertions(V1CamelAmqpBindingModel model) { + assertEquals(TOPIC, model.getTopic()); + assertEquals(CONNECTION_FACTORY, model.getConnectionFactory()); + assertEquals(USERNAME, model.getUsername()); + assertEquals(PASSWORD, model.getPassword()); + assertEquals(CLIENT_ID, model.getClientId()); + assertEquals(DURABLE_SUBSCRIPTION_NAME, model.getDurableSubscriptionName()); + assertEquals(CONCURRENT_CONSUMERS, model.getConcurrentConsumers()); + assertEquals(MAX_CONCURRENT_CONSUMERS, model.getMaxConcurrentConsumers()); + assertEquals(DISABLE_REPLY_TO, model.isDisableReplyTo()); + assertEquals(PRESERVE_MESSAGE_QOS, model.isPreserveMessageQos()); + assertEquals(DELIVERY_PERSISTENT, model.isDeliveryPersistent()); + assertEquals(PRIORITY, model.getPriority()); + assertEquals(EXPLICIT_QOS_ENABLED, model.isExplicitQosEnabled()); + assertEquals(REPLY_TO, model.getReplyTo()); + assertEquals(REPLY_TO_TYPE, model.getReplyToType()); + assertEquals(REQUEST_TIMEOUT, model.getRequestTimeout()); + assertEquals(SELECTOR, model.getSelector()); + assertEquals(TIME_TO_LIVE, model.getTimeToLive()); + assertEquals(TRANSACTED, model.isTransacted()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-amqp/src/test/resources/v1/switchyard-amqp-binding-beans.xml b/components/camel/camel-amqp/src/test/resources/v1/switchyard-amqp-binding-beans.xml new file mode 100644 index 000000000..81ff866eb --- /dev/null +++ b/components/camel/camel-amqp/src/test/resources/v1/switchyard-amqp-binding-beans.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + esb_in_topic + connFactory + camel + isMyFriend + esb_in + esb_in_sub + 5 + 15 + true + true + false + 9 + true + esb_out + Shared + 300 + DEST='ESB' + 3600 + true + + + + + diff --git a/components/camel/camel-atom/pom.xml b/components/camel/camel-atom/pom.xml new file mode 100644 index 000000000..fe4494a7e --- /dev/null +++ b/components/camel/camel-atom/pom.xml @@ -0,0 +1,69 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-atom + bundle + SwitchYard: Camel Component :: Atom Binding + http://switchyard.org + + + org.switchyard.component.camel.atom.* + + + org.apache.camel.component.atom, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.abdera + abdera-parser + + + org.apache.camel + camel-atom + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/deploy/CamelAtomComponent.java b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/deploy/CamelAtomComponent.java new file mode 100644 index 000000000..9120a057b --- /dev/null +++ b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/deploy/CamelAtomComponent.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.atom.deploy; + +import org.switchyard.component.camel.atom.model.v1.V1CamelAtomBindingModel; +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; + +/** + * Atom binding component. + */ +public class CamelAtomComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelAtomComponent() { + super("CamelAtomComponent", V1CamelAtomBindingModel.ATOM); + } + +} diff --git a/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/CamelAtomBindingModel.java b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/CamelAtomBindingModel.java new file mode 100644 index 000000000..b6024b89d --- /dev/null +++ b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/CamelAtomBindingModel.java @@ -0,0 +1,134 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.atom.model; + +import java.net.URI; +import java.util.Date; + +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.common.model.consumer.CamelScheduledPollConsumer; + +/** + * Represents the configuration settings for an Atom endpoint in Camel. The + * Atom component only supports consumer processing, so this binding can only + * be used on a service (not a reference). + */ +public interface CamelAtomBindingModel extends CamelBindingModel { + + /** + * The Atom feed URI which will be polled. + * @return the feed URI or null if it has not been specified + */ + URI getFeedURI(); + + /** + * Set the Atom feed URI. + * @param uri feed URI + * @return a reference to this Atom binding model + */ + CamelAtomBindingModel setFeedURI(URI uri); + + /** + * Whether feed entries will be split on each poll. + * @return split setting or null if no configuration has been specified + */ + Boolean isSplitEntries(); + + /** + * Specify that feed entries will be split on each poll. + * @param split true if entries should be split, false otherwise + * @return a reference to this Atom binding model + */ + CamelAtomBindingModel setSplitEntries(Boolean split); + + /** + * Whether the component should only return new RSS entries. + * @return filter setting or null if no configuration has been specified + */ + Boolean isFilter(); + + /** + * Specify that the source feed should be filtered. + * @param filter true to filter the feed + * @return a reference to this Atom binding model + */ + CamelAtomBindingModel setFilter(Boolean filter); + + /** + * Set the start date used by the filter for pulling new feeds. + * @param lastUpdate date after which entries should be pulled + * @return a reference to this Atom binding model + */ + CamelAtomBindingModel setLastUpdate(Date lastUpdate); + + /** + * The start date used by the filter for pulling new feeds. + * @return date after which entries should be pulled or null if no + * configuration has been specified + */ + Date getLastUpdate(); + + /** + * Enables throttled delivery of feeds. + * @param throttled specify true to enable throttling + * @return a reference to this Atom binding model + */ + CamelAtomBindingModel setThrottleEntries(Boolean throttled); + + /** + * Whether throttling is enabled for this endpoint. + * @return throttle setting or null if no configuration has been specified + */ + Boolean isThrottleEntries(); + + /** + * Specify whether the underlying Abdera feed object is included as a header. + * @param header true to include the header, false to not include + * @return a reference to this Atom binding model + */ + CamelAtomBindingModel setFeedHeader(Boolean header); + + /** + * Whether the Abdera feed object is included as a header. + * @return feed header setting or null if no configuration has been specified + */ + Boolean isFeedHeader(); + + /** + * Specifies whether split entries are sorted by date. + * @param sorted set to true for split entries to be sorted + * @return a reference to this Atom binding model + */ + CamelAtomBindingModel setSortEntries(Boolean sorted); + + /** + * Whether split entries are sorted by date. + * @return sort setting or null if no configuration has been specified + */ + Boolean isSortEntries(); + + /** + * Sets consumer properties for atom. + * + * @param consumer Configuration of consumer. + * @return a reference to this Atom binding model + */ + CamelAtomBindingModel setConsumer(CamelScheduledPollConsumer consumer); + + /** + * @return Atom consumer configuration. + */ + CamelScheduledPollConsumer getConsumer(); + +} diff --git a/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/CamelAtomNamespace.java b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/CamelAtomNamespace.java new file mode 100644 index 000000000..9baeb2cfb --- /dev/null +++ b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/CamelAtomNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.atom.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Atom config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelAtomNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelAtomNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelAtomNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelAtomNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelAtomNamespace + */ + public static CamelAtomNamespace fromUri(String uri) { + return Util.fromUri(CamelAtomNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelAtomNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-atom:config", version); + } + } + +} diff --git a/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomBindingModel.java b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomBindingModel.java new file mode 100644 index 000000000..8bce7a5e4 --- /dev/null +++ b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomBindingModel.java @@ -0,0 +1,194 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.atom.model.v1; + +import java.net.URI; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.switchyard.component.camel.atom.model.CamelAtomBindingModel; +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.consumer.CamelScheduledPollConsumer; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledPollConsumer; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of AtomBindingModel. + */ +public class V1CamelAtomBindingModel extends V1BaseCamelBindingModel + implements CamelAtomBindingModel { + + /** + * Camel endpoint type. + */ + public static final String ATOM = "atom"; + + /** + * Camel endpoint configuration values. + */ + private static final String FEED_URI = "feedURI"; + private static final String SPLIT_ENTRIES = "splitEntries"; + private static final String FILTER = "filter"; + private static final String LAST_UPDATE = "lastUpdate"; + private static final String THROTTLE_ENTRIES = "throttleEntries"; + private static final String FEED_HEADER = "feedHeader"; + private static final String SORT_ENTRIES = "sortEntries"; + + private CamelScheduledPollConsumer _consume; + + // Used for dateTime fields + private static final String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss"; + + /** + * Create a new AtomBindingModel. + * @param namespace namespace + */ + public V1CamelAtomBindingModel(String namespace) { + super(ATOM, namespace); + + setModelChildrenOrder(FEED_URI, SPLIT_ENTRIES, FILTER, LAST_UPDATE, + THROTTLE_ENTRIES, FEED_HEADER, SORT_ENTRIES, CONSUME); + } + + /** + * Create a AtomBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelAtomBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public URI getFeedURI() { + String uriStr = getConfig(FEED_URI); + if (uriStr != null) { + return URI.create(uriStr); + } else { + return null; + } + } + + @Override + public V1CamelAtomBindingModel setFeedURI(URI uri) { + return setConfig(FEED_URI, uri.toString()); + } + + @Override + public Date getLastUpdate() { + final DateFormat lastUpdateDateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return getDateConfig(LAST_UPDATE, lastUpdateDateFormat); + } + + @Override + public V1CamelAtomBindingModel setLastUpdate(Date date) { + final DateFormat lastUpdateDateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + setConfig(LAST_UPDATE, lastUpdateDateFormat.format(date)); + return this; + } + + @Override + public Boolean isFeedHeader() { + return getBooleanConfig(FEED_HEADER); + } + + @Override + public V1CamelAtomBindingModel setFeedHeader(Boolean feedHeader) { + return setConfig(FEED_HEADER, feedHeader); + } + + @Override + public Boolean isFilter() { + return getBooleanConfig(FILTER); + } + + @Override + public V1CamelAtomBindingModel setFilter(Boolean filtered) { + return setConfig(FILTER, filtered); + } + + @Override + public Boolean isSortEntries() { + return getBooleanConfig(SORT_ENTRIES); + } + + @Override + public V1CamelAtomBindingModel setSortEntries(Boolean sorted) { + return setConfig(SORT_ENTRIES, sorted); + } + + @Override + public Boolean isSplitEntries() { + return getBooleanConfig(SPLIT_ENTRIES); + } + + @Override + public V1CamelAtomBindingModel setSplitEntries(Boolean split) { + return setConfig(SPLIT_ENTRIES, String.valueOf(split)); + } + + @Override + public Boolean isThrottleEntries() { + return getBooleanConfig(THROTTLE_ENTRIES); + } + + @Override + public V1CamelAtomBindingModel setThrottleEntries(Boolean throttled) { + return setConfig(THROTTLE_ENTRIES, String.valueOf(throttled)); + } + + + @Override + public CamelScheduledPollConsumer getConsumer() { + if (_consume == null) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + _consume = new V1CamelScheduledPollConsumer(config, + getModelDescriptor()); + } + return _consume; + } + + @Override + public V1CamelAtomBindingModel setConsumer(CamelScheduledPollConsumer consumer) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(CONSUME); + getModelConfiguration().addChild(((V1CamelScheduledPollConsumer) consumer) + .getModelConfiguration()); + } else { + setChildModel((V1CamelScheduledPollConsumer) consumer); + } + _consume = consumer; + return this; + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = ATOM + "://" + getFeedURI(); + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, FEED_URI); + + return URI.create(baseUri + queryStr.toString()); + } +} diff --git a/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomModelMarshaller.java b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomModelMarshaller.java new file mode 100644 index 000000000..f6ef03cbf --- /dev/null +++ b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.atom.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Atom model marshaller. + */ +public class V1CamelAtomModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_ATOM = BindingModel.BINDING + '.' + V1CamelAtomBindingModel.ATOM; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelAtomModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_ATOM.equals(name)) { + return new V1CamelAtomBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/transformer/AtomTransforms.java b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/transformer/AtomTransforms.java new file mode 100644 index 000000000..a00e52db6 --- /dev/null +++ b/components/camel/camel-atom/src/main/java/org/switchyard/component/camel/atom/transformer/AtomTransforms.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.atom.transformer; + +import org.apache.abdera.parser.stax.FOMEntry; + +import org.switchyard.annotations.Transformer; + +/** + * Provide a default transformer from org.apache.abdera.parser.stax.FOMEntry->String, + * which is useful for creating a simple service using the Camel Atom binding. + * + * @author tcunning + */ +public class AtomTransforms { + + /** + * Singleton instance. + */ + public static final AtomTransforms TRANSFORMER = new AtomTransforms(); + + /** + * Transform FOMEntry->String. + * @param entry entry + * @return String + */ + @Transformer + public String toString(FOMEntry entry) { + return entry.toString(); + } + +} diff --git a/components/camel/camel-atom/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-atom/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..66ef4be38 --- /dev/null +++ b/components/camel/camel-atom/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.atom.deploy.CamelAtomComponent diff --git a/components/camel/camel-atom/src/main/resources/META-INF/switchyard/transforms.xml b/components/camel/camel-atom/src/main/resources/META-INF/switchyard/transforms.xml new file mode 100644 index 000000000..11c619769 --- /dev/null +++ b/components/camel/camel-atom/src/main/resources/META-INF/switchyard/transforms.xml @@ -0,0 +1,3 @@ + + + diff --git a/components/camel/camel-atom/src/main/resources/OSGI-INF/blueprint/transformers.xml b/components/camel/camel-atom/src/main/resources/OSGI-INF/blueprint/transformers.xml new file mode 100644 index 000000000..d7c903944 --- /dev/null +++ b/components/camel/camel-atom/src/main/resources/OSGI-INF/blueprint/transformers.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v1/camel-atom_1_0.xsd b/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v1/camel-atom_1_0.xsd new file mode 100644 index 000000000..299665512 --- /dev/null +++ b/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v1/camel-atom_1_0.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v1/camel-atom_1_1.xsd b/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v1/camel-atom_1_1.xsd new file mode 100644 index 000000000..27900a94c --- /dev/null +++ b/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v1/camel-atom_1_1.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v2/camel-atom_2_0.xsd b/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v2/camel-atom_2_0.xsd new file mode 100644 index 000000000..40112537a --- /dev/null +++ b/components/camel/camel-atom/src/main/resources/org/switchyard/component/camel/atom/model/v2/camel-atom_2_0.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-atom/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-atom/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..c153ee7c8 --- /dev/null +++ b/components/camel/camel-atom/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_atom_1_0.section=urn:switchyard-component-camel-atom:config +camel_atom_1_0.version=1.0 +camel_atom_1_0.namespace=urn:switchyard-component-camel-atom:config:1.0 +camel_atom_1_0.schema=camel-atom_1_0.xsd +camel_atom_1_0.location=/org/switchyard/component/camel/atom/model/v1/ +camel_atom_1_0.marshaller=org.switchyard.component.camel.atom.model.v1.V1CamelAtomModelMarshaller + +camel_atom_1_1.section=urn:switchyard-component-camel-atom:config +camel_atom_1_1.version=1.1 +camel_atom_1_1.namespace=urn:switchyard-component-camel-atom:config:1.1 +camel_atom_1_1.schema=camel-atom_1_1.xsd +camel_atom_1_1.location=/org/switchyard/component/camel/atom/model/v1/ +camel_atom_1_1.marshaller=org.switchyard.component.camel.atom.model.v1.V1CamelAtomModelMarshaller + +camel_atom_2_0.section=urn:switchyard-component-camel-atom:config +camel_atom_2_0.version=2.0 +camel_atom_2_0.namespace=urn:switchyard-component-camel-atom:config:2.0 +camel_atom_2_0.schema=camel-atom_2_0.xsd +camel_atom_2_0.location=/org/switchyard/component/camel/atom/model/v2/ +camel_atom_2_0.marshaller=org.switchyard.component.camel.atom.model.v1.V1CamelAtomModelMarshaller diff --git a/components/camel/camel-atom/src/test/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomBindingModelTest.java b/components/camel/camel-atom/src/test/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomBindingModelTest.java new file mode 100644 index 000000000..674464d83 --- /dev/null +++ b/components/camel/camel-atom/src/test/java/org/switchyard/component/camel/atom/model/v1/V1CamelAtomBindingModelTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.atom.model.v1; + +import static junit.framework.Assert.assertEquals; + +import java.net.URI; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.camel.component.feed.FeedEndpoint; +import org.switchyard.component.camel.atom.model.CamelAtomNamespace; +import org.switchyard.component.camel.common.model.consumer.CamelScheduledPollConsumer; +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledPollConsumer; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; + +/** + * Test of atom binding model. + */ +public class V1CamelAtomBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-atom-binding.xml"; + + private static final String CAMEL_URI = + "atom://file:///dev/null?feedHeader=true&filter=true&lastUpdate=2011-01-01T12:00:00" + + "&sortEntries=true&splitEntries=true&throttleEntries=true" + + "&delay=15000&initialDelay=20000&useFixedDelay=true"; + + private Date referenceDate; + private static final URI FEED_URI = URI.create("file:///dev/null"); + private static final Boolean FEED_HEADER = true; + private static final Boolean FILTERED = true; + private static final Boolean SORTED = true; + private static final Boolean SPLIT = true; + private static final Boolean THROTTLED = true; + + public V1CamelAtomBindingModelTest() throws ParseException { + super(FeedEndpoint.class, CAMEL_XML); + + referenceDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") + .parse("2011-01-01T12:00:00"); + } + + + @Override + protected void createModelAssertions(V1CamelAtomBindingModel model) { + assertEquals(FEED_URI, model.getFeedURI()); + assertEquals(referenceDate.toString(), model.getLastUpdate().toString()); + assertEquals(FEED_HEADER, model.isFeedHeader()); + assertEquals(FILTERED, model.isFilter()); + assertEquals(SORTED, model.isSortEntries()); + assertEquals(SPLIT, model.isSplitEntries()); + assertEquals(THROTTLED, model.isThrottleEntries()); + } + + @Override + protected V1CamelAtomBindingModel createTestModel() { + V1CamelAtomBindingModel abm = new V1CamelAtomBindingModel(CamelAtomNamespace.V_1_0.uri()) + .setFeedURI(FEED_URI) + .setSplitEntries(SPLIT) + .setFilter(FILTERED) + .setLastUpdate(referenceDate) + .setThrottleEntries(THROTTLED) + .setFeedHeader(FEED_HEADER) + .setSortEntries(SORTED); + + CamelScheduledPollConsumer consumer = new V1CamelScheduledPollConsumer(CamelAtomNamespace.V_1_0.uri(), V1CamelAtomBindingModel.CONSUME) + .setInitialDelay(20000) + .setDelay(15000) + .setUseFixedDelay(true); + return abm.setConsumer(consumer); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-atom/src/test/resources/v1/switchyard-atom-binding.xml b/components/camel/camel-atom/src/test/resources/v1/switchyard-atom-binding.xml new file mode 100644 index 000000000..eb02539c1 --- /dev/null +++ b/components/camel/camel-atom/src/test/resources/v1/switchyard-atom-binding.xml @@ -0,0 +1,39 @@ + + + + + + + + + file:///dev/null + true + true + 2011-01-01T12:00:00 + true + true + true + + 20000 + 15000 + true + + + + + + diff --git a/components/camel/camel-core/Readme.md b/components/camel/camel-core/Readme.md new file mode 100644 index 000000000..8733c2dfa --- /dev/null +++ b/components/camel/camel-core/Readme.md @@ -0,0 +1,242 @@ +# SwitchYard Camel Component +This project deals with integrating Apache Camel with SwitchYard. + +## Using Apache Camel components as gateways/entrypoint into SwitchYard + + + + + + + + + + + + + + + + + + + +In the configuration above you see an example of a service that is using a Camel binding. What will happen is that SwitchYard +will create a CamelContext add add a route for the configured component, which is identified in this case using the *configUri* +attribute. This route will look like this for the above configuration: + + from("direct://input").to("switchyard://SimpleCamelService?operationName=print"); + +The *operationName* is optional if the Service only has a single method and can left out in that case. + +_ _ _ + +## Using SwitchYard reference bindings with Apache Camel +A configuration of a reference binding could look like this: + + + + + + + + + + + + + + + + + + + + + +In this configuration we have defined a reference binding which has specified a configURI attribute which identifies the +Camel endpoint to be called. The *OrderComponent* is configured with an implementation of the *OrderService* interface and +a concreate implementation of *OrderServiceImpl*: + + public interface OrderService { + public String getTitleForItem(String itemId); + } + + import javax.inject.Inject; + + import org.switchyard.component.bean.Reference; + import org.switchyard.component.bean.Service; + + @Service(OrderService.class) + public class OrderServiceImpl implements OrderService { + + @Inject @Reference + WarehouseService _warehouseService; + + @Override + public String getTitleForItem(String itemId) { + return _warehouseService.hasItem(itemId); + } + } +Notice that *OrderServiceImpl* requires a *WarehouseService* instance. This is declared in the configuration using the +reference element on the *OrderComponent* and SwitchYard will inject a proxy that will delegate to the Camel endpoint. + +--- +# Transactions with Camel Service Bindings +Certain Camel Components support transactions, for example the JMS Component, and there are a few options that can be configured which +will be described in this section. + +## Local Transaction configuration +A Service Binding for Camel using the JMS Component with a local transaction can look like this: + + +This configures a JMS Component to use a local transaction. This means that if the route, in our case this is the +route that sends the JMS Message content to the target SwitchYard Service, completes successfully the transaction will +be committed. If the route does not end successfully, for example an exception is thrown from the Service Implementation, +the transaction will be rolled back and the message will still be in the JMS Brokers queue. + +**Note: The default transaction error handler will determine the policy for redelivery and this is currently not configurable. This is something that we going to attend to for the next 0.4 release.** + +## JTA Transaction configuration +Using local transactions as described in the previous example is nice for cases where the service implementation does +not need to take part of the same transaction. If for example your service implementation does require participation, for +example if it persists data to a database, you will need to configure a JTA transaction manager that will coordinate the +transaction. +The following examples shows how to configure a JTA transaction manager: + + + +The _#jtaTransactionManager_ is a reference to a bean in the Camel Registry. This would normally be configured using Spring XML +when outside of SwitchYard. Is is possible to specify a custom transaction manager by using a CDI bean which will be describe +later in this document. By default though, if you configure the _transactionManager_ to be _#jtaTransactionManager_, SwitchYard will +perform lookups in JNDI to try to determine which TransactionManager to use to drive the transactions. The order is as follows: + +1. java:jboss/UserTransaction +2. java:comp/UserTransaction + + +## Custom Transaction Manager +If you are deploying SwitchYard in an environment that does not have the transaction managers available that were listed in + the previous section you can use CDI to have a JTA Transaction Manager injected into the Camel Registry. +Example of a custom JTA Transaction Manager using CDI: + + import javax.enterprise.context.ApplicationScoped; + import javax.enterprise.inject.Produces; + import javax.inject.Named; + + import org.springframework.transaction.PlatformTransactionManager; + import org.springframework.transaction.jta.JtaTransactionManager; + + @ApplicationScoped + public class CustomTransactionManager { + + @Produces @Named ("myTransactionManager") + public PlatformTransactionManager create() { + final JtaTransactionManager transactionManager = new JtaTransactionManager(); + transactionManager.setUserTransactionName("UserTransactionJndiName"); + transactionManager.setTransactionManagerName("TransactionManagerJndiName"); + transactionManager.setTransactionSynchronizationRegistryName("TransactionSynchronizationRegistryJndiName"); + transactionManager.afterPropertiesSet(); + return transactionManager; + } + + } + +_ _ _ +## Using SwitchYard implementation.camel with Apache Camel +A Camel route can be used as the implementation for a service. This is done by using the *implementation.camel* element which can contain a Camel route. +SwitchYard takes care of creating a service for the interface which sole purpose is to trigger the Camel route. It does this by creating a *from* route +that triggers the Camel route. This allows SwitchYard clients to use the service interface to invoke the Camel route. + +For example: + + route.xml : + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +As you can see in the above configuration that the route in *implementation.camel* does not contain a *from* route. Switchyard will add a *from* route for the service. + +The above would be invokable by using the following code from a SwitchYard test: + + String title = newInvoker("OrderService").operation("getTitleForItem").sendInOut("10").getContent(String.class); + +Running the above code snippet would generate the following in you console log: + + 10:57:45,915 INFO [impl.DefaultCamelContext] Apache Camel 2.6.0 (CamelContext: camel-1) started in 0.838 seconds + 10:57:46,284 INFO [impl.DefaultCamelContext] Route: Camel Test Route started and consuming from: Endpoint[switchyard://OrderService] + 10:57:46,307 INFO [impl.DefaultCamelContext] Apache Camel 2.6.0 (CamelContext: camel-1) is starting + 10:57:46,307 INFO [impl.DefaultCamelContext] Total 1 routes, of which 1 is started. + 10:57:46,307 INFO [impl.DefaultCamelContext] Apache Camel 2.6.0 (CamelContext: camel-1) started in 0.000 seconds + 10:57:46,428 INFO [Camel Test Route] ItemId [10] + 10:57:46,434 INFO [Camel Test Route] Title Name [Fletch] + +Notice the Camel Endpoint **switchyard://OrderService**, this is the endpoint that SwitchYard generates and can be configured by setting the schema property like demonstrated above. + +--- +## SwitchYard Transformers and Camel's TypeConverters +SwitchYard has build in transformers and custom transformers can be registered with the runtime. Camel has TypeConverters +that basically perform similar tasks. + +SwitchYards Camel component provides a SwitchYard transformer that delegates to Camel's TypeConverters. To accomplish this the different type of converters have to be registered with SwitchYard as transformers. This is currently a static file, *META-INF/switchyard/transforms.xml* +which is parsed by SwitchYard. In future versions these will be dynamically registred with SwitchYard. + +If users have customer Camel TypeConverters they can be specified by either adding them to the transforms.xml in the SwitchYard Camel component or they +can add a transforms.xml to there deployment archive. + +_ _ _ + +## Calling a SwitchYard service from Apache Camel: + + + + + + + + + + +_ _ _ diff --git a/components/camel/camel-core/pom.xml b/components/camel/camel-core/pom.xml new file mode 100644 index 000000000..f95c72052 --- /dev/null +++ b/components/camel/camel-core/pom.xml @@ -0,0 +1,60 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-core + bundle + SwitchYard: Camel Component :: Core Binding + http://switchyard.org + + + org.switchyard.component.camel.core.* + + + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-core + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/deploy/CamelCoreComponent.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/deploy/CamelCoreComponent.java new file mode 100644 index 000000000..8513bb2b0 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/deploy/CamelCoreComponent.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.core.model.v1.V1CamelUriBindingModel; +import org.switchyard.component.camel.core.model.v1.V1CamelDirectBindingModel; +import org.switchyard.component.camel.core.model.v1.V1CamelMockBindingModel; +import org.switchyard.component.camel.core.model.v1.V1CamelSedaBindingModel; +import org.switchyard.component.camel.core.model.v1.V1CamelTimerBindingModel; + +/** + * Camel core component. Supports camel-core bindings. + */ +public class CamelCoreComponent extends BaseBindingComponent { + + /** + * Creates new core binding component. + */ + public CamelCoreComponent() { + super("CamelCoreComponent", + V1CamelUriBindingModel.URI, + V1CamelDirectBindingModel.DIRECT, + V1CamelSedaBindingModel.SEDA, + V1CamelTimerBindingModel.TIMER, + V1CamelMockBindingModel.MOCK + ); + } + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/deploy/CamelMockBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/deploy/CamelMockBindingModel.java new file mode 100644 index 000000000..96f9a3356 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/deploy/CamelMockBindingModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.deploy; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Represents the configuration settings for a Mock endpoint in Camel. + * + * The Mock component provides a powerful declarative testing mechanism, + * which is similar to jMock in that it allows declarative expectations + * to be created on any Mock endpoint before a test begins. Then the test + * is run, which typically fires messages to one or more endpoints, and + * finally the expectations can be asserted in a test case to ensure the + * system worked as expected. + * + * @author Mario Antollini + * + */ +public interface CamelMockBindingModel extends CamelBindingModel { + + /** + * The name that uniquely identifies the endpoint. + * @return The name that uniquely identifies the endpoint + */ + String getEndpointName(); + + /** + * The name that uniquely identifies the endpoint. + * @param name the name that uniquely identifies the endpoint + * @return a reference to this Mock binding model + */ + CamelMockBindingModel setEndpointName(String name); + + /** + * An integer that specifies a group size for throughput logging. + * @return the group size for throughput logging + */ + Integer getReportGroup(); + + /** + * Specify a group size for throughput logging. + * @param size the group size for throughput logging + * @return a reference to this Mock binding model + */ + CamelMockBindingModel setReportGroup(Integer size); + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelCoreNamespace.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelCoreNamespace.java new file mode 100644 index 000000000..245506760 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelCoreNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Core config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelCoreNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelCoreNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelCoreNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelCoreNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelCoreNamespace + */ + public static CamelCoreNamespace fromUri(String uri) { + return Util.fromUri(CamelCoreNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelCoreNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-core:config", version); + } + } + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelDirectBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelDirectBindingModel.java new file mode 100644 index 000000000..2c62cd063 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelDirectBindingModel.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Represents the configuration settings for a Direct endpoint in Camel. The + * direct component provides direct, synchronous invocation of any consumers + * when a producer sends a message exchange. This endpoint can be used to + * connect existing routes in the same camel context. + */ +public interface CamelDirectBindingModel extends CamelBindingModel { + + /** + * The name can be any String to uniquely identify the endpoint. + * @return the unique identifier for the endpoint + */ + String getEndpointName(); + + /** + * The name can be any String to uniquely identify the endpoint. + * @param name the unique identifier for the endpoint + * @return a reference to this Direct binding model + */ + CamelDirectBindingModel setEndpointName(String name); + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelSedaBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelSedaBindingModel.java new file mode 100644 index 000000000..7813368e5 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelSedaBindingModel.java @@ -0,0 +1,148 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Represents the configuration settings for a SEDA endpoint in Camel. + * + * The SEDA component provides asynchronous SEDA behavior, so that messages + * are exchanged on a BlockingQueue and consumers are invoked in a separate + * thread from the producer. + * Note that queues are only visible within a single CamelContext. If you + * want to communicate across CamelContext instances (for example, + * communicating between Web applications), see the VM component. This + * component does not implement any kind of persistence or recovery, if + * the VM terminates while messages are yet to be processed. If you need + * persistence, reliability or distributed SEDA, try using either JMS + * or ActiveMQ. + * + * @author Mario Antollini + */ +public interface CamelSedaBindingModel extends CamelBindingModel { + + /** + * The name that uniquely identifies the endpoint within the + * current CamelContext. + * @return The name that uniquely identifies the endpoint within the + * current CamelContext + */ + String getEndpointName(); + + /** + * The name that uniquely identifies the endpoint within the + * current CamelContext. + * @param name the name that uniquely identifies the endpoint within the + * current CamelContext + * @return a reference to this SEDA binding model + */ + CamelSedaBindingModel setEndpointName(String name); + + /** + * The maximum size (= capacity of the number of messages it can max hold) + * of the SEDA queue. + * @return the maximum size of the SEDA queue + */ + Integer getSize(); + + /** + * Specify the maximum size (= capacity of the number of messages it can + * max hold) of the SEDA queue. + * @param size the number of messages it can max hold + * @return a reference to this SEDA binding model + */ + CamelSedaBindingModel setSize(Integer size); + + /** + * Number of concurrent threads processing exchanges. + * @return the number of concurrent threads processing exchanges. + */ + Integer getConcurrentConsumers(); + + /** + * Specify the number of concurrent threads processing exchanges. + * @param concurrentConsumers the number of concurrent threads + * @return a reference to this SEDA binding model + */ + CamelSedaBindingModel setConcurrentConsumers(Integer concurrentConsumers); + + /** + * Whether the caller should wait for the async task to complete or not + * before continuing. + * @return one of the following: Always, Never or IfReplyExpected. The + * first two values are self-explanatory. The last value, IfReplyExpected, + * will only wait if the message is Request Reply based. + */ + String getWaitForTaskToComplete(); + + /** + * Specify whether the caller should wait for the async task to complete or not + * before continuing. The following three options are supported: Always, + * Never or IfReplyExpected. + * The first two values are self-explanatory. The last value, IfReplyExpected, + * will only wait if the message is Request Reply based. + * The default option is IfReplyExpected. + * @param waitForTaskToComplete The following three options are supported: Always, + * Never or IfReplyExpected + * @return a reference to this SEDA binding model + */ + CamelSedaBindingModel setWaitForTaskToComplete(String waitForTaskToComplete); + + /** + * Timeout in milliseconds a SEDA producer will at most waiting for an async + * task to complete. + * @return the time in milliseconds + */ + Long getTimeout(); + + /** + * Timeout in milliseconds a SEDA producer will at most waiting for an async + * task to complete. + * @param timeout the timeout in milliseconds + * @return a reference to this SEDA binding model + */ + CamelSedaBindingModel setTimeout(Long timeout); + + /** + * Whether multiple consumers is allowed or not. + * @return true if multiple consumers is allowed; false otherwise + */ + Boolean isMultipleConsumers(); + + /** + * Specify whether multiple consumers is allowed or not. If enabled you can + * use SEDA for a pubsub kinda style messaging. Send a message to a SEDA queue and + * have multiple consumers receive a copy of the message. + * @param multipleConsumers true if multiple consumers is allowed; false + * otherwise + * @return a reference to this SEDA binding model + */ + CamelSedaBindingModel setMultipleConsumers(Boolean multipleConsumers); + + /** + * Whether to limit the concurrentConsumers to maximum 500. + * If its configured with a higher number an exception will be thrown. + * @return true if the limit is enabled; false if the limit is disabled + */ + Boolean isLimitConcurrentConsumers(); + + /** + * Whether to limit the concurrentConsumers to maximum 500. + * If its configured with a higher number an exception will be thrown. + * @param limitConcurrentConsumers true to limit to 500; false otherwise + * @return a reference to this SEDA binding model + */ + CamelSedaBindingModel setLimitConcurrentConsumers(Boolean limitConcurrentConsumers); +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelTimerBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelTimerBindingModel.java new file mode 100644 index 000000000..3e0ea3650 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/CamelTimerBindingModel.java @@ -0,0 +1,130 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model; + +import java.util.Date; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Represents the configuration settings for Camel Timer binding. + * + * @author Mario Antollini + */ +public interface CamelTimerBindingModel extends CamelBindingModel { + + /** + * The timer name. + * @return the timer name + */ + String getTimerName(); + + /** + * Specify the timer name. + * @param name the timer name + * @return a reference to this Camel Timer binding model + */ + CamelTimerBindingModel setTimerName(String name); + + /** + * A java.util.Date the first event should be generated. + * If using the URI, the pattern expected is: yyyy-MM-dd HH:mm:ss + * or yyyy-MM-dd'T'HH:mm:ss. + * @return the first event date + */ + Date getTime(); + + /** + * Specify the java.util.Date the first event should be generated. + * If using the URI, the pattern expected is: yyyy-MM-dd HH:mm:ss + * or yyyy-MM-dd'T'HH:mm:ss + * @param time the specified first event date + * @return a reference to this Camel Timer binding model + */ + CamelTimerBindingModel setTime(Date time); + + /** + * A custom Date pattern to use for setting the time option using URI syntax. + * @return the custom Date pattern + */ + String getPattern(); + + /** + * Specify a custom Date pattern to use for setting the time option + * using URI syntax. + * @param pattern the custom Date pattern + * @return a reference to this Camel Timer binding model + */ + CamelTimerBindingModel setPattern(String pattern); + + /** + * The time in milliseconds to generate periodic events. + * @return the period in milliseconds + */ + Long getPeriod(); + + /** + * If greater than 0, generate periodic events every period milliseconds. + * @param period the period in milliseconds + * @return a reference to this Camel Timer binding model + */ + CamelTimerBindingModel setPeriod(Long period); + + /** + * The number of milliseconds to wait before the first event is generated. + * @return the number of milliseconds to wait before the first event + */ + Long getDelay(); + + /** + * Specify the number of milliseconds to wait before the first event is + * generated. + * Should not be used in conjunction with the time option. + * @param delay The number of milliseconds to wait + * @return a reference to this Camel Timer binding model + */ + CamelTimerBindingModel setDelay(Long delay); + + /** + * Events take place at approximately regular intervals, separated by + * the specified period. + * @return true if events take place at regular intervals, false otherwihse + */ + Boolean isFixedRate(); + + /** + * Specify whether events take place at approximately regular intervals, separated by + * the specified period. + * @param fixedRate whether events take place at approximately regular intervals (true), + * or not (false) + * @return a reference to this Camel Timer binding model + */ + CamelTimerBindingModel setFixedRate(Boolean fixedRate); + + /** + * Whether or not the thread associated with the timer endpoint + * runs as a daemon. + * @return true if the thread runs as a daemon, false otherwise + */ + Boolean isDaemon(); + + /** + * Specify whether or not the thread associated with the timer endpoint + * runs as a daemon. + * @param daemon true if the thread runs as a daemon, false otherwise + * @return a reference to this Camel Timer binding model + */ + CamelTimerBindingModel setDaemon(Boolean daemon); + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelCoreModelMarshaller.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelCoreModelMarshaller.java new file mode 100644 index 000000000..976aa8068 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelCoreModelMarshaller.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * A Marshaler that is able to read a {@link Configuration} and populate a + * corresponding Model to the configuration informations. + *

+ * + * @author Daniel Bevenius + */ +public class V1CamelCoreModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_URI = BindingModel.BINDING + '.' + V1CamelUriBindingModel.URI; + private static final String BINDING_DIRECT = BindingModel.BINDING + '.' + V1CamelDirectBindingModel.DIRECT; + private static final String BINDING_TIMER = BindingModel.BINDING + '.' + V1CamelTimerBindingModel.TIMER; + private static final String BINDING_SEDA = BindingModel.BINDING + '.' + V1CamelSedaBindingModel.SEDA; + private static final String BINDING_MOCK = BindingModel.BINDING + '.' + V1CamelMockBindingModel.MOCK; + + /** + * Sole constructor. + * + * @param desc The switchyard descriptor. + */ + public V1CamelCoreModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_URI.equals(name)) { + return new V1CamelUriBindingModel(config, desc); + } else if (BINDING_DIRECT.equals(name)) { + return new V1CamelDirectBindingModel(config, desc); + } else if (BINDING_TIMER.equals(name)) { + return new V1CamelTimerBindingModel(config, desc); + } else if (BINDING_SEDA.equals(name)) { + return new V1CamelSedaBindingModel(config, desc); + } else if (BINDING_MOCK.equals(name)) { + return new V1CamelMockBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelDirectBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelDirectBindingModel.java new file mode 100644 index 000000000..a286839a0 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelDirectBindingModel.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model.v1; + +import java.net.URI; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.core.model.CamelDirectBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of AtomBindingModel. + */ +public class V1CamelDirectBindingModel extends V1BaseCamelBindingModel + implements CamelDirectBindingModel { + + /** + * Camel endpoint type. + */ + public static final String DIRECT = "direct"; + + /** + * Camel endpoint configuration values. + */ + private static final String NAME = "name"; + + /** + * Create a new CamelDirectBindingModel. + * @param namespace namespace + */ + public V1CamelDirectBindingModel(String namespace) { + super(DIRECT, namespace); + + setModelChildrenOrder(NAME); + } + + /** + * Create a CamelDirectBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelDirectBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getEndpointName() { + return getConfig(NAME); + } + + @Override + public V1CamelDirectBindingModel setEndpointName(String name) { + return setConfig(NAME, name); + } + + @Override + public URI getComponentURI() { + // base URI without params + String uriStr = DIRECT + "://" + getConfig(NAME); + return URI.create(uriStr.toString()); + } + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelMockBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelMockBindingModel.java new file mode 100644 index 000000000..9de52f942 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelMockBindingModel.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model.v1; + +import java.net.URI; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.core.deploy.CamelMockBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Represents the configuration settings for Camel Mock binding. + * + * @author Mario Antollini + */ +public class V1CamelMockBindingModel extends V1BaseCamelBindingModel + implements CamelMockBindingModel { + + /** + * Camel endpoint type. + */ + public static final String MOCK = "mock"; + + /** + * Camel endpoint configuration values. + */ + private static final String NAME = "name"; + private static final String REPORT_GROUP = "reportGroup"; + + /** + * Create a new CamelMockBindingModel. + * @param namespace namespace + */ + public V1CamelMockBindingModel(String namespace) { + super(MOCK, namespace); + + setModelChildrenOrder(NAME, REPORT_GROUP); + } + + /** + * Create a CamelMockBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelMockBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getEndpointName() { + return getConfig(NAME); + } + + @Override + public V1CamelMockBindingModel setEndpointName(String name) { + return setConfig(NAME, name); + } + + @Override + public Integer getReportGroup() { + return getIntegerConfig(REPORT_GROUP); + } + + @Override + public V1CamelMockBindingModel setReportGroup(Integer reportGroup) { + return setConfig(REPORT_GROUP, String.valueOf(reportGroup)); + } + + @Override + public URI getComponentURI() { + // base URI without params + String uriStr = MOCK + "://" + getConfig(NAME); + // create query string from config values + QueryString queryStr = new QueryString().add(REPORT_GROUP, getConfig(REPORT_GROUP)); + + return URI.create(uriStr.toString() + queryStr); + } + + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelSedaBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelSedaBindingModel.java new file mode 100644 index 000000000..dce16ec3f --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelSedaBindingModel.java @@ -0,0 +1,149 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model.v1; + +import java.net.URI; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.core.model.CamelSedaBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Represents the configuration settings for Camel Timer binding. + * + * @author Mario Antollini + */ +public class V1CamelSedaBindingModel extends V1BaseCamelBindingModel + implements CamelSedaBindingModel { + + /** + * Camel endpoint type. + */ + public static final String SEDA = "seda"; + + /** + * Camel Seda configuration values. + */ + private static final String NAME = "name"; + private static final String SIZE = "size"; + private static final String CONCURRENT_CONSUMERS = "concurrentConsumers"; + private static final String WAIT_FOR_TASK_TO_COMPLETE = "waitForTaskToComplete"; + private static final String TIMEOUT = "timeout"; + private static final String MULTIPLE_CONSUMERS = "multipleConsumers"; + private static final String LIMIT_CONCURRENT_CONSUMERS = "limitConcurrentConsumers"; + + /** + * Create a new CamelSedaBindingModel. + * @param namespace namespace + */ + public V1CamelSedaBindingModel(String namespace) { + super(SEDA, namespace); + + setModelChildrenOrder(NAME, SIZE, CONCURRENT_CONSUMERS, WAIT_FOR_TASK_TO_COMPLETE, + TIMEOUT, MULTIPLE_CONSUMERS, LIMIT_CONCURRENT_CONSUMERS); + } + + /** + * Create a CamelSedaBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelSedaBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getEndpointName() { + return getConfig(NAME); + } + + @Override + public V1CamelSedaBindingModel setEndpointName(String name) { + return setConfig(NAME, name); + } + + @Override + public Integer getSize() { + return getIntegerConfig(SIZE); + } + + @Override + public V1CamelSedaBindingModel setSize(Integer size) { + return setConfig(SIZE, String.valueOf(size)); + } + + @Override + public Integer getConcurrentConsumers() { + return getIntegerConfig(CONCURRENT_CONSUMERS); + } + + @Override + public V1CamelSedaBindingModel setConcurrentConsumers(Integer concurrentConsumers) { + return setConfig(CONCURRENT_CONSUMERS, concurrentConsumers); + } + + @Override + public String getWaitForTaskToComplete() { + return getConfig(WAIT_FOR_TASK_TO_COMPLETE); + } + + @Override + public V1CamelSedaBindingModel setWaitForTaskToComplete(String waitForTaskToComplete) { + return setConfig(WAIT_FOR_TASK_TO_COMPLETE, waitForTaskToComplete); + } + + @Override + public Long getTimeout() { + return getLongConfig(TIMEOUT); + } + + @Override + public V1CamelSedaBindingModel setTimeout(Long timeout) { + return setConfig(TIMEOUT, timeout); + } + + @Override + public Boolean isMultipleConsumers() { + return getBooleanConfig(MULTIPLE_CONSUMERS); + } + + @Override + public V1CamelSedaBindingModel setMultipleConsumers(Boolean multipleConsumers) { + return setConfig(MULTIPLE_CONSUMERS, multipleConsumers); + } + + @Override + public Boolean isLimitConcurrentConsumers() { + return getBooleanConfig(LIMIT_CONCURRENT_CONSUMERS); + } + + @Override + public V1CamelSedaBindingModel setLimitConcurrentConsumers(Boolean limitConcurrentConsumers) { + return setConfig(LIMIT_CONCURRENT_CONSUMERS, limitConcurrentConsumers); + } + + @Override + public URI getComponentURI() { + String uriStr = SEDA + "://" + getConfig(NAME); + // create query string from config values + QueryString queryString = new QueryString(); + traverseConfiguration(getModelConfiguration().getChildren(), queryString, NAME); + + return URI.create(uriStr.toString() + queryString); + } + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelTimerBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelTimerBindingModel.java new file mode 100644 index 000000000..8deb464a4 --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelTimerBindingModel.java @@ -0,0 +1,161 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model.v1; + +import java.net.URI; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.core.model.CamelTimerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Represents the configuration settings for Camel Timer binding. + * + * @author Mario Antollini + */ +public class V1CamelTimerBindingModel extends V1BaseCamelBindingModel + implements CamelTimerBindingModel { + + /** + * Camel endpoint type. + */ + public static final String TIMER = "timer"; + + /** + * Date format string. + */ + public static final String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss"; + + /** + * Camel endpoint configuration values. + */ + private static final String NAME = "name"; + private static final String TIME = "time"; + private static final String PATTERN = "pattern"; + private static final String PERIOD = "period"; + private static final String DELAY = "delay"; + private static final String FIXED_RATE = "fixedRate"; + private static final String DAEMON = "daemon"; + + /** + * Create a new CamelTimerBindingModel. + * @param namespace namespace + */ + public V1CamelTimerBindingModel(String namespace) { + super(TIMER, namespace); + + setModelChildrenOrder(NAME, TIME, PATTERN, PERIOD, DELAY, FIXED_RATE, DAEMON); + } + + /** + * Create a CamelTimerBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelTimerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getTimerName() { + return getConfig(NAME); + } + + @Override + public V1CamelTimerBindingModel setTimerName(String name) { + return setConfig(NAME, name); + } + + @Override + public Date getTime() { + final DateFormat dateConfigFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return getDateConfig(TIME, dateConfigFormat); + } + + @Override + public V1CamelTimerBindingModel setTime(Date time) { + final DateFormat timeDateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return setConfig(TIME, timeDateFormat.format(time)); + } + + @Override + public String getPattern() { + return getConfig(PATTERN); + } + + @Override + public V1CamelTimerBindingModel setPattern(String pattern) { + return setConfig(PATTERN, pattern); + } + + @Override + public Long getPeriod() { + return getLongConfig(PERIOD); + } + + @Override + public V1CamelTimerBindingModel setPeriod(Long period) { + return setConfig(PERIOD, period); + } + + @Override + public Long getDelay() { + return getLongConfig(DELAY); + } + + @Override + public V1CamelTimerBindingModel setDelay(Long delay) { + return setConfig(DELAY, delay); + } + + @Override + public Boolean isFixedRate() { + return getBooleanConfig(FIXED_RATE); + } + + @Override + public V1CamelTimerBindingModel setFixedRate(Boolean fixedRate) { + return setConfig(FIXED_RATE, fixedRate); + } + + @Override + public Boolean isDaemon() { + return getBooleanConfig(DAEMON); + } + + @Override + public V1CamelTimerBindingModel setDaemon(Boolean daemon) { + return setConfig(DAEMON, daemon); + } + + @Override + public URI getComponentURI() { + // base URI without params + String uriStr = TIMER + "://" + getConfig(NAME); + // create query string from config values + QueryString queryStr = new QueryString(); + traverseConfiguration(getModelConfiguration().getChildren(), queryStr, NAME); + + return URI.create(uriStr.toString() + queryStr); + } + + + +} diff --git a/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelUriBindingModel.java b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelUriBindingModel.java new file mode 100644 index 000000000..d5eb9a8ba --- /dev/null +++ b/components/camel/camel-core/src/main/java/org/switchyard/component/camel/core/model/v1/V1CamelUriBindingModel.java @@ -0,0 +1,109 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.core.model.v1; + +import java.net.URI; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A generic binding definintion for Apache Camel components. + * + * Example of a binding implemem + * .tation: + *

+ * {@code
+ *  
+ *     
+ *        
+ *     
+ *  
+ * }
+ * 
+ * + *
    + *
  • The 'configURI' attribute can be used to specify a Camel component uri.
  • + *
+ * + * @author Daniel Bevenius + */ +public class V1CamelUriBindingModel extends V1BaseCamelBindingModel { + + /** + * The binding type (binding.camel). + */ + public static final String URI = "uri"; + + /** + * This is the name of the uri attribute. + */ + public static final String CONFIG_URI = "configURI"; + + /** + * This is the name of the transacted attribute. + */ + public static final String TRANSACTED = "transacted"; + + /** + * The name of the transacedRef attribute. + */ + public static final String TRANSACTED_REF = "transactedRef"; + + /** + * Create a new CamelBindingModel. + * @param namespace namespace + */ + public V1CamelUriBindingModel(String namespace) { + super(URI, namespace); + } + + /** + * Create a CamelBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelUriBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(); + } + + /** + * Gets the binding uri attribute from the underlying model. + * + * @return URI The binding uri attribute. + */ + public URI getConfigURI() { + return java.net.URI.create(getModelAttribute(CONFIG_URI)); + } + + /** + * Sets the "uri" element on the underlying model. + * + * @param uri The Camel Component URI + * @return {@link org.switchyard.component.camel.common.model.CamelBindingModel CamelBindingModel} to support method chaining. + */ + public V1CamelUriBindingModel setConfigURI(URI uri) { + setModelAttribute(CONFIG_URI, uri.toString()); + return this; + } + + @Override + public URI getComponentURI() { + return getConfigURI(); + } + +} diff --git a/components/camel/camel-core/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-core/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..0ccc55f15 --- /dev/null +++ b/components/camel/camel-core/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.core.deploy.CamelCoreComponent \ No newline at end of file diff --git a/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v1/camel-core_1_0.xsd b/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v1/camel-core_1_0.xsd new file mode 100644 index 000000000..6e695d057 --- /dev/null +++ b/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v1/camel-core_1_0.xsd @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v1/camel-core_1_1.xsd b/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v1/camel-core_1_1.xsd new file mode 100644 index 000000000..052c4fc26 --- /dev/null +++ b/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v1/camel-core_1_1.xsd @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v2/camel-core_2_0.xsd b/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v2/camel-core_2_0.xsd new file mode 100644 index 000000000..f61df21f9 --- /dev/null +++ b/components/camel/camel-core/src/main/resources/org/switchyard/component/camel/core/model/v2/camel-core_2_0.xsd @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-core/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-core/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..15d51ef69 --- /dev/null +++ b/components/camel/camel-core/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_core_1_0.section=urn:switchyard-component-camel-core:config +camel_core_1_0.version=1.0 +camel_core_1_0.namespace=urn:switchyard-component-camel-core:config:1.0 +camel_core_1_0.schema=camel-core_1_0.xsd +camel_core_1_0.location=/org/switchyard/component/camel/core/model/v1/ +camel_core_1_0.marshaller=org.switchyard.component.camel.core.model.v1.V1CamelCoreModelMarshaller + +camel_core_1_1.section=urn:switchyard-component-camel-core:config +camel_core_1_1.version=1.1 +camel_core_1_1.namespace=urn:switchyard-component-camel-core:config:1.1 +camel_core_1_1.schema=camel-core_1_1.xsd +camel_core_1_1.location=/org/switchyard/component/camel/core/model/v1/ +camel_core_1_1.marshaller=org.switchyard.component.camel.core.model.v1.V1CamelCoreModelMarshaller + +camel_core_2_0.section=urn:switchyard-component-camel-core:config +camel_core_2_0.version=2.0 +camel_core_2_0.namespace=urn:switchyard-component-camel-core:config:2.0 +camel_core_2_0.schema=camel-core_2_0.xsd +camel_core_2_0.location=/org/switchyard/component/camel/core/model/v2/ +camel_core_2_0.marshaller=org.switchyard.component.camel.core.model.v1.V1CamelCoreModelMarshaller diff --git a/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelDirectBindingModelTest.java b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelDirectBindingModelTest.java new file mode 100644 index 000000000..9e4d543a9 --- /dev/null +++ b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelDirectBindingModelTest.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.config.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.direct.DirectEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.core.model.CamelCoreNamespace; +import org.switchyard.component.camel.core.model.v1.V1CamelUriBindingModel; +import org.switchyard.component.camel.core.model.v1.V1CamelDirectBindingModel; + +/** + * Test for {@link V1CamelUriBindingModel}. + * + * @author Mario Antollini + */ +public class V1CamelDirectBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "switchyard-direct-binding-beans.xml"; + + private static final String NAME = "fooDirectName"; + + private static final String CAMEL_URI = "direct://fooDirectName"; + + public V1CamelDirectBindingModelTest() { + super(DirectEndpoint.class, CAMEL_XML); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + + @Override + protected void createModelAssertions(V1CamelDirectBindingModel model) { + assertEquals(NAME, model.getEndpointName()); + } + + @Override + protected V1CamelDirectBindingModel createTestModel() { + return new V1CamelDirectBindingModel(CamelCoreNamespace.V_1_0.uri()).setEndpointName(NAME); + } + +} \ No newline at end of file diff --git a/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelMockBindingModelTest.java b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelMockBindingModelTest.java new file mode 100644 index 000000000..4f7224931 --- /dev/null +++ b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelMockBindingModelTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.config.model.v1; + +import static org.junit.Assert.assertEquals; + +import org.apache.camel.component.mock.MockEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.core.model.CamelCoreNamespace; +import org.switchyard.component.camel.core.model.v1.V1CamelUriBindingModel; +import org.switchyard.component.camel.core.model.v1.V1CamelMockBindingModel; + +/** + * Test for {@link V1CamelUriBindingModel}. + * + * @author Mario Antollini + */ +public class V1CamelMockBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "switchyard-mock-binding-beans.xml"; + + private static final String NAME = "fooMockName"; + private static final Integer REPORT_GROUP = new Integer(999); + + private static final String CAMEL_URI = "mock://fooMockName?reportGroup=999"; + + public V1CamelMockBindingModelTest() { + super(MockEndpoint.class, CAMEL_XML); + } + + @Override + protected V1CamelMockBindingModel createTestModel() { + return new V1CamelMockBindingModel(CamelCoreNamespace.V_1_0.uri()).setEndpointName(NAME).setReportGroup(REPORT_GROUP); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + + @Override + protected void createModelAssertions(V1CamelMockBindingModel model) { + assertEquals(NAME, model.getEndpointName()); + assertEquals(REPORT_GROUP, model.getReportGroup()); + } + +} \ No newline at end of file diff --git a/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelReferenceBindingModelTest.java b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelReferenceBindingModelTest.java new file mode 100644 index 000000000..5125c5f11 --- /dev/null +++ b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelReferenceBindingModelTest.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.config.model.v1; + +import static org.junit.Assert.assertEquals; + +import java.net.URI; + +import org.apache.camel.component.direct.DirectEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.core.model.CamelCoreNamespace; +import org.switchyard.component.camel.core.model.v1.V1CamelUriBindingModel; + +/** + * Test for {@link V1CamelUriBindingModel}. + * + * @author Daniel Bevenius + */ +public class V1CamelReferenceBindingModelTest extends V1BaseCamelReferenceBindingModelTest { + + private final static String CAMEL_XML = "switchyard-camel-ref-beans.xml"; + private final static String CAMEL_URI = "direct://input"; + + public V1CamelReferenceBindingModelTest() { + super(DirectEndpoint.class, CAMEL_XML); + } + + @Override + protected V1CamelUriBindingModel createTestModel() { + return new V1CamelUriBindingModel(CamelCoreNamespace.V_1_0.uri()) + .setConfigURI(URI.create("direct://input")); + } + + @Override + protected void createModelAssertions(V1CamelUriBindingModel model) { + assertEquals("uri", model.getType()); + assertEquals("direct", model.getConfigURI().getScheme()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelSedaBindingModelTest.java b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelSedaBindingModelTest.java new file mode 100644 index 000000000..0607fa104 --- /dev/null +++ b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelSedaBindingModelTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.config.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.seda.SedaEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.core.model.CamelCoreNamespace; +import org.switchyard.component.camel.core.model.v1.V1CamelUriBindingModel; +import org.switchyard.component.camel.core.model.v1.V1CamelSedaBindingModel; + +/** + * Test for {@link V1CamelUriBindingModel}. + * + * @author Mario Antollini + */ +public class V1CamelSedaBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "switchyard-seda-binding-beans.xml"; + + private static final String NAME = "fooSedaName"; + private static final Integer SIZE = new Integer(55); + private static final Integer CONCURRENT_CONSUMERS = new Integer(3); + private static final String WAIT_FOR_TASK_TO_COMPLETE = "Always"; + private static final Long TIMEOUT = new Long(1000); + private static final Boolean MULTIPLE_CONSUMERS = Boolean.TRUE; + private static final Boolean LIMIT_CONCURRENT_CONSUMERS = Boolean.FALSE; + + private static final String CAMEL_URI = "seda://fooSedaName?size=55" + + "&waitForTaskToComplete=Always&concurrentConsumers=3" + + "&timeout=1000&multipleConsumers=true&limitConcurrentConsumers=false"; + + public V1CamelSedaBindingModelTest() { + super(SedaEndpoint.class, CAMEL_XML); + } + + @Override + protected void createModelAssertions(V1CamelSedaBindingModel model) { + assertEquals(NAME, model.getEndpointName()); + assertEquals(SIZE, model.getSize()); + assertEquals(CONCURRENT_CONSUMERS, model.getConcurrentConsumers()); + assertEquals(WAIT_FOR_TASK_TO_COMPLETE, model.getWaitForTaskToComplete()); + assertEquals(TIMEOUT, model.getTimeout()); + assertEquals(MULTIPLE_CONSUMERS, model.isMultipleConsumers()); + assertEquals(LIMIT_CONCURRENT_CONSUMERS, model.isLimitConcurrentConsumers()); + } + + @Override + protected V1CamelSedaBindingModel createTestModel() { + return new V1CamelSedaBindingModel(CamelCoreNamespace.V_1_0.uri()).setEndpointName(NAME) + .setSize(SIZE) + .setConcurrentConsumers(CONCURRENT_CONSUMERS) + .setWaitForTaskToComplete(WAIT_FOR_TASK_TO_COMPLETE) + .setTimeout(TIMEOUT) + .setMultipleConsumers(MULTIPLE_CONSUMERS) + .setLimitConcurrentConsumers(LIMIT_CONCURRENT_CONSUMERS); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} \ No newline at end of file diff --git a/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelServiceBindingModelTest.java b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelServiceBindingModelTest.java new file mode 100644 index 000000000..226190730 --- /dev/null +++ b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelServiceBindingModelTest.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.config.model.v1; + +import static org.junit.Assert.assertEquals; + +import java.net.URI; + +import org.apache.camel.component.direct.DirectEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.core.model.CamelCoreNamespace; +import org.switchyard.component.camel.core.model.v1.V1CamelUriBindingModel; + +/** + * Test for {@link V1CamelUriBindingModel}. + * + * @author Daniel Bevenius + */ +public class V1CamelServiceBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private final static String CAMEL_XML = "switchyard-camel-binding-beans.xml"; + private final static String CAMEL_URI = "direct://input"; + + public V1CamelServiceBindingModelTest() { + super(DirectEndpoint.class, CAMEL_XML); + } + + @Override + protected V1CamelUriBindingModel createTestModel() { + return new V1CamelUriBindingModel(CamelCoreNamespace.V_1_0.uri()) + .setConfigURI(URI.create("direct://input")); + } + + @Override + protected void createModelAssertions(V1CamelUriBindingModel model) { + assertEquals("uri", model.getType()); + assertEquals("direct", model.getConfigURI().getScheme()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelTimerBindingModelTest.java b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelTimerBindingModelTest.java new file mode 100644 index 000000000..cdab47057 --- /dev/null +++ b/components/camel/camel-core/src/test/java/org/switchyard/component/camel/config/model/v1/V1CamelTimerBindingModelTest.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.camel.config.model.v1; + +import static junit.framework.Assert.assertEquals; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.camel.component.timer.TimerEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.core.model.CamelCoreNamespace; +import org.switchyard.component.camel.core.model.v1.V1CamelUriBindingModel; +import org.switchyard.component.camel.core.model.v1.V1CamelTimerBindingModel; + +/** + * Test for {@link V1CamelUriBindingModel}. + * + * @author Mario Antollini + */ +public class V1CamelTimerBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "switchyard-timer-binding-beans.xml"; + + private static final String NAME = "fooTimer"; + private static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss"; + private static final Long PERIOD = new Long(555); + private static final Long DELAY = new Long(100); + private static final Boolean FIXED_RATE = Boolean.TRUE; + private static final Boolean DAEMON = Boolean.FALSE; + + private static final String CAMEL_URI = + "timer://fooTimer?time=2011-01-01T12:00:00&pattern=yyyy-MM-dd'T'HH:mm:ss&" + + "period=555&delay=100&fixedRate=true&daemon=false"; + + private Date referenceDate; + + public V1CamelTimerBindingModelTest() throws ParseException { + super(TimerEndpoint.class, CAMEL_XML); + + referenceDate = new SimpleDateFormat(PATTERN).parse("2011-01-01T12:00:00"); + } + + @Override + protected void createModelAssertions(V1CamelTimerBindingModel model) { + assertEquals(NAME, model.getTimerName()); + assertEquals(referenceDate.toString(), model.getTime().toString()); + assertEquals(PATTERN, model.getPattern()); + assertEquals(PERIOD, model.getPeriod()); + assertEquals(DELAY, model.getDelay()); + assertEquals(FIXED_RATE, model.isFixedRate()); + assertEquals(DAEMON, model.isDaemon()); + } + + @Override + protected V1CamelTimerBindingModel createTestModel() { + return new V1CamelTimerBindingModel(CamelCoreNamespace.V_1_0.uri()).setTimerName(NAME) + .setTime(referenceDate) + .setPattern(PATTERN) + .setPeriod(PERIOD) + .setDelay(DELAY) + .setFixedRate(FIXED_RATE) + .setDaemon(DAEMON); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-camel-binding-beans.xml b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-camel-binding-beans.xml new file mode 100644 index 000000000..3083d56a9 --- /dev/null +++ b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-camel-binding-beans.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-camel-ref-beans.xml b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-camel-ref-beans.xml new file mode 100644 index 000000000..a7f16d319 --- /dev/null +++ b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-camel-ref-beans.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-direct-binding-beans.xml b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-direct-binding-beans.xml new file mode 100644 index 000000000..2f9e9cbfd --- /dev/null +++ b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-direct-binding-beans.xml @@ -0,0 +1,27 @@ + + + + + + + + fooDirectName + + + + + diff --git a/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-mock-binding-beans.xml b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-mock-binding-beans.xml new file mode 100644 index 000000000..0550f0704 --- /dev/null +++ b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-mock-binding-beans.xml @@ -0,0 +1,28 @@ + + + + + + + + fooMockName + 999 + + + + + diff --git a/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-seda-binding-beans.xml b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-seda-binding-beans.xml new file mode 100644 index 000000000..2121ccd99 --- /dev/null +++ b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-seda-binding-beans.xml @@ -0,0 +1,33 @@ + + + + + + + + fooSedaName + 55 + 3 + Always + 1000 + true + false + + + + + diff --git a/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-timer-binding-beans.xml b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-timer-binding-beans.xml new file mode 100644 index 000000000..08bf60e04 --- /dev/null +++ b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-timer-binding-beans.xml @@ -0,0 +1,33 @@ + + + + + + + + fooTimer + 2011-01-01T12:00:00 + yyyy-MM-dd'T'HH:mm:ss + 555 + 100 + true + false + + + + + diff --git a/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-vm-binding-beans.xml b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-vm-binding-beans.xml new file mode 100644 index 000000000..e0398a183 --- /dev/null +++ b/components/camel/camel-core/src/test/resources/org/switchyard/component/camel/config/model/v1/switchyard-vm-binding-beans.xml @@ -0,0 +1,28 @@ + + + + + + + + vmTransporter + 3 + + + + + diff --git a/components/camel/camel-cxf/pom.xml b/components/camel/camel-cxf/pom.xml new file mode 100644 index 000000000..216dc111f --- /dev/null +++ b/components/camel/camel-cxf/pom.xml @@ -0,0 +1,61 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-cxf + bundle + SwitchYard: Camel Component :: CXF Binding + http://switchyard.org + + + org.switchyard.component.camel.cxf.* + + + org.apache.camel.component.cxf, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-core + compile + + + org.apache.camel + camel-cxf + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/deploy/CamelCxfComponent.java b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/deploy/CamelCxfComponent.java new file mode 100644 index 000000000..e210bc355 --- /dev/null +++ b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/deploy/CamelCxfComponent.java @@ -0,0 +1,32 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.cxf.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.cxf.model.v2.V2CamelCxfBindingModel; + +/** + * Camel cxf component. + */ +public class CamelCxfComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelCxfComponent() { + super("CamelCxfComponent", V2CamelCxfBindingModel.CXF); + } + +} + diff --git a/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/CamelCxfBindingModel.java b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/CamelCxfBindingModel.java new file mode 100644 index 000000000..23811bb4f --- /dev/null +++ b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/CamelCxfBindingModel.java @@ -0,0 +1,310 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.cxf.model; + +import java.net.URI; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Camel CXF binding model. + */ +public interface CamelCxfBindingModel extends CamelBindingModel { + /** + * Gets cxfURI. + * @return cxfURI + */ + URI getCxfURI(); + + /** + * Sets cxfURI. + * @param cxfURI cxfURI + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setCxfURI(URI cxfURI); + + /** + * Gets wsdlURL. + * @return wsdlURL + */ + String getWsdlURL(); + + /** + * Sets wsdlURL. + * @param wsdlURL wsdlURL + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setWsdlURL(String wsdlURL); + + /** + * Gets serviceClass. + * @return serviceClass + */ + String getServiceClass(); + + /** + * Sets serviceClass. + * @param serviceClass serviceClass + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setServiceClass(String serviceClass); + + /** + * Gets serviceName. + * @return serviceName + */ + String getServiceName(); + + /** + * Sets serviceName. + * @param serviceName serviceName + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setServiceName(String serviceName); + + /** + * Gets portName. + * @return portName + */ + String getPortName(); + + /** + * Sets portName. + * @param portName portName + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setPortName(String portName); + + /** + * Gets dataFormat. + * @return dataFormat + */ + String getDataFormat(); + + /** + * Sets dataFormat. + * @param dataFormat dataFormat + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setDataFormat(String dataFormat); + + /** + * Gets relayHeaders. + * @return relayHeaders + */ + Boolean isRelayHeaders(); + + /** + * Sets relayHeaders. + * @param relayHeaders relayHeaders + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setRelayHeaders(Boolean relayHeaders); + + /** + * Gets wrapped. + * @return wrapped + */ + Boolean isWrapped(); + + /** + * Sets wrapped. + * @param wrapped wrapped + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setWrapped(Boolean wrapped); + + /** + * Gets wrappedStyle. + * @return wrappedStyle + */ + Boolean isWrappedStyle(); + + /** + * Sets wrappedStyle. + * @param wrappedStyle wrappedStyle + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setWrappedStyle(Boolean wrappedStyle); + + /** + * Gets setDefaultBus. + * @return setDefaultBus + */ + Boolean isSetDefaultBus(); + + /** + * Sets setDefaultBus. + * @param setDefaultBus setDefaultBus + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setSetDefaultBus(Boolean setDefaultBus); + + /** + * Gets bus. + * @return bus + */ + String getBus(); + + /** + * Sets bus. + * @param bus bus + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setBus(String bus); + + /** + * Gets cxfBinding. + * @return cxfBinding + */ + String getCxfBinding(); + + /** + * Sets cxfBinding. + * @param cxfBinding cxfBinding + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setCxfBinding(String cxfBinding); + + /** + * Gets headerFilterStrategy. + * @return headerFilterStrategy + */ + String getHeaderFilterStrategy(); + + /** + * Sets headerFilterStrategy. + * @param headerFilterStrategy headerFilterStrategy + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setHeaderFilterStrategy(String headerFilterStrategy); + + /** + * Gets loggingFeatureEnabled. + * @return loggingFeatureEnabled + */ + Boolean isLoggingFeatureEnabled(); + + /** + * Sets loggingFeatureEnabled. + * @param loggingFeatureEnabled loggingFeatureEnabled + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setLoggingFeatureEnabled(Boolean loggingFeatureEnabled); + + /** + * Gets defaultOperationName. + * @return defaultOperationName + */ + String getDefaultOperationName(); + + /** + * Sets defaultOperationName. + * @param defaultOperationName defaultOperationName + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setDefaultOperationName(String defaultOperationName); + + /** + * Gets defaultOperationNamespace. + * @return defaultOperationNamespace + */ + String getDefaultOperationNamespace(); + + /** + * Sets defaultOperationNamespace. + * @param defaultOperationNamespace defaultOperationNamespace + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setDefaultOperationNamespace(String defaultOperationNamespace); + + /** + * Gets synchronous. + * @return synchronous + */ + Boolean isSynchronous(); + + /** + * Sets synchronous. + * @param synchronous synchronous + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setSynchronous(Boolean synchronous); + + /** + * Gets publishedEndpointUrl. + * @return publishedEndpointUrl + */ + String getPublishedEndpointUrl(); + + /** + * Sets publishedEndpointUrl. + * @param publishedEndpointUrl publishedEndpointUrl + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setPublishedEndpointUrl(String publishedEndpointUrl); + + /** + * Gets allowStreaming. + * @return allowStreaming + */ + Boolean isAllowStreaming(); + + /** + * Sets allowStreaming. + * @param allowStreaming allowStreaming + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setAllowStreaming(Boolean allowStreaming); + + /** + * Gets skipFaultLogging. + * @return skipFaultLogging + */ + Boolean isSkipFaultLogging(); + + /** + * Sets skipFaultLogging. + * @param skipFaultLogging skipFaultLogging + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setSkipFaultLogging(Boolean skipFaultLogging); + + /** + * Gets username. + * @return username + */ + String getUsername(); + + /** + * Sets username. + * @param username username + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setUsername(String username); + + /** + * Gets password. + * @return password + */ + String getPassword(); + + /** + * Sets password. + * @param password password + * @return this BindingModel (useful for chaining) + */ + CamelCxfBindingModel setPassword(String password); + +} diff --git a/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/CamelCxfNamespace.java b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/CamelCxfNamespace.java new file mode 100644 index 000000000..633a1624e --- /dev/null +++ b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/CamelCxfNamespace.java @@ -0,0 +1,105 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.cxf.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Cxf config model namespace. + */ +public enum CamelCxfNamespace implements Namespace { + + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelCxfNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelCxfNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelCxfNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelCxfNamespace + */ + public static CamelCxfNamespace fromUri(String uri) { + return Util.fromUri(CamelCxfNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelCxfNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-cxf:config", version); + } + } + +} diff --git a/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfBindingModel.java b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfBindingModel.java new file mode 100644 index 000000000..21bf2f472 --- /dev/null +++ b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfBindingModel.java @@ -0,0 +1,361 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.cxf.model.v2; + +import java.net.URI; +import java.util.List; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.cxf.model.CamelCxfBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2Camel CXF binding model. + */ +public class V2CamelCxfBindingModel extends V1BaseCamelBindingModel + implements CamelCxfBindingModel { + + /** + * The name of this binding type ("binding.cxf"). + */ + public static final String CXF = "cxf"; + + private static final String CXFURI = "cxfURI"; + private static final String WSDLURL = "wsdlURL"; + private static final String SERVICECLASS = "serviceClass"; + private static final String SERVICENAME = "serviceName"; + private static final String PORTNAME = "portName"; + private static final String DATAFORMAT = "dataFormat"; + private static final String RELAYHEADERS = "relayHeaders"; + private static final String WRAPPED = "wrapped"; + private static final String WRAPPEDSTYLE = "wrappedStyle"; + private static final String SETDEFAULTBUS = "setDefaultBus"; + private static final String BUS = "bus"; + private static final String CXFBINDING = "cxfBinding"; + private static final String HEADERFILTERSTRATEGY = "headerFilterStrategy"; + private static final String LOGGINGFEATUREENABLED = "loggingFeatureEnabled"; + private static final String DEFAULTOPERATIONNAME = "defaultOperationName"; + private static final String DEFAULTOPERATIONNAMESPACE = "defaultOperationNamespace"; + private static final String SYNCHRONOUS = "synchronous"; + private static final String PUBLISHEDENDPOINTURL = "publishedEndpointUrl"; + private static final String ALLOWSTREAMING = "allowStreaming"; + private static final String SKIPFAULTLOGGING = "skipFaultLogging"; + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + + /** + * Create a new CxfBindingModel. + * @param namespace namespace + */ + public V2CamelCxfBindingModel(String namespace) { + super(CXF, namespace); + + setModelChildrenOrder(CXFURI, WSDLURL, SERVICECLASS, SERVICENAME, PORTNAME, DATAFORMAT, RELAYHEADERS, WRAPPED, WRAPPEDSTYLE, SETDEFAULTBUS, BUS, CXFBINDING, HEADERFILTERSTRATEGY, LOGGINGFEATUREENABLED, DEFAULTOPERATIONNAME, DEFAULTOPERATIONNAMESPACE, SYNCHRONOUS, PUBLISHEDENDPOINTURL, ALLOWSTREAMING, SKIPFAULTLOGGING, USERNAME, PASSWORD); + } + + /** + * Create a CxfBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V2CamelCxfBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public URI getCxfURI() { + String uriStr = getConfig(CXFURI); + if (uriStr != null) { + return URI.create(uriStr); + } else { + return null; + } + } + + @Override + public V2CamelCxfBindingModel setCxfURI(URI cxfURI) { + setConfig(CXFURI, cxfURI); + return this; + } + + + @Override + public String getWsdlURL() { + return getConfig(WSDLURL); + } + + @Override + public V2CamelCxfBindingModel setWsdlURL(String wsdlURL) { + setConfig(WSDLURL, wsdlURL); + return this; + } + + + @Override + public String getServiceClass() { + return getConfig(SERVICECLASS); + } + + @Override + public V2CamelCxfBindingModel setServiceClass(String serviceClass) { + setConfig(SERVICECLASS, serviceClass); + return this; + } + + + @Override + public String getServiceName() { + return getConfig(SERVICENAME); + } + + @Override + public V2CamelCxfBindingModel setServiceName(String serviceName) { + setConfig(SERVICENAME, serviceName); + return this; + } + + + @Override + public String getPortName() { + return getConfig(PORTNAME); + } + + @Override + public V2CamelCxfBindingModel setPortName(String portName) { + setConfig(PORTNAME, portName); + return this; + } + + + @Override + public String getDataFormat() { + return getConfig(DATAFORMAT); + } + + @Override + public V2CamelCxfBindingModel setDataFormat(String dataFormat) { + setConfig(DATAFORMAT, dataFormat); + return this; + } + + + @Override + public Boolean isRelayHeaders() { + return getBooleanConfig(RELAYHEADERS); + } + + @Override + public V2CamelCxfBindingModel setRelayHeaders(Boolean relayHeaders) { + setConfig(RELAYHEADERS, relayHeaders); + return this; + } + + + @Override + public Boolean isWrapped() { + return getBooleanConfig(WRAPPED); + } + + @Override + public V2CamelCxfBindingModel setWrapped(Boolean wrapped) { + setConfig(WRAPPED, wrapped); + return this; + } + + + @Override + public Boolean isWrappedStyle() { + return getBooleanConfig(WRAPPEDSTYLE); + } + + @Override + public V2CamelCxfBindingModel setWrappedStyle(Boolean wrappedStyle) { + setConfig(WRAPPEDSTYLE, wrappedStyle); + return this; + } + + + @Override + public Boolean isSetDefaultBus() { + return getBooleanConfig(SETDEFAULTBUS); + } + + @Override + public V2CamelCxfBindingModel setSetDefaultBus(Boolean setDefaultBus) { + setConfig(SETDEFAULTBUS, setDefaultBus); + return this; + } + + + @Override + public String getBus() { + return getConfig(BUS); + } + + @Override + public V2CamelCxfBindingModel setBus(String bus) { + setConfig(BUS, bus); + return this; + } + + + @Override + public String getCxfBinding() { + return getConfig(CXFBINDING); + } + + @Override + public V2CamelCxfBindingModel setCxfBinding(String cxfBinding) { + setConfig(CXFBINDING, cxfBinding); + return this; + } + + + @Override + public String getHeaderFilterStrategy() { + return getConfig(HEADERFILTERSTRATEGY); + } + + @Override + public V2CamelCxfBindingModel setHeaderFilterStrategy(String headerFilterStrategy) { + setConfig(HEADERFILTERSTRATEGY, headerFilterStrategy); + return this; + } + + + @Override + public Boolean isLoggingFeatureEnabled() { + return getBooleanConfig(LOGGINGFEATUREENABLED); + } + + @Override + public V2CamelCxfBindingModel setLoggingFeatureEnabled(Boolean loggingFeatureEnabled) { + setConfig(LOGGINGFEATUREENABLED, loggingFeatureEnabled); + return this; + } + + + @Override + public String getDefaultOperationName() { + return getConfig(DEFAULTOPERATIONNAME); + } + + @Override + public V2CamelCxfBindingModel setDefaultOperationName(String defaultOperationName) { + setConfig(DEFAULTOPERATIONNAME, defaultOperationName); + return this; + } + + + @Override + public String getDefaultOperationNamespace() { + return getConfig(DEFAULTOPERATIONNAMESPACE); + } + + @Override + public V2CamelCxfBindingModel setDefaultOperationNamespace(String defaultOperationNamespace) { + setConfig(DEFAULTOPERATIONNAMESPACE, defaultOperationNamespace); + return this; + } + + + @Override + public Boolean isSynchronous() { + return getBooleanConfig(SYNCHRONOUS); + } + + @Override + public V2CamelCxfBindingModel setSynchronous(Boolean synchronous) { + setConfig(SYNCHRONOUS, synchronous); + return this; + } + + + @Override + public String getPublishedEndpointUrl() { + return getConfig(PUBLISHEDENDPOINTURL); + } + + @Override + public V2CamelCxfBindingModel setPublishedEndpointUrl(String publishedEndpointUrl) { + setConfig(PUBLISHEDENDPOINTURL, publishedEndpointUrl); + return this; + } + + + @Override + public Boolean isAllowStreaming() { + return getBooleanConfig(ALLOWSTREAMING); + } + + @Override + public V2CamelCxfBindingModel setAllowStreaming(Boolean allowStreaming) { + setConfig(ALLOWSTREAMING, allowStreaming); + return this; + } + + + @Override + public Boolean isSkipFaultLogging() { + return getBooleanConfig(SKIPFAULTLOGGING); + } + + @Override + public V2CamelCxfBindingModel setSkipFaultLogging(Boolean skipFaultLogging) { + setConfig(SKIPFAULTLOGGING, skipFaultLogging); + return this; + } + + + @Override + public String getUsername() { + return getConfig(USERNAME); + } + + @Override + public V2CamelCxfBindingModel setUsername(String username) { + setConfig(USERNAME, username); + return this; + } + + + @Override + public String getPassword() { + return getConfig(PASSWORD); + } + + @Override + public V2CamelCxfBindingModel setPassword(String password) { + setConfig(PASSWORD, password); + return this; + } + + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = CXF + "://" + getCxfURI(); + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, CXFURI); + + return URI.create(baseUri + queryStr.toString()); + } + +} diff --git a/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfModelMarshaller.java b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfModelMarshaller.java new file mode 100644 index 000000000..eb0e45728 --- /dev/null +++ b/components/camel/camel-cxf/src/main/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.cxf.model.v2; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * V2 Cxf model marshaller. + */ +public class V2CamelCxfModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_CXF = BindingModel.BINDING + '.' + V2CamelCxfBindingModel.CXF; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V2CamelCxfModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_CXF.equals(name)) { + return new V2CamelCxfBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-cxf/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-cxf/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..02d6485d6 --- /dev/null +++ b/components/camel/camel-cxf/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.cxf.deploy.CamelCxfComponent diff --git a/components/camel/camel-cxf/src/main/resources/org/switchyard/component/camel/cxf/model/v2/camel-cxf_2_0.xsd b/components/camel/camel-cxf/src/main/resources/org/switchyard/component/camel/cxf/model/v2/camel-cxf_2_0.xsd new file mode 100644 index 000000000..07a45fb22 --- /dev/null +++ b/components/camel/camel-cxf/src/main/resources/org/switchyard/component/camel/cxf/model/v2/camel-cxf_2_0.xsd @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-cxf/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-cxf/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..0cbcb524f --- /dev/null +++ b/components/camel/camel-cxf/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,18 @@ +# Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_cxf_2_0.section=urn:switchyard-component-camel-cxf:config +camel_cxf_2_0.version=2.0 +camel_cxf_2_0.namespace=urn:switchyard-component-camel-cxf:config:2.0 +camel_cxf_2_0.schema=camel-cxf_2_0.xsd +camel_cxf_2_0.location=/org/switchyard/component/camel/cxf/model/v2/ +camel_cxf_2_0.marshaller=org.switchyard.component.camel.cxf.model.v2.V2CamelCxfModelMarshaller diff --git a/components/camel/camel-cxf/src/test/java/org/switchyard/component/camel/cxf/HelloWorldService.java b/components/camel/camel-cxf/src/test/java/org/switchyard/component/camel/cxf/HelloWorldService.java new file mode 100644 index 000000000..2bfb58dc6 --- /dev/null +++ b/components/camel/camel-cxf/src/test/java/org/switchyard/component/camel/cxf/HelloWorldService.java @@ -0,0 +1,32 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.cxf; + + +/** + * HelloWorldService Interface. + */ +public interface HelloWorldService { + + /** + * Interface method. + * @param input the input + * @return the response + */ + public String sayHello(String input); + +} diff --git a/components/camel/camel-cxf/src/test/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfBindingModelTest.java b/components/camel/camel-cxf/src/test/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfBindingModelTest.java new file mode 100644 index 000000000..96bc76337 --- /dev/null +++ b/components/camel/camel-cxf/src/test/java/org/switchyard/component/camel/cxf/model/v2/V2CamelCxfBindingModelTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.cxf.model.v2; + +import static org.junit.Assert.assertEquals; + +import java.net.URI; +import java.text.ParseException; +import java.util.Collections; + +import org.apache.camel.component.cxf.CxfEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.cxf.model.CamelCxfNamespace; + +/** + * Test of cxf binding model. + */ +public class V2CamelCxfBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-cxf-binding.xml"; + + private static final String CAMEL_URI = + "cxf://http://localhost:8080/testWS?wsdlURL=http://localhost:8080/testWS?wsdl&serviceClass=org.switchyard.component.camel.cxf.HelloWorldService&serviceName={org.foo}Service&portName={org.foo}Port&dataFormat=PAYLOAD&wrapped=true&wrappedStyle=true&setDefaultBus=true&loggingFeatureEnabled=false&defaultOperationName=opName&defaultOperationNamespace=org.foo&synchronous=true&publishedEndpointUrl=scheme://form&allowStreaming=false&skipFaultLogging=false&properties.foo=bar"; + private static final URI CXFURI = URI.create("http://localhost:8080/testWS"); + private static final String WSDLURL = "http://localhost:8080/testWS?wsdl"; + private static final String SERVICECLASS = "org.switchyard.component.camel.cxf.HelloWorldService"; + private static final String SERVICENAME = "{org.foo}Service"; + private static final String PORTNAME = "{org.foo}Port"; + private static final String DATAFORMAT = "PAYLOAD"; + private static final Boolean WRAPPED = true; + private static final Boolean WRAPPEDSTYLE = true; + private static final Boolean SETDEFAULTBUS = true; + private static final Boolean LOGGINGFEATUREENABLED = false; + private static final String DEFAULTOPERATIONNAME = "opName"; + private static final String DEFAULTOPERATIONNAMESPACE = "org.foo"; + private static final Boolean SYNCHRONOUS = true; + private static final String PUBLISHEDENDPOINTURL = "scheme://form"; + private static final Boolean ALLOWSTREAMING = false; + private static final Boolean SKIPFAULTLOGGING = false; + + public V2CamelCxfBindingModelTest() throws ParseException { + super(CxfEndpoint.class, CAMEL_XML); + } + + @Override + protected void createModelAssertions(V2CamelCxfBindingModel model) { + assertEquals(CXFURI, model. getCxfURI()); + assertEquals(WSDLURL, model. getWsdlURL()); + assertEquals(SERVICECLASS, model. getServiceClass()); + assertEquals(SERVICENAME, model. getServiceName()); + assertEquals(PORTNAME, model. getPortName()); + assertEquals(DATAFORMAT, model. getDataFormat()); + assertEquals(WRAPPED, model. isWrapped()); + assertEquals(WRAPPEDSTYLE, model. isWrappedStyle()); + assertEquals(SETDEFAULTBUS, model. isSetDefaultBus()); + assertEquals(LOGGINGFEATUREENABLED, model. isLoggingFeatureEnabled()); + assertEquals(DEFAULTOPERATIONNAME, model. getDefaultOperationName()); + assertEquals(DEFAULTOPERATIONNAMESPACE, model. getDefaultOperationNamespace()); + assertEquals(SYNCHRONOUS, model. isSynchronous()); + assertEquals(PUBLISHEDENDPOINTURL, model. getPublishedEndpointUrl()); + assertEquals(ALLOWSTREAMING, model. isAllowStreaming()); + assertEquals(SKIPFAULTLOGGING, model. isSkipFaultLogging()); + } + + @Override + protected V2CamelCxfBindingModel createTestModel() { + V2CamelCxfBindingModel abm = new V2CamelCxfBindingModel(CamelCxfNamespace.V_2_0.uri()); + abm.setAdditionalUriParameters(createAdditionalUriParametersModel(CamelCxfNamespace.V_2_0.uri(), Collections.singletonMap("properties.foo", "bar"))); + abm + .setCxfURI(CXFURI) + .setWsdlURL(WSDLURL) + .setServiceClass(SERVICECLASS) + .setServiceName(SERVICENAME) + .setPortName(PORTNAME) + .setDataFormat(DATAFORMAT) + .setWrapped(WRAPPED) + .setWrappedStyle(WRAPPEDSTYLE) + .setSetDefaultBus(SETDEFAULTBUS) + .setLoggingFeatureEnabled(LOGGINGFEATUREENABLED) + .setDefaultOperationName(DEFAULTOPERATIONNAME) + .setDefaultOperationNamespace(DEFAULTOPERATIONNAMESPACE) + .setSynchronous(SYNCHRONOUS) + .setPublishedEndpointUrl(PUBLISHEDENDPOINTURL) + .setAllowStreaming(ALLOWSTREAMING) + .setSkipFaultLogging(SKIPFAULTLOGGING); + return abm; + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-cxf/src/test/resources/v2/switchyard-cxf-binding.xml b/components/camel/camel-cxf/src/test/resources/v2/switchyard-cxf-binding.xml new file mode 100644 index 000000000..740c7aa27 --- /dev/null +++ b/components/camel/camel-cxf/src/test/resources/v2/switchyard-cxf-binding.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + http://localhost:8080/testWS + http://localhost:8080/testWS?wsdl + org.switchyard.component.camel.cxf.HelloWorldService + {org.foo}Service + {org.foo}Port + PAYLOAD + true + true + true + false + opName + org.foo + true + scheme://form + false + false + + + + diff --git a/components/camel/camel-file/pom.xml b/components/camel/camel-file/pom.xml new file mode 100644 index 000000000..4307642af --- /dev/null +++ b/components/camel/camel-file/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-file + bundle + SwitchYard: Camel Component :: File Binding + http://switchyard.org + + + org.switchyard.component.camel.file.* + + + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-core + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/deploy/CamelFileComponent.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/deploy/CamelFileComponent.java new file mode 100644 index 000000000..19932e158 --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/deploy/CamelFileComponent.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.file.model.v1.V1CamelFileBindingModel; + +/** + * Camel file component. + */ +public class CamelFileComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelFileComponent() { + super("CamelFileComponent", V1CamelFileBindingModel.FILE); + } + +} diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileBindingModel.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileBindingModel.java new file mode 100644 index 000000000..84af2d4aa --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileBindingModel.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.model; + +import org.switchyard.component.camel.common.model.file.GenericFileBindingModel; +import org.switchyard.component.camel.common.model.file.GenericFileProducerBindingModel; + +/** + * Represents the configuration settings for Camel File binding. + */ +public interface CamelFileBindingModel extends GenericFileBindingModel { + + /** + * The consumer's configurations. + * @return an instance of the camel file consumer binding model + */ + CamelFileConsumerBindingModel getConsumer(); + + /** + * Specify the consumer binding model. + * @param consumer the consumer binding model + * @return a reference to this Camel File binding model + */ + GenericFileBindingModel setConsumer(CamelFileConsumerBindingModel consumer); + + /** + * The producers's configurations. + * @return an instance of the camel file producer binding model + */ + GenericFileProducerBindingModel getProducer(); + + /** + * Specify the producer binding model. + * @param producer the producer binding model + * @return a reference to this Camel File binding model + */ + GenericFileBindingModel setProducer(GenericFileProducerBindingModel producer); + +} diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileConsumerBindingModel.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileConsumerBindingModel.java new file mode 100644 index 000000000..7d6d041d0 --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileConsumerBindingModel.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.model; + +import org.switchyard.component.camel.common.model.file.GenericFileConsumerBindingModel; + +/** + * Represents the configuration settings for a File Consumer binding in Camel. + * + * @author Mario Antollini + */ +public interface CamelFileConsumerBindingModel extends GenericFileConsumerBindingModel { + +} diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileNamespace.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileNamespace.java new file mode 100644 index 000000000..a1956c577 --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel File config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelFileNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelFileNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelFileNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelFileNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelFileNamespace + */ + public static CamelFileNamespace fromUri(String uri) { + return Util.fromUri(CamelFileNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelFileNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-file:config", version); + } + } + +} diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileProducerBindingModel.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileProducerBindingModel.java new file mode 100644 index 000000000..20426f7cb --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/CamelFileProducerBindingModel.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.model; + +import org.switchyard.component.camel.common.model.file.GenericFileProducerBindingModel; + +/** + * Represents the configuration settings for a File Producer binding in Camel. + * + * @author Mario Antollini + */ +public interface CamelFileProducerBindingModel extends GenericFileProducerBindingModel { + +} diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileBindingModel.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileBindingModel.java new file mode 100644 index 000000000..333959961 --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileBindingModel.java @@ -0,0 +1,136 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.model.v1; + +import java.net.URI; +import java.util.List; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.file.GenericFileProducerBindingModel; +import org.switchyard.component.camel.common.model.file.v1.V1GenericFileBindingModel; +import org.switchyard.component.camel.common.model.file.v1.V1GenericFileProducerBindingModel; +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledPollConsumer; +import org.switchyard.component.camel.file.model.CamelFileBindingModel; +import org.switchyard.component.camel.file.model.CamelFileConsumerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +/** + * A binding for Camel's file component. + * + * @author Daniel Bevenius + * + */ +public class V1CamelFileBindingModel extends V1GenericFileBindingModel + implements CamelFileBindingModel { + + /** + * The name of this binding type ("binding.file"). + */ + public static final String FILE = "file"; + + /** + * In charge of parsing out consumer options + */ + private CamelFileConsumerBindingModel _consume; + + /** + * In charge of parsing out producer options + */ + private GenericFileProducerBindingModel _produce; + + /** + * Create a new V1CamelFileBindingModel. + * @param namespace namespace + */ + public V1CamelFileBindingModel(String namespace) { + super(FILE, namespace); + + setModelChildrenOrder(CONSUME, PRODUCE); + } + + /** + * Constructor. + * + * @param config + * The switchyard configuration instance. + * @param desc + * The switchyard descriptor instance. + */ + public V1CamelFileBindingModel(final Configuration config, final Descriptor desc) { + super(config, desc); + } + + @Override + public CamelFileConsumerBindingModel getConsumer() { + if (_consume == null) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + _consume = new V1CamelFileConsumerBindingModel(config, getModelDescriptor()); + } + return _consume; + } + + @Override + public V1CamelFileBindingModel setConsumer(CamelFileConsumerBindingModel consumer) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(CONSUME); + getModelConfiguration().addChild( + ((V1CamelScheduledPollConsumer) consumer) + .getModelConfiguration()); + } else { + setChildModel((V1CamelScheduledPollConsumer) consumer); + } + _consume = consumer; + return this; + } + + @Override + public GenericFileProducerBindingModel getProducer() { + if (_produce == null) { + Configuration config = getModelConfiguration().getFirstChild(PRODUCE); + _produce = new V1CamelFileProducerBindingModel(config, getModelDescriptor()); + } + return _produce; + } + + @Override + public V1CamelFileBindingModel setProducer(GenericFileProducerBindingModel producer) { + Configuration config = getModelConfiguration().getFirstChild(PRODUCE); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(PRODUCE); + getModelConfiguration().addChild( + ((V1GenericFileProducerBindingModel) producer) + .getModelConfiguration()); + } else { + setChildModel((V1GenericFileProducerBindingModel) producer); + } + _produce = producer; + return this; + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + QueryString queryString = new QueryString(); + traverseConfiguration(children, queryString, DIRECTORY); + + URI newURI = URI.create(FILE + "://" + getDirectory() + queryString); + return newURI; + } + +} diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileConsumerBindingModel.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileConsumerBindingModel.java new file mode 100644 index 000000000..5589af621 --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileConsumerBindingModel.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.model.v1; + +import org.switchyard.component.camel.common.model.file.v1.V1GenericFileConsumerBindingModel; +import org.switchyard.component.camel.file.model.CamelFileConsumerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A binding for Camel's file component, for consumer configs. + * + * @author Mario Antollini + */ +public class V1CamelFileConsumerBindingModel extends V1GenericFileConsumerBindingModel + implements CamelFileConsumerBindingModel { + + /** + * Create a new V1CamelFileConsumerBindingModel. + * @param namespace namespace + */ + public V1CamelFileConsumerBindingModel(String namespace) { + super(namespace, V1CamelFileBindingModel.CONSUME); + } + + /** + * Create a V1CamelFileConsumerBindingModel from the specified configuration + * and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelFileConsumerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + +} diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileModelMarshaller.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileModelMarshaller.java new file mode 100644 index 000000000..c02767318 --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileModelMarshaller.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * File model marshaller. + */ +public class V1CamelFileModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_FILE = BindingModel.BINDING + '.' + V1CamelFileBindingModel.FILE; + + /** + * Creates new marshaller. + * + * @param desc Descriptor. + */ + public V1CamelFileModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_FILE.equals(name)) { + return new V1CamelFileBindingModel(config, desc); + } + // V1CamelFileConsumerBindingModel and V1CamelFileProducerBindingModel get created by V1CamelFileBindingModel + return super.read(config); + } + +} diff --git a/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileProducerBindingModel.java b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileProducerBindingModel.java new file mode 100644 index 000000000..75fd8f487 --- /dev/null +++ b/components/camel/camel-file/src/main/java/org/switchyard/component/camel/file/model/v1/V1CamelFileProducerBindingModel.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.model.v1; + +import org.switchyard.component.camel.common.model.file.v1.V1GenericFileProducerBindingModel; +import org.switchyard.component.camel.file.model.CamelFileProducerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A binding for Camel's file component, for producer configurations. + * + * @author Mario Antollini + */ +public class V1CamelFileProducerBindingModel extends V1GenericFileProducerBindingModel + implements CamelFileProducerBindingModel { + + /** + * Create a new V1CamelFileProducerBindingModel. + * @param namespace namespace + */ + public V1CamelFileProducerBindingModel(String namespace) { + super(namespace, V1CamelFileBindingModel.PRODUCE); + } + + /** + * Create a V1CamelFileProducerBindingModel from the specified configuration + * and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelFileProducerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + +} diff --git a/components/camel/camel-file/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-file/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..3fe7e4212 --- /dev/null +++ b/components/camel/camel-file/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.file.deploy.CamelFileComponent \ No newline at end of file diff --git a/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v1/camel-file_1_0.xsd b/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v1/camel-file_1_0.xsd new file mode 100644 index 000000000..67add3763 --- /dev/null +++ b/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v1/camel-file_1_0.xsd @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v1/camel-file_1_1.xsd b/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v1/camel-file_1_1.xsd new file mode 100644 index 000000000..0bc851bd1 --- /dev/null +++ b/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v1/camel-file_1_1.xsd @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v2/camel-file_2_0.xsd b/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v2/camel-file_2_0.xsd new file mode 100644 index 000000000..a3a808463 --- /dev/null +++ b/components/camel/camel-file/src/main/resources/org/switchyard/component/camel/file/model/v2/camel-file_2_0.xsd @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-file/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-file/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..68f045530 --- /dev/null +++ b/components/camel/camel-file/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_file_1_0.section=urn:switchyard-component-camel-file:config +camel_file_1_0.version=1.0 +camel_file_1_0.namespace=urn:switchyard-component-camel-file:config:1.0 +camel_file_1_0.schema=camel-file_1_0.xsd +camel_file_1_0.location=/org/switchyard/component/camel/file/model/v1/ +camel_file_1_0.marshaller=org.switchyard.component.camel.file.model.v1.V1CamelFileModelMarshaller + +camel_file_1_1.section=urn:switchyard-component-camel-file:config +camel_file_1_1.version=1.1 +camel_file_1_1.namespace=urn:switchyard-component-camel-file:config:1.1 +camel_file_1_1.schema=camel-file_1_1.xsd +camel_file_1_1.location=/org/switchyard/component/camel/file/model/v1/ +camel_file_1_1.marshaller=org.switchyard.component.camel.file.model.v1.V1CamelFileModelMarshaller + +camel_file_2_0.section=urn:switchyard-component-camel-file:config +camel_file_2_0.version=2.0 +camel_file_2_0.namespace=urn:switchyard-component-camel-file:config:2.0 +camel_file_2_0.schema=camel-file_2_0.xsd +camel_file_2_0.location=/org/switchyard/component/camel/file/model/v2/ +camel_file_2_0.marshaller=org.switchyard.component.camel.file.model.v1.V1CamelFileModelMarshaller diff --git a/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileBindingModelTest.java b/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileBindingModelTest.java new file mode 100644 index 000000000..e759fd428 --- /dev/null +++ b/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileBindingModelTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.file.FileEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.file.model.CamelFileNamespace; +import org.switchyard.component.camel.file.model.v1.V1CamelFileBindingModel; + +/** + * Test for {@link V1CamelBindingModel}. + * + * @author Daniel Bevenius + */ +public class V1CamelFileBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-file-binding-beans.xml"; + private static final String DIRECTORY = "/input/directory"; + private static final Boolean AUTO_CREATE = false; + private static final Integer BUFFER_SIZE = 2048; + private static final String FILE_NAME = "fname"; + private static final String CHARSET = "cp1250"; + private static final Boolean FLATTEN = true; + private static final String CAMEL_URI = "file:///input/directory?autoCreate=false&" + + "bufferSize=2048&charset=cp1250&fileName=fname&flatten=true"; + + public V1CamelFileBindingModelTest() { + super(FileEndpoint.class, CAMEL_XML); + } + + @Override + protected void createModelAssertions(V1CamelFileBindingModel model) { + assertEquals(DIRECTORY, model.getDirectory()); + assertEquals(AUTO_CREATE, model.isAutoCreate()); + assertEquals(BUFFER_SIZE, model.getBufferSize()); + assertEquals(FILE_NAME, model.getFileName()); + assertEquals(FLATTEN, model.isFlatten()); + assertEquals(CHARSET, model.getCharset()); + } + + @Override + protected V1CamelFileBindingModel createTestModel() { + return (V1CamelFileBindingModel) new V1CamelFileBindingModel(CamelFileNamespace.V_1_0.uri()) + .setDirectory(DIRECTORY) + .setAutoCreate(AUTO_CREATE) + .setBufferSize(BUFFER_SIZE) + .setFileName(FILE_NAME) + .setFlatten(FLATTEN) + .setCharset(CHARSET); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileConsumerBindingModelTest.java b/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileConsumerBindingModelTest.java new file mode 100644 index 000000000..7e9d2d04f --- /dev/null +++ b/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileConsumerBindingModelTest.java @@ -0,0 +1,122 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.file.FileEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.file.model.CamelFileConsumerBindingModel; +import org.switchyard.component.camel.file.model.CamelFileNamespace; +import org.switchyard.component.camel.file.model.v1.V1CamelFileBindingModel; +import org.switchyard.component.camel.file.model.v1.V1CamelFileConsumerBindingModel; + +/** + * Test for {@link V1CamelBindingModel}. + * + * @author Mario Antollini + */ +public class V1CamelFileConsumerBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-file-binding-consumer-beans.xml"; + + private static final String DIRECTORY = "/input/directory"; + private static final Integer INITIAL_DELAY = 500; + private static final Integer DELAY = 1000; + private static final Integer MAX_MESSAGES_PER_POLL = 100; + private static final Boolean DELETE = Boolean.FALSE; + private static final Boolean RECURSIVE = true; + private static final Boolean NOOP = false; + private static final String PRE_MOVE = ".inProgress"; + private static final String MOVE = ".done"; + private static final String MOVE_FAILED = ".failed"; + private static final String INCLUDE = "*.csv"; + private static final String EXCLUDE = "*.xml"; + private static final Boolean IDEMPOTENT = true; + private static final String SORT_BY = "file:name"; + private static final String READ_LOCK = "fileLock"; + private static final Long READ_LOCK_TIMEOUT = 10L; + private static final Integer READ_LOCK_CHECK_INTERVAL = new Integer(1000); + private static final Boolean STARTING_DIRECTORY_MUST_EXIST = false; + private static final Boolean DIRECTORY_MUST_EXIST = Boolean.TRUE; + private static final String DONE_FILE_NAME = "done"; + private static final String CAMEL_URI = "file:///input/directory?delay=1000&initialDelay=500&maxMessagesPerPoll=100&delete=false&" + + "recursive=true&noop=false&preMove=.inProgress&move=.done&moveFailed=.failed&" + + "include=*.csv&exclude=*.xml&idempotent=true&sortBy=file:name&" + + "readLock=fileLock&readLockTimeout=10&readLockCheckInterval=1000&" + + "startingDirectoryMustExist=false&directoryMustExist=true&doneFileName=done"; + + public V1CamelFileConsumerBindingModelTest() { + super(FileEndpoint.class, CAMEL_XML); + } + + @Override + protected V1CamelFileBindingModel createTestModel() { + V1CamelFileBindingModel fileModel = new V1CamelFileBindingModel(CamelFileNamespace.V_1_0.uri()); + fileModel.setDirectory(DIRECTORY); + + V1CamelFileConsumerBindingModel model = (V1CamelFileConsumerBindingModel) new V1CamelFileConsumerBindingModel(CamelFileNamespace.V_1_0.uri()) + .setInitialDelay(INITIAL_DELAY) + .setDelay(DELAY); + model.setMaxMessagesPerPoll(MAX_MESSAGES_PER_POLL); + model.setDelete(DELETE) + .setRecursive(RECURSIVE) + .setNoop(NOOP) + .setPreMove(PRE_MOVE) + .setMove(MOVE) + .setMoveFailed(MOVE_FAILED) + .setInclude(INCLUDE) + .setExclude(EXCLUDE) + .setIdempotent(IDEMPOTENT) + .setSortBy(SORT_BY) + .setReadLock(READ_LOCK) + .setReadLockTimeout(READ_LOCK_TIMEOUT) + .setReadLockCheckInterval(READ_LOCK_CHECK_INTERVAL) + .setStartingDirectoryMustExist(STARTING_DIRECTORY_MUST_EXIST) + .setDirectoryMustExist(DIRECTORY_MUST_EXIST) + .setDoneFileName(DONE_FILE_NAME); + return fileModel.setConsumer(model); + } + + @Override + protected void createModelAssertions(V1CamelFileBindingModel model) { + CamelFileConsumerBindingModel consumer = model.getConsumer(); + + assertEquals(INITIAL_DELAY, consumer.getInitialDelay()); + assertEquals(DELAY, consumer.getDelay()); + assertEquals(MAX_MESSAGES_PER_POLL, consumer.getMaxMessagesPerPoll()); + assertEquals(RECURSIVE, consumer.isRecursive()); + assertEquals(DELETE, consumer.isDelete()); + assertEquals(NOOP, consumer.isNoop()); + assertEquals(PRE_MOVE, consumer.getPreMove()); + assertEquals(MOVE, consumer.getMove()); + assertEquals(MOVE_FAILED, consumer.getMoveFailed()); + assertEquals(INCLUDE, consumer.getInclude()); + assertEquals(EXCLUDE, consumer.getExclude()); + assertEquals(IDEMPOTENT, consumer.isIdempotent()); + assertEquals(SORT_BY, consumer.getSortBy()); + assertEquals(READ_LOCK, consumer.getReadLock()); + assertEquals(READ_LOCK_TIMEOUT, consumer.getReadLockTimeout()); + assertEquals(READ_LOCK_CHECK_INTERVAL, consumer.getReadLockCheckInterval()); + assertEquals(STARTING_DIRECTORY_MUST_EXIST, consumer.isStartingDirectoryMustExist()); + assertEquals(DIRECTORY_MUST_EXIST, consumer.isDirectoryMustExist()); + assertEquals(DONE_FILE_NAME, consumer.getDoneFileName()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileProducerBindingModelTest.java b/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileProducerBindingModelTest.java new file mode 100644 index 000000000..676d58578 --- /dev/null +++ b/components/camel/camel-file/src/test/java/org/switchyard/component/camel/file/v1/V1CamelFileProducerBindingModelTest.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.file.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.file.FileEndpoint; +import org.switchyard.component.camel.common.model.file.GenericFileProducerBindingModel; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.file.model.CamelFileNamespace; +import org.switchyard.component.camel.file.model.v1.V1CamelFileBindingModel; +import org.switchyard.component.camel.file.model.v1.V1CamelFileProducerBindingModel; + +/** + * Test for {@link V1CamelBindingModel}. + * + * @author Mario Antollini + */ +public class V1CamelFileProducerBindingModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-file-binding-producer-beans.xml"; + + private static final String DIRECTORY = "/input/directory"; + private static final Boolean AUTO_CREATE = Boolean.FALSE; + private static final String FILE_EXIST = "Override"; + private static final String TEMP_PREFIX = "prefix_"; + private static final Boolean KEEP_LAST_MODIFIED = Boolean.FALSE; + private static final Boolean EAGER_DELETE_TARGET_FLE = Boolean.TRUE; + private static final String DONE_FILENAME = "processed"; + private static final String CAMEL_URI = + "file:///input/directory?autoCreate=false&fileExist=Override" + + "&tempPrefix=prefix_&keepLastModified=false" + + "&eagerDeleteTargetFile=true&doneFileName=processed"; + + public V1CamelFileProducerBindingModelTest() { + super(FileEndpoint.class, CAMEL_XML); + } + + @Override + protected void createModelAssertions(V1CamelFileBindingModel model) { + GenericFileProducerBindingModel producer = model.getProducer(); + assertEquals(FILE_EXIST, producer.getFileExist()); + assertEquals(TEMP_PREFIX, producer.getTempPrefix()); + assertEquals(KEEP_LAST_MODIFIED, producer.isKeepLastModified()); + assertEquals(EAGER_DELETE_TARGET_FLE, producer.isEagerDeleteTargetFile()); + assertEquals(DONE_FILENAME, producer.getDoneFileName()); + } + + @Override + protected V1CamelFileBindingModel createTestModel() { + V1CamelFileBindingModel fileModel = (V1CamelFileBindingModel) new V1CamelFileBindingModel(CamelFileNamespace.V_1_0.uri()) + .setDirectory(DIRECTORY) + .setAutoCreate(AUTO_CREATE); + + GenericFileProducerBindingModel producer = new V1CamelFileProducerBindingModel(CamelFileNamespace.V_1_0.uri()) + .setFileExist(FILE_EXIST) + .setTempPrefix(TEMP_PREFIX) + .setKeepLastModified(KEEP_LAST_MODIFIED) + .setEagerDeleteTargetFile(EAGER_DELETE_TARGET_FLE) + .setDoneFileName(DONE_FILENAME); + return fileModel.setProducer(producer); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-beans.xml b/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-beans.xml new file mode 100644 index 000000000..1d81a8d52 --- /dev/null +++ b/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-beans.xml @@ -0,0 +1,32 @@ + + + + + + + + /input/directory + false + 2048 + fname + true + cp1250 + + + + + diff --git a/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-consumer-beans.xml b/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-consumer-beans.xml new file mode 100644 index 000000000..311e51f1a --- /dev/null +++ b/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-consumer-beans.xml @@ -0,0 +1,47 @@ + + + + + + + + /input/directory + + 500 + 1000 + 100 + false + true + false + .inProgress + .done + .failed + *.csv + *.xml + true + file:name + fileLock + 10 + 1000 + false + true + done + + + + + diff --git a/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-producer-beans.xml b/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-producer-beans.xml new file mode 100644 index 000000000..45a5883c5 --- /dev/null +++ b/components/camel/camel-file/src/test/resources/v1/switchyard-file-binding-producer-beans.xml @@ -0,0 +1,35 @@ + + + + + + + + /input/directory + false + + Override + prefix_ + false + true + processed + + + + + + diff --git a/components/camel/camel-ftp/pom.xml b/components/camel/camel-ftp/pom.xml new file mode 100644 index 000000000..49ab15973 --- /dev/null +++ b/components/camel/camel-ftp/pom.xml @@ -0,0 +1,58 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-ftp + bundle + SwitchYard: Camel Component :: FTP Binding + http://switchyard.org + + + org.switchyard.component.camel.ftp.*; + org.switchyard.component.camel.ftps.*; + org.switchyard.component.camel.sftp.*; + + + org.apache.camel.component.file.remote, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-ftp + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/deploy/CamelFtpComponent.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/deploy/CamelFtpComponent.java new file mode 100644 index 000000000..4f628402e --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/deploy/CamelFtpComponent.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.ftp.model.v1.V1CamelFtpBindingModel; +import org.switchyard.component.camel.ftp.model.v1.V1CamelFtpsBindingModel; +import org.switchyard.component.camel.ftp.model.v1.V1CamelSftpBindingModel; + +/** + * Ftp/ftps/sftp binding component. + */ +public class CamelFtpComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelFtpComponent() { + super("CamelFtpComponent", + V1CamelFtpBindingModel.FTP, + V1CamelFtpsBindingModel.FTPS, + V1CamelSftpBindingModel.SFTP + ); + } + +} diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpBindingModel.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpBindingModel.java new file mode 100644 index 000000000..431e2210a --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpBindingModel.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model; + +import org.switchyard.component.camel.common.model.remote.CamelRemoteFileBindingModel; + +/** + * Ftp endpoint binding. + * + * @author Lukasz Dywicki + */ +public interface CamelFtpBindingModel extends CamelRemoteFileBindingModel { + + /** + * Should connection be used in passive mode. + * + * @return Passive mode. + */ + Boolean isPassiveMode(); + + /** + * Sets passive mode. + * + * @param passive Passive mode. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setPassiveMode(boolean passive); + + /** + * Gets timeout parameter. + * + * @return Timeout (in milliseconds). + */ + Integer getTimeout(); + + /** + * Sets timeout. + * + * @param timeout Timeout. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setTimeout(int timeout); + + /** + * Get socket timeout. + * + * @return Socket timeout (in milliseconds). + */ + Integer getSoTimeout(); + + /** + * Sets socket timeout. + * + * @param timeout Timeout (in milliseconds). + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setSoTimeout(int timeout); + + /** + * Gets site command. + * + * @return Site command. + */ + String getSiteCommand(); + + /** + * Sets site command. + * + * @param command Site command. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setSiteCommand(String command); + +} diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpNamespace.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpNamespace.java new file mode 100644 index 000000000..b3a62356a --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Ftp config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelFtpNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelFtpNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelFtpNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelFtpNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelFtpNamespace + */ + public static CamelFtpNamespace fromUri(String uri) { + return Util.fromUri(CamelFtpNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelFtpNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-ftp:config", version); + } + } + +} diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpsBindingModel.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpsBindingModel.java new file mode 100644 index 000000000..6c060c0d5 --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelFtpsBindingModel.java @@ -0,0 +1,108 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model; + + +/** + * Ftps endpoint binding. + * + * @author Lukasz Dywicki + */ +public interface CamelFtpsBindingModel extends CamelFtpBindingModel { + + /** + * Gets security protocol. + * + * @return Protocol to use. + */ + String getSecurityProtocol(); + + /** + * Sets the underlying security protocol. The following values are defined: + * TLS: Transport Layer Security + * SSL: Secure Sockets Layer + * + * @param protocol Protocol to use. + * @return a reference to this binding model + */ + CamelFtpsBindingModel setSecurityProtocol(String protocol); + + /** + * Gets security mode. + * + * @return True if security mode is implicit. + */ + Boolean isImplict(); + + /** + * Sets the security mode(implicit/explicit). Default is explicit (false). + * + * @param implicit Implicit flag. + * @return a reference to this binding model + */ + CamelFtpsBindingModel setImplict(Boolean implicit); + + /** + * Gets buffer size for secure data channel. + * + * @return Buffer size. + */ + Long getExecPbsz(); + + /** + * This option specifies the buffer size of the secure data channel. If option useSecureDataChannel + * has been enabled and this option has not been explicit set, then value 0 is used. + * + * @param pbsz Buffer size for secure data channel. + * @return a reference to this binding model + */ + CamelFtpsBindingModel setExecPbsz(Long pbsz); + + /** + * Gets actual execProt value. + * + * @return Prot value. + */ + String getExecProt(); + + /** + * Will by default use option P if secure data channel defaults hasn't been disabled. Possible values are: + * C: Clear + * S: Safe (SSL protocol only) + * E: Confidential (SSL protocol only) + * P: Private + * + * @param prot Prot mode + * @return a reference to this binding model + */ + CamelFtpsBindingModel setExecProt(String prot); + + /** + * Gets mode of secure channel defaults. + * + * @return True if defaults for PROT and PBSZ are disabled. + */ + Boolean isDisableSecureDataChannelDefaults(); + + /** + * Whether or not to disable using default values for execPbsz and execProt when using secure data transfer. + * You can set this option to true if you want to be in absolute full control what the options execPbsz and execProt + * should be used. + * + * @param disableSecureDataChannelDefaults Flag to disable defaults. + * @return a reference to this binding model + */ + CamelFtpsBindingModel setDisableSecureDataChannelDefaults(Boolean disableSecureDataChannelDefaults); + +} diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelSftpBindingModel.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelSftpBindingModel.java new file mode 100644 index 000000000..bbfe73fb7 --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/CamelSftpBindingModel.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model; + +import org.switchyard.component.camel.common.model.remote.CamelRemoteFileBindingModel; + +/** + * Sftp endpoint binding. + * + * @author Lukasz Dywicki + */ +public interface CamelSftpBindingModel extends CamelRemoteFileBindingModel { + + /** + * The known hosts file. + * + * @return File used to host key signature verification. + */ + String getKnownHostsFile(); + + /** + * Sets the known_hosts file, so that the SFTP endpoint can do host key verification. + * + * @param knownHostsFile File with known hosts. + * @return a reference to this binding model + */ + CamelSftpBindingModel setKnownHostsFile(String knownHostsFile); + + /** + * Endpoint private key used for authorization. + * + * @return Private key file. + */ + String getPrivateKeyFile(); + + /** + * Set the private key file to that the SFTP endpoint can do private key verification. + * + * @param privateKeyFile Private key file. + * @return a reference to this binding model + */ + CamelSftpBindingModel setPrivateKeyFile(String privateKeyFile); + + /** + * Passphrase used for private key. + * + * @return Private key passphrase. + */ + String getPrivateKeyFilePassphrase(); + + /** + * Set the private key file passphrase to that the SFTP endpoint can do private key verification. + * + * @param passphrase Passphrase for key file. + * @return a reference to this binding model + */ + CamelSftpBindingModel setPrivateKeyFilePassphrase(String passphrase); + +} diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpBindingModel.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpBindingModel.java new file mode 100644 index 000000000..2a91e79ce --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpBindingModel.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model.v1; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.remote.v1.V1CamelRemoteFileBindingModel; +import org.switchyard.component.camel.ftp.model.CamelFtpBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of ftp configuration binding. + * + * @author Lukasz Dywicki + */ +public class V1CamelFtpBindingModel extends V1CamelRemoteFileBindingModel implements + CamelFtpBindingModel { + + /** + * Ftp endpoint prefix. + */ + public static final String FTP = "ftp"; + + /** + * Name of 'passiveMode' element. + */ + protected static final String PASSIVE_MODE = "passiveMode"; + + /** + * Name of 'timeout' element. + */ + protected static final String TIMEOUT = "timeout"; + + /** + * Name of 'soTimeout' element. + */ + protected static final String SO_TIMEOUT = "soTimeout"; + + /** + * Name of 'siteCommand' element. + */ + protected static final String SITE_COMMAND = "siteCommand"; + + /** + * Create a CamelFtpBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param descriptor The switchyard descriptor instance. + */ + public V1CamelFtpBindingModel(Configuration config, Descriptor descriptor) { + super(config, descriptor); + } + + /** + * Default constructor. Creates CamelFtpBindingModel. + * @param namespace namespace + */ + public V1CamelFtpBindingModel(String namespace) { + this(FTP, namespace); + } + + /** + * Creates ftp binding model with different protocol scheme. + * + * @param protocol Protocol scheme. + * @param namespace Namespace of extension. + */ + protected V1CamelFtpBindingModel(String protocol, String namespace) { + super(protocol, namespace); + + setModelChildrenOrder(PASSIVE_MODE, TIMEOUT, SO_TIMEOUT, SITE_COMMAND, CONSUME, PRODUCE); + } + + @Override + public Boolean isPassiveMode() { + return getBooleanConfig(PASSIVE_MODE); + } + + @Override + public V1CamelFtpBindingModel setPassiveMode(boolean passive) { + return setConfig(PASSIVE_MODE, passive); + } + + @Override + public Integer getTimeout() { + return getIntegerConfig(TIMEOUT); + } + + @Override + public V1CamelFtpBindingModel setTimeout(int timeout) { + return setConfig(TIMEOUT, timeout); + } + + @Override + public Integer getSoTimeout() { + return getIntegerConfig(SO_TIMEOUT); + } + + @Override + public V1CamelFtpBindingModel setSoTimeout(int timeout) { + return setConfig(SO_TIMEOUT, timeout); + } + + @Override + public String getSiteCommand() { + return getConfig(SITE_COMMAND); + } + + @Override + public V1CamelFtpBindingModel setSiteCommand(String command) { + return setConfig(SITE_COMMAND, command); + } + + @Override + protected void enrichQueryString(QueryString queryString) { + // nothing to do here.. + } + + @Override + protected String getEndpointProtocol() { + return FTP; + } + +} diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpModelMarshaller.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpModelMarshaller.java new file mode 100644 index 000000000..21b0d1df9 --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpModelMarshaller.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Ftp/ftps/sftp model marshaller. + */ +public class V1CamelFtpModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_FTP = BindingModel.BINDING + '.' + V1CamelFtpBindingModel.FTP; + private static final String BINDING_FTPS = BindingModel.BINDING + '.' + V1CamelFtpsBindingModel.FTPS; + private static final String BINDING_SFTP = BindingModel.BINDING + '.' + V1CamelSftpBindingModel.SFTP; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelFtpModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_FTP.equals(name)) { + return new V1CamelFtpBindingModel(config, desc); + } else if (BINDING_FTPS.equals(name)) { + return new V1CamelFtpsBindingModel(config, desc); + } else if (BINDING_SFTP.equals(name)) { + return new V1CamelSftpBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpsBindingModel.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpsBindingModel.java new file mode 100644 index 000000000..c09bbc45b --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpsBindingModel.java @@ -0,0 +1,120 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model.v1; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.ftp.model.CamelFtpsBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of ftps configuration binding. + * + * @author Lukasz Dywicki + */ +public class V1CamelFtpsBindingModel extends V1CamelFtpBindingModel implements + CamelFtpsBindingModel { + + /** + * Ftps endpoint prefix. + */ + public static final String FTPS = "ftps"; + + private static final String SECURITY_PROTOCOL = "securityProtocol"; + private static final String IMPLICT = "isImplicit"; + private static final String EXEC_PBSZ = "execPbsz"; + private static final String EXEC_PROT = "execProt"; + private static final String DISABLE_SECURE_DATA_CHANNEL_DEFAULTS = "disableSecureDataChannelDefaults"; + + /** + * Create a CamelFtpBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param descriptor The switchyard descriptor instance. + */ + public V1CamelFtpsBindingModel(Configuration config, Descriptor descriptor) { + super(config, descriptor); + } + + /** + * Default constructor. Creates CamelFtpBindingModel. + * @param namespace namespace + */ + public V1CamelFtpsBindingModel(String namespace) { + super(FTPS, namespace); + + setModelChildrenOrder(SECURITY_PROTOCOL, IMPLICT, EXEC_PBSZ, EXEC_PROT, DISABLE_SECURE_DATA_CHANNEL_DEFAULTS); + } + + @Override + protected String getEndpointProtocol() { + return FTPS; + } + + @Override + public String getSecurityProtocol() { + return getConfig(SECURITY_PROTOCOL); + } + + @Override + public V1CamelFtpsBindingModel setSecurityProtocol(String protocol) { + return setConfig(SECURITY_PROTOCOL, protocol); + } + + @Override + public Boolean isImplict() { + return getBooleanConfig(IMPLICT); + } + + @Override + public V1CamelFtpsBindingModel setImplict(Boolean implict) { + return setConfig(IMPLICT, String.valueOf(implict)); + } + + @Override + public Long getExecPbsz() { + return getLongConfig(EXEC_PBSZ); + } + + @Override + public V1CamelFtpsBindingModel setExecPbsz(Long pbsz) { + return setConfig(EXEC_PBSZ, String.valueOf(pbsz)); + } + + @Override + public String getExecProt() { + return getConfig(EXEC_PROT); + } + + @Override + public V1CamelFtpsBindingModel setExecProt(String prot) { + return setConfig(EXEC_PROT, prot); + } + + @Override + public Boolean isDisableSecureDataChannelDefaults() { + return getBooleanConfig(DISABLE_SECURE_DATA_CHANNEL_DEFAULTS); + } + + @Override + public V1CamelFtpsBindingModel setDisableSecureDataChannelDefaults(Boolean disableDefaults) { + return setConfig(DISABLE_SECURE_DATA_CHANNEL_DEFAULTS, String.valueOf(disableDefaults)); + } + + @Override + protected void enrichQueryString(QueryString queryString) { + // nothing to do here.. + } + +} diff --git a/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelSftpBindingModel.java b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelSftpBindingModel.java new file mode 100644 index 000000000..02664a052 --- /dev/null +++ b/components/camel/camel-ftp/src/main/java/org/switchyard/component/camel/ftp/model/v1/V1CamelSftpBindingModel.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model.v1; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.remote.v1.V1CamelRemoteFileBindingModel; +import org.switchyard.component.camel.ftp.model.CamelSftpBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Sftp protocol binding. + * + * @author Lukasz Dywicki + */ +public class V1CamelSftpBindingModel extends V1CamelRemoteFileBindingModel + implements CamelSftpBindingModel { + + /** + * Sftp protocol/endpoint scheme. + */ + public static final String SFTP = "sftp"; + + private static final String KNOWN_HOSTS_FILE = "knownHostsFile"; + private static final String PRIVATE_KEY_FILE = "privateKeyFile"; + private static final String PRIVATE_KEY_FILE_PASSPHRASE = "privateKeyFilePassphrase"; + + /** + * Create a CamelSftpBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param descriptor The switchyard descriptor instance. + */ + public V1CamelSftpBindingModel(Configuration config, Descriptor descriptor) { + super(config, descriptor); + } + + /** + * Create CamelSftpBindingModel. + * @param namespace namespace + */ + public V1CamelSftpBindingModel(String namespace) { + super(SFTP, namespace); + + setModelChildrenOrder(KNOWN_HOSTS_FILE, PRIVATE_KEY_FILE, PRIVATE_KEY_FILE_PASSPHRASE, + PRODUCE, CONSUME); + } + + @Override + public String getKnownHostsFile() { + return getConfig(KNOWN_HOSTS_FILE); + } + + @Override + public V1CamelSftpBindingModel setKnownHostsFile(String knownHostsFile) { + return setConfig(KNOWN_HOSTS_FILE, knownHostsFile); + } + + @Override + public String getPrivateKeyFile() { + return getConfig(PRIVATE_KEY_FILE); + } + + @Override + public V1CamelSftpBindingModel setPrivateKeyFile(String privateKeyFile) { + return setConfig(PRIVATE_KEY_FILE, privateKeyFile); + } + + @Override + public String getPrivateKeyFilePassphrase() { + return getConfig(PRIVATE_KEY_FILE_PASSPHRASE); + } + + @Override + public V1CamelSftpBindingModel setPrivateKeyFilePassphrase(String passphrase) { + return setConfig(PRIVATE_KEY_FILE_PASSPHRASE, passphrase); + } + + @Override + protected String getEndpointProtocol() { + return SFTP; + } + + @Override + protected void enrichQueryString(QueryString queryString) { + // nothing to do there + } + +} diff --git a/components/camel/camel-ftp/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-ftp/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..5abd5a11d --- /dev/null +++ b/components/camel/camel-ftp/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.ftp.deploy.CamelFtpComponent \ No newline at end of file diff --git a/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v1/camel-ftp_1_0.xsd b/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v1/camel-ftp_1_0.xsd new file mode 100644 index 000000000..4a809b07e --- /dev/null +++ b/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v1/camel-ftp_1_0.xsd @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v1/camel-ftp_1_1.xsd b/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v1/camel-ftp_1_1.xsd new file mode 100644 index 000000000..8974a1ae1 --- /dev/null +++ b/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v1/camel-ftp_1_1.xsd @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v2/camel-ftp_2_0.xsd b/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v2/camel-ftp_2_0.xsd new file mode 100644 index 000000000..faf59d144 --- /dev/null +++ b/components/camel/camel-ftp/src/main/resources/org/switchyard/component/camel/ftp/model/v2/camel-ftp_2_0.xsd @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-ftp/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-ftp/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..8197be3be --- /dev/null +++ b/components/camel/camel-ftp/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_ftp_1_0.section=urn:switchyard-component-camel-ftp:config +camel_ftp_1_0.version=1.0 +camel_ftp_1_0.namespace=urn:switchyard-component-camel-ftp:config:1.0 +camel_ftp_1_0.schema=camel-ftp_1_0.xsd +camel_ftp_1_0.location=/org/switchyard/component/camel/ftp/model/v1/ +camel_ftp_1_0.marshaller=org.switchyard.component.camel.ftp.model.v1.V1CamelFtpModelMarshaller + +camel_ftp_1_1.section=urn:switchyard-component-camel-ftp:config +camel_ftp_1_1.version=1.1 +camel_ftp_1_1.namespace=urn:switchyard-component-camel-ftp:config:1.1 +camel_ftp_1_1.schema=camel-ftp_1_1.xsd +camel_ftp_1_1.location=/org/switchyard/component/camel/ftp/model/v1/ +camel_ftp_1_1.marshaller=org.switchyard.component.camel.ftp.model.v1.V1CamelFtpModelMarshaller + +camel_ftp_2_0.section=urn:switchyard-component-camel-ftp:config +camel_ftp_2_0.version=2.0 +camel_ftp_2_0.namespace=urn:switchyard-component-camel-ftp:config:2.0 +camel_ftp_2_0.schema=camel-ftp_2_0.xsd +camel_ftp_2_0.location=/org/switchyard/component/camel/ftp/model/v2/ +camel_ftp_2_0.marshaller=org.switchyard.component.camel.ftp.model.v1.V1CamelFtpModelMarshaller diff --git a/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpBindingModelTest.java b/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpBindingModelTest.java new file mode 100644 index 000000000..d90a23ec2 --- /dev/null +++ b/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpBindingModelTest.java @@ -0,0 +1,117 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.file.remote.FtpEndpoint; +import org.switchyard.component.camel.common.model.remote.CamelRemoteFileBindingModel.PathSeparator; +import org.switchyard.component.camel.common.model.remote.v1.V1CamelRemoteFileConsumerBindingModel; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.ftp.model.CamelFtpNamespace; + +/** + * Test for {@link V1CamelFtpBindingModel}. + * + * @author Lukasz Dywicki + */ +@SuppressWarnings("rawtypes") +public class V1CamelFtpBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-ftp-binding-beans.xml"; + + private static final String DIRECTORY = "test"; + private static final Boolean AUTO_CREATE = false; + private static final String HOST = "localhost"; + private static final Integer PORT = 203; + private static final String USERNAME = "camel"; + private static final String PASSWORD = "secret"; + private static final Boolean BINARY = true; + private static final Integer CONNECT_TIMEOUT = 10; + private static final Boolean DISCONNECT = true; + private static final Integer MAXIMUM_RECONNECT_ATTEMPTS = 10; + private static final Integer RECONNECT_DELAY = 10; + private static final PathSeparator SEPARATOR = PathSeparator.UNIX; + private static final Boolean STEPWISE = true; + private static final Boolean THROW_EXCEPTION_ON_CONNECT_FAIL = true; + private static final Integer TIMEOUT = 10; + private static final Integer SO_TIMEOUT = 10; + private static final Boolean PASSIVE_MODE = true; + private static final String SITE_COMMAND = "PWD"; + private static final Integer INITIAL_DELAY = 500; + + private static final String CAMEL_URI = "ftp://camel:secret@localhost:203/test?autoCreate=false&binary=true&" + + "connectTimeout=10&disconnect=true&maximumReconnectAttempts=10&reconnectDelay=10&" + + "separator=UNIX&stepwise=true&throwExceptionOnConnectFailed=true&passiveMode=true&" + + "timeout=10&soTimeout=10&siteCommand=PWD&initialDelay=500"; + + public V1CamelFtpBindingModelTest() { + super(FtpEndpoint.class, CAMEL_XML); + } + + @Override + protected V1CamelFtpBindingModel createTestModel() { + V1CamelFtpBindingModel model = (V1CamelFtpBindingModel) new V1CamelFtpBindingModel(CamelFtpNamespace.V_1_0.uri()) + .setDirectory(DIRECTORY) + .setAutoCreate(AUTO_CREATE); + model.setHost(HOST) + .setPort(PORT) + .setUsername(USERNAME) + .setPassword(PASSWORD) + .setBinary(BINARY) + .setConnectionTimeout(CONNECT_TIMEOUT) + .setDisconnect(DISCONNECT) + .setMaximumReconnectAttempts(MAXIMUM_RECONNECT_ATTEMPTS) + .setReconnectDelay(RECONNECT_DELAY) + .setSeparator(SEPARATOR.name()) + .setStepwise(STEPWISE) + .setThrowExceptionOnConnectFailed(THROW_EXCEPTION_ON_CONNECT_FAIL); + model.setPassiveMode(PASSIVE_MODE) + .setTimeout(TIMEOUT) + .setSoTimeout(SO_TIMEOUT) + .setSiteCommand(SITE_COMMAND); + V1CamelRemoteFileConsumerBindingModel consumer = new V1CamelRemoteFileConsumerBindingModel(CamelFtpNamespace.V_1_0.uri(), V1CamelFtpBindingModel.CONSUME); + consumer.setInitialDelay(INITIAL_DELAY); + model.setConsumer(consumer); + return model; + } + + @Override + protected void createModelAssertions(V1CamelFtpBindingModel model) { + assertEquals(PASSIVE_MODE, model.isPassiveMode()); + assertEquals(TIMEOUT, model.getTimeout()); + assertEquals(SO_TIMEOUT, model.getSoTimeout()); + assertEquals(SITE_COMMAND, model.getSiteCommand()); + assertEquals(DIRECTORY, model.getDirectory()); + assertEquals(HOST, model.getHost()); + assertEquals(PORT, model.getPort()); + assertEquals(USERNAME, model.getUsername()); + assertEquals(PASSWORD, model.getPassword()); + assertEquals(BINARY, model.isBinary()); + assertEquals(CONNECT_TIMEOUT, model.getConnectTimeout()); + assertEquals(THROW_EXCEPTION_ON_CONNECT_FAIL, model.isThrowExceptionOnConnectFailed()); + assertEquals(STEPWISE, model.isStepwise()); + assertEquals(SEPARATOR, model.getSeparator()); + assertEquals(RECONNECT_DELAY, model.getReconnectDelay()); + assertEquals(MAXIMUM_RECONNECT_ATTEMPTS, model.getMaximumReconnectAttempts()); + assertEquals(DISCONNECT, model.getDisconnect()); + assertEquals(INITIAL_DELAY, model.getConsumer().getInitialDelay()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpsBindingModelTest.java b/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpsBindingModelTest.java new file mode 100644 index 000000000..6ae8cefc4 --- /dev/null +++ b/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelFtpsBindingModelTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model.v1; + +import static org.junit.Assert.assertEquals; + +import org.apache.camel.component.file.remote.FtpsEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.ftp.model.CamelFtpNamespace; +import org.switchyard.component.camel.ftp.model.v1.V1CamelFtpsBindingModel; + +/** + * Test for {@link V1CamelFtpsBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelFtpsBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-ftps-binding-beans.xml"; + private static final String DIRECTORY = "test"; + private static final String HOST = "localhost"; + private static final Boolean IMPLICT = false; + private static final String CAMEL_URI = "ftps://localhost/test?isImplicit=false"; + + public V1CamelFtpsBindingModelTest() { + super(FtpsEndpoint.class, CAMEL_XML); + } + + @Override + protected V1CamelFtpsBindingModel createTestModel() { + V1CamelFtpsBindingModel model = (V1CamelFtpsBindingModel) new V1CamelFtpsBindingModel(CamelFtpNamespace.V_1_0.uri()) + .setDirectory(DIRECTORY) + .setHost(HOST); + + return model.setImplict(IMPLICT); + } + + @Override + protected void createModelAssertions(V1CamelFtpsBindingModel model) { + assertEquals(DIRECTORY, model.getDirectory()); + assertEquals(HOST, model.getHost()); + assertEquals(IMPLICT, model.isImplict()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelSftpBindingModelTest.java b/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelSftpBindingModelTest.java new file mode 100644 index 000000000..e6e2bca60 --- /dev/null +++ b/components/camel/camel-ftp/src/test/java/org/switchyard/component/camel/ftp/model/v1/V1CamelSftpBindingModelTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.ftp.model.v1; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertTrue; + +import java.util.Collections; + +import org.apache.camel.component.file.remote.SftpEndpoint; +import org.junit.Test; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.ftp.model.CamelFtpNamespace; +import org.switchyard.component.camel.ftp.model.v1.V1CamelSftpBindingModel; +import org.switchyard.config.model.Validation; + +/** + * Test for {@link V1CamelSftpBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelSftpBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-sftp-binding-beans.xml"; + + private static final String DIRECTORY = "test"; + private static final String HOST = "localhost"; + private static final int PORT = 9022; + private static final String KNOWN_HOSTS = "known_hosts"; + private static final String PRIVATE_KEY = "my.key"; + private static final String PRIVATE_KEY_PASSPHRASE = "test"; + + private static final String CAMEL_URI = "sftp://localhost:9022/test?knownHostsFile=known_hosts" + + "&privateKeyFile=my.key&privateKeyFilePassphrase=test&maxMessagesPerPoll=5"; + + public V1CamelSftpBindingModelTest() { + super(SftpEndpoint.class, CAMEL_XML); + } + + @Test + public void validateCamelBindingModelWithBeanElement() throws Exception { + final V1CamelSftpBindingModel bindingModel = getFirstCamelBinding(CAMEL_XML); + final Validation validateModel = bindingModel.validateModel(); + + assertTrue(validateModel.getMessage(), validateModel.isValid()); + } + + @Override + protected void createModelAssertions(V1CamelSftpBindingModel model) { + assertEquals(DIRECTORY, model.getDirectory()); + assertEquals(HOST, model.getHost()); + assertEquals(KNOWN_HOSTS, model.getKnownHostsFile()); + assertEquals(PRIVATE_KEY, model.getPrivateKeyFile()); + assertEquals(PRIVATE_KEY_PASSPHRASE, model.getPrivateKeyFilePassphrase()); + } + + @Override + protected V1CamelSftpBindingModel createTestModel() { + V1CamelSftpBindingModel model = (V1CamelSftpBindingModel) new V1CamelSftpBindingModel(CamelFtpNamespace.V_1_1.uri()); + model.getModelConfiguration().setPropertyResolver(new PropertyResolver() { + @Override + public Object resolveProperty(String key) { + if ("maxMessagesPerPoll".equals(key)) { + return 5; + } + return null; + } + }); + model.setAdditionalUriParameters(createAdditionalUriParametersModel(CamelFtpNamespace.V_1_1.uri(), Collections.singletonMap("maxMessagesPerPoll", "${maxMessagesPerPoll}"))); + model.setDirectory(DIRECTORY) + .setHost(HOST) + .setPort(PORT); + + return model.setKnownHostsFile(KNOWN_HOSTS) + .setPrivateKeyFile(PRIVATE_KEY) + .setPrivateKeyFilePassphrase(PRIVATE_KEY_PASSPHRASE); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + + +} diff --git a/components/camel/camel-ftp/src/test/resources/v1/switchyard-ftp-binding-beans.xml b/components/camel/camel-ftp/src/test/resources/v1/switchyard-ftp-binding-beans.xml new file mode 100644 index 000000000..2522e81dd --- /dev/null +++ b/components/camel/camel-ftp/src/test/resources/v1/switchyard-ftp-binding-beans.xml @@ -0,0 +1,47 @@ + + + + + + + + test + false + localhost + 203 + camel + secret + true + 10 + true + 10 + 10 + UNIX + true + true + true + 10 + 10 + PWD + + 500 + + + + + + diff --git a/components/camel/camel-ftp/src/test/resources/v1/switchyard-ftps-binding-beans.xml b/components/camel/camel-ftp/src/test/resources/v1/switchyard-ftps-binding-beans.xml new file mode 100644 index 000000000..375874648 --- /dev/null +++ b/components/camel/camel-ftp/src/test/resources/v1/switchyard-ftps-binding-beans.xml @@ -0,0 +1,29 @@ + + + + + + + + test + localhost + false + + + + + diff --git a/components/camel/camel-ftp/src/test/resources/v1/switchyard-sftp-binding-beans.xml b/components/camel/camel-ftp/src/test/resources/v1/switchyard-sftp-binding-beans.xml new file mode 100644 index 000000000..189fc7415 --- /dev/null +++ b/components/camel/camel-ftp/src/test/resources/v1/switchyard-sftp-binding-beans.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + test + localhost + 9022 + known_hosts + my.key + test + + + + + + + + + + diff --git a/components/camel/camel-jms/pom.xml b/components/camel/camel-jms/pom.xml new file mode 100644 index 000000000..9aeda7d50 --- /dev/null +++ b/components/camel/camel-jms/pom.xml @@ -0,0 +1,61 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-jms + bundle + SwitchYard: Camel Component :: JMS Binding + http://switchyard.org + + + org.switchyard.component.camel.jms.* + + + org.apache.camel.component.jms, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-jms + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/deploy/CamelJmsComponent.java b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/deploy/CamelJmsComponent.java new file mode 100644 index 000000000..23833f1a4 --- /dev/null +++ b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/deploy/CamelJmsComponent.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jms.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.jms.model.v1.V1CamelJmsBindingModel; + +/** + * Jms binding component. + */ +public class CamelJmsComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelJmsComponent() { + super("CamelJmsComponent", V1CamelJmsBindingModel.JMS); + } + +} diff --git a/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/CamelJmsBindingModel.java b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/CamelJmsBindingModel.java new file mode 100644 index 000000000..6508d8e3d --- /dev/null +++ b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/CamelJmsBindingModel.java @@ -0,0 +1,396 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jms.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Represents the configuration settings for a JMS endpoint in Camel. + */ +public interface CamelJmsBindingModel extends CamelBindingModel { + + /** + * Get JMS queue name to consume from/produce to. + * + * @return destination name. + */ + String getQueue(); + + /** + * Specify the queue name to consume from. + * + * @param queue Queue name. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setQueue(String queue); + + /** + * Get JMS queue name to consume from/produce to. + * + * @return destination name. + */ + String getTopic(); + + /** + * Specify the topic name to consume from. + * + * @param topic Topic name. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setTopic(String topic); + + /** + * Connection factory used to consume/produce messages. + * + * @return Connection factory. + */ + String getConnectionFactory(); + + /** + * Specify connection factory instance name to use. + * + * @param connectionFactory Name of bean from camel registry. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setConnectionFactory(String connectionFactory); + + /** + * The username for the connection factory. + * + * @return Username for connection factory. + */ + String getUsername(); + + /** + * Specify username for connection factory. + * + * @param username Username. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setUsername(String username); + + /** + * The password for the connector factory. + * + * @return Password used to authorize user. + */ + String getPassword(); + + /** + * Specify password to use. + * + * @param password Password. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setPassword(String password); + + /** + * Obtain client id. + * + * @return Client id set for connection. + */ + String getClientId(); + + /** + * Sets the JMS client ID to use. Note that this value, if specified, must be unique and + * can only be used by a single JMS connection instance. It is typically only required + * for durable topic subscriptions. + * + * @param clientId Client id. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setClientId(String clientId); + + /** + * The durable subscriber name for specifying durable topic subscriptions. + * The clientId option must be configured as well. + * + * @return Subscription name. + */ + String getDurableSubscriptionName(); + + /** + * Specify name of subscription created by camel endpoint. + * + * @param durableSubscriptionName Subscription name. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setDurableSubscriptionName(String durableSubscriptionName); + + /** + * Get number of concurrent consumers. + * + * @return Concurrent consumers count. + */ + Integer getConcurrentConsumers(); + + /** + * Specifies the default number of concurrent consumers. + * + * @param concurrentConsumers Number of concurrent consumers + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setConcurrentConsumers(Integer concurrentConsumers); + + /** + * Number of maximum consumers. + * + * @return Maximum number of concurrent consumers. + */ + Integer getMaxConcurrentConsumers(); + + /** + * Specifies the maximum number of concurrent consumers. + * + * @param maxConcurrentConsumers Maximum number of consumers to use. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setMaxConcurrentConsumers(Integer maxConcurrentConsumers); + + /** + * If true, a producer will behave like a InOnly exchange with the exception that + * JMSReplyTo header is sent out and not be suppressed like in the case of InOnly. + * Like InOnly the producer will not wait for a reply. A consumer with this flag + * will behave like InOnly. This feature can be used to bridge InOut requests to + * another queue so that a route on the other queue will send it´s response directly + * back to the original JMSReplyTo. + * + * @return Should reply to be disabled and JMSReplyTo header be ignored. + */ + Boolean isDisableReplyTo(); + + /** + * Specify behavior for JMSReplyTo header. + * + * @param disableReplyTo True if reply to should be disabled. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setDisableReplyTo(Boolean disableReplyTo); + + /** + * Get the way of handling for quality of service related headers. + * + * @return True if JMSPriority and JMSDeliveryMode be preserved. + */ + Boolean isPreserveMessageQos(); + + /** + * Set to true, if you want to send message using the QoS settings specified on the message, + * instead of the QoS settings on the JMS endpoint. The following three headers are considered + * JMSPriority, JMSDeliveryMode, and JMSExpiration. You can provide all or only some of them. + * If not provided, Camel will fall back to use the values from the endpoint instead. + * So, when using this option, the headers override the values from the endpoint. + * The explicitQosEnabled option, by contrast, will only use options set on the endpoint, + * and not values from the message header. + * + * @param preserveMessageQos Should JMSPriority and JMSDeliveryMode be preserved. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setPreserveMessageQos(Boolean preserveMessageQos); + + /** + * Should message be sent in persistent mode? + * + * @return True if delivery should be persistent, false otherwise. + */ + Boolean isDeliveryPersistent(); + + /** + * Specifies whether persistent delivery is used by default. + * + * @param deliveryPersistent Should delivery be persistent. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setDeliveryPersistent(Boolean deliveryPersistent); + + /** + * Values greater than 1 specify the message priority when sending + * (where 0 is the lowest priority and 9 is the highest). + * + * @return Priority of message to send. + */ + Integer getPriority(); + + /** + * Specifies message priority. + * + * @param priority Message priority. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setPriority(Integer priority); + + /** + * Set if the deliveryMode, priority or timeToLive qualities of service should be used + * when sending messages. This option is based on Spring's JmsTemplate. + * The deliveryMode, priority and timeToLive options are applied to the current endpoint. + * This contrasts with the preserveMessageQos option, which operates at message granularity, + * reading QoS properties exclusively from the Camel In message headers. + * + * @param explicitQosEnabled Should QOS be explicitly set? + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setExplicitQosEnabled(Boolean explicitQosEnabled); + + /** + * Get the status of QOS for endpoint. + * + * @return True if delivery should be persistent, false otherwise. + */ + Boolean isExplicitQosEnabled(); + + /** + * Get name of reply destination. + * + * @return Reply destination name. + */ + String getReplyTo(); + + /** + * Provides an explicit ReplyTo destination, which overrides any incoming value + * of Message.getJMSReplyTo(). + * + * @param replyTo Name of destination used to send reply. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setReplyTo(String replyTo); + + /** + * Get reply to type. + * + * @return Type of reply destination. + */ + String getReplyToType(); + + /** + * Allows for explicitly specifying which kind of strategy to use for replyTo queues + * when doing request/reply over JMS. Possible values are: Temporary, Shared, or Exclusive. + * By default Camel will use temporary queues. However if replyTo has been configured, + * then Shared is used by default. This option allows you to use exclusive queues + * instead of shared ones. + * + * @param replyToType Type of reply to destination (Temporary, Shared or Exclusive). + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setReplyToType(String replyToType); + + /** + * Producer only: The timeout for waiting for a reply when using the InOut + * Exchange Pattern (in milliseconds). The default is 20 seconds. + * + * @return Request timeout for in out communication. + */ + Integer getRequestTimeout(); + + /** + * Specify request timeout. + * + * @param requestTimeout Request timeout. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setRequestTimeout(Integer requestTimeout); + + /** + * JMS Selector to use. + * + * @return Selector for message consumption. + */ + String getSelector(); + + /** + * Sets the JMS Selector, which is an SQL 92 predicate that is used to filter + * messages within the broker. You may have to encode special characters such as = as %3D + * + * @param selector Message selector. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setSelector(String selector); + + /** + * Message time to live. + * + * @return Time to live. + */ + Integer getTimeToLive(); + + /** + * Specifies the time-to-live of the message (in milliseconds). + * + * @param timeToLive Time to live for message. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setTimeToLive(Integer timeToLive); + + /** + * Checks if transaction should be used to consume/receive messages. + * + * @return If JMS session is transacted. + */ + Boolean isTransacted(); + + /** + * Specifies whether to use transacted mode for sending/receiving messages using the InOnly. + * + * @param transacted Should session be transacted. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setTransacted(Boolean transacted); + + /** + * The Spring transaction manager to use. + * + * @return Transaction manager. + */ + String getTransactionManager(); + + /** + * Specifies transaction manager to use with endpoint. + * + * @param transactionManager Spring transaction manager bean. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setTransactionManager(String transactionManager); + + /** + * The JMS acknowledgement mode name to use. + * + * @return Acknowledgement Mode Name. + */ + String getAcknowledgementModeName(); + + /** + * Specifies the JMS acknowledgement mode name to use with endpoint. + * One of SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE + * + * @param acknowledgementModeName String describing the JMS acknowledgement mode. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setAcknowledgementModeName(String acknowledgementModeName); + + /** + * The Integer value of the JMS acknowledgement mode to use. + * + * @return Acknowledgement Mode. + */ + Integer getAcknowledgementMode(); + + /** + * Specifies Integer value of the JMS acknowledgement mode to use with endpoint. + * Primarily facilitates vendor specific extensions beyond the standard values + * + * @param acknowledgementMode Integer describing the JMS acknowledgement mode. + * @return a reference to this Camel binding model + */ + CamelJmsBindingModel setAcknowledgementMode(Integer acknowledgementMode); + +} diff --git a/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/CamelJmsNamespace.java b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/CamelJmsNamespace.java new file mode 100644 index 000000000..4084cfa09 --- /dev/null +++ b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/CamelJmsNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jms.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Jms config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelJmsNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelJmsNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelJmsNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelJmsNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelJmsNamespace + */ + public static CamelJmsNamespace fromUri(String uri) { + return Util.fromUri(CamelJmsNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelJmsNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-jms:config", version); + } + } + +} diff --git a/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsBindingModel.java b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsBindingModel.java new file mode 100644 index 000000000..ddcfd2717 --- /dev/null +++ b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsBindingModel.java @@ -0,0 +1,346 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jms.model.v1; + +import java.net.URI; +import java.util.List; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.jms.model.CamelJmsBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of {@link CamelJmsBindingModel}. + */ +public class V1CamelJmsBindingModel extends V1BaseCamelBindingModel + implements CamelJmsBindingModel { + + /** + * Camel endpoint type. + */ + public static final String JMS = "jms"; + + private static final String QUEUE = "queue"; + private static final String TOPIC = "topic"; + private static final String CONNECTION_FACTORY = "connectionFactory"; + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + private static final String CLIENT_ID = "clientId"; + private static final String DURABLE_SUBSCRIPTION_NAME = "durableSubscriptionName"; + private static final String CONCURRENT_CONSUMERS = "concurrentConsumers"; + private static final String MAX_CONCURRENT_CONSUMERS = "maxConcurrentConsumers"; + private static final String DISABLE_REPLY_TO = "disableReplyTo"; + private static final String PRESERVE_MESSAGE_QOS = "preserveMessageQos"; + private static final String DELIVERY_PERSISTENT = "deliveryPersistent"; + private static final String PRIORITY = "priority"; + private static final String EXPLICIT_QOS_ENABLED = "explicitQosEnabled"; + private static final String REPLY_TO = "replyTo"; + private static final String REPLY_TO_TYPE = "replyToType"; + private static final String REQUEST_TIMEOUT = "requestTimeout"; + private static final String SELECTOR = "selector"; + private static final String TIME_TO_LIVE = "timeToLive"; + private static final String TRANSACTED = "transacted"; + private static final String TRANSACTION_MANAGER = "transactionManager"; + private static final String ACKNOWLEDGEMENTMODE_NAME = "acknowledgementModeName"; + private static final String ACKNOWLEDGEMENTMODE = "acknowledgementMode"; + + /** + * Create a new CamelJmsBindingModel. + * @param namespace namespace + */ + public V1CamelJmsBindingModel(String namespace) { + this(JMS, namespace); + } + + /** + * Create a binding model from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param descriptor The switchyard descriptor instance. + */ + public V1CamelJmsBindingModel(Configuration config, Descriptor descriptor) { + super(config, descriptor); + } + + /** + * Extension constructor. + * + * @param type Type of binding. + * @param namespace Binding namespace. + */ + protected V1CamelJmsBindingModel(String type, String namespace) { + super(type, namespace); + setModelChildrenOrder(QUEUE, TOPIC, CONNECTION_FACTORY, USERNAME, PASSWORD, + CLIENT_ID, DURABLE_SUBSCRIPTION_NAME, CONCURRENT_CONSUMERS, MAX_CONCURRENT_CONSUMERS, + DISABLE_REPLY_TO, PRESERVE_MESSAGE_QOS, DELIVERY_PERSISTENT, PRIORITY, + EXPLICIT_QOS_ENABLED, REPLY_TO, REPLY_TO_TYPE, REQUEST_TIMEOUT, SELECTOR, + TIME_TO_LIVE, TRANSACTED, TRANSACTION_MANAGER); + } + + @Override + public String getQueue() { + return getConfig(QUEUE); + } + + @Override + public V1CamelJmsBindingModel setQueue(String queue) { + return setConfig(QUEUE, queue); + } + + @Override + public String getTopic() { + return getConfig(TOPIC); + } + + @Override + public V1CamelJmsBindingModel setTopic(String topic) { + return setConfig(TOPIC, topic); + } + + @Override + public String getConnectionFactory() { + return getConfig(CONNECTION_FACTORY); + } + + @Override + public V1CamelJmsBindingModel setConnectionFactory(String connectionFactory) { + return setConfig(CONNECTION_FACTORY, connectionFactory); + } + + @Override + public String getUsername() { + return getConfig(USERNAME); + } + + @Override + public V1CamelJmsBindingModel setUsername(String username) { + return setConfig(USERNAME, username); + } + + @Override + public String getPassword() { + return getConfig(PASSWORD); + } + + @Override + public V1CamelJmsBindingModel setPassword(String password) { + return setConfig(PASSWORD, password); + } + + @Override + public String getClientId() { + return getConfig(CLIENT_ID); + } + + @Override + public V1CamelJmsBindingModel setClientId(String clientId) { + return setConfig(CLIENT_ID, clientId); + } + + @Override + public String getDurableSubscriptionName() { + return getConfig(DURABLE_SUBSCRIPTION_NAME); + } + + @Override + public V1CamelJmsBindingModel setDurableSubscriptionName(String durableSubscriptionName) { + return setConfig(DURABLE_SUBSCRIPTION_NAME, durableSubscriptionName); + } + + @Override + public Integer getConcurrentConsumers() { + return getIntegerConfig(CONCURRENT_CONSUMERS); + } + + @Override + public V1CamelJmsBindingModel setConcurrentConsumers(Integer concurrentConsumers) { + return setConfig(CONCURRENT_CONSUMERS, concurrentConsumers); + } + + @Override + public Integer getMaxConcurrentConsumers() { + return getIntegerConfig(MAX_CONCURRENT_CONSUMERS); + } + + @Override + public V1CamelJmsBindingModel setMaxConcurrentConsumers(Integer maxConcurrentConsumers) { + return setConfig(MAX_CONCURRENT_CONSUMERS, maxConcurrentConsumers); + } + + @Override + public Boolean isDisableReplyTo() { + return getBooleanConfig(DISABLE_REPLY_TO); + } + + @Override + public V1CamelJmsBindingModel setDisableReplyTo(Boolean disableReplyTo) { + return setConfig(DISABLE_REPLY_TO, disableReplyTo); + } + + @Override + public Boolean isPreserveMessageQos() { + return getBooleanConfig(PRESERVE_MESSAGE_QOS); + } + + @Override + public V1CamelJmsBindingModel setPreserveMessageQos(Boolean preserveMessageQos) { + return setConfig(PRESERVE_MESSAGE_QOS, preserveMessageQos); + } + + @Override + public Boolean isDeliveryPersistent() { + return getBooleanConfig(DELIVERY_PERSISTENT); + } + + @Override + public V1CamelJmsBindingModel setDeliveryPersistent(Boolean deliveryPersistent) { + return setConfig(DELIVERY_PERSISTENT, deliveryPersistent); + } + + @Override + public Integer getPriority() { + return getIntegerConfig(PRIORITY); + } + + @Override + public V1CamelJmsBindingModel setPriority(Integer priority) { + return setConfig(PRIORITY, priority); + } + + @Override + public Boolean isExplicitQosEnabled() { + return getBooleanConfig(EXPLICIT_QOS_ENABLED); + } + + @Override + public V1CamelJmsBindingModel setExplicitQosEnabled(Boolean explicitQosEnabled) { + return setConfig(EXPLICIT_QOS_ENABLED, explicitQosEnabled); + } + + @Override + public String getReplyTo() { + return getConfig(REPLY_TO); + } + + @Override + public V1CamelJmsBindingModel setReplyTo(String replyTo) { + return setConfig(REPLY_TO, replyTo); + } + + @Override + public String getReplyToType() { + return getConfig(REPLY_TO_TYPE); + } + + @Override + public V1CamelJmsBindingModel setReplyToType(String replyToType) { + return setConfig(REPLY_TO_TYPE, replyToType); + } + + @Override + public Integer getRequestTimeout() { + return getIntegerConfig(REQUEST_TIMEOUT); + } + + @Override + public V1CamelJmsBindingModel setRequestTimeout(Integer requestTimeout) { + return setConfig(REQUEST_TIMEOUT, requestTimeout); + } + + @Override + public String getSelector() { + return getConfig(SELECTOR); + } + + @Override + public V1CamelJmsBindingModel setSelector(String selector) { + return setConfig(SELECTOR, selector); + } + + @Override + public Integer getTimeToLive() { + return getIntegerConfig(TIME_TO_LIVE); + } + + @Override + public V1CamelJmsBindingModel setTimeToLive(Integer timeToLive) { + return setConfig(TIME_TO_LIVE, timeToLive); + } + + @Override + public Boolean isTransacted() { + return getBooleanConfig(TRANSACTED); + } + + @Override + public V1CamelJmsBindingModel setTransacted(Boolean transacted) { + return setConfig(TRANSACTED, transacted); + } + + @Override + public String getTransactionManager() { + return getConfig(TRANSACTION_MANAGER); + } + + @Override + public V1CamelJmsBindingModel setTransactionManager(String transactionManager) { + return setConfig(TRANSACTION_MANAGER, transactionManager); + } + + @Override + public String getAcknowledgementModeName() { + return getConfig(ACKNOWLEDGEMENTMODE_NAME); + } + + @Override + public V1CamelJmsBindingModel setAcknowledgementModeName( + String acknowledgementModeName) { + return setConfig(ACKNOWLEDGEMENTMODE_NAME, acknowledgementModeName); + } + + @Override + public Integer getAcknowledgementMode() { + return getIntegerConfig(ACKNOWLEDGEMENTMODE); + } + + @Override + public V1CamelJmsBindingModel setAcknowledgementMode(Integer acknowledgementMode) { + return setConfig(ACKNOWLEDGEMENTMODE, acknowledgementMode); + } + + @Override + public URI getComponentURI() { + return getComponentURI(JMS); + } + + protected URI getComponentURI(String prefix) { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = prefix + ":"; + if (getQueue() != null) { + baseUri += "queue:" + getQueue(); + } else if (getTopic() != null) { + baseUri += "topic:" + getTopic(); + } + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, QUEUE, TOPIC); + + return URI.create(baseUri + queryStr.toString()); + } + +} diff --git a/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsModelMarshaller.java b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsModelMarshaller.java new file mode 100644 index 000000000..fab5d36db --- /dev/null +++ b/components/camel/camel-jms/src/main/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jms.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Jms model marshaller. + */ +public class V1CamelJmsModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_JMS = BindingModel.BINDING + '.' + V1CamelJmsBindingModel.JMS; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelJmsModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_JMS.equals(name)) { + return new V1CamelJmsBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-jms/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-jms/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..7a883e710 --- /dev/null +++ b/components/camel/camel-jms/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.jms.deploy.CamelJmsComponent diff --git a/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v1/camel-jms_1_0.xsd b/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v1/camel-jms_1_0.xsd new file mode 100644 index 000000000..6ec8805b1 --- /dev/null +++ b/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v1/camel-jms_1_0.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v1/camel-jms_1_1.xsd b/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v1/camel-jms_1_1.xsd new file mode 100644 index 000000000..fdc01f00f --- /dev/null +++ b/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v1/camel-jms_1_1.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v2/camel-jms_2_0.xsd b/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v2/camel-jms_2_0.xsd new file mode 100644 index 000000000..eb3d2170b --- /dev/null +++ b/components/camel/camel-jms/src/main/resources/org/switchyard/component/camel/jms/model/v2/camel-jms_2_0.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-jms/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-jms/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..92b2c696f --- /dev/null +++ b/components/camel/camel-jms/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_jms_1_0.section=urn:switchyard-component-camel-jms:config +camel_jms_1_0.version=1.0 +camel_jms_1_0.namespace=urn:switchyard-component-camel-jms:config:1.0 +camel_jms_1_0.schema=camel-jms_1_0.xsd +camel_jms_1_0.location=/org/switchyard/component/camel/jms/model/v1/ +camel_jms_1_0.marshaller=org.switchyard.component.camel.jms.model.v1.V1CamelJmsModelMarshaller + +camel_jms_1_1.section=urn:switchyard-component-camel-jms:config +camel_jms_1_1.version=1.1 +camel_jms_1_1.namespace=urn:switchyard-component-camel-jms:config:1.1 +camel_jms_1_1.schema=camel-jms_1_1.xsd +camel_jms_1_1.location=/org/switchyard/component/camel/jms/model/v1/ +camel_jms_1_1.marshaller=org.switchyard.component.camel.jms.model.v1.V1CamelJmsModelMarshaller + +camel_jms_2_0.section=urn:switchyard-component-camel-jms:config +camel_jms_2_0.version=2.0 +camel_jms_2_0.namespace=urn:switchyard-component-camel-jms:config:2.0 +camel_jms_2_0.schema=camel-jms_2_0.xsd +camel_jms_2_0.location=/org/switchyard/component/camel/jms/model/v2/ +camel_jms_2_0.marshaller=org.switchyard.component.camel.jms.model.v1.V1CamelJmsModelMarshaller diff --git a/components/camel/camel-jms/src/test/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsBindingModelTest.java b/components/camel/camel-jms/src/test/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsBindingModelTest.java new file mode 100644 index 000000000..47d611cdc --- /dev/null +++ b/components/camel/camel-jms/src/test/java/org/switchyard/component/camel/jms/model/v1/V1CamelJmsBindingModelTest.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jms.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.jms.JmsEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.jms.model.CamelJmsNamespace; + +/** + * Test for {@link V1CamelJmsBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelJmsBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-jms-binding-beans.xml"; + + private static String TOPIC = "esb_in_topic"; + private static String CONNECTION_FACTORY = "connFactory"; + private static String USERNAME = "camel"; + private static String PASSWORD = "isMyFriend"; + private static String CLIENT_ID = "esb_in"; + private static String DURABLE_SUBSCRIPTION_NAME = "esb_in_sub"; + private static Integer CONCURRENT_CONSUMERS = 5; + private static Integer MAX_CONCURRENT_CONSUMERS = 15; + private static Boolean DISABLE_REPLY_TO = true; + private static Boolean PRESERVE_MESSAGE_QOS = true; + private static Boolean DELIVERY_PERSISTENT = false; + private static Integer PRIORITY = 9; + private static Boolean EXPLICIT_QOS_ENABLED = true; + private static String REPLY_TO = "esb_out"; + private static String REPLY_TO_TYPE= "Shared"; + private static Integer REQUEST_TIMEOUT = 300; + private static String SELECTOR = "DEST='ESB'"; + private static Integer TIME_TO_LIVE = 3600; + private static Boolean TRANSACTED = true; + private static String ACKNOWLEDGEMENTMODE_NAME = "AUTO_ACKNOWLEDGE"; + private static Integer ACKNOWLEDGEMENTMODE = -1; + + private static final String CAMEL_URI = "jms:topic:esb_in_topic?connectionFactory=connFactory&" + + "username=camel&password=isMyFriend&clientId=esb_in&durableSubscriptionName=esb_in_sub&" + + "concurrentConsumers=5&maxConcurrentConsumers=15&disableReplyTo=true&preserveMessageQos=true&" + + "deliveryPersistent=false&priority=9&explicitQosEnabled=true&replyTo=esb_out&replyToType=Shared&" + + "requestTimeout=300&selector=DEST='ESB'&timeToLive=3600&transacted=true&acknowledgementModeName=AUTO_ACKNOWLEDGE&acknowledgementMode=-1"; + + public V1CamelJmsBindingModelTest() { + super(JmsEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelJmsBindingModel createTestModel() { + return (V1CamelJmsBindingModel) new V1CamelJmsBindingModel(CamelJmsNamespace.V_1_1.uri()) + .setTopic(TOPIC) + .setConnectionFactory(CONNECTION_FACTORY) + .setUsername(USERNAME) + .setPassword(PASSWORD) + .setClientId(CLIENT_ID) + .setDurableSubscriptionName(DURABLE_SUBSCRIPTION_NAME) + .setConcurrentConsumers(CONCURRENT_CONSUMERS) + .setMaxConcurrentConsumers(MAX_CONCURRENT_CONSUMERS) + .setDisableReplyTo(DISABLE_REPLY_TO) + .setPreserveMessageQos(PRESERVE_MESSAGE_QOS) + .setDeliveryPersistent(DELIVERY_PERSISTENT) + .setPriority(PRIORITY) + .setExplicitQosEnabled(EXPLICIT_QOS_ENABLED) + .setReplyTo(REPLY_TO) + .setReplyToType(REPLY_TO_TYPE) + .setRequestTimeout(REQUEST_TIMEOUT) + .setSelector(SELECTOR) + .setTimeToLive(TIME_TO_LIVE) + .setTransacted(TRANSACTED) + .setAcknowledgementModeName(ACKNOWLEDGEMENTMODE_NAME) + .setAcknowledgementMode(ACKNOWLEDGEMENTMODE); + } + + @Override + protected void createModelAssertions(V1CamelJmsBindingModel model) { + assertEquals(TOPIC, model.getTopic()); + assertEquals(CONNECTION_FACTORY, model.getConnectionFactory()); + assertEquals(USERNAME, model.getUsername()); + assertEquals(PASSWORD, model.getPassword()); + assertEquals(CLIENT_ID, model.getClientId()); + assertEquals(DURABLE_SUBSCRIPTION_NAME, model.getDurableSubscriptionName()); + assertEquals(CONCURRENT_CONSUMERS, model.getConcurrentConsumers()); + assertEquals(MAX_CONCURRENT_CONSUMERS, model.getMaxConcurrentConsumers()); + assertEquals(DISABLE_REPLY_TO, model.isDisableReplyTo()); + assertEquals(PRESERVE_MESSAGE_QOS, model.isPreserveMessageQos()); + assertEquals(DELIVERY_PERSISTENT, model.isDeliveryPersistent()); + assertEquals(PRIORITY, model.getPriority()); + assertEquals(EXPLICIT_QOS_ENABLED, model.isExplicitQosEnabled()); + assertEquals(REPLY_TO, model.getReplyTo()); + assertEquals(REPLY_TO_TYPE, model.getReplyToType()); + assertEquals(REQUEST_TIMEOUT, model.getRequestTimeout()); + assertEquals(SELECTOR, model.getSelector()); + assertEquals(TIME_TO_LIVE, model.getTimeToLive()); + assertEquals(TRANSACTED, model.isTransacted()); + assertEquals(ACKNOWLEDGEMENTMODE_NAME, model.getAcknowledgementModeName()); + assertEquals(ACKNOWLEDGEMENTMODE, model.getAcknowledgementMode()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-jms/src/test/resources/v1/switchyard-invalid-jms-binding-beans.xml b/components/camel/camel-jms/src/test/resources/v1/switchyard-invalid-jms-binding-beans.xml new file mode 100644 index 000000000..fe4941658 --- /dev/null +++ b/components/camel/camel-jms/src/test/resources/v1/switchyard-invalid-jms-binding-beans.xml @@ -0,0 +1,29 @@ + + + + + + + + esb_in_queue + esb_in_topic + + + + + diff --git a/components/camel/camel-jms/src/test/resources/v1/switchyard-jms-binding-beans.xml b/components/camel/camel-jms/src/test/resources/v1/switchyard-jms-binding-beans.xml new file mode 100644 index 000000000..3438f99cc --- /dev/null +++ b/components/camel/camel-jms/src/test/resources/v1/switchyard-jms-binding-beans.xml @@ -0,0 +1,47 @@ + + + + + + + + esb_in_topic + connFactory + camel + isMyFriend + esb_in + esb_in_sub + 5 + 15 + true + true + false + 9 + true + esb_out + Shared + 300 + DEST='ESB' + 3600 + true + AUTO_ACKNOWLEDGE + -1 + + + + + diff --git a/components/camel/camel-jpa/pom.xml b/components/camel/camel-jpa/pom.xml new file mode 100644 index 000000000..2efaf0419 --- /dev/null +++ b/components/camel/camel-jpa/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-jpa + bundle + SwitchYard: Camel Component :: JPA Binding + http://switchyard.org + + + org.switchyard.component.camel.jpa.* + + + org.apache.camel.component.jpa, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common-camel + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-core + + + org.apache.camel + camel-jpa + + + org.hibernate.javax.persistence + hibernate-jpa-2.0-api + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaActivator.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaActivator.java new file mode 100644 index 000000000..7a9d47d25 --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaActivator.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.composer.CamelComposition; +import org.switchyard.component.camel.common.deploy.BaseBindingActivator; +import org.switchyard.component.camel.common.handler.InboundHandler; +import org.switchyard.component.camel.common.handler.OutboundHandler; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.jpa.model.CamelJpaBindingModel; + +/** + * Camel jpa activator. + */ +public class CamelJpaActivator extends BaseBindingActivator { + + /** + * Creates new activator instance. + * + * @param context Camel context. + * @param types Activation types. + */ + public CamelJpaActivator(SwitchYardCamelContext context, String[] types) { + super(context, types); + } + + @SuppressWarnings("unchecked") + @Override + protected InboundHandler createInboundHandler(QName serviceName, CamelBindingModel binding) { + return new CamelJpaInboundHandler((CamelJpaBindingModel)binding, getCamelContext(), serviceName, getServiceDomain()); + } + + @Override + protected OutboundHandler createOutboundHandler(CamelBindingModel binding) { + return new CamelJpaOutboundHandler((CamelJpaBindingModel)binding, getCamelContext(), CamelComposition.getMessageComposer(binding), getServiceDomain()); + } +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaComponent.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaComponent.java new file mode 100644 index 000000000..4d591a222 --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaComponent.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.deploy; + +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.deploy.BaseBindingActivator; +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.jpa.model.v1.V1CamelJpaBindingModel; + +/** + * Jpa binding component. + */ +public class CamelJpaComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelJpaComponent() { + super("CamelJpaComponent", V1CamelJpaBindingModel.JPA); + } + + @Override + protected BaseBindingActivator createActivator(SwitchYardCamelContext context, String... types) { + return new CamelJpaActivator(context, types); + } +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaInboundHandler.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaInboundHandler.java new file mode 100644 index 000000000..e25c12b3b --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaInboundHandler.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.deploy; + +import java.util.HashMap; + +import javax.persistence.EntityManagerFactory; +import javax.xml.namespace.QName; + +import org.apache.camel.model.RouteDefinition; +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.handler.InboundHandler; +import org.switchyard.component.camel.jpa.model.CamelJpaBindingModel; + +/** + * Inbound handler for JPA binding. Resolve EntityManagerFactory instance in case it runs on OSGi container. + */ +public class CamelJpaInboundHandler extends InboundHandler { + + /** + * Sole constructor. + * + * @param camelBindingModel The CamelBindingModel. + * @param camelContext The camel context instance. + * @param serviceName The target service name. + * @param domain the service domain. + */ + public CamelJpaInboundHandler(CamelJpaBindingModel camelBindingModel, + SwitchYardCamelContext camelContext, QName serviceName, ServiceDomain domain) { + super(camelBindingModel, camelContext, serviceName, domain); + } + + @Override + protected RouteDefinition createRouteDefinition() { + CamelJpaBindingModel bindingModel = getBindingModel(); + EntityManagerFactory emf = EntityManagerFactoryLocator.locateEntityManagerFactory(bindingModel.getPersistenceUnit(), new HashMap()); + if (emf != null) { + getSwitchYardCamelContext().getWritebleRegistry().put(EntityManagerFactory.class.getName(), emf); + } + + return super.createRouteDefinition(); + } + +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaOutboundHandler.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaOutboundHandler.java new file mode 100644 index 000000000..f106cacf0 --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/CamelJpaOutboundHandler.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.deploy; + +import java.util.HashMap; + +import javax.persistence.EntityManagerFactory; + +import org.apache.camel.ProducerTemplate; +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.handler.OutboundHandler; +import org.switchyard.component.camel.jpa.model.CamelJpaBindingModel; +import org.switchyard.component.common.composer.MessageComposer; + +/** + * Outbound handler for JPA binding. Resolve EntityManagerFactory instance in case it runs on OSGi container. + */ +public class CamelJpaOutboundHandler extends OutboundHandler { + + /** + * A constructor. @see OutboundHandler#OutboundHandler(CamelBindingModel, SwitchYardCamelContext, MessageComposer, ProducerTemplate, ServiceDomain) + * @param binding binding model + * @param context camel context + * @param messageComposer message composer + * @param producerTemplate producer template + * @param domain service domain + */ + public CamelJpaOutboundHandler(CamelJpaBindingModel binding, + SwitchYardCamelContext context, + MessageComposer messageComposer, + ProducerTemplate producerTemplate, ServiceDomain domain) { + super(binding, context, messageComposer, producerTemplate, domain); + + EntityManagerFactory emf = EntityManagerFactoryLocator.locateEntityManagerFactory(binding.getPersistenceUnit(), new HashMap()); + if (emf != null) { + context.getWritebleRegistry().put(EntityManagerFactory.class.getName(), emf); + } + } + + /** + * A constructor. @see OutboundHandler#OutboundHandler(CamelBindingModel, SwitchYardCamelContext, MessageComposer, ServiceDomain) + * @param binding binding + * @param context camel context + * @param messageComposer message composer + * @param domain service domain + */ + public CamelJpaOutboundHandler(CamelJpaBindingModel binding, + SwitchYardCamelContext context, + MessageComposer messageComposer, + ServiceDomain domain) { + this(binding, context, messageComposer, null, domain); + } +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/EntityManagerFactoryLocator.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/EntityManagerFactoryLocator.java new file mode 100644 index 000000000..8ebfc70f1 --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/deploy/EntityManagerFactoryLocator.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.deploy; + +import java.util.Map; + +import javax.naming.InitialContext; +import javax.persistence.EntityManagerFactory; +import javax.persistence.spi.PersistenceProvider; + +import org.jboss.logging.Logger; + +/** + * EntityManagerFactory locator for Camel JPA component. + */ +public final class EntityManagerFactoryLocator { + + private static Logger _logger = Logger.getLogger(EntityManagerFactoryLocator.class); + + /** + * OSGi specific PersistenceProvider JNDI name. + */ + public static final String OSGI_PERSISTENCE_PROVIDER_JNDI_NAME = "osgi:service/javax.persistence.spi.PersistenceProvider"; + + /** + * OSGi specific EntityManagerFactory JNDI name. + */ + public static final String OSGI_ENTITY_MANAGER_FACTORY_JNDI_NAME = "osgi:service/javax.persistence.EntityManagerFactory"; + + private EntityManagerFactoryLocator() { + } + + /** + * Lookup EntityManagerFactory from JNDI. + * @param unitName JPA unit name. + * @param props A Map of properties for use by the persistence provider. + * @return EntityManagerFactory + */ + public static EntityManagerFactory locateEntityManagerFactory(String unitName, Map props) { + InitialContext ic = null; + try { + ic = new InitialContext(); + } catch (Exception e) { + _logger.debug(e); + return null; + } + + try { + EntityManagerFactory emf = (EntityManagerFactory) lookupInJndi(ic, OSGI_ENTITY_MANAGER_FACTORY_JNDI_NAME); + if (emf != null) { + return emf; + } + + PersistenceProvider pp = (PersistenceProvider) lookupInJndi(ic, OSGI_PERSISTENCE_PROVIDER_JNDI_NAME); + if (pp != null) { + return pp.createEntityManagerFactory(unitName, props); + } + } finally { + try { + ic.close(); + } catch (Exception e) { + _logger.debug(e); + } + } + return null; + } + + private static Object lookupInJndi(InitialContext ic, String name) { + try { + return ic.lookup(name); + } catch (Exception e) { + _logger.debug(e); + return null; + } + } +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaBindingModel.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaBindingModel.java new file mode 100644 index 000000000..7f25730a5 --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaBindingModel.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Jpa binding model definition. + * + * @author Lukasz Dywicki + */ +public interface CamelJpaBindingModel extends CamelBindingModel { + + /** + * The entity class name. + * + * @return Name of entity class. + */ + String getEntityClassName(); + + /** + * Specify JPA entity class name. + * + * @param entityClassName Class name. + * @return a reference to this binding model + */ + CamelJpaBindingModel setEntityClassName(String entityClassName); + + /** + * Name of persistence unit. + * + * @return Persistence unit. + */ + String getPersistenceUnit(); + + /** + * Specify name of persistence unit used by camel. + * + * @param persistenceUnit Persistence unit name. + * @return a reference to this binding model + */ + CamelJpaBindingModel setPersistenceUnit(String persistenceUnit); + + /** + * Name of Spring platform transaction manager to use. + * + * @return Transaction manager bean name. + */ + String getTransactionManager(); + + /** + * Specify name of Spring transaction manager bean used for transaction + * handling. + * + * @param transactionManager Name of transaction manager bean. + * @return a reference to this binding model + */ + CamelJpaBindingModel setTransactionManager(String transactionManager); + + /** + * The consumer's configurations. + * + * @return an instance of the camel jpa consumer binding model + */ + CamelJpaConsumerBindingModel getConsumer(); + + /** + * Specify the consumer binding model. + * + * @param consumer The consumer binding model + * @return a reference to this binding model + */ + CamelJpaBindingModel setConsumer(CamelJpaConsumerBindingModel consumer); + + /** + * The producer's configurations. + * + * @return an instance of the camel jpa producer binding model + */ + CamelJpaProducerBindingModel getProducer(); + + /** + * Specify the producer binding model. + * + * @param producer The producer binding model + * @return a reference to this binding model + */ + CamelJpaBindingModel setProducer(CamelJpaProducerBindingModel producer); + + + +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaConsumerBindingModel.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaConsumerBindingModel.java new file mode 100644 index 000000000..13c281c2b --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaConsumerBindingModel.java @@ -0,0 +1,151 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model; + +import org.switchyard.component.camel.common.model.consumer.CamelScheduledBatchPollConsumer; + +/** + * Camel based jpa consumer configuration. + * + * @author Lukasz Dywicki + */ +public interface CamelJpaConsumerBindingModel extends CamelScheduledBatchPollConsumer { + + /** + * If true, the entity is deleted after it is consumed; if false, the entity is not deleted. + * + * @return Should entity be deleted. + */ + Boolean isConsumeDelete(); + + /** + * Specify delete - or not behavior. + * + * @param consumeDelete If true entity will be removed after consumption. + * @return a reference to this binding model + */ + CamelJpaConsumerBindingModel setConsumeDelete(Boolean consumeDelete); + + /** + * Checks if the entity should be locked for processing. + * + * @return True if lock should be acquired. + */ + Boolean isConsumeLockEntity(); + + /** + * Specifies whether or not to set an exclusive lock on each entity bean while + * processing the results from polling. + * + * @param consumeLockEntity Should lock be acquired. + * @return a reference to this binding model + */ + CamelJpaConsumerBindingModel setConsumeLockEntity(Boolean consumeLockEntity); + + /** + * Gets number of maximum results in one query execution. + * + * @return Limit of query results. + */ + Integer getMaximumResults(); + + /** + * Set the maximum number of results to retrieve on the Query. + * + * @param maximumResults Number of maximum results in one poll + * @return a reference to this binding model + */ + CamelJpaConsumerBindingModel setMaximumResults(Integer maximumResults); + + /** + * Custom query to use when consuming data. + * + * @return JPA query to use for polling. + */ + String getQuery(); + + /** + * Specify query to use for polling. + * + * @param query JPA query. + * @return a reference to this binding model + */ + CamelJpaConsumerBindingModel setQuery(String query); + + /** + * Named query to use when consuming data. + * + * @return Named query. + */ + String getNamedQuery(); + + /** + * Specify named query to use for polling. + * + * @param namedQuery Named query to use. + * @return a reference to this binding model + */ + CamelJpaConsumerBindingModel setNamedQuery(String namedQuery); + + /** + * Custom, native and database specific query to use for polling. + * + * @return SQL query to use. + */ + String getNativeQuery(); + + /** + * Specify native query to use for polling. + * + * @param nativeQuery Native query to use. + * @return a reference to this binding model + */ + CamelJpaConsumerBindingModel setNativeQuery(String nativeQuery); + + /** + * Type of result class. + * + * @return Class name. + */ + String getResultClass(); + + /** + * Defines the type of the returned payload. Without this option, we will return + * an object array. Only has an affect when using in conjunction with native query + * when consuming data. + * + * @param resultClass Result class used for native call. + * @return a reference to this binding model + */ + CamelJpaConsumerBindingModel setResultClass(String resultClass); + + /** + * Get the transaction behavior. + * + * @return True if whole batch should be covered by one transaction. + */ + Boolean isTransacted(); + + /** + * Whether to run the consumer in transacted mode, by which all messages will + * either commit or rollback, when the entire batch has been processed. The default behavior + * is to commit all the previously successfully processed messages, and only + * rollback the last failed message. + * + * @param transacted Should whole processing be transactional. + * @return a reference to this binding model + */ + CamelJpaConsumerBindingModel setTransacted(Boolean transacted); + +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaNamespace.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaNamespace.java new file mode 100644 index 000000000..73149b99b --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Jpa config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelJpaNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelJpaNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelJpaNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelJpaNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelJpaNamespace + */ + public static CamelJpaNamespace fromUri(String uri) { + return Util.fromUri(CamelJpaNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelJpaNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-jpa:config", version); + } + } + +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaProducerBindingModel.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaProducerBindingModel.java new file mode 100644 index 000000000..a0e57d64b --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/CamelJpaProducerBindingModel.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model; + +/** + * JPA Producer configuration. + * + * @author Lukasz Dywicki + */ +public interface CamelJpaProducerBindingModel { + + /** + * If flush should be executed after persist call. + * + * @return True if flush should be executed after every store operation. + */ + Boolean isFlushOnSend(); + + /** + * Flushes the EntityManager after the entity bean has been persisted. + * + * @param flushOnSend Should flush be executed after every persist/merge. + * @return a reference to this binding model + */ + CamelJpaProducerBindingModel setFlushOnSend(Boolean flushOnSend); + + /** + * Get the persist flag. + * + * @return True if persist will be used to store entity. + */ + Boolean isUsePersist(); + + /** + * Indicates to use entityManager.persist(entity) instead of entityManager.merge(entity). + * Note: entityManager.persist(entity) doesn't work for detached entities + * (where the EntityManager has to execute an UPDATE instead of an INSERT query)! + * + * @param usePersist Should camel call persist instead of merge for entities. + * @return a reference to this binding model + */ + CamelJpaProducerBindingModel setUsePersist(Boolean usePersist); + +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaBindingModel.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaBindingModel.java new file mode 100644 index 000000000..3b625268e --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaBindingModel.java @@ -0,0 +1,162 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model.v1; + +import java.net.URI; +import java.util.List; + +import org.apache.camel.util.UnsafeUriCharactersEncoder; +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.jpa.model.CamelJpaBindingModel; +import org.switchyard.component.camel.jpa.model.CamelJpaConsumerBindingModel; +import org.switchyard.component.camel.jpa.model.CamelJpaProducerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of JPA configuration binding model. + * + * @author Lukasz Dywicki + */ +public class V1CamelJpaBindingModel extends V1BaseCamelBindingModel + implements CamelJpaBindingModel { + + /** + * Camel endpoint type. + */ + public static final String JPA = "jpa"; + + private static final String ENTITY_CLASS_NAME = "entityClassName"; + private static final String PERSISTENCE_UNIT = "persistenceUnit"; + private static final String TRANSACTION_MANAGER = "transcationManager"; + + private CamelJpaConsumerBindingModel _consume; + private CamelJpaProducerBindingModel _produce; + + /** + * Creates a binding. + * @param namespace namespace + */ + public V1CamelJpaBindingModel(String namespace) { + super(JPA, namespace); + + setModelChildrenOrder(ENTITY_CLASS_NAME, PERSISTENCE_UNIT, TRANSACTION_MANAGER, + CONSUME, PRODUCE); + } + + /** + * Create a binding from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelJpaBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getEntityClassName() { + return getConfig(ENTITY_CLASS_NAME); + } + + @Override + public V1CamelJpaBindingModel setEntityClassName(String entityClassName) { + return setConfig(ENTITY_CLASS_NAME, entityClassName); + } + + @Override + public String getPersistenceUnit() { + return getConfig(PERSISTENCE_UNIT); + } + + @Override + public V1CamelJpaBindingModel setPersistenceUnit(String persistenceUnit) { + return setConfig(PERSISTENCE_UNIT, persistenceUnit); + } + + @Override + public String getTransactionManager() { + return getConfig(TRANSACTION_MANAGER); + } + + @Override + public V1CamelJpaBindingModel setTransactionManager(String transactionManager) { + return setConfig(TRANSACTION_MANAGER, transactionManager); + } + + @Override + public CamelJpaConsumerBindingModel getConsumer() { + if (_consume == null) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + _consume = new V1CamelJpaConsumerBindingModel(config, + getModelDescriptor()); + } + return _consume; + } + + @Override + public V1CamelJpaBindingModel setConsumer(CamelJpaConsumerBindingModel consumer) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(CONSUME); + getModelConfiguration().addChild(((V1CamelJpaConsumerBindingModel) consumer) + .getModelConfiguration()); + } else { + setChildModel((V1CamelJpaConsumerBindingModel) consumer); + } + _consume = consumer; + return this; + } + + @Override + public CamelJpaProducerBindingModel getProducer() { + if (_produce == null) { + Configuration config = getModelConfiguration().getFirstChild(PRODUCE); + _produce = new V1CamelJpaProducerBindingModel(config, + getModelDescriptor()); + } + return _produce; + } + + @Override + public V1CamelJpaBindingModel setProducer(CamelJpaProducerBindingModel producer) { + Configuration config = getModelConfiguration().getFirstChild(PRODUCE); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(PRODUCE); + getModelConfiguration().addChild(((V1CamelJpaProducerBindingModel) producer) + .getModelConfiguration()); + } else { + setChildModel((V1CamelJpaProducerBindingModel) producer); + } + _produce = producer; + return this; + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = JPA + "://" + getEntityClassName(); + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, ENTITY_CLASS_NAME); + + return URI.create(baseUri + UnsafeUriCharactersEncoder.encode(queryStr.toString())); + } + +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaConsumerBindingModel.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaConsumerBindingModel.java new file mode 100644 index 000000000..998e271d6 --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaConsumerBindingModel.java @@ -0,0 +1,139 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledBatchPollConsumer; +import org.switchyard.component.camel.jpa.model.CamelJpaConsumerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of jpa consumer configuration binding. + * + * @author Lukasz Dywicki + */ +public class V1CamelJpaConsumerBindingModel extends V1CamelScheduledBatchPollConsumer + implements CamelJpaConsumerBindingModel { + + private static final String CONSUME_DELETE = "consumeDelete"; + private static final String CONSUME_LOCK_ENTITY = "consumeLockEntity"; + private static final String MAXIMUM_RESULTS = "maximumResults"; + private static final String QUERY = "consumer.query"; + private static final String NAMED_QUERY = "consumer.namedQuery"; + private static final String NATIVE_QUERY = "consumer.nativeQuery"; + private static final String RESULT_CLASS = "consumer.resultClass"; + private static final String TRANSACTED = "consumer.transacted"; + + /** + * Create a binding from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelJpaConsumerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + + setModelChildrenOrder(CONSUME_DELETE, CONSUME_LOCK_ENTITY, MAXIMUM_RESULTS, QUERY, + NAMED_QUERY, NATIVE_QUERY, RESULT_CLASS, TRANSACTED); + } + + /** + * Creates new binding model. + * @param namespace namespace + */ + public V1CamelJpaConsumerBindingModel(String namespace) { + super(namespace, V1CamelJpaBindingModel.CONSUME); + } + + @Override + public Boolean isConsumeDelete() { + return getBooleanConfig(CONSUME_DELETE); + } + + @Override + public V1CamelJpaConsumerBindingModel setConsumeDelete(Boolean consumeDelete) { + return setConfig(CONSUME_DELETE, consumeDelete); + } + + @Override + public Boolean isConsumeLockEntity() { + return getBooleanConfig(CONSUME_LOCK_ENTITY); + } + + @Override + public V1CamelJpaConsumerBindingModel setConsumeLockEntity(Boolean consumeLockEntity) { + return setConfig(CONSUME_LOCK_ENTITY, consumeLockEntity); + } + + @Override + public Integer getMaximumResults() { + return getIntegerConfig(MAXIMUM_RESULTS); + } + + @Override + public V1CamelJpaConsumerBindingModel setMaximumResults(Integer maximumResults) { + return setConfig(MAXIMUM_RESULTS, maximumResults); + } + + @Override + public String getQuery() { + return getConfig(QUERY); + } + + @Override + public V1CamelJpaConsumerBindingModel setQuery(String query) { + return setConfig(QUERY, query); + } + + @Override + public String getNamedQuery() { + return getConfig(NAMED_QUERY); + } + + @Override + public V1CamelJpaConsumerBindingModel setNamedQuery(String namedQuery) { + return setConfig(NAMED_QUERY, namedQuery); + } + + @Override + public String getNativeQuery() { + return getConfig(NATIVE_QUERY); + } + + @Override + public V1CamelJpaConsumerBindingModel setNativeQuery(String nativeQuery) { + return setConfig(NATIVE_QUERY, nativeQuery); + } + + @Override + public String getResultClass() { + return getConfig(RESULT_CLASS); + } + + @Override + public V1CamelJpaConsumerBindingModel setResultClass(String resultClass) { + return setConfig(RESULT_CLASS, resultClass); + } + + @Override + public Boolean isTransacted() { + return getBooleanConfig(TRANSACTED); + } + + @Override + public V1CamelJpaConsumerBindingModel setTransacted(Boolean transacted) { + return setConfig(TRANSACTED, transacted); + } + +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaModelMarshaller.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaModelMarshaller.java new file mode 100644 index 000000000..9c529e23d --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaModelMarshaller.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Jpa model marshaller. + */ +public class V1CamelJpaModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_JPA = BindingModel.BINDING + '.' + V1CamelJpaBindingModel.JPA; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelJpaModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_JPA.equals(name)) { + return new V1CamelJpaBindingModel(config, desc); + } + // V1CamelJpaConsumerBindingModel and V1CamelJpaProducerBindingModel get created by V1CamelJpaBindingModel + return super.read(config); + } + +} diff --git a/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaProducerBindingModel.java b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaProducerBindingModel.java new file mode 100644 index 000000000..c030eafa3 --- /dev/null +++ b/components/camel/camel-jpa/src/main/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaProducerBindingModel.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelModel; +import org.switchyard.component.camel.jpa.model.CamelJpaProducerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of jpa producer binding model. + * + * @author Lukasz Dywicki + */ +public class V1CamelJpaProducerBindingModel extends V1BaseCamelModel + implements CamelJpaProducerBindingModel { + + private static final String FLUS_ON_SEND = "flushOnSend"; + private static final String USE_PERSIST = "usePersist"; + + /** + * Create a binding from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelJpaProducerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + + setModelChildrenOrder(FLUS_ON_SEND, USE_PERSIST); + } + + /** + * Creates new binding model. + * @param namespace namespace + */ + public V1CamelJpaProducerBindingModel(String namespace) { + super(namespace, V1CamelJpaBindingModel.PRODUCE); + } + + @Override + public Boolean isFlushOnSend() { + return getBooleanConfig(FLUS_ON_SEND); + } + + @Override + public V1CamelJpaProducerBindingModel setFlushOnSend(Boolean flushOnSend) { + return setConfig(FLUS_ON_SEND, flushOnSend); + } + + @Override + public Boolean isUsePersist() { + return getBooleanConfig(USE_PERSIST); + } + + @Override + public V1CamelJpaProducerBindingModel setUsePersist(Boolean usePersist) { + return setConfig(USE_PERSIST, usePersist); + } + +} diff --git a/components/camel/camel-jpa/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-jpa/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..3cd66788b --- /dev/null +++ b/components/camel/camel-jpa/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.jpa.deploy.CamelJpaComponent diff --git a/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v1/camel-jpa_1_0.xsd b/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v1/camel-jpa_1_0.xsd new file mode 100644 index 000000000..36fc9428a --- /dev/null +++ b/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v1/camel-jpa_1_0.xsd @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v1/camel-jpa_1_1.xsd b/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v1/camel-jpa_1_1.xsd new file mode 100644 index 000000000..e5e78dc3a --- /dev/null +++ b/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v1/camel-jpa_1_1.xsd @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v2/camel-jpa_2_0.xsd b/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v2/camel-jpa_2_0.xsd new file mode 100644 index 000000000..5ba912edc --- /dev/null +++ b/components/camel/camel-jpa/src/main/resources/org/switchyard/component/camel/jpa/model/v2/camel-jpa_2_0.xsd @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-jpa/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-jpa/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..74f53a465 --- /dev/null +++ b/components/camel/camel-jpa/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_jpa_1_0.section=urn:switchyard-component-camel-jpa:config +camel_jpa_1_0.version=1.0 +camel_jpa_1_0.namespace=urn:switchyard-component-camel-jpa:config:1.0 +camel_jpa_1_0.schema=camel-jpa_1_0.xsd +camel_jpa_1_0.location=/org/switchyard/component/camel/jpa/model/v1/ +camel_jpa_1_0.marshaller=org.switchyard.component.camel.jpa.model.v1.V1CamelJpaModelMarshaller + +camel_jpa_1_1.section=urn:switchyard-component-camel-jpa:config +camel_jpa_1_1.version=1.1 +camel_jpa_1_1.namespace=urn:switchyard-component-camel-jpa:config:1.1 +camel_jpa_1_1.schema=camel-jpa_1_1.xsd +camel_jpa_1_1.location=/org/switchyard/component/camel/jpa/model/v1/ +camel_jpa_1_1.marshaller=org.switchyard.component.camel.jpa.model.v1.V1CamelJpaModelMarshaller + +camel_jpa_2_0.section=urn:switchyard-component-camel-jpa:config +camel_jpa_2_0.version=2.0 +camel_jpa_2_0.namespace=urn:switchyard-component-camel-jpa:config:2.0 +camel_jpa_2_0.schema=camel-jpa_2_0.xsd +camel_jpa_2_0.location=/org/switchyard/component/camel/jpa/model/v2/ +camel_jpa_2_0.marshaller=org.switchyard.component.camel.jpa.model.v1.V1CamelJpaModelMarshaller diff --git a/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaBindingModelTest.java b/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaBindingModelTest.java new file mode 100644 index 000000000..6404c38a3 --- /dev/null +++ b/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaBindingModelTest.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.jpa.JpaEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.jpa.model.CamelJpaNamespace; + +/** + * Test for {@link V1CamelJpaBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelJpaBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-jpa-binding-beans.xml"; + private static final String CAMEL_URI = "jpa://some.clazz.Name?persistenceUnit=MyPU"; + static final String ENTITY_CLASS_NAME = "some.clazz.Name"; + static final String PERSISTENCE_UNIT = "MyPU"; + + public V1CamelJpaBindingModelTest() { + super(JpaEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelJpaBindingModel createTestModel() { + return new V1CamelJpaBindingModel(CamelJpaNamespace.V_1_0.uri()) + .setEntityClassName(ENTITY_CLASS_NAME) + .setPersistenceUnit(PERSISTENCE_UNIT); + } + + @Override + protected void createModelAssertions(V1CamelJpaBindingModel model) { + assertEquals(ENTITY_CLASS_NAME, model.getEntityClassName()); + assertEquals(PERSISTENCE_UNIT, model.getPersistenceUnit()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaConsumerBindingModelTest.java b/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaConsumerBindingModelTest.java new file mode 100644 index 000000000..fcc16c976 --- /dev/null +++ b/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaConsumerBindingModelTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.jpa.JpaEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.jpa.model.CamelJpaConsumerBindingModel; +import org.switchyard.component.camel.jpa.model.CamelJpaNamespace; + +/** + * Test for {@link V1CamelJpaConsumerBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelJpaConsumerBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-jpa-binding-consumer-beans.xml"; + + private static final String CAMEL_URI = "jpa://some.clazz.Name?persistenceUnit=MyPU&" + + "consumeDelete=true&consumeLockEntity=true&maximumResults=10&consumer.query=from User&" + + "consumer.namedQuery=fetchUsers&consumer.nativeQuery=select * from users&" + + "consumer.resultClass=java.util.ArrayList&consumer.transacted=true"; + + private static final Boolean CONSUME_DELETE = true; + private static final Boolean CONSUME_LOCK_ENTITY = true; + private static final Integer MAXIMUM_RESULTS = 10; + private static final String NAMED_QUERY = "fetchUsers"; + private static final String QUERY = "from User"; + private static final String NATIVE_QUERY = "select * from users"; + private static final String RESULT_CLASS = "java.util.ArrayList"; + private static final Boolean TRANSACTED = true; + + public V1CamelJpaConsumerBindingModelTest() { + super(JpaEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelJpaBindingModel createTestModel() { + V1CamelJpaBindingModel model = new V1CamelJpaBindingModel(CamelJpaNamespace.V_1_0.uri()); + model.setEntityClassName(V1CamelJpaBindingModelTest.ENTITY_CLASS_NAME); + model.setPersistenceUnit(V1CamelJpaBindingModelTest.PERSISTENCE_UNIT); + + CamelJpaConsumerBindingModel consumer = (CamelJpaConsumerBindingModel) new V1CamelJpaConsumerBindingModel(CamelJpaNamespace.V_1_0.uri()) + .setConsumeDelete(CONSUME_DELETE) + .setConsumeLockEntity(CONSUME_LOCK_ENTITY) + .setMaximumResults(MAXIMUM_RESULTS) + .setQuery(QUERY) + .setNamedQuery(NAMED_QUERY) + .setNativeQuery(NATIVE_QUERY) + .setResultClass(RESULT_CLASS) + .setTransacted(TRANSACTED); + return model.setConsumer(consumer); + } + + @Override + protected void createModelAssertions(V1CamelJpaBindingModel model) { + CamelJpaConsumerBindingModel consumer = model.getConsumer(); + assertEquals(CONSUME_DELETE, consumer.isConsumeDelete()); + assertEquals(CONSUME_LOCK_ENTITY, consumer.isConsumeLockEntity()); + assertEquals(MAXIMUM_RESULTS, consumer.getMaximumResults()); + assertEquals(QUERY, consumer.getQuery()); + assertEquals(NAMED_QUERY, consumer.getNamedQuery()); + assertEquals(RESULT_CLASS, consumer.getResultClass()); + assertEquals(TRANSACTED, consumer.isTransacted()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaProducerBindingModelTest.java b/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaProducerBindingModelTest.java new file mode 100644 index 000000000..89a586ed6 --- /dev/null +++ b/components/camel/camel-jpa/src/test/java/org/switchyard/component/camel/jpa/model/v1/V1CamelJpaProducerBindingModelTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.jpa.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.jpa.JpaEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.jpa.model.CamelJpaProducerBindingModel; +import org.switchyard.component.camel.jpa.model.CamelJpaNamespace; + +/** + * Test for {@link V1CamelJpaProducerBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelJpaProducerBindingModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-jpa-binding-producer-beans.xml"; + + private static final String CAMEL_URI = "jpa://some.clazz.Name?persistenceUnit=MyPU&flushOnSend=false&usePersist=false"; + + private static final Boolean FLUSH_ON_SEND = false; + private static final Boolean USE_PERSIST = false; + + public V1CamelJpaProducerBindingModelTest() { + super(JpaEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelJpaBindingModel createTestModel() { + V1CamelJpaBindingModel model = new V1CamelJpaBindingModel(CamelJpaNamespace.V_1_0.uri()); + model.setEntityClassName(V1CamelJpaBindingModelTest.ENTITY_CLASS_NAME); + model.setPersistenceUnit(V1CamelJpaBindingModelTest.PERSISTENCE_UNIT); + + CamelJpaProducerBindingModel producer = new V1CamelJpaProducerBindingModel(CamelJpaNamespace.V_1_0.uri()) + .setFlushOnSend(FLUSH_ON_SEND) + .setUsePersist(USE_PERSIST); + return model.setProducer(producer); + } + + @Override + protected void createModelAssertions(V1CamelJpaBindingModel model) { + CamelJpaProducerBindingModel producer = model.getProducer(); + assertEquals(FLUSH_ON_SEND, producer.isFlushOnSend()); + assertEquals(USE_PERSIST, producer.isUsePersist()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-beans.xml b/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-beans.xml new file mode 100644 index 000000000..5be3c548e --- /dev/null +++ b/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-beans.xml @@ -0,0 +1,28 @@ + + + + + + + + some.clazz.Name + MyPU + + + + + diff --git a/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-consumer-beans.xml b/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-consumer-beans.xml new file mode 100644 index 000000000..89ece3111 --- /dev/null +++ b/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-consumer-beans.xml @@ -0,0 +1,37 @@ + + + + + + + + some.clazz.Name + MyPU + + true + true + 10 + from User + fetchUsers + select * from users + java.util.ArrayList + true + + + + + diff --git a/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-producer-beans.xml b/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-producer-beans.xml new file mode 100644 index 000000000..6912cf737 --- /dev/null +++ b/components/camel/camel-jpa/src/test/resources/v1/switchyard-jpa-binding-producer-beans.xml @@ -0,0 +1,31 @@ + + + + + + + + some.clazz.Name + MyPU + + false + false + + + + + diff --git a/components/camel/camel-mail/pom.xml b/components/camel/camel-mail/pom.xml new file mode 100644 index 000000000..5b46f2f1f --- /dev/null +++ b/components/camel/camel-mail/pom.xml @@ -0,0 +1,56 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-mail + bundle + SwitchYard: Camel Component :: Mail Binding + http://switchyard.org + + + org.switchyard.component.camel.mail.* + + + org.apache.camel.component.mail, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-mail + compile + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/deploy/CamelMailComponent.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/deploy/CamelMailComponent.java new file mode 100644 index 000000000..890c1b0e4 --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/deploy/CamelMailComponent.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.mail.model.v1.V1CamelMailBindingModel; + +/** + * Mail binding component. + */ +public class CamelMailComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelMailComponent() { + super("CamelMailComponent", V1CamelMailBindingModel.MAIL); + } + +} diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailBindingModel.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailBindingModel.java new file mode 100644 index 000000000..847e506ec --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailBindingModel.java @@ -0,0 +1,145 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Represents the configuration settings for an mail endpoint in Camel. Depends + * on produce/consume part different protocols will be used. + */ +public interface CamelMailBindingModel extends CamelBindingModel { + + /** + * The host name or IP address to connect to. + * + * @return Host name or ip. + */ + String getHost(); + + /** + * Specify host/ip to use. + * + * @param host Host or ip address. + * @return a reference to this Camel binding model + */ + CamelMailBindingModel setHost(String host); + + /** + * The TCP port number to connect on. + * + * @return TCP port number + */ + Integer getPort(); + + /** + * Specify TCP port number to connect. + * + * @param port TCP port to use. + * @return a reference to this Camel binding model + */ + CamelMailBindingModel setPort(Integer port); + + /** + * The user name on the email server. + * + * @return User name/login to connect email server. + */ + String getUsername(); + + /** + * Specify user name to use. + * + * @param username Username to use for logging in on server. + * @return a reference to this Camel binding model + */ + CamelMailBindingModel setUsername(String username); + + /** + * The password on the email server. + * + * @return Password to connect email server. + */ + String getPassword(); + + /** + * Specify password to use. + * + * @param password Password for authentication. + * @return a reference to this Camel binding model + */ + CamelMailBindingModel setPassword(String password); + + /** + * The connection timeout in milliseconds. Default is 30 seconds (30000 millis). + * + * @return Connection timeout. + */ + Integer getConnectionTimeout(); + + /** + * Specify connection timeout. + * + * @param connectionTimeout Connection timeout. + * @return a reference to this Camel binding model + */ + CamelMailBindingModel setConnectionTimeout(Integer connectionTimeout); + + /** + * Returns the secure flag. In other words if connection should be created + * using smtps or smtp protocol scheme. + * + * @return True if secure connection should be used. + */ + Boolean isSecure(); + + /** + * Specify if secure connection should be used. + * + * @param secure True if secure connection should be created. + * @return a reference to this Camel binding model + */ + CamelMailBindingModel setSecure(Boolean secure); + + /** + * Gets consumer binding attached to this mail binding. + * + * @return Consumer binding model. + */ + CamelMailConsumerBindingModel getConsumer(); + + /** + * Specify consumer configuration. + * + * @param consumer Consumer configuration. + * @return a reference to this Camel binding model + */ + CamelMailBindingModel setConsumer(CamelMailConsumerBindingModel consumer); + + /** + * Gets producer binding attached to this mail binding. + * + * @return Producer binding model. + */ + CamelMailProducerBindingModel getProducer(); + + /** + * Specify producer configuration. + * + * @param producer Producer configuration. + * @return a reference to this Camel binding model + */ + CamelMailBindingModel setProducer(CamelMailProducerBindingModel producer); + +} diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailConsumerBindingModel.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailConsumerBindingModel.java new file mode 100644 index 000000000..ca6698236 --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailConsumerBindingModel.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model; + +import org.switchyard.component.camel.common.model.consumer.CamelScheduledBatchPollConsumer; + +/** + * Mail consumer/receiver binding model. + */ +public interface CamelMailConsumerBindingModel extends CamelScheduledBatchPollConsumer { + + /** + * The folder to poll. + * + * @return Folder name. + */ + String getFolderName(); + + /** + * Specify folder name to poll. + * + * @param folderName Folder name to use for polling messages. + * @return a reference to this Camel binding model + */ + CamelMailConsumerBindingModel setFolderName(String folderName); + + /** + * Sets the maximum number of messages to consume during a poll. + * + * This can be used to avoid overloading a mail server, if a mailbox folder contains a lot of messages. + * Default value of -1 means no fetch size and all messages will be consumed. Setting the value to 0 + * is a special corner case, where Camel will not consume any messages at all. + * + * @return Number of messages to read by one connection. + */ + Integer getFetchSize(); + + /** + * Specify maximum number of messages for one poll. + * + * @param fetchSize Number of messages to fetch. + * @return a reference to this Camel binding model + */ + CamelMailConsumerBindingModel setFetchSize(Integer fetchSize); + + /** + * Should camel process only unseen messages (that is, new messages) or all messages. + * + * Note that Camel always skips deleted messages. The default option of true will filter to only + * unseen messages. This setting is applicable only for IMAP. + * + * @return Should camel use SEEN flag for choosing messages to process. + */ + Boolean isUnseen(); + + /** + * Specify to use SEEN flag with IMAP or not. + * + * @param unseen True if camel should process only new (unseen) messages. + * @return a reference to this Camel binding model + */ + CamelMailConsumerBindingModel setUnseen(Boolean unseen); + + /** + * Deletes the messages after they have been processed. + * + * @return True if DELETED flag should be set on email after processing. + */ + Boolean isDelete(); + + /** + * Specify if message should be deleted after processing. + * + * @param delete True if camel should mark processed messages as deleted. + * @return a reference to this Camel binding model + */ + CamelMailConsumerBindingModel setDelete(Boolean delete); + + /** + * After processing a mail message, it can be copied to a mail folder with the given name. + * + * @return Name of folder to copy message after processing. + */ + String getCopyTo(); + + /** + * Specify folder name to store copies of processed messages. + * + * @param copyTo Folder name for storing copies. + * @return a reference to this Camel binding model + */ + CamelMailConsumerBindingModel setCopyTo(String copyTo); + + /** + * Whether the consumer should disconnect after polling. If enabled this forces Camel to connect on each poll. + * + * @return True if connection should be closed/opened for each poll. + */ + Boolean isDisconnect(); + + /** + * Specify if connection should be closed after every poll. + * + * @param disconnect Set to true if connection should be closed after poll. + * @return a reference to this Camel binding model + */ + CamelMailConsumerBindingModel setDisconnect(Boolean disconnect); + + /** + * Get's protocol - pop3[s] or imap[s]. + * + * @return Protocol to use. + */ + String getProtocol(); + + /** + * Specify mail server backend type. + * + * @param accountType Type of server backend. Supported values are IMAP/POP3. + * @return a reference to this Camel binding model + */ + CamelMailConsumerBindingModel setAccountType(String accountType); + +} diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailNamespace.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailNamespace.java new file mode 100644 index 000000000..f8e5cefd1 --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Mail config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelMailNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelMailNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelMailNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelMailNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelMailNamespace + */ + public static CamelMailNamespace fromUri(String uri) { + return Util.fromUri(CamelMailNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelMailNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-mail:config", version); + } + } + +} diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailProducerBindingModel.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailProducerBindingModel.java new file mode 100644 index 000000000..9b4200260 --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/CamelMailProducerBindingModel.java @@ -0,0 +1,118 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model; + +/** + * Mail producer/sender binding model. + */ +public interface CamelMailProducerBindingModel { + + /** + * Subject of the message being sent. + * + * @return Mail subject. + */ + String getSubject(); + + /** + * Specify mail subject to use. + * + * @param subject Mail subject. + * @return a reference to this Camel binding model + */ + CamelMailProducerBindingModel setSubject(String subject); + + /** + * The FROM email address. + * + * @return Sender email address. + */ + String getFrom(); + + /** + * Specify FROM email address. + * + * @param from Sender email. + * @return a reference to this Camel binding model + */ + CamelMailProducerBindingModel setFrom(String from); + + /** + * The TO recipients (the receivers of the mail). Separate multiple email addresses with a comma. + * + * @return Mail recipients. + */ + String getTo(); + + /** + * Specify mail recipients. + * + * @param to Mail recipients. + * @return a reference to this Camel binding model + */ + CamelMailProducerBindingModel setTo(String to); + + /** + * The CC recipients (the receivers of the mail). Separate multiple email addresses with a comma. + * + * @return Mail recipients which should receive copy of sent mail. + */ + String getCC(); + + /** + * Specify mail recipients. + * + * @param cc Copy recipients. + * @return a reference to this Camel binding model + */ + CamelMailProducerBindingModel setCC(String cc); + + /** + * The BCC recipients (the receivers of the mail). Separate multiple email addresses with a comma. + * + * @return Mail recipients which should receive copy of sent mail but stay invisible for others recipients. + */ + String getBCC(); + + /** + * Specify BCC recipients. + * + * @param bcc Hidden mail recipients. + * @return a reference to this Camel binding model + */ + CamelMailProducerBindingModel setBCC(String bcc); + + /** + * The Reply-To recipients (the receivers of the response mail). Separate multiple email addresses with a comma. + * + * @return Reply to flag for mail. + */ + String getReplyTo(); + + /** + * Specifies the addresses that should receive an answer for sent mail. + * + * @param replyTo Reply-to addresses. + * @return a reference to this Camel binding model + */ + CamelMailProducerBindingModel setReplyTo(String replyTo); + + /** + * Get protocol to use - smpt or smpts. + * + * @return Protocol to use. + */ + String getProtocol(); + +} diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailBindingModel.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailBindingModel.java new file mode 100644 index 000000000..d2a723d16 --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailBindingModel.java @@ -0,0 +1,179 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model.v1; + +import java.net.URI; +import java.util.List; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.mail.model.CamelMailBindingModel; +import org.switchyard.component.camel.mail.model.CamelMailConsumerBindingModel; +import org.switchyard.component.camel.mail.model.CamelMailProducerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * First implementation of mail binding. + */ +public class V1CamelMailBindingModel extends V1BaseCamelBindingModel + implements CamelMailBindingModel { + + /** + * Binding name. + */ + public static final String MAIL = "mail"; + + private static final String HOST = "host"; + private static final String PORT = "port"; + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + private static final String CONNECTION_TIMEOUT = "connectionTimeout"; + private static final String SECURE = "secure"; + + /** + * Mail consumer binding. + */ + private V1CamelMailConsumerBindingModel _consume; + + /** + * Mail producer binding. + */ + private V1CamelMailProducerBindingModel _produce; + + /** + * Creates new mail binding model. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelMailBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Creates new mail binding model. + * @param namespace namespace + */ + public V1CamelMailBindingModel(String namespace) { + super(MAIL, namespace); + + setModelChildrenOrder(HOST, PORT, USERNAME, PASSWORD, CONNECTION_TIMEOUT, + CONSUME, PRODUCE); + } + + @Override + public String getHost() { + return getConfig(HOST); + } + + @Override + public V1CamelMailBindingModel setHost(String host) { + return setConfig(HOST, host); + } + + @Override + public Integer getPort() { + return getIntegerConfig(PORT); + } + + @Override + public V1CamelMailBindingModel setPort(Integer port) { + return setConfig(PORT, port); + } + + @Override + public String getUsername() { + return getConfig(USERNAME); + } + + @Override + public V1CamelMailBindingModel setUsername(String username) { + return setConfig(USERNAME, username); + } + + @Override + public String getPassword() { + return getConfig(PASSWORD); + } + + @Override + public V1CamelMailBindingModel setPassword(String password) { + return setConfig(PASSWORD, password); + } + + @Override + public Integer getConnectionTimeout() { + return getIntegerConfig(CONNECTION_TIMEOUT); + } + + @Override + public V1CamelMailBindingModel setConnectionTimeout(Integer connectionTimeout) { + return setConfig(CONNECTION_TIMEOUT, connectionTimeout); + } + + @Override + public Boolean isSecure() { + return Boolean.valueOf(getModelAttribute(SECURE)); + } + + @Override + public V1CamelMailBindingModel setSecure(Boolean secure) { + setModelAttribute(SECURE, Boolean.toString(secure)); + return this; + } + + @Override + public V1CamelMailBindingModel setConsumer(CamelMailConsumerBindingModel consumer) { + _consume = replaceChildren(CONSUME, (V1CamelMailConsumerBindingModel) consumer); + return this; + } + + @Override + public V1CamelMailConsumerBindingModel getConsumer() { + if (_consume == null) { + _consume = new V1CamelMailConsumerBindingModel(getFirstChild(CONSUME), getModelDescriptor()); + } + return _consume; + } + + @Override + public V1CamelMailBindingModel setProducer(CamelMailProducerBindingModel producer) { + _produce = replaceChildren(PRODUCE, (V1CamelMailProducerBindingModel) producer); + return this; + } + + @Override + public V1CamelMailProducerBindingModel getProducer() { + if (_produce == null) { + _produce = new V1CamelMailProducerBindingModel(getFirstChild(PRODUCE), getModelDescriptor()); + } + return _produce; + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + QueryString queryString = new QueryString(); + traverseConfiguration(children, queryString, HOST, PORT); + + String protocol = isReferenceBinding() ? getProducer().getProtocol() : getConsumer().getProtocol(); + String port = getPort() != null ? ":" + getPort() : ""; + + return URI.create(protocol + (isSecure() ? "s" : "") + "://" + getHost() + port + queryString); + } + +} diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailConsumerBindingModel.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailConsumerBindingModel.java new file mode 100644 index 000000000..12debf663 --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailConsumerBindingModel.java @@ -0,0 +1,143 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledBatchPollConsumer; +import org.switchyard.component.camel.mail.model.CamelMailConsumerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * First implementation of mail consumer/receiver binding. + */ +public class V1CamelMailConsumerBindingModel extends V1CamelScheduledBatchPollConsumer + implements CamelMailConsumerBindingModel { + + /** + * Enumeration type representing supported mail server types. + */ + public enum AccountType { + /** + * Imap based backend. + */ + imap, + /** + * POP3 based backend. + */ + pop3; + } + + private static final String ACCOUNT_TYPE = "accountType"; + private static final String FOLDER_NAME = "folderName"; + private static final String FETCH_SIZE = "fetchSize"; + private static final String UNSEEN = "unseen"; + private static final String DELETE = "delete"; + private static final String COPY_TO = "copyTo"; + private static final String DISCONNECT = "disconnect"; + + /** + * Creates new consumer binding model. + * @param namespace namespace + */ + public V1CamelMailConsumerBindingModel(String namespace) { + super(namespace, V1CamelMailBindingModel.CONSUME); + + setModelChildrenOrder(FOLDER_NAME, FETCH_SIZE, UNSEEN, DELETE, COPY_TO, DISCONNECT); + } + + /** + * Creates new consumer binding model. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelMailConsumerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getFolderName() { + return getConfig(FOLDER_NAME); + } + + @Override + public V1CamelMailConsumerBindingModel setFolderName(String folderName) { + return setConfig(FOLDER_NAME, folderName); + } + + @Override + public Integer getFetchSize() { + return getIntegerConfig(FETCH_SIZE); + } + + @Override + public V1CamelMailConsumerBindingModel setFetchSize(Integer fetchSize) { + return setConfig(FETCH_SIZE, fetchSize); + } + + @Override + public Boolean isUnseen() { + return getBooleanConfig(UNSEEN); + } + + @Override + public V1CamelMailConsumerBindingModel setUnseen(Boolean unseen) { + return setConfig(UNSEEN, unseen); + } + + @Override + public Boolean isDelete() { + return getBooleanConfig(DELETE); + } + + @Override + public V1CamelMailConsumerBindingModel setDelete(Boolean delete) { + return setConfig(DELETE, delete); + } + + @Override + public String getCopyTo() { + return getConfig(COPY_TO); + } + + @Override + public V1CamelMailConsumerBindingModel setCopyTo(String copyTo) { + return setConfig(COPY_TO, copyTo); + } + + @Override + public Boolean isDisconnect() { + return getBooleanConfig(DISCONNECT); + } + + @Override + public V1CamelMailConsumerBindingModel setDisconnect(Boolean disconnect) { + return setConfig(DISCONNECT, disconnect); + } + + @Override + public V1CamelMailConsumerBindingModel setAccountType(String accountType) { + setModelAttribute(ACCOUNT_TYPE, accountType); + return this; + } + + @Override + public String getProtocol() { + AccountType accountType = getModelConfiguration() != null + ? AccountType.valueOf(getModelAttribute(ACCOUNT_TYPE)) + : AccountType.imap; + return accountType.name(); + } + +} diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailModelMarshaller.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailModelMarshaller.java new file mode 100644 index 000000000..d8d3adefe --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailModelMarshaller.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Mail model marshaller. + */ +public class V1CamelMailModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_MAIL = BindingModel.BINDING + '.' + V1CamelMailBindingModel.MAIL; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelMailModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_MAIL.equals(name)) { + return new V1CamelMailBindingModel(config, desc); + } + // V1CamelMailConsumerBindingModel and V1CamelMailProducerBindingModel get created by V1CamelMailBindingModel + return super.read(config); + } + +} diff --git a/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailProducerBindingModel.java b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailProducerBindingModel.java new file mode 100644 index 000000000..d834f3a3e --- /dev/null +++ b/components/camel/camel-mail/src/main/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailProducerBindingModel.java @@ -0,0 +1,123 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelModel; +import org.switchyard.component.camel.mail.model.CamelMailProducerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * First implementation of mail producer binding. + */ +public class V1CamelMailProducerBindingModel extends V1BaseCamelModel + implements CamelMailProducerBindingModel { + + /** + * Camel endpoint type used for mail producers. + */ + private static final String SMTP = "smtp"; + + private static final String SUBJECT = "subject"; + private static final String FROM = "from"; + private static final String TO = "to"; + private static final String CC = "CC"; + private static final String BCC = "BCC"; + private static final String REPLY_TO = "replyTo"; + + /** + * Creates new producer binding model. + * @param namespace namespace + */ + public V1CamelMailProducerBindingModel(String namespace) { + super(namespace, V1CamelMailBindingModel.PRODUCE); + setModelChildrenOrder(SUBJECT, FROM, TO, CC, BCC, REPLY_TO); + } + + /** + * Creates new producer binding model. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelMailProducerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getSubject() { + return getConfig(SUBJECT); + } + + @Override + public V1CamelMailProducerBindingModel setSubject(String subject) { + return setConfig(SUBJECT, subject); + } + + @Override + public String getFrom() { + return getConfig(FROM); + } + + @Override + public V1CamelMailProducerBindingModel setFrom(String from) { + return setConfig(FROM, from); + } + + @Override + public String getTo() { + return getConfig(TO); + } + + @Override + public V1CamelMailProducerBindingModel setTo(String to) { + return setConfig(TO, to); + } + + @Override + public String getCC() { + return getConfig(CC); + } + + @Override + public V1CamelMailProducerBindingModel setCC(String cc) { + return setConfig(CC, cc); + } + + @Override + public String getBCC() { + return getConfig(BCC); + } + + @Override + public V1CamelMailProducerBindingModel setBCC(String bcc) { + return setConfig(BCC, bcc); + } + + @Override + public String getReplyTo() { + return getConfig(REPLY_TO); + } + + @Override + public V1CamelMailProducerBindingModel setReplyTo(String replyTo) { + return setConfig(REPLY_TO, replyTo); + } + + @Override + public String getProtocol() { + return SMTP; + } + +} diff --git a/components/camel/camel-mail/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-mail/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..133b1610b --- /dev/null +++ b/components/camel/camel-mail/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.mail.deploy.CamelMailComponent diff --git a/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v1/camel-mail_1_0.xsd b/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v1/camel-mail_1_0.xsd new file mode 100644 index 000000000..56a9d933d --- /dev/null +++ b/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v1/camel-mail_1_0.xsd @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v1/camel-mail_1_1.xsd b/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v1/camel-mail_1_1.xsd new file mode 100644 index 000000000..178aa0772 --- /dev/null +++ b/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v1/camel-mail_1_1.xsd @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v2/camel-mail_2_0.xsd b/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v2/camel-mail_2_0.xsd new file mode 100644 index 000000000..ec54239a3 --- /dev/null +++ b/components/camel/camel-mail/src/main/resources/org/switchyard/component/camel/mail/model/v2/camel-mail_2_0.xsd @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-mail/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-mail/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..7fa81809a --- /dev/null +++ b/components/camel/camel-mail/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_mail_1_0.section=urn:switchyard-component-camel-mail:config +camel_mail_1_0.version=1.0 +camel_mail_1_0.namespace=urn:switchyard-component-camel-mail:config:1.0 +camel_mail_1_0.schema=camel-mail_1_0.xsd +camel_mail_1_0.location=/org/switchyard/component/camel/mail/model/v1/ +camel_mail_1_0.marshaller=org.switchyard.component.camel.mail.model.v1.V1CamelMailModelMarshaller + +camel_mail_1_1.section=urn:switchyard-component-camel-mail:config +camel_mail_1_1.version=1.1 +camel_mail_1_1.namespace=urn:switchyard-component-camel-mail:config:1.1 +camel_mail_1_1.schema=camel-mail_1_1.xsd +camel_mail_1_1.location=/org/switchyard/component/camel/mail/model/v1/ +camel_mail_1_1.marshaller=org.switchyard.component.camel.mail.model.v1.V1CamelMailModelMarshaller + +camel_mail_2_0.section=urn:switchyard-component-camel-mail:config +camel_mail_2_0.version=2.0 +camel_mail_2_0.namespace=urn:switchyard-component-camel-mail:config:2.0 +camel_mail_2_0.schema=camel-mail_2_0.xsd +camel_mail_2_0.location=/org/switchyard/component/camel/mail/model/v2/ +camel_mail_2_0.marshaller=org.switchyard.component.camel.mail.model.v1.V1CamelMailModelMarshaller diff --git a/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailBindingModelTest.java b/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailBindingModelTest.java new file mode 100644 index 000000000..529723ee3 --- /dev/null +++ b/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailBindingModelTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.mail.MailEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.mail.model.CamelMailNamespace; + +/** + * Test for {@link V1CamelMailBindingModel}. + */ +public class V1CamelMailBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-mail-binding-beans.xml"; + private static final Boolean SECURE = true; + + private static final String HOST = "localhost"; + private static final Integer PORT = 233; + private static final String USERNAME = "camel"; + private static final String PASSWORD = "rider"; + private static final Integer CONNECTION_TIMEOUT = 300; + private static final String CAMEL_URI = "imaps://localhost:233?connectionTimeout=300&" + + "password=rider&username=camel"; + + public V1CamelMailBindingModelTest() { + super(MailEndpoint.class, CAMEL_XML); + } + + @Override + protected void createModelAssertions(V1CamelMailBindingModel model) { + assertEquals(SECURE, model.isSecure()); + assertEquals(HOST, model.getHost()); + assertEquals(PORT, model.getPort()); + assertEquals(USERNAME, model.getUsername()); + assertEquals(PASSWORD, model.getPassword()); + assertEquals(CONNECTION_TIMEOUT, model.getConnectionTimeout()); + } + + @Override + protected V1CamelMailBindingModel createTestModel() { + return new V1CamelMailBindingModel(CamelMailNamespace.V_1_0.uri()) + .setSecure(SECURE) + .setHost(HOST) + .setPort(PORT) + .setUsername(USERNAME) + .setPassword(PASSWORD) + .setConnectionTimeout(CONNECTION_TIMEOUT) + ; + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailConsumerBindingModelTest.java b/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailConsumerBindingModelTest.java new file mode 100644 index 000000000..49d9ee885 --- /dev/null +++ b/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailConsumerBindingModelTest.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.mail.MailEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.mail.model.CamelMailConsumerBindingModel; +import org.switchyard.component.camel.mail.model.CamelMailNamespace; +import org.switchyard.component.camel.mail.model.v1.V1CamelMailConsumerBindingModel.AccountType; + +/** + * Test for {@link V1CamelMailBindingModel} with {@link V1CamelMailConsumerBindingModel} set. + */ +public class V1CamelMailConsumerBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-mail-binding-consumer-beans.xml"; + + private static final String HOST = "localhost"; + private static final Boolean SECURE = true; + + private static final String FOLDER_NAME = "Mail/Inbox"; + private static final Integer FETCH_SIZE = 10; + private static final Boolean UNSEEN = false; + private static final Boolean DELETE = true; + private static final String COPY_TO = "SEEN"; + private static final Boolean DISCONNECT = true; + private static final String ACCOUNT_TYPE = AccountType.pop3.name(); + + private static final String CAMEL_URI = "pop3s://localhost?folderName=Mail/Inbox&fetchSize=10&unseen=false&delete=true©To=SEEN&disconnect=true"; + + public V1CamelMailConsumerBindingModelTest() { + super(MailEndpoint.class, CAMEL_XML); + } + + @Override + protected V1CamelMailBindingModel createTestModel() { + V1CamelMailBindingModel model = new V1CamelMailBindingModel(CamelMailNamespace.V_1_0.uri()) { + @Override + public boolean isReferenceBinding() { + return false; + } + }; + + model.setSecure(SECURE); + model.setHost(HOST); + + CamelMailConsumerBindingModel consumer = new V1CamelMailConsumerBindingModel(CamelMailNamespace.V_1_0.uri()) + .setAccountType(ACCOUNT_TYPE) + .setFolderName(FOLDER_NAME) + .setFetchSize(FETCH_SIZE) + .setUnseen(UNSEEN) + .setDelete(DELETE) + .setCopyTo(COPY_TO) + .setDisconnect(DISCONNECT); + model.setConsumer(consumer); + + return model; + } + + @Override + protected void createModelAssertions(V1CamelMailBindingModel model) { + assertEquals(HOST, model.getHost()); + assertEquals(SECURE, model.isSecure()); + + V1CamelMailConsumerBindingModel consumer = model.getConsumer(); + assertEquals(ACCOUNT_TYPE, consumer.getProtocol()); + assertEquals(FOLDER_NAME, consumer.getFolderName()); + assertEquals(FETCH_SIZE, consumer.getFetchSize()); + assertEquals(UNSEEN, consumer.isUnseen()); + assertEquals(DELETE, consumer.isDelete()); + assertEquals(COPY_TO, consumer.getCopyTo()); + assertEquals(DISCONNECT, consumer.isDisconnect()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } +} diff --git a/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailProducerBindingModelTest.java b/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailProducerBindingModelTest.java new file mode 100644 index 000000000..64a300eb3 --- /dev/null +++ b/components/camel/camel-mail/src/test/java/org/switchyard/component/camel/mail/model/v1/V1CamelMailProducerBindingModelTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mail.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.mail.MailEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.mail.model.CamelMailNamespace; + +/** + * Test for {@link V1CamelMailBindingModel} with {@link V1CamelMailProducerBindingModel} set. + */ +public class V1CamelMailProducerBindingModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-mail-binding-producer-beans.xml"; + + private static final String HOST = "rider"; + private static final Boolean SECURE = true; + private static final String SUBJECT = "Desert ride"; + private static final String FROM = "rider@camel"; + private static final String TO = "camel@rider"; + private static final String CC = "mule@rider"; + private static final String BCC = "rider@mule"; + private static final String REPLY_TO = "camel@camel"; + + private static final String CAMEL_URI = "smtps://rider?subject=Desert ride&" + + "from=rider@camel&to=camel@rider&CC=mule@rider&BCC=rider@mule&replyTo=camel@camel"; + + public V1CamelMailProducerBindingModelTest() { + super(MailEndpoint.class, CAMEL_XML); + } + + @Override + protected void createModelAssertions(V1CamelMailBindingModel model) { + assertEquals(HOST, model.getHost()); + assertEquals(SECURE, model.isSecure()); + assertEquals(SUBJECT, model.getProducer().getSubject()); + assertEquals(FROM, model.getProducer().getFrom()); + assertEquals(TO, model.getProducer().getTo()); + assertEquals(CC, model.getProducer().getCC()); + assertEquals(BCC, model.getProducer().getBCC()); + assertEquals(REPLY_TO, model.getProducer().getReplyTo()); + } + + @Override + protected V1CamelMailBindingModel createTestModel() { + V1CamelMailBindingModel model = new V1CamelMailBindingModel(CamelMailNamespace.V_1_0.uri()) { + public boolean isReferenceBinding() { + return true; + } + }; + model.setSecure(SECURE) + .setHost(HOST); + + V1CamelMailProducerBindingModel producer = new V1CamelMailProducerBindingModel(CamelMailNamespace.V_1_0.uri()) + .setSubject(SUBJECT) + .setFrom(FROM) + .setTo(TO) + .setCC(CC) + .setBCC(BCC) + .setReplyTo(REPLY_TO); + + return model.setProducer(producer); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-beans.xml b/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-beans.xml new file mode 100644 index 000000000..aa8d01e58 --- /dev/null +++ b/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-beans.xml @@ -0,0 +1,31 @@ + + + + + + + + localhost + 233 + camel + rider + 300 + + + + + diff --git a/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-consumer-beans.xml b/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-consumer-beans.xml new file mode 100644 index 000000000..6e518c134 --- /dev/null +++ b/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-consumer-beans.xml @@ -0,0 +1,34 @@ + + + + + + + + localhost + + Mail/Inbox + 10 + false + true + SEEN + true + + + + + diff --git a/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-producer-beans.xml b/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-producer-beans.xml new file mode 100644 index 000000000..6486870f0 --- /dev/null +++ b/components/camel/camel-mail/src/test/resources/v1/switchyard-mail-binding-producer-beans.xml @@ -0,0 +1,35 @@ + + + + + + + + rider + + Desert ride + rider@camel + camel@rider + mule@rider + rider@mule + camel@camel + + + + + + diff --git a/components/camel/camel-mqtt/pom.xml b/components/camel/camel-mqtt/pom.xml new file mode 100644 index 000000000..9bcae63b0 --- /dev/null +++ b/components/camel/camel-mqtt/pom.xml @@ -0,0 +1,71 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-mqtt + bundle + SwitchYard: Camel Component :: MQTT Binding + http://switchyard.org + + + org.switchyard.component.camel.mqtt.* + + + org.apache.camel.component.mqtt, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-core + + + org.apache.camel + camel-mqtt + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttActivator.java b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttActivator.java new file mode 100644 index 000000000..9865cc968 --- /dev/null +++ b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttActivator.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mqtt.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.deploy.BaseBindingActivator; +import org.switchyard.component.camel.common.handler.InboundHandler; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.mqtt.model.CamelMqttBindingModel; + +/** + * Camel mqtt activator. + */ +public class CamelMqttActivator extends BaseBindingActivator { + + /** + * Creates new activator instance. + * + * @param context Camel context. + * @param types Activation types. + */ + public CamelMqttActivator(SwitchYardCamelContext context, String[] types) { + super(context, types); + } + + @SuppressWarnings("unchecked") + @Override + protected InboundHandler createInboundHandler(QName serviceName, CamelBindingModel binding) { + return new CamelMqttInboundHandler((CamelMqttBindingModel)binding, getCamelContext(), serviceName, getServiceDomain()); + } + +} diff --git a/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttComponent.java b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttComponent.java new file mode 100644 index 000000000..2dc4ee5a8 --- /dev/null +++ b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttComponent.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mqtt.deploy; + +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.deploy.BaseBindingActivator; +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.mqtt.model.v2.V2CamelMqttBindingModel; + +/** + * MQTT binding component. + */ +public class CamelMqttComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelMqttComponent() { + super("CamelMqttComponent", V2CamelMqttBindingModel.MQTT); + } + + @Override + protected BaseBindingActivator createActivator(SwitchYardCamelContext context, String... types) { + return new CamelMqttActivator(context, types); + } +} diff --git a/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttInboundHandler.java b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttInboundHandler.java new file mode 100644 index 000000000..84bd8fa92 --- /dev/null +++ b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/deploy/CamelMqttInboundHandler.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mqtt.deploy; + +import javax.xml.namespace.QName; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.model.RouteDefinition; +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.type.Classes; +import org.switchyard.component.camel.common.CamelConstants; +import org.switchyard.component.camel.common.handler.InboundHandler; +import org.switchyard.component.camel.common.handler.MessageComposerProcessor; +import org.switchyard.component.camel.common.handler.OperationSelectorProcessor; +import org.switchyard.component.camel.mqtt.model.CamelMqttBindingModel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * Inbound handler for MQTT binding. Set applicationContextClassLoader in CamelContext as a TCCL + * as MQTT consumer runs with other class loader, causes issues. See https://issues.jboss.org/browse/SWITCHYARD-2220 + */ +public class CamelMqttInboundHandler extends InboundHandler { + + private static final String ORIGINAL_CLASS_LOADER = "org.switchyard.component.camel.mqtt.deploy.CamelMqttInboundHandler.originalClassLoader"; + + /** + * Sole constructor. + * + * @param camelBindingModel The CamelBindingModel. + * @param camelContext The camel context instance. + * @param serviceName The target service name. + * @param domain the service domain. + */ + public CamelMqttInboundHandler(CamelMqttBindingModel camelBindingModel, + SwitchYardCamelContext camelContext, QName serviceName, ServiceDomain domain) { + super(camelBindingModel, camelContext, serviceName, domain); + } + + @Override + protected RouteDefinition createRouteDefinition() { + final RouteDefinition route = new RouteDefinition(); + route.routeId(getRouteId()).from(getComponentUri().toString()); + addTransactionPolicy(route) + .doTry() + // SWITCHYARD-2220 - MQTT consumer needs TCCL to be set manually + .process(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + ClassLoader appClassLoader = exchange.getContext().getApplicationContextClassLoader(); + ClassLoader origCl = Classes.setTCCL(appClassLoader); + exchange.setProperty(ORIGINAL_CLASS_LOADER, origCl); + } + }) + .setProperty(ExchangeCompletionEvent.GATEWAY_NAME).simple(getBindingModel().getName(), String.class) + .setProperty(CamelConstants.APPLICATION_NAMESPACE).constant(getServiceName().getNamespaceURI()) + .process(new MessageComposerProcessor(getBindingModel())) + .process(new OperationSelectorProcessor(getServiceName(), getBindingModel())) + .to(getSwitchyardEndpointUri()) + .doFinally() + .process(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + ClassLoader origCl = exchange.getProperty(ORIGINAL_CLASS_LOADER, ClassLoader.class); + if (origCl != null) { + Classes.setTCCL(origCl); + } + } + }); + return route; + } + +} diff --git a/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/CamelMqttBindingModel.java b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/CamelMqttBindingModel.java new file mode 100644 index 000000000..e12e27134 --- /dev/null +++ b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/CamelMqttBindingModel.java @@ -0,0 +1,320 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mqtt.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Configuration binding for mqtt. + * + * @author Douglas Palmer + */ +public interface CamelMqttBindingModel extends CamelBindingModel { + + /** Camel endpoint type. */ + String MQTT = "mqtt"; + + /** + * Gets name. + * + * @return name + */ + String getName(); + + /** + * Sets name. + * + * @param name name + * @return a reference to this binding model + */ + CamelMqttBindingModel setName(String name); + + /** + * Gets host name / ip. + * + * @return Host name. + */ + String getHost(); + + /** + * Sets host name. + * + * @param host Host name. + * @return a reference to this binding model + */ + CamelMqttBindingModel setHost(String host); + + /** + * Gets local address. + * + * @return local address + */ + String getLocalAddress(); + + /** + * Sets local address. + * @param localAddress local address + * @return a reference to this binding model + */ + CamelMqttBindingModel setLocalAddress(String localAddress); + + /** + * Gets connectAttemptsMax. + * + * @return connectAttemptsMax + */ + Integer getConnectAttemptsMax(); + + /** + * Sets the maximum number of connect attempts. + * + * @param connectAttemptsMax Maximum number of connect attempts. + * @return a reference to this binding model + */ + CamelMqttBindingModel setConnectAttemptsMax(int connectAttemptsMax); + + /** + * Gets reconnectAttemptsMax. + * + * @return reconnectAttemptsMax + */ + Integer getReconnectAttemptsMax(); + + /** + * Sets the maximum number of reconnect attempts. + * + * @param reconnectAttemptsMax Maximum number of reconnect attempts. + * @return a reference to this binding model + */ + CamelMqttBindingModel setReconnectAttemptsMax(int reconnectAttemptsMax); + + /** + * Gets reconnect delay. + * + * @return reconnectDelay + */ + Integer getReconnectDelay(); + + /** + * Sets the delay between reconnects. + * + * @param reconnectDelay the time between reconnect attempts. + * @return a reference to this binding model + */ + CamelMqttBindingModel setReconnectDelay(int reconnectDelay); + + /** + * Gets multiplier for incremental backoff between reconnect attempts. + * + * @return reconnectBackOffMultiplier + */ + Double getReconnectBackOffMultiplier(); + + /** + * Sets the multiplier for incremental backoff between reconnect attempts. + * + * @param reconnectBackOffMultiplier the multiplier for incremental backoff between reconnect attempts. + * @return a reference to this binding model + */ + CamelMqttBindingModel setReconnectBackOffMultiplier(double reconnectBackOffMultiplier); + + /** + * Gets the maximum reconnect delay. + * + * @return reconnectDelayMax + */ + Integer getReconnectDelayMax(); + + /** + * Sets the maximum delay between reconnects. + * + * @param reconnectDelayMax the maximum time between reconnect attempts. + * @return a reference to this binding model + */ + CamelMqttBindingModel setReconnectDelayMax(int reconnectDelayMax); + + /** + * Gets user name. + * @return user name + */ + String getUserName(); + + /** + * Sets user name. + * @param username user name + * @return a reference to this binding model + */ + CamelMqttBindingModel setUserName(String username); + + /** + * Gets password. + * @return password + */ + String getPassword(); + + /** + * Sets password. + * @param password password + * @return a reference to this binding model + */ + CamelMqttBindingModel setPassword(String password); + + /** + * Gets quality of service. + * + * @return quality of service + */ + String getQualityOfService(); + + /** + * Sets quality of service. + * @param qualityOfService quality of service + * @return a reference to this binding model + */ + CamelMqttBindingModel setQualityOfService(String qualityOfService); + + /** + * Gets subscribe topic name. + * @return subscribe topic name + */ + String getSubscribeTopicName(); + + /** + * Sets subscribe topic name. + * + * @param subscribeTopicName subscribe topic name + * @return a reference to this binding model + */ + CamelMqttBindingModel setSubscribeTopicName(String subscribeTopicName); + + /** + * Gets publish topic name. + * + * @return publish topic name + */ + String getPublishTopicName(); + + /** + * Sets publish topic name. + * @param publishTopicName publish topic name + * @return a reference to this binding model + */ + CamelMqttBindingModel setPublishTopicName(String publishTopicName); + + /** + * Retain messages by default - on/off. + * + * @return True if messages should be retained by default. + */ + Boolean isByDefaultRetain(); + + /** + * Setting to specify whether messages should be retained by default. + * + * @param byDefaultRetain Should messages be retained by default. + * @return a reference to this binding model + */ + CamelMqttBindingModel setByDefaultRetain(Boolean byDefaultRetain); + + /** + * Gets mqtt topic property name. + * + * @return topic property name + */ + String getMqttTopicPropertyName(); + + /** + * Sets mqtt topic property name. + * + * @param mqttTopicPropertyName topic property name + * @return a reference to this binding model + */ + CamelMqttBindingModel setMqttTopicPropertyName(String mqttTopicPropertyName); + + /** + * Gets mqtt retain property name. + * + * @return retain property name + */ + String getMqttRetainPropertyName(); + + /** + * Sets mqtt retain property name. + * + * @param mqttRetainPropertyName retain property name + * @return a reference to this binding model + */ + CamelMqttBindingModel setMqttRetainPropertyName(String mqttRetainPropertyName); + + /** + * Gets mqtt QoS property name. + * + * @return QoS property name + */ + String getMqttQosPropertyName(); + + /** + * Sets mqtt QoS property name. + * + * @param mqttQosPropertyName QoS property name + * @return a reference to this binding model + */ + CamelMqttBindingModel setMqttQosPropertyName(String mqttQosPropertyName); + + /** + * Gets connect wait in seconds. + * + * @return connect wait in seconds + */ + Integer getConnectWaitInSeconds(); + + /** + * Sets connect wait in seconds. + * + * @param connectWaitInSeconds connect wait in seconds + * @return a reference to this binding model + */ + CamelMqttBindingModel setConnectWaitInSeconds(int connectWaitInSeconds); + + /** + * Gets disconnect wait in seconds. + * + * @return disconnect wait in seconds + */ + Integer getDisconnectWaitInSeconds(); + + /** + * Sets disconnect wait in seconds. + * + * @param disconnectWaitInSeconds disconnect wait in seconds + * @return a reference to this binding model + */ + CamelMqttBindingModel setDisonnectWaitInSeconds(int disconnectWaitInSeconds); + + /** + * Gets send wait in seconds. + * + * @return send wait in seconds + */ + Integer getSendWaitInSeconds(); + + /** + * Sets send wait in seconds. + * + * @param sendWaitInSeconds send wait in seconds + * @return a reference to this binding model + */ + CamelMqttBindingModel setSendWaitInSeconds(int sendWaitInSeconds); + +} diff --git a/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/CamelMqttNamespace.java b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/CamelMqttNamespace.java new file mode 100644 index 000000000..e15ae555d --- /dev/null +++ b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/CamelMqttNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mqtt.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel MQTT config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelMqttNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelMqttNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelMqttNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelMqttNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelMqttNamespace + */ + public static CamelMqttNamespace fromUri(String uri) { + return Util.fromUri(CamelMqttNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelMqttNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-mqtt:config", version); + } + } + +} diff --git a/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttBindingModel.java b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttBindingModel.java new file mode 100644 index 000000000..1f178a3d4 --- /dev/null +++ b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttBindingModel.java @@ -0,0 +1,288 @@ +package org.switchyard.component.camel.mqtt.model.v2; + +import java.net.URI; +import java.util.List; + +import org.apache.camel.util.UnsafeUriCharactersEncoder; +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.mqtt.model.CamelMqttBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 CamelMqttBindingModel. + */ +public class V2CamelMqttBindingModel extends V1BaseCamelBindingModel implements CamelMqttBindingModel { + + /** QoS enum. */ + public enum QualityOfService { + /** at most once. */ + AtMostOnce, + /** at least once. */ + AtLeastOnce, + /** exactly once. */ + ExactlyOnce; + } + + private static final String NAME = "name"; + private static final String HOST = "host"; + private static final String LOCAL_ADDRESS = "localAddress"; + private static final String CONNECT_ATTEMPTS_MAX = "connectAttemptsMax"; + private static final String RECONNECT_ATTEMPTS_MAX = "reconnectAttemptsMax"; + private static final String RECONNECT_DELAY = "reconnectDelay"; + private static final String RECONNECT_BACK_OFF_MULTIPLIER = "reconnectBackOffMultiplier"; + private static final String RECONNECT_DELAY_MAX = "reconnectDelayMax"; + private static final String USER_NAME = "userName"; + private static final String PASSWORD = "password"; + private static final String QUALITY_OF_SERVICE = "qualityOfService"; + private static final String SUBSCRIBE_TOPIC_NAME = "subscribeTopicName"; + private static final String PUBLISH_TOPIC_NAME = "publishTopicName"; + private static final String BY_DEFAULT_RETAIN = "byDefaultRetain"; + private static final String MQTT_TOPIC_PROPERTY_NAME = "mqttTopicPropertyName"; + private static final String MQTT_RETAIN_PROPERTY_NAME = "mqttRetainPropertyName"; + private static final String MQTT_QOS_PROPERTY_NAME = "mqttQosPropertyName"; + private static final String CONNECT_WAIT_IN_SECONDS = "connectWaitInSeconds"; + private static final String DISCONNECT_WAIT_IN_SECONDS = "disconnectWaitInSeconds"; + private static final String SEND_WAIT_IN_SECONDS = "sendWaitInSeconds"; + + /** + * Creates new mqtt binding model. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V2CamelMqttBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Creates new mqtt binding model. + * @param namespace namespace + */ + public V2CamelMqttBindingModel(String namespace) { + super(MQTT, namespace); + + setModelChildrenOrder(NAME, HOST, LOCAL_ADDRESS, CONNECT_ATTEMPTS_MAX, RECONNECT_ATTEMPTS_MAX, RECONNECT_DELAY, RECONNECT_BACK_OFF_MULTIPLIER, RECONNECT_DELAY_MAX, + USER_NAME, PASSWORD, QUALITY_OF_SERVICE, SUBSCRIBE_TOPIC_NAME, PUBLISH_TOPIC_NAME, BY_DEFAULT_RETAIN, MQTT_TOPIC_PROPERTY_NAME, MQTT_RETAIN_PROPERTY_NAME, + MQTT_QOS_PROPERTY_NAME, CONNECT_WAIT_IN_SECONDS, DISCONNECT_WAIT_IN_SECONDS, SEND_WAIT_IN_SECONDS); + } + + @Override + public String getName() { + return getModelAttribute(NAME); + } + + @Override + public V2CamelMqttBindingModel setName(String name) { + setModelAttribute(NAME, name); + return this; + } + + @Override + public String getHost() { + return getConfig(HOST); + } + + @Override + public V2CamelMqttBindingModel setHost(String host) { + return setConfig(HOST, host); + } + + @Override + public String getLocalAddress() { + return getConfig(LOCAL_ADDRESS); + } + + @Override + public V2CamelMqttBindingModel setLocalAddress(String localAddress) { + return setConfig(LOCAL_ADDRESS, localAddress); + } + + @Override + public Integer getConnectAttemptsMax() { + return getIntegerConfig(CONNECT_ATTEMPTS_MAX); + } + + @Override + public V2CamelMqttBindingModel setConnectAttemptsMax(int connectAttemptsMax) { + return setConfig(CONNECT_ATTEMPTS_MAX, connectAttemptsMax); + } + + @Override + public Integer getReconnectAttemptsMax() { + return getIntegerConfig(RECONNECT_ATTEMPTS_MAX); + } + + @Override + public V2CamelMqttBindingModel setReconnectAttemptsMax(int reconnectAttemptsMax) { + return setConfig(RECONNECT_ATTEMPTS_MAX, reconnectAttemptsMax); + } + + @Override + public Integer getReconnectDelay() { + return getIntegerConfig(RECONNECT_DELAY); + } + + @Override + public V2CamelMqttBindingModel setReconnectDelay(int reconnectDelay) { + return setConfig(RECONNECT_DELAY, reconnectDelay); + } + + @Override + public Double getReconnectBackOffMultiplier() { + return getDoubleConfig(RECONNECT_BACK_OFF_MULTIPLIER); + } + + @Override + public V2CamelMqttBindingModel setReconnectBackOffMultiplier(double reconnectBackOffMultiplier) { + return setConfig(RECONNECT_BACK_OFF_MULTIPLIER, reconnectBackOffMultiplier); + } + + @Override + public Integer getReconnectDelayMax() { + return getIntegerConfig(RECONNECT_DELAY_MAX); + } + + @Override + public V2CamelMqttBindingModel setReconnectDelayMax(int reconnectDelayMax) { + return setConfig(RECONNECT_DELAY_MAX, reconnectDelayMax); + } + + @Override + public String getUserName() { + return getConfig(USER_NAME); + } + + @Override + public V2CamelMqttBindingModel setUserName(String username) { + return setConfig(USER_NAME, username); + } + + @Override + public String getPassword() { + return getConfig(PASSWORD); + } + + @Override + public V2CamelMqttBindingModel setPassword(String password) { + return setConfig(PASSWORD, password); + } + + @Override + public String getQualityOfService() { + QualityOfService qualityOfService = getModelConfiguration() != null + ? QualityOfService.valueOf(getConfig(QUALITY_OF_SERVICE)) + : QualityOfService.AtLeastOnce; + return qualityOfService.name(); + } + + @Override + public V2CamelMqttBindingModel setQualityOfService(String qualityOfService) { + return setConfig(QUALITY_OF_SERVICE, qualityOfService); + } + + @Override + public String getSubscribeTopicName() { + return getConfig(SUBSCRIBE_TOPIC_NAME); + } + + @Override + public V2CamelMqttBindingModel setSubscribeTopicName(String subscribeTopicName) { + return setConfig(SUBSCRIBE_TOPIC_NAME, subscribeTopicName); + } + + @Override + public String getPublishTopicName() { + return getConfig(PUBLISH_TOPIC_NAME); + } + + @Override + public V2CamelMqttBindingModel setPublishTopicName(String publishTopicName) { + return setConfig(PUBLISH_TOPIC_NAME, publishTopicName); + } + + @Override + public Boolean isByDefaultRetain() { + return getBooleanConfig(BY_DEFAULT_RETAIN); + } + + @Override + public V2CamelMqttBindingModel setByDefaultRetain(Boolean byDefaultRetain) { + return setConfig(BY_DEFAULT_RETAIN, byDefaultRetain); + } + + @Override + public String getMqttTopicPropertyName() { + return getConfig(MQTT_TOPIC_PROPERTY_NAME); + } + + @Override + public V2CamelMqttBindingModel setMqttTopicPropertyName(String mqttTopicPropertyName) { + return setConfig(MQTT_TOPIC_PROPERTY_NAME, mqttTopicPropertyName); + } + + @Override + public String getMqttRetainPropertyName() { + return getConfig(MQTT_RETAIN_PROPERTY_NAME); + } + + @Override + public V2CamelMqttBindingModel setMqttRetainPropertyName(String mqttRetainPropertyName) { + return setConfig(MQTT_RETAIN_PROPERTY_NAME, mqttRetainPropertyName); + } + + @Override + public String getMqttQosPropertyName() { + return getConfig(MQTT_QOS_PROPERTY_NAME); + } + + @Override + public V2CamelMqttBindingModel setMqttQosPropertyName(String mqttQosPropertyName) { + return setConfig(MQTT_QOS_PROPERTY_NAME, mqttQosPropertyName); + } + + @Override + public Integer getConnectWaitInSeconds() { + return getIntegerConfig(CONNECT_WAIT_IN_SECONDS); + } + + @Override + public V2CamelMqttBindingModel setConnectWaitInSeconds(int connectWaitInSeconds) { + return setConfig(CONNECT_WAIT_IN_SECONDS, connectWaitInSeconds); + } + + @Override + public Integer getDisconnectWaitInSeconds() { + return getIntegerConfig(DISCONNECT_WAIT_IN_SECONDS); + } + + @Override + public V2CamelMqttBindingModel setDisonnectWaitInSeconds(int disconnectWaitInSeconds) { + return setConfig(DISCONNECT_WAIT_IN_SECONDS, disconnectWaitInSeconds); + } + + @Override + public Integer getSendWaitInSeconds() { + return getIntegerConfig(SEND_WAIT_IN_SECONDS); + } + + @Override + public V2CamelMqttBindingModel setSendWaitInSeconds(int sendWaitInSeconds) { + return setConfig(SEND_WAIT_IN_SECONDS, sendWaitInSeconds); + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = MQTT + "://" + getName(); + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, NAME); + + return URI.create(UnsafeUriCharactersEncoder.encode(baseUri + queryStr.toString())); + } + +} diff --git a/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttModelMarshaller.java b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttModelMarshaller.java new file mode 100644 index 000000000..717c2aadd --- /dev/null +++ b/components/camel/camel-mqtt/src/main/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.mqtt.model.v2; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Mqtt model marshaller. + */ +public class V2CamelMqttModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_MQTT = BindingModel.BINDING + '.' + V2CamelMqttBindingModel.MQTT; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V2CamelMqttModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_MQTT.equals(name)) { + return new V2CamelMqttBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-mqtt/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-mqtt/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..250abd75c --- /dev/null +++ b/components/camel/camel-mqtt/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.mqtt.deploy.CamelMqttComponent diff --git a/components/camel/camel-mqtt/src/main/resources/org/switchyard/component/camel/mqtt/model/v2/camel-mqtt_2_0.xsd b/components/camel/camel-mqtt/src/main/resources/org/switchyard/component/camel/mqtt/model/v2/camel-mqtt_2_0.xsd new file mode 100644 index 000000000..5477a50f4 --- /dev/null +++ b/components/camel/camel-mqtt/src/main/resources/org/switchyard/component/camel/mqtt/model/v2/camel-mqtt_2_0.xsd @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-mqtt/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-mqtt/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..1e1a1e55e --- /dev/null +++ b/components/camel/camel-mqtt/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,18 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_mqtt_2_0.section=urn:switchyard-component-camel-mqtt:config +camel_mqtt_2_0.version=2.0 +camel_mqtt_2_0.namespace=urn:switchyard-component-camel-mqtt:config:2.0 +camel_mqtt_2_0.schema=camel-mqtt_2_0.xsd +camel_mqtt_2_0.location=/org/switchyard/component/camel/mqtt/model/v2/ +camel_mqtt_2_0.marshaller=org.switchyard.component.camel.mqtt.model.v2.V2CamelMqttModelMarshaller diff --git a/components/camel/camel-mqtt/src/test/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttBindingModelTest.java b/components/camel/camel-mqtt/src/test/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttBindingModelTest.java new file mode 100644 index 000000000..7a52adb7c --- /dev/null +++ b/components/camel/camel-mqtt/src/test/java/org/switchyard/component/camel/mqtt/model/v2/V2CamelMqttBindingModelTest.java @@ -0,0 +1,101 @@ +package org.switchyard.component.camel.mqtt.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.apache.camel.component.mqtt.MQTTEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.mqtt.model.CamelMqttNamespace; +import org.switchyard.component.camel.mqtt.model.v2.V2CamelMqttBindingModel.QualityOfService; + +public class V2CamelMqttBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String NAME = "Garfield"; + private static final String HOST = "tcp://127.0.0.1:1883"; + private static final String LOCAL_ADDRESS = "tcp://127.0.0.1:1883"; + private static final Integer CONNECT_ATTEMPTS_MAX = 10; + private static final Integer RECONNECT_ATTEMPTS_MAX = 10; + private static final Integer RECONNECT_DELAY = 10; + private static final Double RECONNECT_BACK_OFF_MULTIPLIER = 5.0; + private static final Integer RECONNECT_DELAY_MAX = 100; + private static final String USER_NAME = "karaf"; + private static final String PASSWORD = "karaf"; + private static final String QUALITY_OF_SERVICE = QualityOfService.ExactlyOnce.name(); + private static final String SUBSCRIBE_TOPIC_NAME = "camel/mqtt/test"; + private static final String PUBLISH_TOPIC_NAME = "camel/mqtt/test"; + private static final Boolean BY_DEFAULT_RETAIN = true; + private static final String MQTT_TOPIC_PROPERTY_NAME = "MQTT_TOPIC"; + private static final String MQTT_RETAIN_PROPERTY_NAME = "MQTT_RETAIN"; + private static final String MQTT_QOS_PROPERTY_NAME = "MQTT_QOS"; + private static final Integer CONNECT_WAIT_IN_SECONDS = 10; + private static final Integer DISCONNECT_WAIT_IN_SECONDS = 10; + private static final Integer SEND_WAIT_IN_SECONDS = 10; + + private static final String CAMEL_XML = "/v2/switchyard-mqtt-binding-beans.xml"; + private static final String CAMEL_URI = "mqtt://" + NAME + "?host=" + HOST + "&localAddress=" + LOCAL_ADDRESS + "&connectAttemptsMax=" + CONNECT_ATTEMPTS_MAX + + "&reconnectAttemptsMax=" + RECONNECT_ATTEMPTS_MAX + "&reconnectDelay=" + RECONNECT_DELAY + "&reconnectBackOffMultiplier=" + RECONNECT_BACK_OFF_MULTIPLIER + + "&reconnectDelayMax=" + RECONNECT_DELAY_MAX + "&userName=" + USER_NAME + "&password=" + PASSWORD + "&qualityOfService=" + QUALITY_OF_SERVICE + + "&subscribeTopicName=" + SUBSCRIBE_TOPIC_NAME + "&publishTopicName=" + PUBLISH_TOPIC_NAME + "&byDefaultRetain=" + BY_DEFAULT_RETAIN + + "&mqttTopicPropertyName=" + MQTT_TOPIC_PROPERTY_NAME + "&mqttRetainPropertyName=" + MQTT_RETAIN_PROPERTY_NAME + + "&mqttQosPropertyName=" + MQTT_QOS_PROPERTY_NAME + "&connectWaitInSeconds=" + CONNECT_WAIT_IN_SECONDS + + "&disconnectWaitInSeconds=" + DISCONNECT_WAIT_IN_SECONDS + "&sendWaitInSeconds=" + SEND_WAIT_IN_SECONDS; + + public V2CamelMqttBindingModelTest () { + super(MQTTEndpoint.class, CAMEL_XML); + setSkipCamelEndpointTesting(true); + } + + @Override + protected void createModelAssertions(V2CamelMqttBindingModel model) { + assertEquals(NAME, model.getName()); + assertEquals(HOST, model.getHost()); + assertEquals(LOCAL_ADDRESS, model.getLocalAddress()); + assertEquals(CONNECT_ATTEMPTS_MAX, model.getConnectAttemptsMax()); + assertEquals(RECONNECT_ATTEMPTS_MAX, model.getReconnectAttemptsMax()); + assertEquals(RECONNECT_DELAY, model.getReconnectDelay()); + assertEquals(RECONNECT_BACK_OFF_MULTIPLIER, model.getReconnectBackOffMultiplier()); + assertEquals(RECONNECT_DELAY_MAX, model.getReconnectDelayMax()); + assertEquals(USER_NAME, model.getUserName()); + assertEquals(PASSWORD, model.getPassword()); + assertEquals(QUALITY_OF_SERVICE, model.getQualityOfService()); + assertEquals(SUBSCRIBE_TOPIC_NAME, model.getSubscribeTopicName()); + assertEquals(PUBLISH_TOPIC_NAME, model.getPublishTopicName()); + assertEquals(BY_DEFAULT_RETAIN, model.isByDefaultRetain()); + assertEquals(MQTT_TOPIC_PROPERTY_NAME, model.getMqttTopicPropertyName()); + assertEquals(MQTT_RETAIN_PROPERTY_NAME, model.getMqttRetainPropertyName()); + assertEquals(MQTT_QOS_PROPERTY_NAME, model.getMqttQosPropertyName()); + assertEquals(CONNECT_WAIT_IN_SECONDS, model.getConnectWaitInSeconds()); + assertEquals(DISCONNECT_WAIT_IN_SECONDS, model.getDisconnectWaitInSeconds()); + assertEquals(SEND_WAIT_IN_SECONDS, model.getSendWaitInSeconds()); + } + + @Override + protected V2CamelMqttBindingModel createTestModel() { + return new V2CamelMqttBindingModel(CamelMqttNamespace.V_2_0.uri()) + .setName(NAME) + .setHost(HOST) + .setLocalAddress(LOCAL_ADDRESS) + .setConnectAttemptsMax(CONNECT_ATTEMPTS_MAX) + .setReconnectAttemptsMax(RECONNECT_ATTEMPTS_MAX) + .setReconnectDelay(RECONNECT_DELAY) + .setReconnectBackOffMultiplier(RECONNECT_BACK_OFF_MULTIPLIER) + .setReconnectDelayMax(RECONNECT_DELAY_MAX) + .setUserName(USER_NAME) + .setPassword(PASSWORD) + .setQualityOfService(QUALITY_OF_SERVICE) + .setSubscribeTopicName(SUBSCRIBE_TOPIC_NAME) + .setPublishTopicName(PUBLISH_TOPIC_NAME) + .setByDefaultRetain(BY_DEFAULT_RETAIN) + .setMqttTopicPropertyName(MQTT_TOPIC_PROPERTY_NAME) + .setMqttRetainPropertyName(MQTT_RETAIN_PROPERTY_NAME) + .setMqttQosPropertyName(MQTT_QOS_PROPERTY_NAME) + .setConnectWaitInSeconds(CONNECT_WAIT_IN_SECONDS) + .setDisonnectWaitInSeconds(DISCONNECT_WAIT_IN_SECONDS) + .setSendWaitInSeconds(SEND_WAIT_IN_SECONDS); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-mqtt/src/test/resources/v2/switchyard-mqtt-binding-beans.xml b/components/camel/camel-mqtt/src/test/resources/v2/switchyard-mqtt-binding-beans.xml new file mode 100644 index 000000000..8761ede19 --- /dev/null +++ b/components/camel/camel-mqtt/src/test/resources/v2/switchyard-mqtt-binding-beans.xml @@ -0,0 +1,45 @@ + + + + + + + + tcp://127.0.0.1:1883 + tcp://127.0.0.1:1883 + 10 + 10 + 10 + 5.0 + 100 + karaf + karaf + ExactlyOnce + camel/mqtt/test + camel/mqtt/test + true + MQTT_TOPIC + MQTT_RETAIN + MQTT_QOS + 10 + 10 + 10 + + + + + diff --git a/components/camel/camel-netty/pom.xml b/components/camel/camel-netty/pom.xml new file mode 100644 index 000000000..40671dd8d --- /dev/null +++ b/components/camel/camel-netty/pom.xml @@ -0,0 +1,72 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-netty + bundle + SwitchYard: Camel Component :: Netty Binding + http://switchyard.org + + + org.switchyard.component.camel.netty.* + + + org.apache.camel.component.netty, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.jboss.netty.*;version="[3,4)", + * + + + + + org.switchyard + switchyard-security + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-core + + + org.apache.camel + camel-netty + + + io.netty + netty + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/deploy/CamelNettyComponent.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/deploy/CamelNettyComponent.java new file mode 100644 index 000000000..46dfb7f0a --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/deploy/CamelNettyComponent.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.netty.model.v1.V1CamelNettyTcpBindingModel; +import org.switchyard.component.camel.netty.model.v1.V1CamelNettyUdpBindingModel; + +/** + * Netty tcp & udp binding component. + */ +public class CamelNettyComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelNettyComponent() { + super("CamelNettyComponent", V1CamelNettyTcpBindingModel.TCP, V1CamelNettyUdpBindingModel.UDP); + } + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyBindingModel.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyBindingModel.java new file mode 100644 index 000000000..fa013f843 --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyBindingModel.java @@ -0,0 +1,332 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.netty.model.v1.V1CamelNettyBindingModel; + +/** + * Configuration binding for netty. + * + * @author Lukasz Dywicki + */ +public interface CamelNettyBindingModel extends CamelBindingModel { + + /** + * Gets host name / ip. + * + * @return Host name. + */ + String getHost(); + + /** + * Sets host name. + * + * @param host Host name. + * @return a reference to this binding model + */ + CamelNettyBindingModel setHost(String host); + + /** + * Gets connection port. + * + * @return Port number used to connect remote server. + */ + Integer getPort(); + + /** + * Sets port to use during connection. + * + * @param port Port number. + * @return a reference to this binding model + */ + CamelNettyBindingModel setPort(int port); + + /** + * The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. + * + * @return Inbound buffer size. + */ + Long getReceiveBufferSize(); + + /** + * Specify inbound buffer size. + * + * @param receiveBufferSize Buffer size. + * @return a reference to this binding model + */ + CamelNettyBindingModel setReceiveBufferSize(Long receiveBufferSize); + + /** + * The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. + * + * @return Outbound buffer size. + */ + Long getSendBufferSize(); + + /** + * Specify outbound buffer size. + * + * @param sendBufferSize Buffer size. + * @return a reference to this binding model + */ + CamelNettyBindingModel setSendBufferSize(Long sendBufferSize); + + /** + * SSL status - on/off. + * + * @return True if ssl is enabled for endpoint. + */ + Boolean isSsl(); + + /** + * Setting to specify whether SSL encryption is applied to this endpoint. + * + * @param ssl Should ssl be used. + * @return a reference to this binding model + */ + CamelNettyBindingModel setSsl(Boolean ssl); + + /** + * Return name of bean instance used as ssl handler. + * + * @return Custom ssl handler bean name. + */ + String getSslHandler(); + + /** + * Sets sslHandler bean name.. + * + * @param sslHandler Name of bean used as ssl handler. + * @return a reference to this binding model + */ + CamelNettyBindingModel setSslHandler(String sslHandler); + + /** + * Indicates whether client authentication will be performed for SSL connections. + * @return true if client auth will be performed, false otherwise + */ + public Boolean isNeedClientAuth(); + + /** + * Specifies whether client authentication should be performed as part of an + * SSL exchange. + * @param needClientAuth true to enable client authentication, false to disable + * @return a reference to this binding model + */ + public V1CamelNettyBindingModel setNeedClientAuth(Boolean needClientAuth); + + /** + * Password bean used to access keystore. + * + * @return Keystore password bean reference. + */ + String getPassphrase(); + + /** + * Specify keystore password. + * + * @param passphrase Password. + * @return a reference to this binding model + */ + CamelNettyBindingModel setPassphrase(String passphrase); + + /** + * Returns security provider name. By default SunX509 is used. + * + * @return Security provider name. + */ + String getSecurityProvider(); + + /** + * Specify security provider name. + * + * @param securityProvider Name of JSSE provider. + * @return a reference to this binding model + */ + CamelNettyBindingModel setSecurityProvider(String securityProvider); + + /** + * Returns keystore format. By default JKS is used. + * + * @return Keystore format. + */ + String getKeyStoreFormat(); + + /** + * Specify keystore format. + * + * @param keyStoreFormat Format of the keystore. + * @return a reference to this binding model + */ + CamelNettyBindingModel setKeyStoreFormat(String keyStoreFormat); + + /** + * Returns name of bean pointing to keystore file. + * + * @return Kestore bean name. + */ + String getKeyStoreFile(); + + /** + * Specify keystore file name. + * + * @param keyStoreFile Keystore file bean name. + * @return a reference to this binding model + */ + CamelNettyBindingModel setKeyStoreFile(String keyStoreFile); + + /** + * Returns name of bean pointing to truststore file. + * + * @return Truststore bean name. + */ + String getTrustStoreFile(); + + /** + * Specify truststore file name. + * + * @param trustStoreFile Name of truststore bean. + * @return a reference to this binding model + */ + CamelNettyBindingModel setTrustStoreFile(String trustStoreFile); + + /** + * Gets bean reference name representing SSLContextParameters. + * + * @return Bean reference name. + */ + String getSslContextParametersRef(); + + /** + * Specify SSL context parameters reference name. + * + * @param sslContextParametersRef Name of bean used to retrieve all SSL related settings. + * @return a reference to this binding model + */ + CamelNettyBindingModel setSslContextParametersRef(String sslContextParametersRef); + + /** + * Socket multiplexing. + * + * @return True if multiplexing is turned on. + */ + Boolean isReuseAddress(); + + /** + * Setting to facilitate socket multiplexing. + * + * @param reuseAddress Reuse address. + * @return a reference to this binding model + */ + CamelNettyBindingModel setReuseAddress(Boolean reuseAddress); + + /** + * Encoders list containing ChannelDownStreamHandler implementations. + * + * @return Bean name in registry + */ + String getEncoders(); + + /** + * A list of encoder to be used. You can use a String which have values separated by comma, + * and have the values be looked up in the Registry. Just remember to prefix the value with + * # so Camel knows it should look. + * + * @param encoders Name of list in registry. + * @return a reference to this binding model + */ + CamelNettyBindingModel setEncoders(String encoders); + + /** + * Encoders list containing ChannelUpStreamHandler implementations. + * + * @return Bean name in registry. + */ + String getDecoders(); + + /** + * A list of decorder to be used. You can use a String which have values separated by comma, + * and have the values be looked up in the Registry. Just remember to prefix the value with + * # so Camel knows it should lookup. + * + * @param decoders Name of list in registry. + * @return a reference to this binding model + */ + CamelNettyBindingModel setDecoders(String decoders); + + /** + * Should default codec chanin be used? + * + * @return True to let netty rely on defaults. + */ + Boolean isAllowDefaultCodec(); + + /** + * The netty component installs a default codec if both, encoder/deocder is null and textline is false. + * Setting allowDefaultCodec to false prevents the netty component from installing a default codec + * as the first element in the filter chain. + * + * @param allowDefaultCodec Turn on or off default encoder/decoder chain. + * @return a reference to this binding model + */ + CamelNettyBindingModel setAllowDefaultCodec(Boolean allowDefaultCodec); + + /** + * Number of workers to run. + * + * @return Number of workers. + */ + Integer getWorkerCount(); + + /** + * When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads*2. + * User can use this operation to override the default workerCount from Netty. + * + * @param workerCount Number of workers. + * @return a reference to this binding model + */ + CamelNettyBindingModel setWorkerCount(Integer workerCount); + + /** + * Flag to identify in-out or in only endpoint. + * + * @return True if endpoint is in-out. + */ + Boolean isSync(); + + /** + * Setting to set endpoint as one-way or request-response. + * + * @param sync Should communication be bidirectional or not? + * @return a reference to this binding model + */ + CamelNettyBindingModel setSync(Boolean sync); + + /** + * Disconnect after operation. + * + * @return True if connection should be closed after use. + */ + Boolean isDisconnect(); + + /** + * Whether or not to disconnect(close) from Netty Channel right after use. + * + * @param disconnect Close connection after operation. + * @return a reference to this binding model + */ + CamelNettyBindingModel setDisconnect(Boolean disconnect); + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyNamespace.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyNamespace.java new file mode 100644 index 000000000..5185ebcab --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Netty config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelNettyNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelNettyNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelNettyNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelNettyNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelNettyNamespace + */ + public static CamelNettyNamespace fromUri(String uri) { + return Util.fromUri(CamelNettyNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelNettyNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-netty:config", version); + } + } + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyTcpBindingModel.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyTcpBindingModel.java new file mode 100644 index 000000000..7c01df1c8 --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyTcpBindingModel.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model; + +/** + * Configuration binding for tcp gateway. + * + * @author Lukasz Dywicki + */ +public interface CamelNettyTcpBindingModel extends CamelNettyBindingModel { + + /** + * Mode of endpoint - binary or text based. + * + * @return True if text is chosen. + */ + Boolean isTextline(); + + /** + * If no codec is specified, you can use this flag to indicate a text line based codec; + * if not specified or the value is false, then Object Serialization is assumed over TCP. + * + * @param textline True to use text based communication. + * @return a reference to this binding model + */ + CamelNettyTcpBindingModel setTextline(Boolean textline); + + /** + * TCP_NO_DELAY Flag for socket. + * + * @return True if flag should be set. + */ + Boolean isTcpNoDelay(); + + /** + * Setting to improve TCP protocol performance. + * + * @param tcpNoDelay True if you willing to set TCP_NO_DELAY on socket. + * @return a reference to this binding model + */ + CamelNettyTcpBindingModel setTcpNoDelay(Boolean tcpNoDelay); + + /** + * Should socket be keept open? + * + * @return True to keep socket open. + */ + Boolean isKeepAlive(); + + /** + * Setting to ensure socket is not closed due to inactivity. + * + * @param keepAlive True to keep socket open. + * @return a reference to this binding model + */ + CamelNettyTcpBindingModel setKeepAlive(Boolean keepAlive); + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyUdpBindingModel.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyUdpBindingModel.java new file mode 100644 index 000000000..eab930e0d --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/CamelNettyUdpBindingModel.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model; + +/** + * Configuration binding for tcp gateway. + * + * @author Lukasz Dywicki + */ +public interface CamelNettyUdpBindingModel extends CamelNettyBindingModel { + + /** + * Get type of UDP transmission - broadcast or multicast. + * + * @return True if broadcast should be used. + */ + Boolean isBroadcast(); + + /** + * Setting to choose broadcast over UDP. + * + * @param broadcast Use broadcast instead of multicast + * @return a reference to this binding model + */ + CamelNettyBindingModel setBroadcast(Boolean broadcast); + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyBindingModel.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyBindingModel.java new file mode 100644 index 000000000..0a11e1219 --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyBindingModel.java @@ -0,0 +1,293 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model.v1; + +import java.net.URI; +import java.util.List; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.netty.model.CamelNettyBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of netty binding. + * + * @author Lukasz Dywicki + */ +public abstract class V1CamelNettyBindingModel extends V1BaseCamelBindingModel + implements CamelNettyBindingModel { + + /** + * Camel component prefix. + */ + public static final String NETTY = "netty"; + + private static final String HOST = "host"; + private static final String PORT = "port"; + private static final String RECEIVE_BUFFER_SIZE = "receiveBufferSize"; + private static final String SEND_BUFFER_SIZE = "sendBufferSize"; + private static final String SSL = "ssl"; + private static final String SSL_HANDLER = "sslHandler"; + private static final String NEED_CLIENT_AUTH = "needClientAuth"; + private static final String PASSPHRASE = "passphrase"; + private static final String SECURITY_PROVIDER = "securityProvider"; + private static final String KEY_STORE_FORMAT = "keyStoreFormat"; + private static final String KEY_STORE_FILE = "keyStoreFile"; + private static final String TRUST_STORE_FILE = "trustStoreFile"; + private static final String SSL_CONTEXT_PARAMETERS_REF = "sslContextParametersRef"; + private static final String REUSE_ADDRESS = "reuseAddress"; + private static final String ENCODERS = "encoders"; + private static final String DECODERS = "decoders"; + private static final String ALLOW_DEFAULT_CODEC = "allowDefaultCodec"; + private static final String WORKER_COUNT = "workerCount"; + private static final String SYNC = "sync"; + private static final String DISCONNECT = "disconnect"; + + /** + * Create a V1CamelNettyBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + protected V1CamelNettyBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + protected V1CamelNettyBindingModel(String namespace, String name) { + super(namespace, name); + + setModelChildrenOrder(HOST, PORT, RECEIVE_BUFFER_SIZE, SEND_BUFFER_SIZE, + SSL, SSL_HANDLER, NEED_CLIENT_AUTH, PASSPHRASE, SECURITY_PROVIDER, KEY_STORE_FORMAT, + KEY_STORE_FILE, TRUST_STORE_FILE, SSL_CONTEXT_PARAMETERS_REF, REUSE_ADDRESS, + ENCODERS, DECODERS, ALLOW_DEFAULT_CODEC, WORKER_COUNT, SYNC, DISCONNECT); + } + + @Override + public String getHost() { + return getConfig(HOST); + } + + @Override + public V1CamelNettyBindingModel setHost(String host) { + return setConfig(HOST, host); + } + + @Override + public Integer getPort() { + return getIntegerConfig(PORT); + } + + @Override + public V1CamelNettyBindingModel setPort(int port) { + return setConfig(PORT, port); + } + + @Override + public Long getReceiveBufferSize() { + return getLongConfig(RECEIVE_BUFFER_SIZE); + } + + @Override + public V1CamelNettyBindingModel setReceiveBufferSize(Long receiveBufferSize) { + return setConfig(RECEIVE_BUFFER_SIZE, receiveBufferSize); + } + + @Override + public Long getSendBufferSize() { + return getLongConfig(SEND_BUFFER_SIZE); + } + + @Override + public V1CamelNettyBindingModel setSendBufferSize(Long sendBufferSize) { + return setConfig(SEND_BUFFER_SIZE, sendBufferSize); + } + + @Override + public Boolean isSsl() { + return getBooleanConfig(SSL); + } + + @Override + public V1CamelNettyBindingModel setSsl(Boolean ssl) { + return setConfig(SSL, ssl); + } + + @Override + public String getSslHandler() { + return getConfig(SSL_HANDLER); + } + + @Override + public V1CamelNettyBindingModel setSslHandler(String sslHandler) { + return setConfig(SSL_HANDLER, sslHandler); + } + + @Override + public Boolean isNeedClientAuth() { + return getBooleanConfig(NEED_CLIENT_AUTH); + } + + @Override + public V1CamelNettyBindingModel setNeedClientAuth(Boolean needClientAuth) { + return setConfig(NEED_CLIENT_AUTH, needClientAuth); + } + + @Override + public String getPassphrase() { + return getConfig(PASSPHRASE); + } + + @Override + public V1CamelNettyBindingModel setPassphrase(String passphrase) { + return setConfig(PASSPHRASE, passphrase); + } + + @Override + public String getSecurityProvider() { + return getConfig(SECURITY_PROVIDER); + } + + @Override + public V1CamelNettyBindingModel setSecurityProvider(String securityProvider) { + return setConfig(SECURITY_PROVIDER, securityProvider); + } + + @Override + public String getKeyStoreFormat() { + return getConfig(KEY_STORE_FORMAT); + } + + @Override + public V1CamelNettyBindingModel setKeyStoreFormat(String keyStoreFormat) { + return setConfig(KEY_STORE_FORMAT, keyStoreFormat); + } + + @Override + public String getKeyStoreFile() { + return getConfig(KEY_STORE_FILE); + } + + @Override + public V1CamelNettyBindingModel setKeyStoreFile(String keyStoreFile) { + return setConfig(KEY_STORE_FILE, keyStoreFile); + } + + @Override + public String getTrustStoreFile() { + return getConfig(TRUST_STORE_FILE); + } + + @Override + public V1CamelNettyBindingModel setTrustStoreFile(String trustStoreFile) { + return setConfig(TRUST_STORE_FILE, trustStoreFile); + } + + @Override + public String getSslContextParametersRef() { + return getConfig(SSL_CONTEXT_PARAMETERS_REF); + } + + @Override + public V1CamelNettyBindingModel setSslContextParametersRef(String sslContextParametersRef) { + return setConfig(SSL_CONTEXT_PARAMETERS_REF, sslContextParametersRef); + } + + @Override + public Boolean isReuseAddress() { + return getBooleanConfig(REUSE_ADDRESS); + } + + @Override + public V1CamelNettyBindingModel setReuseAddress(Boolean reuseAddress) { + return setConfig(REUSE_ADDRESS, reuseAddress); + } + + @Override + public String getEncoders() { + return getConfig(ENCODERS); + } + + @Override + public V1CamelNettyBindingModel setEncoders(String encoders) { + return setConfig(ENCODERS, encoders); + } + + @Override + public String getDecoders() { + return getConfig(DECODERS); + } + + @Override + public V1CamelNettyBindingModel setDecoders(String decoders) { + return setConfig(DECODERS, decoders); + } + + @Override + public Boolean isAllowDefaultCodec() { + return getBooleanConfig(ALLOW_DEFAULT_CODEC); + } + + @Override + public V1CamelNettyBindingModel setAllowDefaultCodec(Boolean allowDefaultCodec) { + return setConfig(ALLOW_DEFAULT_CODEC, allowDefaultCodec); + } + + @Override + public Integer getWorkerCount() { + return getIntegerConfig(WORKER_COUNT); + } + + @Override + public V1CamelNettyBindingModel setWorkerCount(Integer workerCount) { + return setConfig(WORKER_COUNT, workerCount); + } + + @Override + public Boolean isSync() { + return getBooleanConfig(SYNC); + } + + @Override + public V1CamelNettyBindingModel setSync(Boolean sync) { + return setConfig(SYNC, sync); + } + + @Override + public Boolean isDisconnect() { + return getBooleanConfig(DISCONNECT); + } + + @Override + public V1CamelNettyBindingModel setDisconnect(Boolean disconnect) { + return setConfig(DISCONNECT, disconnect); + } + + protected abstract String getProtocol(); + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = NETTY + ":" + getProtocol() + "://" + getHost() + ":" + getPort(); + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, HOST, PORT); + + return URI.create(baseUri + queryStr.toString()); + } + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyModelMarshaller.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyModelMarshaller.java new file mode 100644 index 000000000..706c65d8e --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyModelMarshaller.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Netty tcp & udp model marshaller. + */ +public class V1CamelNettyModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_TCP = BindingModel.BINDING + '.' + V1CamelNettyTcpBindingModel.TCP; + private static final String BINDING_UDP = BindingModel.BINDING + '.' + V1CamelNettyUdpBindingModel.UDP; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelNettyModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_TCP.equals(name)) { + return new V1CamelNettyTcpBindingModel(config, desc); + } else if (BINDING_UDP.equals(name)) { + return new V1CamelNettyUdpBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyTcpBindingModel.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyTcpBindingModel.java new file mode 100644 index 000000000..4fb3fe123 --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyTcpBindingModel.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model.v1; + +import org.switchyard.component.camel.netty.model.CamelNettyTcpBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of netty binding. + * + * @author Lukasz Dywicki + */ +public class V1CamelNettyTcpBindingModel extends V1CamelNettyBindingModel + implements CamelNettyTcpBindingModel { + + /** + * Protocol scheme. + */ + public static final String TCP = "tcp"; + + private static final String TEXTLINE = "textline"; + private static final String TCP_NO_DELAY = "tcpNoDelay"; + private static final String KEEP_ALIVE = "keepAlive"; + + + /** + * Create a new CamelNettyTcpBindingModel. + * @param namespace namespace + */ + public V1CamelNettyTcpBindingModel(String namespace) { + super(TCP, namespace); + setModelChildrenOrder(TEXTLINE, TCP_NO_DELAY, KEEP_ALIVE); + } + + /** + * Create a V1CamelNettyBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelNettyTcpBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public Boolean isTextline() { + return getBooleanConfig(TEXTLINE); + } + + @Override + public V1CamelNettyTcpBindingModel setTextline(Boolean textline) { + return setConfig(TEXTLINE, textline); + } + + @Override + public Boolean isTcpNoDelay() { + return getBooleanConfig(TCP_NO_DELAY); + } + + @Override + public V1CamelNettyTcpBindingModel setTcpNoDelay(Boolean tcpNoDelay) { + return setConfig(TCP_NO_DELAY, tcpNoDelay); + } + + @Override + public Boolean isKeepAlive() { + return getBooleanConfig(KEEP_ALIVE); + } + + @Override + public V1CamelNettyTcpBindingModel setKeepAlive(Boolean keepAlive) { + return setConfig(KEEP_ALIVE, keepAlive); + } + + @Override + protected String getProtocol() { + return TCP; + } + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyUdpBindingModel.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyUdpBindingModel.java new file mode 100644 index 000000000..102cb78f2 --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyUdpBindingModel.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model.v1; + +import org.switchyard.component.camel.netty.model.CamelNettyUdpBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of netty udp binding. + * + * @author Lukasz Dywicki + */ +public class V1CamelNettyUdpBindingModel extends V1CamelNettyBindingModel + implements CamelNettyUdpBindingModel { + + /** + * Protocol scheme. + */ + public static final String UDP = "udp"; + + private static final String BROADCAST = "broadcast"; + + /** + * Create a new CamelNettyUdpBindingModel. + * @param namespace namespace + */ + public V1CamelNettyUdpBindingModel(String namespace) { + super(UDP, namespace); + + setModelChildrenOrder(BROADCAST); + } + + /** + * Create a V1CamelNettyBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelNettyUdpBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + protected String getProtocol() { + return UDP; + } + + @Override + public Boolean isBroadcast() { + return getBooleanConfig(BROADCAST); + } + + @Override + public V1CamelNettyUdpBindingModel setBroadcast(Boolean broadcast) { + return setConfig(BROADCAST, broadcast); + } + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/ssl/NettyBindingData.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/ssl/NettyBindingData.java new file mode 100644 index 000000000..46f4c4175 --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/ssl/NettyBindingData.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.ssl; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.camel.Message; +import org.apache.camel.component.netty.NettyConstants; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.handler.ssl.SslHandler; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.common.composer.SecurityBindingData; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.extractor.SSLSessionCredentialExtractor; + +/** + * Extension of {@link CamelBindingData} which provides {@link SecurityBindingData} + * extracted from SSLEngine used by netty. + */ +public class NettyBindingData extends CamelBindingData implements SecurityBindingData { + + /** + * Creates netty binding data with given message. + * + * @param message Camel message. + */ + public NettyBindingData(Message message) { + super(message); + } + + @Override + public Set extractCredentials() { + HashSet credentials = new HashSet(); + ChannelHandlerContext handlerContext = getMessage().getHeader(NettyConstants.NETTY_CHANNEL_HANDLER_CONTEXT, ChannelHandlerContext.class); + if (handlerContext != null) { + SslHandler sslHandler = handlerContext.getPipeline().get(SslHandler.class); + if (sslHandler != null) { + credentials.addAll(new SSLSessionCredentialExtractor().extract(sslHandler.getEngine().getSession())); + } + } + return credentials; + } + +} diff --git a/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/ssl/NettyBindingDataCreator.java b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/ssl/NettyBindingDataCreator.java new file mode 100644 index 000000000..9527bd601 --- /dev/null +++ b/components/camel/camel-netty/src/main/java/org/switchyard/component/camel/netty/ssl/NettyBindingDataCreator.java @@ -0,0 +1,29 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.ssl; + +import org.apache.camel.Message; +import org.switchyard.component.camel.common.composer.BindingDataCreator; + +/** + * Netty-specific binding data creator. + */ +public class NettyBindingDataCreator implements BindingDataCreator { + + @Override + public NettyBindingData createBindingData(Message message) { + return new NettyBindingData(message); + } + +} diff --git a/components/camel/camel-netty/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-netty/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..28c4833dd --- /dev/null +++ b/components/camel/camel-netty/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.netty.deploy.CamelNettyComponent diff --git a/components/camel/camel-netty/src/main/resources/META-INF/services/org/switchyard/component/camel/NettyEndpoint b/components/camel/camel-netty/src/main/resources/META-INF/services/org/switchyard/component/camel/NettyEndpoint new file mode 100644 index 000000000..9ff84cc05 --- /dev/null +++ b/components/camel/camel-netty/src/main/resources/META-INF/services/org/switchyard/component/camel/NettyEndpoint @@ -0,0 +1 @@ +class=org.switchyard.component.camel.netty.ssl.NettyBindingDataCreator \ No newline at end of file diff --git a/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v1/camel-netty_1_0.xsd b/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v1/camel-netty_1_0.xsd new file mode 100644 index 000000000..a51fa798b --- /dev/null +++ b/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v1/camel-netty_1_0.xsd @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v1/camel-netty_1_1.xsd b/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v1/camel-netty_1_1.xsd new file mode 100644 index 000000000..bbfee56c9 --- /dev/null +++ b/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v1/camel-netty_1_1.xsd @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v2/camel-netty_2_0.xsd b/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v2/camel-netty_2_0.xsd new file mode 100644 index 000000000..97de37e08 --- /dev/null +++ b/components/camel/camel-netty/src/main/resources/org/switchyard/component/camel/netty/model/v2/camel-netty_2_0.xsd @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-netty/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-netty/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..9f9ee6c7f --- /dev/null +++ b/components/camel/camel-netty/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_netty_1_0.section=urn:switchyard-component-camel-netty:config +camel_netty_1_0.version=1.0 +camel_netty_1_0.namespace=urn:switchyard-component-camel-netty:config:1.0 +camel_netty_1_0.schema=camel-netty_1_0.xsd +camel_netty_1_0.location=/org/switchyard/component/camel/netty/model/v1 +camel_netty_1_0.marshaller=org.switchyard.component.camel.netty.model.v1.V1CamelNettyModelMarshaller + +camel_netty_1_1.section=urn:switchyard-component-camel-netty:config +camel_netty_1_1.version=1.1 +camel_netty_1_1.namespace=urn:switchyard-component-camel-netty:config:1.1 +camel_netty_1_1.schema=camel-netty_1_1.xsd +camel_netty_1_1.location=/org/switchyard/component/camel/netty/model/v1 +camel_netty_1_1.marshaller=org.switchyard.component.camel.netty.model.v1.V1CamelNettyModelMarshaller + +camel_netty_2_0.section=urn:switchyard-component-camel-netty:config +camel_netty_2_0.version=2.0 +camel_netty_2_0.namespace=urn:switchyard-component-camel-netty:config:2.0 +camel_netty_2_0.schema=camel-netty_2_0.xsd +camel_netty_2_0.location=/org/switchyard/component/camel/netty/model/v2 +camel_netty_2_0.marshaller=org.switchyard.component.camel.netty.model.v1.V1CamelNettyModelMarshaller diff --git a/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/CamelNettyTcpBindingSslContextParameterRefModelTest.java b/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/CamelNettyTcpBindingSslContextParameterRefModelTest.java new file mode 100644 index 000000000..2887d7c6e --- /dev/null +++ b/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/CamelNettyTcpBindingSslContextParameterRefModelTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.netty.NettyEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.netty.model.CamelNettyNamespace; + +/** + * Test for {@link V1CamelNettyBindingModel} checking if it works with sslContextParametersRef. + * + * @author Lukasz Dywicki + */ +public class CamelNettyTcpBindingSslContextParameterRefModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-netty-tcp-binding-ssl-config-beans.xml"; + + private static final String HOST = "google.com"; + private static final Integer PORT = 10230; + private static final Boolean SSL = true; + private static final String SSL_CONTEXT_PARAMETERS_REF = "#sslConfig"; + + private static final String CAMEL_URI = "netty:tcp://google.com:10230?" + + "ssl=true&sslContextParametersRef=#sslConfig"; + + public CamelNettyTcpBindingSslContextParameterRefModelTest() { + super(NettyEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelNettyTcpBindingModel createTestModel() { + return (V1CamelNettyTcpBindingModel) new V1CamelNettyTcpBindingModel(CamelNettyNamespace.V_1_0.uri()) + .setHost(HOST) + .setPort(PORT) + .setSsl(SSL) + .setSslContextParametersRef(SSL_CONTEXT_PARAMETERS_REF); + } + + @Override + protected void createModelAssertions(V1CamelNettyTcpBindingModel model) { + assertEquals(HOST, model.getHost()); + assertEquals(PORT, model.getPort()); + assertEquals(SSL, model.isSsl()); + assertEquals(SSL_CONTEXT_PARAMETERS_REF, model.getSslContextParametersRef()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } +} \ No newline at end of file diff --git a/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyTcpBindingModelTest.java b/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyTcpBindingModelTest.java new file mode 100644 index 000000000..6d4316083 --- /dev/null +++ b/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyTcpBindingModelTest.java @@ -0,0 +1,118 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.netty.NettyEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.netty.model.CamelNettyNamespace; + +/** + * Test for {@link V1CamelNettyBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelNettyTcpBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-netty-tcp-binding-beans.xml"; + + private static final String HOST = "google.com"; + private static final Integer PORT = 10230; + private static final Long RECEIVE_BUFFER_SIZE = 1024l; + private static final Long SEND_BUFFER_SIZE = 128l; + private static final Boolean SSL = true; + private static final String SSL_HANDLER = "#myCustomHandler"; + private static final String PASSPHRASE = "camelRider"; + private static final String SECURITY_PROVIDER = "BC"; + private static final String KEY_STORE_FORMAT = "PCKS12"; + private static final String KEY_STORE_FILE = "#ks"; + private static final String TRUST_STORE_FILE = "#ts"; + private static final Boolean REUSE_ADDRESS = true; + private static final Boolean ALLOW_DEFAULT_CODEC = false; + private static final Integer WORKER_COUNT = 10; + private static final Boolean SYNC = false; + private static final Boolean NEED_CLIENT_AUTH = true; + private static final Boolean DISCONNECT = true; + private static final Boolean TEXTLINE = false; + private static final Boolean TCP_NO_DELAY = true; + private static final Boolean KEEP_ALIVE = false; + + private static final String CAMEL_URI = "netty:tcp://google.com:10230?" + + "receiveBufferSize=1024&sendBufferSize=128&reuseAddress=true&allowDefaultCodec=false&" + + "workerCount=10&sync=false&disconnect=true&textline=false&tcpNoDelay=true&" + + "keepAlive=false&keyStoreFormat=PCKS12&passphrase=camelRider&keyStoreFile=#ks&trustStoreFile=#ts&" + + "ssl=true&sslHandler=#myCustomHandler&needClientAuth=true&securityProvider=BC"; + + public V1CamelNettyTcpBindingModelTest() { + super(NettyEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelNettyTcpBindingModel createTestModel() { + return ((V1CamelNettyTcpBindingModel) new V1CamelNettyTcpBindingModel(CamelNettyNamespace.V_1_1.uri()) + .setHost(HOST) + .setPort(PORT) + .setReceiveBufferSize(RECEIVE_BUFFER_SIZE) + .setSendBufferSize(SEND_BUFFER_SIZE) + .setSsl(SSL) + .setSslHandler(SSL_HANDLER) + .setNeedClientAuth(NEED_CLIENT_AUTH) + .setPassphrase(PASSPHRASE) + .setSecurityProvider(SECURITY_PROVIDER) + .setKeyStoreFormat(KEY_STORE_FORMAT) + .setKeyStoreFile(KEY_STORE_FILE) + .setTrustStoreFile(TRUST_STORE_FILE) + .setReuseAddress(REUSE_ADDRESS) + .setAllowDefaultCodec(ALLOW_DEFAULT_CODEC) + .setWorkerCount(WORKER_COUNT) + .setSync(SYNC) + .setDisconnect(DISCONNECT)) + .setTextline(TEXTLINE) + .setTcpNoDelay(TCP_NO_DELAY) + .setKeepAlive(KEEP_ALIVE) + ; + } + + @Override + protected void createModelAssertions(V1CamelNettyTcpBindingModel model) { + assertEquals(HOST, model.getHost()); + assertEquals(PORT, model.getPort()); + assertEquals(RECEIVE_BUFFER_SIZE, model.getReceiveBufferSize()); + assertEquals(SEND_BUFFER_SIZE, model.getSendBufferSize()); + assertEquals(SSL, model.isSsl()); + assertEquals(SSL_HANDLER, model.getSslHandler()); + assertEquals(NEED_CLIENT_AUTH, model.isNeedClientAuth()); + assertEquals(SECURITY_PROVIDER, model.getSecurityProvider()); + assertEquals(PASSPHRASE, model.getPassphrase()); + assertEquals(KEY_STORE_FORMAT, model.getKeyStoreFormat()); + assertEquals(KEY_STORE_FILE, model.getKeyStoreFile()); + assertEquals(TRUST_STORE_FILE, model.getTrustStoreFile()); + assertEquals(REUSE_ADDRESS, model.isReuseAddress()); + assertEquals(ALLOW_DEFAULT_CODEC, model.isAllowDefaultCodec()); + assertEquals(WORKER_COUNT, model.getWorkerCount()); + assertEquals(SYNC, model.isSync()); + assertEquals(DISCONNECT, model.isDisconnect()); + assertEquals(TEXTLINE, model.isTextline()); + assertEquals(TCP_NO_DELAY, model.isTcpNoDelay()); + assertEquals(KEEP_ALIVE, model.isKeepAlive()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } +} \ No newline at end of file diff --git a/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyUdpBindingModelTest.java b/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyUdpBindingModelTest.java new file mode 100644 index 000000000..7ab9e06b5 --- /dev/null +++ b/components/camel/camel-netty/src/test/java/org/switchyard/component/camel/netty/model/v1/V1CamelNettyUdpBindingModelTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.netty.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.netty.NettyEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.netty.model.CamelNettyNamespace; + +/** + * Test for {@link V1CamelNettyBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelNettyUdpBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-netty-udp-binding-beans.xml"; + + private static final String HOST = "google.com"; + private static final Integer PORT = 10231; + private static final Boolean BROADCAST = true; + + private static final String CAMEL_URI = "netty:udp://google.com:10231?broadcast=true"; + + public V1CamelNettyUdpBindingModelTest() { + super(NettyEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelNettyUdpBindingModel createTestModel() { + return ((V1CamelNettyUdpBindingModel) new V1CamelNettyUdpBindingModel(CamelNettyNamespace.V_1_0.uri()) + .setHost(HOST) + .setPort(PORT)) + .setBroadcast(BROADCAST); + } + + @Override + protected void createModelAssertions(V1CamelNettyUdpBindingModel model) { + assertEquals(HOST, model.getHost()); + assertEquals(PORT, model.getPort()); + assertEquals(BROADCAST, model.isBroadcast()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } +} \ No newline at end of file diff --git a/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-tcp-binding-beans.xml b/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-tcp-binding-beans.xml new file mode 100644 index 000000000..dba734c4a --- /dev/null +++ b/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-tcp-binding-beans.xml @@ -0,0 +1,46 @@ + + + + + + + + google.com + 10230 + 1024 + 128 + true + #myCustomHandler + true + camelRider + BC + PCKS12 + #ks + #ts + true + false + 10 + false + true + false + true + false + + + + + diff --git a/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-tcp-binding-ssl-config-beans.xml b/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-tcp-binding-ssl-config-beans.xml new file mode 100644 index 000000000..80ec80a7c --- /dev/null +++ b/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-tcp-binding-ssl-config-beans.xml @@ -0,0 +1,30 @@ + + + + + + + + google.com + 10230 + true + #sslConfig + + + + + diff --git a/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-udp-binding-beans.xml b/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-udp-binding-beans.xml new file mode 100644 index 000000000..23ac26518 --- /dev/null +++ b/components/camel/camel-netty/src/test/resources/v1/switchyard-netty-udp-binding-beans.xml @@ -0,0 +1,29 @@ + + + + + + + + google.com + 10231 + true + + + + + diff --git a/components/camel/camel-quartz/pom.xml b/components/camel/camel-quartz/pom.xml new file mode 100644 index 000000000..6af39f267 --- /dev/null +++ b/components/camel/camel-quartz/pom.xml @@ -0,0 +1,71 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-quartz + bundle + SwitchYard: Camel Component :: Quartz Binding + http://switchyard.org + + + org.switchyard.component.camel.quartz.* + + + org.apache.camel.component.quartz, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-core + + + org.apache.camel + camel-quartz + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/deploy/CamelQuartzActivator.java b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/deploy/CamelQuartzActivator.java new file mode 100644 index 000000000..d4ba99c4a --- /dev/null +++ b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/deploy/CamelQuartzActivator.java @@ -0,0 +1,75 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.deploy; + +import java.io.IOException; +import java.net.URL; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.camel.component.quartz.QuartzComponent; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.type.Classes; +import org.switchyard.component.camel.common.deploy.BaseBindingActivator; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.deploy.ServiceHandler; + +/** + * Camel quartz activator. + */ +public class CamelQuartzActivator extends BaseBindingActivator { + + /** + * Creates new activator instance. + * + * @param context Camel context. + * @param types Activation types. + */ + public CamelQuartzActivator(SwitchYardCamelContext context, String[] types) { + super(context, types); + } + + @Override + public ServiceHandler activateBinding(QName serviceName, BindingModel config) { + // SWITCHYARD-1970 - custom quartz.properties support + probeQuartzProperties(); + + return super.activateBinding(serviceName, config); + } + + private void probeQuartzProperties() { + try { + URL props = Classes.getResource("org/quartz/quartz.properties"); + if (props == null) { + return; + } + } catch (IOException e) { + return; + } + + Set components = getCamelContext().getRegistry().findByType(QuartzComponent.class); + if (components.isEmpty()) { + QuartzComponent quartz = getCamelContext().getInjector().newInstance(QuartzComponent.class); + getCamelContext().getWritebleRegistry().put("quartz", quartz); + components.add(quartz); + } + for (QuartzComponent quartz : components) { + if (quartz.getPropertiesFile() == null) { + quartz.setPropertiesFile("org/quartz/quartz.properties"); + } + } + } + +} diff --git a/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/deploy/CamelQuartzComponent.java b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/deploy/CamelQuartzComponent.java new file mode 100644 index 000000000..51fc160a2 --- /dev/null +++ b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/deploy/CamelQuartzComponent.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.deploy; + +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.deploy.BaseBindingActivator; +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.quartz.model.v2.V2CamelQuartzBindingModel; + +/** + * Quartz binding component. + */ +public class CamelQuartzComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelQuartzComponent() { + super("CamelQuartzComponent", V2CamelQuartzBindingModel.QUARTZ); + } + + @Override + protected BaseBindingActivator createActivator(SwitchYardCamelContext context, String... types) { + return new CamelQuartzActivator(context, types); + } + +} diff --git a/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/CamelQuartzBindingModel.java b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/CamelQuartzBindingModel.java new file mode 100644 index 000000000..f1c4a6912 --- /dev/null +++ b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/CamelQuartzBindingModel.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.model; + +import java.util.Date; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Binding model for quartz endpoint. + * + * @author Lukasz Dywicki + */ +public interface CamelQuartzBindingModel extends CamelBindingModel { + + /** + * Binding / camel endpoint prefix. + */ + String QUARTZ = "quartz"; + + /** + * Returns the name of the timer. + * @return timer name + */ + String getTimerName(); + + /** + * Sets the name of the timer. + * @param name timer name + * @return a reference to this config model + */ + CamelQuartzBindingModel setTimerName(String name); + + /** + * Returns the cron expression for this quartz endpoint. + * @return cron expression + */ + String getCron(); + + /** + * Sets the cron expression for this quartz endpoint. + * @param cron expression + * @return a reference to this config model + */ + CamelQuartzBindingModel setCron(String cron); + + /** + * Whether the quartz schedule is stateful. + * @return true if the endpoint is stateful, false otherwise + */ + Boolean isStateful(); + + /** + * Specifies whether the schedule should be stateful. + * @param stateful true for stateful, false for stateless + * @return a reference to this config model + */ + CamelQuartzBindingModel setStateful(Boolean stateful); + + /** + * Returns the schedule start time. + * @return Date corresponding to the schedule start time. + */ + Date getStartTime(); + + /** + * Sets the schedule start time. + * @param startTime Date corresponding to the schedule start time. + * @return a reference to this config model + */ + CamelQuartzBindingModel setStartTime(Date startTime); + + /** + * Returns the schedule end time. + * @return Date corresponding to the schedule end time. + */ + Date getEndTime(); + + /** + * Sets the schedule end time. + * @param endTime Date corresponding to the schedule end time. + * @return a reference to this config model + */ + CamelQuartzBindingModel setEndTime(Date endTime); + + /** + * Returns the schedule timezone. + * @return timeZone corresponding to the schedule timezone. + */ + String getTimeZone(); + + /** + * Sets the schedule timezone. + * @param timeZone String corresponding to the schedule timezone. + * @return a reference to this config model + */ + CamelQuartzBindingModel setTimeZone(String timeZone); + + /** + * Returns the schedule repeat count. + * @return repeatCount Integer corresponding to the schedule repeat count. + */ + Integer getRepeatCount(); + + /** + * Sets the schedule repeat interval. + * @param repeatCount Integer corresponding to the schedule repeat count. + * @return a reference to this config model + */ + CamelQuartzBindingModel setRepeatCount(Integer repeatCount); + + /** + * Returns the schedule repeat interval. + * @return repeatInterval Long corresponding to the schedule repeat interval. + */ + Long getRepeatInterval(); + + /** + * Sets the repeat interval. + * @param repeatInterval Long corresponding to the schedule repeat interval. + * @return a reference to this config model + */ + CamelQuartzBindingModel setRepeatInterval(Long repeatInterval); +} diff --git a/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/CamelQuartzNamespace.java b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/CamelQuartzNamespace.java new file mode 100644 index 000000000..d924879f1 --- /dev/null +++ b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/CamelQuartzNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Quartz config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelQuartzNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelQuartzNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelQuartzNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelQuartzNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelQuartzNamespace + */ + public static CamelQuartzNamespace fromUri(String uri) { + return Util.fromUri(CamelQuartzNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelQuartzNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-quartz:config", version); + } + } + +} diff --git a/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzBindingModel.java b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzBindingModel.java new file mode 100644 index 000000000..23f101ee5 --- /dev/null +++ b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzBindingModel.java @@ -0,0 +1,166 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.model.v1; + +import java.net.URI; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.apache.camel.util.UnsafeUriCharactersEncoder; +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.quartz.model.CamelQuartzBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Configuration binding for quartz. + * + * @author Lukasz Dywicki + */ +public class V1CamelQuartzBindingModel extends V1BaseCamelBindingModel + implements CamelQuartzBindingModel { + + private static final String NAME = "name"; + private static final String CRON = "cron"; + private static final String STATEFUL = "stateful"; + private static final String START_TIME = "trigger.startTime"; + private static final String END_TIME = "trigger.endTime"; + private static final String TIMEZONE = "trigger.timeZone"; + private static final String REPEAT_COUNT = "trigger.repeatCount"; + private static final String REPEAT_INTERVAL = "trigger.repeartInterval"; + + // Used for dateTime fields + private static final String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss"; + + /** + * Create a new CamelQuartzBindingModel. + * @param namespace namespace + */ + public V1CamelQuartzBindingModel(String namespace) { + super(QUARTZ, namespace); + + setModelChildrenOrder(NAME, CRON, STATEFUL, START_TIME, END_TIME, TIMEZONE); + } + + /** + * Create a V1CamelQuartzBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelQuartzBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getTimerName() { + return getConfig(NAME); + } + + @Override + public V1CamelQuartzBindingModel setTimerName(String name) { + return setConfig(NAME, name); + } + + @Override + public String getCron() { + return getConfig(CRON); + } + + @Override + public V1CamelQuartzBindingModel setCron(String cron) { + return setConfig(CRON, cron); + } + + @Override + public Boolean isStateful() { + return getBooleanConfig(STATEFUL); + } + + @Override + public V1CamelQuartzBindingModel setStateful(Boolean stateful) { + return setConfig(STATEFUL, stateful); + } + + @Override + public Date getStartTime() { + DateFormat startTimeFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return getDateConfig(START_TIME, startTimeFormat); + } + + @Override + public V1CamelQuartzBindingModel setStartTime(Date startTime) { + DateFormat startTimeForamt = new SimpleDateFormat(DATE_FORMAT_STRING); + return setConfig(START_TIME, startTimeForamt.format(startTime)); + } + + @Override + public Date getEndTime() { + DateFormat endTimeFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return getDateConfig(END_TIME, endTimeFormat); + } + + @Override + public V1CamelQuartzBindingModel setEndTime(Date endTime) { + DateFormat endTimeFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return setConfig(END_TIME, endTimeFormat.format(endTime)); + } + + @Override + public String getTimeZone() { + return getConfig(TIMEZONE); + } + + @Override + public V1CamelQuartzBindingModel setTimeZone(String timeZone) { + return setConfig(TIMEZONE, timeZone); + } + + @Override + public Integer getRepeatCount() { + return getIntegerConfig(REPEAT_COUNT); + } + + @Override + public V1CamelQuartzBindingModel setRepeatCount(Integer repeatCount) { + return setConfig(REPEAT_COUNT, repeatCount); + } + + @Override + public Long getRepeatInterval() { + return getLongConfig(REPEAT_INTERVAL); + } + + @Override + public V1CamelQuartzBindingModel setRepeatInterval(Long repeatInterval) { + return setConfig(REPEAT_INTERVAL, repeatInterval); + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = QUARTZ + "://" + getTimerName(); + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, NAME); + + return URI.create(UnsafeUriCharactersEncoder.encode(baseUri + queryStr.toString())); + } + +} diff --git a/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzModelMarshaller.java b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzModelMarshaller.java new file mode 100644 index 000000000..6f8f23ccc --- /dev/null +++ b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Camel quartz v1 model marshaler. + */ +public class V1CamelQuartzModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_QUARTZ = BindingModel.BINDING + '.' + V1CamelQuartzBindingModel.QUARTZ; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelQuartzModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_QUARTZ.equals(name)) { + return new V1CamelQuartzBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzBindingModel.java b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzBindingModel.java new file mode 100644 index 000000000..5e7d54a22 --- /dev/null +++ b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzBindingModel.java @@ -0,0 +1,166 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.model.v2; + +import java.net.URI; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.apache.camel.util.UnsafeUriCharactersEncoder; +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.quartz.model.CamelQuartzBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Configuration binding for quartz. + * + * @author Lukasz Dywicki + */ +public class V2CamelQuartzBindingModel extends V1BaseCamelBindingModel + implements CamelQuartzBindingModel { + + private static final String NAME = "name"; + private static final String CRON = "cron"; + private static final String STATEFUL = "stateful"; + private static final String START_TIME = "trigger.startTime"; + private static final String END_TIME = "trigger.endTime"; + private static final String TIMEZONE = "trigger.timeZone"; + private static final String REPEAT_COUNT = "trigger.repeatCount"; + private static final String REPEAT_INTERVAL = "trigger.repeatInterval"; + + // Used for dateTime fields + private static final String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss"; + + /** + * Create a new CamelQuartzBindingModel. + * @param namespace namespace + */ + public V2CamelQuartzBindingModel(String namespace) { + super(QUARTZ, namespace); + + setModelChildrenOrder(NAME, CRON, REPEAT_COUNT, REPEAT_INTERVAL, STATEFUL, START_TIME, END_TIME, TIMEZONE); + } + + /** + * Create a V1CamelQuartzBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V2CamelQuartzBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getTimerName() { + return getConfig(NAME); + } + + @Override + public V2CamelQuartzBindingModel setTimerName(String name) { + return setConfig(NAME, name); + } + + @Override + public String getCron() { + return getConfig(CRON); + } + + @Override + public V2CamelQuartzBindingModel setCron(String cron) { + return setConfig(CRON, cron); + } + + @Override + public Boolean isStateful() { + return getBooleanConfig(STATEFUL); + } + + @Override + public V2CamelQuartzBindingModel setStateful(Boolean stateful) { + return setConfig(STATEFUL, stateful); + } + + @Override + public Date getStartTime() { + DateFormat startTimeFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return getDateConfig(START_TIME, startTimeFormat); + } + + @Override + public V2CamelQuartzBindingModel setStartTime(Date startTime) { + DateFormat startTimeForamt = new SimpleDateFormat(DATE_FORMAT_STRING); + return setConfig(START_TIME, startTimeForamt.format(startTime)); + } + + @Override + public Date getEndTime() { + DateFormat endTimeFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return getDateConfig(END_TIME, endTimeFormat); + } + + @Override + public V2CamelQuartzBindingModel setEndTime(Date endTime) { + DateFormat endTimeFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return setConfig(END_TIME, endTimeFormat.format(endTime)); + } + + @Override + public String getTimeZone() { + return getConfig(TIMEZONE); + } + + @Override + public V2CamelQuartzBindingModel setTimeZone(String timeZone) { + return setConfig(TIMEZONE, timeZone); + } + + @Override + public Integer getRepeatCount() { + return getIntegerConfig(REPEAT_COUNT); + } + + @Override + public V2CamelQuartzBindingModel setRepeatCount(Integer repeatCount) { + return setConfig(REPEAT_COUNT, repeatCount); + } + + @Override + public Long getRepeatInterval() { + return getLongConfig(REPEAT_INTERVAL); + } + + @Override + public V2CamelQuartzBindingModel setRepeatInterval(Long repeatInterval) { + return setConfig(REPEAT_INTERVAL, repeatInterval); + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = QUARTZ + "://" + getTimerName(); + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, NAME); + + return URI.create(UnsafeUriCharactersEncoder.encode(baseUri + queryStr.toString())); + } + +} diff --git a/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzModelMarshaller.java b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzModelMarshaller.java new file mode 100644 index 000000000..dc9a6520d --- /dev/null +++ b/components/camel/camel-quartz/src/main/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.model.v2; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Camel quartz v2 model marshaler. + */ +public class V2CamelQuartzModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_QUARTZ = BindingModel.BINDING + '.' + V2CamelQuartzBindingModel.QUARTZ; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V2CamelQuartzModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_QUARTZ.equals(name)) { + return new V2CamelQuartzBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-quartz/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-quartz/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..4f97b37f3 --- /dev/null +++ b/components/camel/camel-quartz/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.quartz.deploy.CamelQuartzComponent diff --git a/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v1/camel-quartz_1_0.xsd b/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v1/camel-quartz_1_0.xsd new file mode 100644 index 000000000..cc4fc81f3 --- /dev/null +++ b/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v1/camel-quartz_1_0.xsd @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v1/camel-quartz_1_1.xsd b/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v1/camel-quartz_1_1.xsd new file mode 100644 index 000000000..1e32b43ec --- /dev/null +++ b/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v1/camel-quartz_1_1.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v2/camel-quartz_2_0.xml b/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v2/camel-quartz_2_0.xml new file mode 100644 index 000000000..c2fa0b04f --- /dev/null +++ b/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v2/camel-quartz_2_0.xml @@ -0,0 +1,4 @@ + + + tns:name + diff --git a/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v2/camel-quartz_2_0.xsd b/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v2/camel-quartz_2_0.xsd new file mode 100644 index 000000000..87e648a56 --- /dev/null +++ b/components/camel/camel-quartz/src/main/resources/org/switchyard/component/camel/quartz/model/v2/camel-quartz_2_0.xsd @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-quartz/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-quartz/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..b63b44808 --- /dev/null +++ b/components/camel/camel-quartz/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_quartz_1_0.section=urn:switchyard-component-camel-quartz:config +camel_quartz_1_0.version=1.0 +camel_quartz_1_0.namespace=urn:switchyard-component-camel-quartz:config:1.0 +camel_quartz_1_0.schema=camel-quartz_1_0.xsd +camel_quartz_1_0.location=/org/switchyard/component/camel/quartz/model/v1/ +camel_quartz_1_0.marshaller=org.switchyard.component.camel.quartz.model.v1.V1CamelQuartzModelMarshaller + +camel_quartz_1_1.section=urn:switchyard-component-camel-quartz:config +camel_quartz_1_1.version=1.1 +camel_quartz_1_1.namespace=urn:switchyard-component-camel-quartz:config:1.1 +camel_quartz_1_1.schema=camel-quartz_1_1.xsd +camel_quartz_1_1.location=/org/switchyard/component/camel/quartz/model/v1/ +camel_quartz_1_1.marshaller=org.switchyard.component.camel.quartz.model.v1.V1CamelQuartzModelMarshaller + +camel_quartz_2_0.section=urn:switchyard-component-camel-quartz:config +camel_quartz_2_0.version=2.0 +camel_quartz_2_0.namespace=urn:switchyard-component-camel-quartz:config:2.0 +camel_quartz_2_0.schema=camel-quartz_2_0.xsd +camel_quartz_2_0.location=/org/switchyard/component/camel/quartz/model/v2/ +camel_quartz_2_0.marshaller=org.switchyard.component.camel.quartz.model.v2.V2CamelQuartzModelMarshaller diff --git a/components/camel/camel-quartz/src/test/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzBindingModelTest.java b/components/camel/camel-quartz/src/test/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzBindingModelTest.java new file mode 100644 index 000000000..dedc197dd --- /dev/null +++ b/components/camel/camel-quartz/src/test/java/org/switchyard/component/camel/quartz/model/v1/V1CamelQuartzBindingModelTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.model.v1; + +import static junit.framework.Assert.assertEquals; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; + +import org.apache.camel.component.quartz.QuartzEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.quartz.model.CamelQuartzNamespace; + +/** + * Test for {@link V1CamelQuartzBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelQuartzBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-quartz-binding-beans.xml"; + + // Used for dateTime fields + private static DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + + private static final String NAME = "MyJob"; + private static final String CRON = "0 0 12 * * ?"; + private static final Boolean STATEFUL = true; + private static Date START_TIME; + private static Date END_TIME; + private static String TIMEZONE; + + private static final String CAMEL_URI = "quartz://MyJob?cron=0 0 12 * * ?&stateful=true" + + "&trigger.startTime=2011-01-01T12:00:00&trigger.endTime=2011-01-01T12:00:00&trigger.timeZone=America/New_York"; + + static { + try { + START_TIME = _dateFormat.parse("2011-01-01T12:00:00"); + END_TIME = _dateFormat.parse("2011-01-01T12:00:00"); + TIMEZONE = "America/New_York"; + } catch (Exception e) { /* ignore */ } + } + + public V1CamelQuartzBindingModelTest() { + super(QuartzEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelQuartzBindingModel createTestModel() { + final V1CamelQuartzBindingModel model = new V1CamelQuartzBindingModel(CamelQuartzNamespace.V_1_1.uri()); + model.setAdditionalUriParameters(createAdditionalUriParametersModel(CamelQuartzNamespace.V_1_1.uri(), Collections.singletonMap("trigger.timeZone", "GMT"))); + return (V1CamelQuartzBindingModel) model + .setTimerName(NAME) + .setCron(CRON) + .setStateful(STATEFUL) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setTimeZone(TIMEZONE); + } + + @Override + protected void createModelAssertions(V1CamelQuartzBindingModel model) { + assertEquals(NAME, model.getTimerName()); + assertEquals(CRON, model.getCron()); + assertEquals(STATEFUL, model.isStateful()); + assertEquals(START_TIME, model.getStartTime()); + assertEquals(END_TIME, model.getEndTime()); + assertEquals(TIMEZONE, model.getTimeZone()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-quartz/src/test/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzBindingModelTest.java b/components/camel/camel-quartz/src/test/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzBindingModelTest.java new file mode 100644 index 000000000..e55704af3 --- /dev/null +++ b/components/camel/camel-quartz/src/test/java/org/switchyard/component/camel/quartz/model/v2/V2CamelQuartzBindingModelTest.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.quartz.model.v2; + +import static junit.framework.Assert.assertEquals; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; + +import org.apache.camel.component.quartz.QuartzEndpoint; +import org.junit.Test; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.quartz.model.CamelQuartzNamespace; + +/** + * Test for {@link V2CamelQuartzBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V2CamelQuartzBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-quartz-binding-beans.xml"; + + // Used for dateTime fields + private static DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + + private static final String NAME = "MyJob"; + private static final String CRON = "0 0 12 * * ?"; + private static final Integer REPEAT_COUNT = new Integer(3); + private static final Long REPEAT_INTERVAL = new Long(100000); + private static final Boolean STATEFUL = true; + private static Date START_TIME; + private static Date END_TIME; + private static String TIMEZONE; + + private static final String CAMEL_URI = "quartz://MyJob?cron=0 0 12 * * ?&stateful=true" + + "&trigger.startTime=2011-01-01T12:00:00&trigger.endTime=2011-01-01T12:00:00&trigger.timeZone=America/New_York"; + + static { + try { + START_TIME = _dateFormat.parse("2011-01-01T12:00:00"); + END_TIME = _dateFormat.parse("2011-01-01T12:00:00"); + TIMEZONE = "America/New_York"; + } catch (Exception e) { /* ignore */ } + } + + public V2CamelQuartzBindingModelTest() { + super(QuartzEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelQuartzBindingModel createTestModel() { + final V2CamelQuartzBindingModel model = new V2CamelQuartzBindingModel(CamelQuartzNamespace.V_2_0.uri()); + model.setAdditionalUriParameters(createAdditionalUriParametersModel(CamelQuartzNamespace.V_2_0.uri(), Collections.singletonMap("trigger.timeZone", "GMT"))); + return (V2CamelQuartzBindingModel) model + .setTimerName(NAME) + .setCron(CRON) + .setStateful(STATEFUL) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setTimeZone(TIMEZONE); + } + + protected V2CamelQuartzBindingModel createAlternateTestModel() { + final V2CamelQuartzBindingModel model = new V2CamelQuartzBindingModel(CamelQuartzNamespace.V_2_0.uri()); + model.setAdditionalUriParameters(createAdditionalUriParametersModel(CamelQuartzNamespace.V_2_0.uri(), Collections.singletonMap("trigger.timeZone", "GMT"))); + return (V2CamelQuartzBindingModel) model + .setTimerName(NAME) + .setRepeatCount(REPEAT_COUNT) + .setRepeatInterval(REPEAT_INTERVAL) + .setStateful(STATEFUL) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setTimeZone(TIMEZONE); + } + + /** + * Verify correctness of model created by test. + * + * @throws Exception If model can not be read + */ + @Test + public void testAlternateModelIsValid() throws Exception { + validModel(createAlternateTestModel()); + } + + /** + * Verify assertions with model binding. + */ + @Test + public void testModelAssertionsFromAlternateModel() { + createAlternateModelAssertions(createAlternateTestModel()); + } + + @Override + protected void createModelAssertions(V2CamelQuartzBindingModel model) { + assertEquals(NAME, model.getTimerName()); + assertEquals(CRON, model.getCron()); + assertEquals(STATEFUL, model.isStateful()); + assertEquals(START_TIME, model.getStartTime()); + assertEquals(END_TIME, model.getEndTime()); + assertEquals(TIMEZONE, model.getTimeZone()); + } + + protected void createAlternateModelAssertions(V2CamelQuartzBindingModel model) { + assertEquals(NAME, model.getTimerName()); + assertEquals(REPEAT_INTERVAL, model.getRepeatInterval()); + assertEquals(REPEAT_COUNT, model.getRepeatCount()); + assertEquals(STATEFUL, model.isStateful()); + assertEquals(START_TIME, model.getStartTime()); + assertEquals(END_TIME, model.getEndTime()); + assertEquals(TIMEZONE, model.getTimeZone()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-quartz/src/test/resources/v1/switchyard-quartz-binding-beans.xml b/components/camel/camel-quartz/src/test/resources/v1/switchyard-quartz-binding-beans.xml new file mode 100644 index 000000000..d01ea54ab --- /dev/null +++ b/components/camel/camel-quartz/src/test/resources/v1/switchyard-quartz-binding-beans.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + MyJob + 0 0 12 * * ? + true + 2011-01-01T12:00:00 + 2011-01-01T12:00:00 + America/New_York + + + + + diff --git a/components/camel/camel-quartz/src/test/resources/v2/switchyard-quartz-binding-beans.xml b/components/camel/camel-quartz/src/test/resources/v2/switchyard-quartz-binding-beans.xml new file mode 100644 index 000000000..dbbb1f1ff --- /dev/null +++ b/components/camel/camel-quartz/src/test/resources/v2/switchyard-quartz-binding-beans.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + MyJob + 0 0 12 * * ? + true + 2011-01-01T12:00:00 + 2011-01-01T12:00:00 + America/New_York + + + + + diff --git a/components/camel/camel-rss/pom.xml b/components/camel/camel-rss/pom.xml new file mode 100644 index 000000000..84684300d --- /dev/null +++ b/components/camel/camel-rss/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-rss + bundle + SwitchYard: Camel Component :: RSS Binding + http://switchyard.org + + + org.switchyard.component.camel.rss.* + + + org.apache.camel.component.rss, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-rss + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/deploy/CamelRSSComponent.java b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/deploy/CamelRSSComponent.java new file mode 100644 index 000000000..b210f25dc --- /dev/null +++ b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/deploy/CamelRSSComponent.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.rss.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.rss.model.v2.V2CamelRSSBindingModel; + +/** + * RSS binding component. + */ +public class CamelRSSComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelRSSComponent() { + super("CamelRSSComponent", V2CamelRSSBindingModel.RSS); + } + +} diff --git a/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/CamelRSSBindingModel.java b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/CamelRSSBindingModel.java new file mode 100644 index 000000000..e46908e48 --- /dev/null +++ b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/CamelRSSBindingModel.java @@ -0,0 +1,134 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.rss.model; + +import java.net.URI; +import java.util.Date; + +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.common.model.consumer.CamelScheduledPollConsumer; + +/** + * Represents the configuration settings for an RSS endpoint in Camel. The + * RSS component only supports consumer processing, so this binding can only + * be used on a service (not a reference). + */ +public interface CamelRSSBindingModel extends CamelBindingModel { + + /** + * The RSS feed URI which will be polled. + * @return the feed URI or null if it has not been specified + */ + URI getFeedURI(); + + /** + * Set the RSS feed URI. + * @param uri feed URI + * @return a reference to this RSS binding model + */ + CamelRSSBindingModel setFeedURI(URI uri); + + /** + * Whether feed entries will be split on each poll. + * @return split setting or null if no configuration has been specified + */ + Boolean isSplitEntries(); + + /** + * Specify that feed entries will be split on each poll. + * @param split true if entries should be split, false otherwise + * @return a reference to this RSS binding model + */ + CamelRSSBindingModel setSplitEntries(Boolean split); + + /** + * Whether the component should only return new RSS entries. + * @return filter setting or null if no configuration has been specified + */ + Boolean isFilter(); + + /** + * Specify that the source feed should be filtered. + * @param filter true to filter the feed + * @return a reference to this RSS binding model + */ + CamelRSSBindingModel setFilter(Boolean filter); + + /** + * Set the start date used by the filter for pulling new feeds. + * @param lastUpdate date after which entries should be pulled + * @return a reference to this RSS binding model + */ + CamelRSSBindingModel setLastUpdate(Date lastUpdate); + + /** + * The start date used by the filter for pulling new feeds. + * @return date after which entries should be pulled or null if no + * configuration has been specified + */ + Date getLastUpdate(); + + /** + * Enables throttled delivery of feeds. + * @param throttled specify true to enable throttling + * @return a reference to this RSS binding model + */ + CamelRSSBindingModel setThrottleEntries(Boolean throttled); + + /** + * Whether throttling is enabled for this endpoint. + * @return throttle setting or null if no configuration has been specified + */ + Boolean isThrottleEntries(); + + /** + * Specify whether the underlying Abdera feed object is included as a header. + * @param header true to include the header, false to not include + * @return a reference to this RSS binding model + */ + CamelRSSBindingModel setFeedHeader(Boolean header); + + /** + * Whether the Abdera feed object is included as a header. + * @return feed header setting or null if no configuration has been specified + */ + Boolean isFeedHeader(); + + /** + * Specifies whether split entries are sorted by date. + * @param sorted set to true for split entries to be sorted + * @return a reference to this RSS binding model + */ + CamelRSSBindingModel setSortEntries(Boolean sorted); + + /** + * Whether split entries are sorted by date. + * @return sort setting or null if no configuration has been specified + */ + Boolean isSortEntries(); + + /** + * Sets consumer properties for RSS. + * + * @param consumer Configuration of consumer. + * @return a reference to this RSS binding model + */ + CamelRSSBindingModel setConsumer(CamelScheduledPollConsumer consumer); + + /** + * @return RSS consumer configuration. + */ + CamelScheduledPollConsumer getConsumer(); + +} diff --git a/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/CamelRSSNamespace.java b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/CamelRSSNamespace.java new file mode 100644 index 000000000..584b81f48 --- /dev/null +++ b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/CamelRSSNamespace.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.rss.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel RSS config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelRSSNamespace implements Namespace { + + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelRSSNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelRSSNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelRSSNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelRSSNamespace + */ + public static CamelRSSNamespace fromUri(String uri) { + return Util.fromUri(CamelRSSNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelRSSNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-rss:config", version); + } + } + +} diff --git a/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSBindingModel.java b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSBindingModel.java new file mode 100644 index 000000000..ef309a8b4 --- /dev/null +++ b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSBindingModel.java @@ -0,0 +1,194 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.rss.model.v2; + +import java.net.URI; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.consumer.CamelScheduledPollConsumer; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledPollConsumer; +import org.switchyard.component.camel.rss.model.CamelRSSBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of RSSBindingModel. + */ +public class V2CamelRSSBindingModel extends V1BaseCamelBindingModel + implements CamelRSSBindingModel { + + /** + * Camel endpoint type. + */ + public static final String RSS = "rss"; + + /** + * Camel endpoint configuration values. + */ + private static final String FEED_URI = "feedURI"; + private static final String SPLIT_ENTRIES = "splitEntries"; + private static final String FILTER = "filter"; + private static final String LAST_UPDATE = "lastUpdate"; + private static final String THROTTLE_ENTRIES = "throttleEntries"; + private static final String FEED_HEADER = "feedHeader"; + private static final String SORT_ENTRIES = "sortEntries"; + + private CamelScheduledPollConsumer _consume; + + // Used for dateTime fields + private static final String DATE_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ss"; + + /** + * Create a new RSSBindingModel. + * @param namespace namespace + */ + public V2CamelRSSBindingModel(String namespace) { + super(RSS, namespace); + + setModelChildrenOrder(FEED_URI, SPLIT_ENTRIES, FILTER, LAST_UPDATE, + THROTTLE_ENTRIES, FEED_HEADER, SORT_ENTRIES, CONSUME); + } + + /** + * Create a RSSBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V2CamelRSSBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public URI getFeedURI() { + String uriStr = getConfig(FEED_URI); + if (uriStr != null) { + return URI.create(uriStr); + } else { + return null; + } + } + + @Override + public V2CamelRSSBindingModel setFeedURI(URI uri) { + return setConfig(FEED_URI, uri.toString()); + } + + @Override + public Date getLastUpdate() { + final DateFormat lastUpdateDateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + return getDateConfig(LAST_UPDATE, lastUpdateDateFormat); + } + + @Override + public V2CamelRSSBindingModel setLastUpdate(Date date) { + final DateFormat lastUpdateDateFormat = new SimpleDateFormat(DATE_FORMAT_STRING); + setConfig(LAST_UPDATE, lastUpdateDateFormat.format(date)); + return this; + } + + @Override + public Boolean isFeedHeader() { + return getBooleanConfig(FEED_HEADER); + } + + @Override + public V2CamelRSSBindingModel setFeedHeader(Boolean feedHeader) { + return setConfig(FEED_HEADER, feedHeader); + } + + @Override + public Boolean isFilter() { + return getBooleanConfig(FILTER); + } + + @Override + public V2CamelRSSBindingModel setFilter(Boolean filtered) { + return setConfig(FILTER, filtered); + } + + @Override + public Boolean isSortEntries() { + return getBooleanConfig(SORT_ENTRIES); + } + + @Override + public V2CamelRSSBindingModel setSortEntries(Boolean sorted) { + return setConfig(SORT_ENTRIES, sorted); + } + + @Override + public Boolean isSplitEntries() { + return getBooleanConfig(SPLIT_ENTRIES); + } + + @Override + public V2CamelRSSBindingModel setSplitEntries(Boolean split) { + return setConfig(SPLIT_ENTRIES, String.valueOf(split)); + } + + @Override + public Boolean isThrottleEntries() { + return getBooleanConfig(THROTTLE_ENTRIES); + } + + @Override + public V2CamelRSSBindingModel setThrottleEntries(Boolean throttled) { + return setConfig(THROTTLE_ENTRIES, String.valueOf(throttled)); + } + + + @Override + public CamelScheduledPollConsumer getConsumer() { + if (_consume == null) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + _consume = new V1CamelScheduledPollConsumer(config, + getModelDescriptor()); + } + return _consume; + } + + @Override + public V2CamelRSSBindingModel setConsumer(CamelScheduledPollConsumer consumer) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(CONSUME); + getModelConfiguration().addChild(((V1CamelScheduledPollConsumer) consumer) + .getModelConfiguration()); + } else { + setChildModel((V1CamelScheduledPollConsumer) consumer); + } + _consume = consumer; + return this; + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String baseUri = RSS + "://" + getFeedURI(); + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, FEED_URI); + + return URI.create(baseUri + queryStr.toString()); + } +} diff --git a/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSModelMarshaller.java b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSModelMarshaller.java new file mode 100644 index 000000000..448d8480f --- /dev/null +++ b/components/camel/camel-rss/src/main/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.rss.model.v2; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Atom model marshaller. + */ +public class V2CamelRSSModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_RSS = BindingModel.BINDING + '.' + V2CamelRSSBindingModel.RSS; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V2CamelRSSModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V2BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_RSS.equals(name)) { + return new V2CamelRSSBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-rss/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-rss/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..370658dc6 --- /dev/null +++ b/components/camel/camel-rss/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.rss.deploy.CamelRSSComponent diff --git a/components/camel/camel-rss/src/main/resources/org/switchyard/component/camel/rss/model/v2/camel-rss_2_0.xsd b/components/camel/camel-rss/src/main/resources/org/switchyard/component/camel/rss/model/v2/camel-rss_2_0.xsd new file mode 100644 index 000000000..1be739cb7 --- /dev/null +++ b/components/camel/camel-rss/src/main/resources/org/switchyard/component/camel/rss/model/v2/camel-rss_2_0.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-rss/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-rss/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..9d86ef5c0 --- /dev/null +++ b/components/camel/camel-rss/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,18 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_rss_2_0.section=urn:switchyard-component-camel-rss:config +camel_rss_2_0.version=2.0 +camel_rss_2_0.namespace=urn:switchyard-component-camel-rss:config:2.0 +camel_rss_2_0.schema=camel-rss_2_0.xsd +camel_rss_2_0.location=/org/switchyard/component/camel/rss/model/v2/ +camel_rss_2_0.marshaller=org.switchyard.component.camel.rss.model.v2.V2CamelRSSModelMarshaller diff --git a/components/camel/camel-rss/src/test/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSBindingModelTest.java b/components/camel/camel-rss/src/test/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSBindingModelTest.java new file mode 100644 index 000000000..5040e03d7 --- /dev/null +++ b/components/camel/camel-rss/src/test/java/org/switchyard/component/camel/rss/model/v2/V2CamelRSSBindingModelTest.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.rss.model.v2; + +import static junit.framework.Assert.assertEquals; + +import java.net.URI; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.apache.camel.component.feed.FeedEndpoint; +import org.switchyard.component.camel.common.model.consumer.CamelScheduledPollConsumer; +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledPollConsumer; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.rss.model.CamelRSSNamespace; +import org.switchyard.component.camel.rss.model.v2.V2CamelRSSBindingModel; + +/** + * Test of rss binding model. + */ +public class V2CamelRSSBindingModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-rss-binding.xml"; + + private static final String CAMEL_URI = + "rss://file:///dev/null?feedHeader=true&filter=true&lastUpdate=2011-01-01T12:00:00" + + "&sortEntries=true&splitEntries=true&throttleEntries=true" + + "&delay=15000&initialDelay=20000&useFixedDelay=true"; + + private Date referenceDate; + private static final URI FEED_URI = URI.create("file:///dev/null"); + private static final Boolean FEED_HEADER = true; + private static final Boolean FILTERED = true; + private static final Boolean SORTED = true; + private static final Boolean SPLIT = true; + private static final Boolean THROTTLED = true; + + public V2CamelRSSBindingModelTest() throws ParseException { + super(FeedEndpoint.class, CAMEL_XML); + + referenceDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") + .parse("2011-01-01T12:00:00"); + } + + + @Override + protected void createModelAssertions(V2CamelRSSBindingModel model) { + assertEquals(FEED_URI, model.getFeedURI()); + assertEquals(referenceDate.toString(), model.getLastUpdate().toString()); + assertEquals(FEED_HEADER, model.isFeedHeader()); + assertEquals(FILTERED, model.isFilter()); + assertEquals(SORTED, model.isSortEntries()); + assertEquals(SPLIT, model.isSplitEntries()); + assertEquals(THROTTLED, model.isThrottleEntries()); + } + + @Override + protected V2CamelRSSBindingModel createTestModel() { + V2CamelRSSBindingModel abm = new V2CamelRSSBindingModel(CamelRSSNamespace.V_2_0.uri()) + .setFeedURI(FEED_URI) + .setSplitEntries(SPLIT) + .setFilter(FILTERED) + .setLastUpdate(referenceDate) + .setThrottleEntries(THROTTLED) + .setFeedHeader(FEED_HEADER) + .setSortEntries(SORTED); + + CamelScheduledPollConsumer consumer = new V1CamelScheduledPollConsumer(CamelRSSNamespace.V_2_0.uri(), V2CamelRSSBindingModel.CONSUME) + .setInitialDelay(20000) + .setDelay(15000) + .setUseFixedDelay(true); + return abm.setConsumer(consumer); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-rss/src/test/resources/v2/switchyard-rss-binding.xml b/components/camel/camel-rss/src/test/resources/v2/switchyard-rss-binding.xml new file mode 100644 index 000000000..fbce9e49e --- /dev/null +++ b/components/camel/camel-rss/src/test/resources/v2/switchyard-rss-binding.xml @@ -0,0 +1,38 @@ + + + + + + + + + file:///dev/null + true + true + 2011-01-01T12:00:00 + true + true + true + + 20000 + 15000 + true + + + + + diff --git a/components/camel/camel-sap/pom.xml b/components/camel/camel-sap/pom.xml new file mode 100644 index 000000000..87c6c6a70 --- /dev/null +++ b/components/camel/camel-sap/pom.xml @@ -0,0 +1,59 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-sap + bundle + SwitchYard: Camel Component :: SAP JCO Binding + http://switchyard.org + + + org.switchyard.component.camel.sap.* + + + org.fusesource.camel.component.sap.*, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard + switchyard-config + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.fusesource + camel-sap + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/deploy/CamelSapComponent.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/deploy/CamelSapComponent.java new file mode 100644 index 000000000..b3e4cab97 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/deploy/CamelSapComponent.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.sap.model.v2.Constants; + +/** + * Camel sap component. + */ +public class CamelSapComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelSapComponent() { + super("CamelSapComponent", Constants.SAP); + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/CamelSapBindingModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/CamelSapBindingModel.java new file mode 100644 index 000000000..51510fdd1 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/CamelSapBindingModel.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Camel SAP binding model. + */ +public interface CamelSapBindingModel extends CamelBindingModel { + + /** + * Gets endpoint. + * @return server + */ + EndpointModel getEndpointModel(); + + /** + * Sets endpoint. + * @param endpoint endpoint + * @return this BindingModel (useful for chaining) + */ + CamelSapBindingModel setEndpointModel(EndpointModel endpoint); + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/CamelSapNamespace.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/CamelSapNamespace.java new file mode 100644 index 000000000..ee2bf317b --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/CamelSapNamespace.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Sap config model namespace. + */ +public enum CamelSapNamespace implements Namespace { + + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new CamelSapNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelSapNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelSapNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelSqlNamespace + */ + public static CamelSapNamespace fromUri(String uri) { + return Util.fromUri(CamelSapNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelSapNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-sap:config", version); + } + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/DestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/DestinationModel.java new file mode 100644 index 000000000..0c9060ffa --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/DestinationModel.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +/** + * camel-sap destination model. + */ +public interface DestinationModel extends EndpointModel { + /** + * Gets destination name. + * @return destination name + */ + public String getDestinationName(); + + /** + * Sets destination name. + * @param destination destination + * @return this model (useful for chaining) + */ + public DestinationModel setDestinationName(String destination); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/EndpointModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/EndpointModel.java new file mode 100644 index 000000000..db7fa5439 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/EndpointModel.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.config.model.Model; + +/** + * camel-sap endpoint model. + */ +public interface EndpointModel extends Model { + /** + * Gets schema. + * @return schema + */ + public String getSchema(); + + /** + * Gets name. + * @return name + */ + public String getName(); + + /** + * Sets name. + * @param name name + * @return this model (useful for chaining) + */ + public EndpointModel setName(String name); + + /** + * Gets base URI string. + * @param queryString query string + * @return base URI string + */ + public StringBuilder createBaseURIString(QueryString queryString); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/IDocDestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/IDocDestinationModel.java new file mode 100644 index 000000000..1a60dc13d --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/IDocDestinationModel.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +/** + * camel-sap IDoc destination model. + */ +public interface IDocDestinationModel extends DestinationModel { + /** + * Gets IDoc type. + * @return IDoc type + */ + public String getIdocType(); + + /** + * Sets IDoc type. + * @param idoc IDoc type + * @return this model (useful for chaining) + */ + public IDocDestinationModel setIdocType(String idoc); + + /** + * Gets IDoc type extension. + * @return IDoc type extension + */ + public String getIdocTypeExtension(); + + /** + * Sets IDoc type extension. + * @param idocExt IDoc type extension + * @return this model (useful for chaiming) + */ + public IDocServerModel setIdocTypeExtension(String idocExt); + + /** + * Gets system release. + * @return system release + */ + public String getSystemRelease(); + + /** + * Sets system release. + * @param sysRelease system release + * @return this model (useful for chaining) + */ + public IDocDestinationModel setSystemRelease(String sysRelease); + + /** + * Gets application release. + * @return application release + */ + public String getApplicationRelease(); + + /** + * Sets application release. + * @param appRelease application release + * @return this model (useful for chaining) + */ + public IDocDestinationModel setApplicationRelease(String appRelease); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/IDocServerModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/IDocServerModel.java new file mode 100644 index 000000000..84dc552eb --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/IDocServerModel.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +/** + * camel-sap IDoc server model. + */ +public interface IDocServerModel extends ServerModel { + /** + * Gets IDoc type. + * @return IDoc type. + */ + public String getIdocType(); + + /** + * Sets IDoc type. + * @param idoc IDoc type + * @return this model (useful for chaining) + */ + public IDocServerModel setIdocType(String idoc); + + /** + * Gets IDoc type extension. + * @return IDoc type extension + */ + public String getIdocTypeExtension(); + + /** + * Sets IDoc type extension. + * @param idocExt IDoc type extension + * @return this model (useful for chaiming) + */ + public IDocServerModel setIdocTypeExtension(String idocExt); + + /** + * Gets system release. + * @return system release + */ + public String getSystemRelease(); + + /** + * Sets system release. + * @param sysRelease system release + * @return this model (useful for chaining) + */ + public IDocServerModel setSystemRelease(String sysRelease); + + /** + * Gets application release. + * @return application release + */ + public String getApplicationRelease(); + + /** + * Sets application release. + * @param appRelease application release + * @return this model (useful for chaining) + */ + public IDocServerModel setApplicationRelease(String appRelease); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/QIDocDestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/QIDocDestinationModel.java new file mode 100644 index 000000000..75d207232 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/QIDocDestinationModel.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +/** + * camel-sap queued IDoc destination model. + */ +public interface QIDocDestinationModel extends IDocDestinationModel { + /** + * Gets queue name. + * @return destination name + */ + public String getQueueName(); + + /** + * Sets queue name. + * @param queue queue name + * @return this model (useful for chaining) + */ + public QIDocDestinationModel setQueueName(String queue); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/QRfcDestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/QRfcDestinationModel.java new file mode 100644 index 000000000..fca9eb4cf --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/QRfcDestinationModel.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +/** + * camel-sap destination model. + */ +public interface QRfcDestinationModel extends RfcDestinationModel { + /** + * Gets queue name. + * @return destination name + */ + public String getQueueName(); + + /** + * Sets queue name. + * @param queue queue name + * @return this model (useful for chaining) + */ + public QRfcDestinationModel setQueueName(String queue); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/RfcDestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/RfcDestinationModel.java new file mode 100644 index 000000000..9459a1ced --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/RfcDestinationModel.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +/** + * camel-sap destination model. + */ +public interface RfcDestinationModel extends DestinationModel { + /** + * Gets RFC name. + * @return destination name + */ + public String getRfcName(); + + /** + * Sets RFC name. + * @param rfc RFC name. + * @return this model (useful for chaining) + */ + public RfcDestinationModel setRfcName(String rfc); + + /** + * Gets if it's transacted. + * @return true if it's transacted + */ + public boolean isTransacted(); + + /** + * Sets if it's transacted. + * @param transacted true if it's transacted + * @return this model (useful for chaining) + */ + public RfcDestinationModel setTransacted(boolean transacted); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/RfcServerModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/RfcServerModel.java new file mode 100644 index 000000000..866dadba6 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/RfcServerModel.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +/** + * camel-sap RFC server model. + */ +public interface RfcServerModel extends ServerModel { + /** + * Gets RFC name. + * @return RFC name + */ + public String getRfcName(); + + /** + * Sets RFC name. + * @param rfc RFC name + * @return this model (useful for chaining) + */ + public RfcServerModel setRfcName(String rfc); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/ServerModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/ServerModel.java new file mode 100644 index 000000000..974af0773 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/ServerModel.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model; + +/** + * camel-sap server model. + */ +public interface ServerModel extends EndpointModel { + /** + * Gets server name. + * @return server name + */ + public String getServerName(); + + /** + * Sets server name. + * @param server server name + * @return this model (useful for chaining) + */ + public ServerModel setServerName(String server); +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/Constants.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/Constants.java new file mode 100644 index 000000000..2fc607920 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/Constants.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.config.model.composite.BindingModel; + +/** + * V2 camel-sap constants. + */ +public final class Constants { + + private Constants() { + } + + /** sap. */ + public static final String SAP = "sap"; + /** binding.sap. */ + public static final String BINDING_SAP = BindingModel.BINDING + "." + SAP; + + /** idoclist-server. */ + public static final String IDOCLIST_SERVER = "idoclist-server"; + /** srfc-server. */ + public static final String SRFC_SERVER = "srfc-server"; + /** trfc-server. */ + public static final String TRFC_SERVER = "trfc-server"; + /** idoc-destination. */ + public static final String IDOC_DESTINATION = "idoc-destination"; + /** idoclist-destination. */ + public static final String IDOCLIST_DESTINATION = "idoclist-destination"; + /** qidoc-destination. */ + public static final String QIDOC_DESTINATION = "qidoc-destination"; + /** qidoclist-destination. */ + public static final String QIDOCLIST_DESTINATION = "qidoclist-destination"; + /** qrfc-destination. */ + public static final String QRFC_DESTINATION = "qrfc-destination"; + /** srfc-destination. */ + public static final String SRFC_DESTINATION = "srfc-destination"; + /** trfc-destination. */ + public static final String TRFC_DESTINATION = "trfc-destination"; + + /** serverName. */ + public static final String SERVER_NAME = "serverName"; + /** destinationName. */ + public static final String DESTINATION_NAME = "destinationName"; + /** rfcName. */ + public static final String RFC_NAME = "rfcName"; + /** queueName. */ + public static final String QUEUE_NAME = "queueName"; + /** idocType. */ + public static final String IDOC_TYPE = "idocType"; + /** idocTypeExtension. */ + public static final String IDOC_TYPE_EXTENSION = "idocTypeExtension"; + /** systemRelease. */ + public static final String SYSTEM_RELEASE = "systemRelease"; + /** applicationRelease. */ + public static final String APPLICATION_RELEASE = "applicationRelease"; + /** transacted. */ + public static final String TRANSACTED = "transacted"; +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapBindingModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapBindingModel.java new file mode 100644 index 000000000..c7ddf435e --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapBindingModel.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import java.net.URI; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.sap.model.CamelSapBindingModel; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +/** + * A binding for Camel's sap component. + */ +public class V2CamelSapBindingModel extends V1BaseCamelBindingModel implements CamelSapBindingModel { + + /** + * Constructor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V2CamelSapBindingModel(final Configuration config, final Descriptor desc) { + super(config, desc); + } + + /** + * Create a new V2CamelSapBindingModel. + * @param namespace namespace + */ + public V2CamelSapBindingModel(String namespace) { + super(Constants.SAP, namespace); + setModelChildrenOrder(Constants.IDOCLIST_SERVER, Constants.SRFC_SERVER, Constants.TRFC_SERVER, + Constants.IDOC_DESTINATION, Constants.IDOCLIST_DESTINATION, Constants.QIDOC_DESTINATION, + Constants.QIDOCLIST_DESTINATION, Constants.QRFC_DESTINATION, Constants.SRFC_DESTINATION, + Constants.TRFC_DESTINATION); + } + + @Override + public EndpointModel getEndpointModel() { + for (Model child : getModelChildren()) { + if (child instanceof EndpointModel) { + return (EndpointModel) child; + } + } + return null; + } + + @Override + public V2CamelSapBindingModel setEndpointModel(EndpointModel endpoint) { + for (Model child : getModelChildren()) { + if (child instanceof EndpointModel) { + EndpointModel endpointChild = EndpointModel.class.cast(child); + getModelConfiguration().removeChildren( + new QName(CamelSapNamespace.V_2_0.uri(), endpointChild.getName())); + break; + } + } + setChildModel(endpoint); + return this; + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + QueryString queryString = new QueryString(); + StringBuilder buf = getEndpointModel().createBaseURIString(queryString); + traverseConfiguration(children, queryString, getEndpointModel().getName()); + buf.append(queryString.toString()); + + return URI.create(buf.toString()); + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapModelMarshaller.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapModelMarshaller.java new file mode 100644 index 000000000..05bc1b1d7 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapModelMarshaller.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; + +/** + * SAP model marshaller. + */ +public class V2CamelSapModelMarshaller extends V1BaseCamelMarshaller { + + /** + * Creates new marshaller. + * + * @param desc Descriptor. + */ + public V2CamelSapModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various models. + * If not found, it falls back to the super class (V2BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (Constants.BINDING_SAP.equals(name)) { + return new V2CamelSapBindingModel(config, desc); + } + if (Constants.IDOCLIST_SERVER.equals(name)) { + return new V2IDocServerModel(config, desc); + } + if (Constants.SRFC_SERVER.equals(name) || Constants.TRFC_SERVER.equals(name)) { + return new V2RfcServerModel(config, desc); + } + if (Constants.IDOC_DESTINATION.equals(name) || Constants.IDOCLIST_DESTINATION.equals(name)) { + return new V2IDocDestinationModel(config, desc); + } + if (Constants.QIDOC_DESTINATION.equals(name) || Constants.QIDOCLIST_DESTINATION.equals(name)) { + return new V2QIDocDestinationModel(config, desc); + } + if (Constants.QRFC_DESTINATION.equals(name)) { + return new V2QRfcDestinationModel(config, desc); + } + if (Constants.SRFC_DESTINATION.equals(name) || Constants.TRFC_DESTINATION.equals(name)) { + return new V2RfcDestinationModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2DestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2DestinationModel.java new file mode 100644 index 000000000..fbc1e767e --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2DestinationModel.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.sap.model.DestinationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 camel-sap destination model. + */ +public abstract class V2DestinationModel extends V2EndpointModel implements DestinationModel { + + protected V2DestinationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + protected V2DestinationModel(String namespace, String name) { + super(namespace, name); + } + + @Override + public String getDestinationName() { + return getConfig(Constants.DESTINATION_NAME); + } + + @Override + public V2DestinationModel setDestinationName(String destination) { + setConfig(Constants.DESTINATION_NAME, destination); + return this; + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2EndpointModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2EndpointModel.java new file mode 100644 index 000000000..bc8502936 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2EndpointModel.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelModel; +import org.switchyard.component.camel.sap.model.EndpointModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 camel-sap endpoint model. + */ +public abstract class V2EndpointModel extends V1BaseCamelModel implements EndpointModel { + + private String _name; + + protected V2EndpointModel(Configuration config, Descriptor desc) { + super(config, desc); + _name = config.getQName().getLocalPart(); + } + + protected V2EndpointModel(String namespace, String name) { + super(namespace, name); + _name = name; + } + + @Override + public String getName() { + return _name; + } + + @Override + public V2EndpointModel setName(String name) { + _name = name; + return this; + } + + @Override + public String getSchema() { + return Constants.SAP + "-" + _name; + } +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2IDocDestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2IDocDestinationModel.java new file mode 100644 index 000000000..d712f720f --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2IDocDestinationModel.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.sap.model.IDocDestinationModel; +import org.switchyard.component.camel.sap.model.IDocServerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 camel-sap IDoc destination model. + */ +public class V2IDocDestinationModel extends V2DestinationModel implements IDocDestinationModel { + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V2IDocDestinationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Constructor. + * @param namespace namespace + * @param name name + */ + public V2IDocDestinationModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(Constants.DESTINATION_NAME, Constants.IDOC_TYPE, + Constants.IDOC_TYPE_EXTENSION, Constants.SYSTEM_RELEASE, Constants.APPLICATION_RELEASE); + } + + @Override + public String getIdocType() { + return getConfig(Constants.IDOC_TYPE); + } + + @Override + public IDocDestinationModel setIdocType(String idoc) { + setConfig(Constants.IDOC_TYPE, idoc); + return this; + } + + @Override + public String getIdocTypeExtension() { + return getConfig(Constants.IDOC_TYPE_EXTENSION); + } + + @Override + public IDocServerModel setIdocTypeExtension(String idocExt) { + setConfig(Constants.IDOC_TYPE_EXTENSION, idocExt); + return null; + } + + @Override + public String getSystemRelease() { + return getConfig(Constants.SYSTEM_RELEASE); + } + + @Override + public IDocDestinationModel setSystemRelease(String sysRelease) { + setConfig(Constants.SYSTEM_RELEASE, sysRelease); + return this; + } + + @Override + public String getApplicationRelease() { + return getConfig(Constants.APPLICATION_RELEASE); + } + + @Override + public IDocDestinationModel setApplicationRelease(String appRelease) { + setConfig(Constants.APPLICATION_RELEASE, appRelease); + return this; + } + + @Override + public StringBuilder createBaseURIString(QueryString queryString) { + StringBuilder buf = new StringBuilder(getSchema()) + .append(':').append(getDestinationName()) + .append(':').append(getIdocType()); + String idocTypeExt = getIdocTypeExtension(); + if (idocTypeExt != null && !idocTypeExt.isEmpty()) { + buf.append(':').append(idocTypeExt); + String sysRel = getSystemRelease(); + if (sysRel != null && !sysRel.isEmpty()) { + buf.append(':').append(sysRel); + String appRel = getApplicationRelease(); + if (appRel != null && !appRel.isEmpty()) { + buf.append(':').append(appRel); + } + } + } + return buf; + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2IDocServerModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2IDocServerModel.java new file mode 100644 index 000000000..85af4b5ad --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2IDocServerModel.java @@ -0,0 +1,110 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.sap.model.IDocServerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 IDoc server model. + */ +public class V2IDocServerModel extends V2ServerModel implements IDocServerModel { + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V2IDocServerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Constructor. + * @param namespace namespace + * @param name name + */ + public V2IDocServerModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(Constants.SERVER_NAME, Constants.IDOC_TYPE, + Constants.IDOC_TYPE_EXTENSION, Constants.SYSTEM_RELEASE, Constants.APPLICATION_RELEASE); + } + + @Override + public String getIdocType() { + return getConfig(Constants.IDOC_TYPE); + } + + @Override + public IDocServerModel setIdocType(String idoc) { + setConfig(Constants.IDOC_TYPE, idoc); + return this; + } + + @Override + public String getIdocTypeExtension() { + return getConfig(Constants.IDOC_TYPE_EXTENSION); + } + + @Override + public IDocServerModel setIdocTypeExtension(String idocExt) { + setConfig(Constants.IDOC_TYPE_EXTENSION, idocExt); + return this; + } + + @Override + public String getSystemRelease() { + return getConfig(Constants.SYSTEM_RELEASE); + } + + @Override + public IDocServerModel setSystemRelease(String sysRelease) { + setConfig(Constants.SYSTEM_RELEASE, sysRelease); + return null; + } + + @Override + public String getApplicationRelease() { + return getConfig(Constants.APPLICATION_RELEASE); + } + + @Override + public IDocServerModel setApplicationRelease(String appRelease) { + setConfig(Constants.APPLICATION_RELEASE, appRelease); + return this; + } + + @Override + public StringBuilder createBaseURIString(QueryString queryString) { + StringBuilder buf = new StringBuilder(getSchema()) + .append(':').append(getServerName()) + .append(':').append(getIdocType()); + String idocTypeExt = getIdocTypeExtension(); + if (idocTypeExt != null && !idocTypeExt.isEmpty()) { + buf.append(':').append(idocTypeExt); + String sysRel = getSystemRelease(); + if (sysRel != null && !sysRel.isEmpty()) { + buf.append(':').append(sysRel); + String appRel = getApplicationRelease(); + if (appRel != null && !appRel.isEmpty()) { + buf.append(':').append(appRel); + } + } + } + return buf; + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2QIDocDestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2QIDocDestinationModel.java new file mode 100644 index 000000000..9c96d01ba --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2QIDocDestinationModel.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.sap.model.QIDocDestinationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 Queued IDoc destination model. + */ +public class V2QIDocDestinationModel extends V2IDocDestinationModel implements QIDocDestinationModel { + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V2QIDocDestinationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Constructor. + * @param namespace namespace + * @param name name + */ + public V2QIDocDestinationModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(Constants.DESTINATION_NAME, Constants.QUEUE_NAME, Constants.IDOC_TYPE, + Constants.IDOC_TYPE_EXTENSION, Constants.SYSTEM_RELEASE, Constants.APPLICATION_RELEASE); + } + + @Override + public String getQueueName() { + return getConfig(Constants.QUEUE_NAME); + } + + @Override + public QIDocDestinationModel setQueueName(String queue) { + setConfig(Constants.QUEUE_NAME, queue); + return this; + } + + @Override + public StringBuilder createBaseURIString(QueryString queryString) { + StringBuilder buf = new StringBuilder(getSchema()) + .append(':').append(getDestinationName()) + .append(':').append(getQueueName()) + .append(':').append(getIdocType()); + String idocTypeExt = getIdocTypeExtension(); + if (idocTypeExt != null && !idocTypeExt.isEmpty()) { + buf.append(':').append(idocTypeExt); + String sysRel = getSystemRelease(); + if (sysRel != null && !sysRel.isEmpty()) { + buf.append(':').append(sysRel); + String appRel = getApplicationRelease(); + if (appRel != null && !appRel.isEmpty()) { + buf.append(':').append(appRel); + } + } + } + return buf; + } +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2QRfcDestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2QRfcDestinationModel.java new file mode 100644 index 000000000..70aa3a158 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2QRfcDestinationModel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.sap.model.QRfcDestinationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 camel-sap Queued RFC destination model. + */ +public class V2QRfcDestinationModel extends V2RfcDestinationModel implements QRfcDestinationModel { + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V2QRfcDestinationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Constructor. + * @param namespace namespace + * @param name name + */ + public V2QRfcDestinationModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(Constants.DESTINATION_NAME, Constants.QUEUE_NAME, Constants.RFC_NAME, Constants.TRANSACTED); + } + + @Override + public String getQueueName() { + return getConfig(Constants.QUEUE_NAME); + } + + @Override + public QRfcDestinationModel setQueueName(String queue) { + setConfig(Constants.QUEUE_NAME, queue); + return this; + } + + @Override + public StringBuilder createBaseURIString(QueryString queryString) { + queryString.add(Constants.TRANSACTED, isTransacted()); + return new StringBuilder(getSchema()) + .append(':').append(getDestinationName()) + .append(':').append(getQueueName()) + .append(':').append(getRfcName()); + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2RfcDestinationModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2RfcDestinationModel.java new file mode 100644 index 000000000..1213dac9f --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2RfcDestinationModel.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.sap.model.RfcDestinationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 camel-sap RFC destination model. + */ +public class V2RfcDestinationModel extends V2DestinationModel implements RfcDestinationModel { + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V2RfcDestinationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Constructor. + * @param namespace namespace + * @param name name + */ + public V2RfcDestinationModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(Constants.DESTINATION_NAME, Constants.RFC_NAME, Constants.TRANSACTED); + } + + @Override + public String getRfcName() { + return getConfig(Constants.RFC_NAME); + } + + @Override + public V2RfcDestinationModel setRfcName(String rfc) { + setConfig(Constants.RFC_NAME, rfc); + return this; + } + + @Override + public boolean isTransacted() { + return getBooleanConfig(Constants.TRANSACTED); + } + + @Override + public V2RfcDestinationModel setTransacted(boolean transacted) { + setConfig(Constants.TRANSACTED, transacted); + return this; + } + + @Override + public StringBuilder createBaseURIString(QueryString queryString) { + queryString.add(Constants.TRANSACTED, isTransacted()); + return new StringBuilder(getSchema()) + .append(':').append(getDestinationName()) + .append(':').append(getRfcName()); + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2RfcServerModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2RfcServerModel.java new file mode 100644 index 000000000..80841a9b6 --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2RfcServerModel.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.sap.model.RfcServerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 RFC server model. + */ +public class V2RfcServerModel extends V2ServerModel implements RfcServerModel { + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V2RfcServerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Constructor. + * @param namespace namespace + * @param name name + */ + public V2RfcServerModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(Constants.SERVER_NAME, Constants.RFC_NAME); + } + + @Override + public String getRfcName() { + return getConfig(Constants.RFC_NAME); + } + + @Override + public V2RfcServerModel setRfcName(String rfc) { + setConfig(Constants.RFC_NAME, rfc); + return this; + } + + @Override + public StringBuilder createBaseURIString(QueryString queryString) { + return new StringBuilder(getSchema()) + .append(':').append(getServerName()) + .append(':').append(getRfcName()); + } + +} diff --git a/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2ServerModel.java b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2ServerModel.java new file mode 100644 index 000000000..6dc21433b --- /dev/null +++ b/components/camel/camel-sap/src/main/java/org/switchyard/component/camel/sap/model/v2/V2ServerModel.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import org.switchyard.component.camel.sap.model.ServerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V2 camel-sap server model. + */ +public abstract class V2ServerModel extends V2EndpointModel implements ServerModel { + + protected V2ServerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + protected V2ServerModel(String namespace, String name) { + super(namespace, name); + } + + @Override + public String getServerName() { + return getConfig(Constants.SERVER_NAME); + } + + @Override + public V2ServerModel setServerName(String server) { + setConfig(Constants.SERVER_NAME, server); + return this; + } + +} diff --git a/components/camel/camel-sap/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-sap/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..0dca65463 --- /dev/null +++ b/components/camel/camel-sap/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.sap.deploy.CamelSapComponent diff --git a/components/camel/camel-sap/src/main/resources/META-INF/services/org/apache/camel/TypeConverter b/components/camel/camel-sap/src/main/resources/META-INF/services/org/apache/camel/TypeConverter new file mode 100644 index 000000000..80bbd4806 --- /dev/null +++ b/components/camel/camel-sap/src/main/resources/META-INF/services/org/apache/camel/TypeConverter @@ -0,0 +1,18 @@ +# +# Copyright 2013 Red Hat, Inc. +# +# Red Hat licenses this file to you under the Apache License, version +# 2.0 (the "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 a workaround for the original TypeConverter file which doesn't work on JBoss +# The original file contains a package name, but the converter is not loaded properly. +org.fusesource.camel.component.sap.converter.StructureConverter diff --git a/components/camel/camel-sap/src/main/resources/org/switchyard/component/camel/sap/model/v2/camel-sap_2_0.xsd b/components/camel/camel-sap/src/main/resources/org/switchyard/component/camel/sap/model/v2/camel-sap_2_0.xsd new file mode 100644 index 000000000..114355bd8 --- /dev/null +++ b/components/camel/camel-sap/src/main/resources/org/switchyard/component/camel/sap/model/v2/camel-sap_2_0.xsd @@ -0,0 +1,134 @@ + + + + + + + + + + + + SAP Binding configuration. *-server is for service binding, and *-destination is for reference binding. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-sap/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-sap/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..50fbaeabf --- /dev/null +++ b/components/camel/camel-sap/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,18 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_sap_2_0.section=urn:switchyard-component-camel-sap:config +camel_sap_2_0.version=2.0 +camel_sap_2_0.namespace=urn:switchyard-component-camel-sap:config:2.0 +camel_sap_2_0.schema=camel-sap_2_0.xsd +camel_sap_2_0.location=/org/switchyard/component/camel/sap/model/v2 +camel_sap_2_0.marshaller=org.switchyard.component.camel.sap.model.v2.V2CamelSapModelMarshaller diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocDestinationModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocDestinationModelTest.java new file mode 100644 index 000000000..e7d9cd322 --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocDestinationModelTest.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapTransactionalIDocDestinationEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapIDocDestinationModel}. + */ +public class V2CamelSapIDocDestinationModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-idoc-destination-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.IDOC_DESTINATION; + private static final String DESTINATION_NAME = "nplHost"; + private static final String IDOC_TYPE = "BAPI_FLTRIP_GETLIST"; + private static final String IDOC_TYPE_EXTENSION = "IDOC_TYPE_EXTENSION"; + private static final String SYSTEM_RELEASE = "SYSTEM_RELEASE"; + private static final String APPLICATION_RELEASE = "APPLICATION_RELEASE"; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + DESTINATION_NAME + ":" + IDOC_TYPE + + ":" + IDOC_TYPE_EXTENSION + ":" + SYSTEM_RELEASE + ":" + APPLICATION_RELEASE; + + public V2CamelSapIDocDestinationModelTest() { + super(SapTransactionalIDocDestinationEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2CamelSapBindingModel binding = + new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()) { + @Override + public boolean isReferenceBinding() { + return true; + } + }; + V2IDocDestinationModel endpoint = new V2IDocDestinationModel(CamelSapNamespace.V_2_0.uri(), + Constants.IDOC_DESTINATION); + endpoint.setDestinationName(DESTINATION_NAME); + endpoint.setIdocType(IDOC_TYPE); + endpoint.setIdocTypeExtension(IDOC_TYPE_EXTENSION); + endpoint.setSystemRelease(SYSTEM_RELEASE); + endpoint.setApplicationRelease(APPLICATION_RELEASE); + return binding.setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2IDocDestinationModel.class, endpoint.getClass()); + V2IDocDestinationModel idocDest = V2IDocDestinationModel.class.cast(endpoint); + assertEquals(DESTINATION_NAME, idocDest.getDestinationName()); + assertEquals(IDOC_TYPE, idocDest.getIdocType()); + assertEquals(IDOC_TYPE_EXTENSION, idocDest.getIdocTypeExtension()); + assertEquals(SYSTEM_RELEASE, idocDest.getSystemRelease()); + assertEquals(APPLICATION_RELEASE, idocDest.getApplicationRelease()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocListDestinationModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocListDestinationModelTest.java new file mode 100644 index 000000000..6f6179292 --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocListDestinationModelTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapTransactionalIDocListDestinationEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapIDocListDestinationModel}. + */ +public class V2CamelSapIDocListDestinationModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-idoclist-destination-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.IDOCLIST_DESTINATION; + private static final String DESTINATION_NAME = "nplHost"; + private static final String IDOC_TYPE = "BAPI_FLTRIP_GETLIST"; + private static final String IDOC_TYPE_EXTENSION = "IDOC_TYPE_EXTENSION"; + private static final String SYSTEM_RELEASE = "SYSTEM_RELEASE"; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + DESTINATION_NAME + ":" + IDOC_TYPE + + ":" + IDOC_TYPE_EXTENSION + ":" + SYSTEM_RELEASE; + + public V2CamelSapIDocListDestinationModelTest() { + super(SapTransactionalIDocListDestinationEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2CamelSapBindingModel binding = + new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()) { + @Override + public boolean isReferenceBinding() { + return true; + } + }; + V2IDocDestinationModel endpoint = new V2IDocDestinationModel(CamelSapNamespace.V_2_0.uri(), + Constants.IDOCLIST_DESTINATION); + endpoint.setDestinationName(DESTINATION_NAME); + endpoint.setIdocType(IDOC_TYPE); + endpoint.setIdocTypeExtension(IDOC_TYPE_EXTENSION); + endpoint.setSystemRelease(SYSTEM_RELEASE); + return binding.setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2IDocDestinationModel.class, endpoint.getClass()); + V2IDocDestinationModel idocDest = V2IDocDestinationModel.class.cast(endpoint); + assertEquals(DESTINATION_NAME, idocDest.getDestinationName()); + assertEquals(IDOC_TYPE, idocDest.getIdocType()); + assertEquals(IDOC_TYPE_EXTENSION, idocDest.getIdocTypeExtension()); + assertEquals(SYSTEM_RELEASE, idocDest.getSystemRelease()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocListServerModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocListServerModelTest.java new file mode 100644 index 000000000..3017a04ee --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapIDocListServerModelTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapTransactionalIDocListServerEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapIDocListServerModel}. + */ +public class V2CamelSapIDocListServerModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-idoclist-server-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.IDOCLIST_SERVER; + private static final String SERVER_NAME = "nplserver"; + private static final String IDOC_TYPE = "BOOK_FLIGHT"; + private static final String IDOC_TYPE_EXTENSION = "IDOC_TYPE_EXTENSION"; + private static final String SYSTEM_RELEASE = "SYSTEM_RELEASE"; + private static final String APPLICATION_RELEASE = "APPLICATION_RELEASE"; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + SERVER_NAME + ":" + IDOC_TYPE + + ":" + IDOC_TYPE_EXTENSION + ":" + SYSTEM_RELEASE + ":" + APPLICATION_RELEASE; + + public V2CamelSapIDocListServerModelTest() { + super(SapTransactionalIDocListServerEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2IDocServerModel endpoint = new V2IDocServerModel(CamelSapNamespace.V_2_0.uri(), Constants.IDOCLIST_SERVER); + endpoint.setServerName(SERVER_NAME); + endpoint.setIdocType(IDOC_TYPE); + endpoint.setIdocTypeExtension(IDOC_TYPE_EXTENSION); + endpoint.setSystemRelease(SYSTEM_RELEASE); + endpoint.setApplicationRelease(APPLICATION_RELEASE); + return new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()).setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2IDocServerModel.class, endpoint.getClass()); + V2IDocServerModel idocServer = V2IDocServerModel.class.cast(endpoint); + assertEquals(SERVER_NAME, idocServer.getServerName()); + assertEquals(IDOC_TYPE, idocServer.getIdocType()); + assertEquals(IDOC_TYPE_EXTENSION, idocServer.getIdocTypeExtension()); + assertEquals(SYSTEM_RELEASE, idocServer.getSystemRelease()); + assertEquals(APPLICATION_RELEASE, idocServer.getApplicationRelease()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQIDocDestinationModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQIDocDestinationModelTest.java new file mode 100644 index 000000000..a3f63e99b --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQIDocDestinationModelTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapQueuedIDocDestinationEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapQIDocDestinationModel}. + */ +public class V2CamelSapQIDocDestinationModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-qidoc-destination-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.QIDOC_DESTINATION; + private static final String DESTINATION_NAME = "nplHost"; + private static final String QUEUE_NAME = "QUEUE_NAME"; + private static final String IDOC_TYPE = "BAPI_FLTRIP_GETLIST"; + private static final String IDOC_TYPE_EXTENSION = "IDOC_TYPE_EXTENSION"; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + DESTINATION_NAME + + ":" + QUEUE_NAME + ":" + IDOC_TYPE + ":" + IDOC_TYPE_EXTENSION; + + public V2CamelSapQIDocDestinationModelTest() { + super(SapQueuedIDocDestinationEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2CamelSapBindingModel binding = + new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()) { + @Override + public boolean isReferenceBinding() { + return true; + } + }; + V2QIDocDestinationModel endpoint = new V2QIDocDestinationModel(CamelSapNamespace.V_2_0.uri(), + Constants.QIDOC_DESTINATION); + endpoint.setDestinationName(DESTINATION_NAME); + endpoint.setQueueName(QUEUE_NAME); + endpoint.setIdocType(IDOC_TYPE); + endpoint.setIdocTypeExtension(IDOC_TYPE_EXTENSION); + return binding.setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2QIDocDestinationModel.class, endpoint.getClass()); + V2QIDocDestinationModel qidocDest = V2QIDocDestinationModel.class.cast(endpoint); + assertEquals(DESTINATION_NAME, qidocDest.getDestinationName()); + assertEquals(QUEUE_NAME, qidocDest.getQueueName()); + assertEquals(IDOC_TYPE, qidocDest.getIdocType()); + assertEquals(IDOC_TYPE_EXTENSION, qidocDest.getIdocTypeExtension()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQIDocListDestinationModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQIDocListDestinationModelTest.java new file mode 100644 index 000000000..cc853d3b1 --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQIDocListDestinationModelTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapQueuedIDocListDestinationEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapQIDocListDestinationModel}. + */ +public class V2CamelSapQIDocListDestinationModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-qidoclist-destination-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.QIDOCLIST_DESTINATION; + private static final String DESTINATION_NAME = "nplHost"; + private static final String QUEUE_NAME = "QUEUE_NAME"; + private static final String IDOC_TYPE = "BAPI_FLTRIP_GETLIST"; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + DESTINATION_NAME + + ":" + QUEUE_NAME + ":" + IDOC_TYPE; + + public V2CamelSapQIDocListDestinationModelTest() { + super(SapQueuedIDocListDestinationEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2CamelSapBindingModel binding = + new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()) { + @Override + public boolean isReferenceBinding() { + return true; + } + }; + V2QIDocDestinationModel endpoint = new V2QIDocDestinationModel(CamelSapNamespace.V_2_0.uri(), + Constants.QIDOCLIST_DESTINATION); + endpoint.setDestinationName(DESTINATION_NAME); + endpoint.setQueueName(QUEUE_NAME); + endpoint.setIdocType(IDOC_TYPE); + return binding.setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2QIDocDestinationModel.class, endpoint.getClass()); + V2QIDocDestinationModel qidocDest = V2QIDocDestinationModel.class.cast(endpoint); + assertEquals(DESTINATION_NAME, qidocDest.getDestinationName()); + assertEquals(QUEUE_NAME, qidocDest.getQueueName()); + assertEquals(IDOC_TYPE, qidocDest.getIdocType()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQRfcDestinationModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQRfcDestinationModelTest.java new file mode 100644 index 000000000..ff631841d --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapQRfcDestinationModelTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapQueuedRfcDestinationEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapQRfcDestinationModel}. + */ +public class V2CamelSapQRfcDestinationModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-qrfc-destination-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.QRFC_DESTINATION; + private static final String DESTINATION_NAME = "nplHost"; + private static final String QUEUE_NAME = "QUEUE_NAME"; + private static final String RFC_NAME = "BAPI_FLTRIP_GETLIST"; + private static final Boolean TRANSACTED = Boolean.TRUE; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + DESTINATION_NAME + ":" + QUEUE_NAME + + ":" + RFC_NAME + "?transacted=" + TRANSACTED; + + public V2CamelSapQRfcDestinationModelTest() { + super(SapQueuedRfcDestinationEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2CamelSapBindingModel binding = + new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()) { + @Override + public boolean isReferenceBinding() { + return true; + } + }; + V2QRfcDestinationModel endpoint = new V2QRfcDestinationModel(CamelSapNamespace.V_2_0.uri(), + Constants.QRFC_DESTINATION); + endpoint.setDestinationName(DESTINATION_NAME); + endpoint.setQueueName(QUEUE_NAME); + endpoint.setRfcName(RFC_NAME); + endpoint.setTransacted(TRANSACTED); + return binding.setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2QRfcDestinationModel.class, endpoint.getClass()); + V2QRfcDestinationModel rfcDest = V2QRfcDestinationModel.class.cast(endpoint); + assertEquals(DESTINATION_NAME, rfcDest.getDestinationName()); + assertEquals(QUEUE_NAME, rfcDest.getQueueName()); + assertEquals(RFC_NAME, rfcDest.getRfcName()); + assertEquals(TRANSACTED, rfcDest.isTransacted()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapSRfcDestinationModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapSRfcDestinationModelTest.java new file mode 100644 index 000000000..93e634b32 --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapSRfcDestinationModelTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapTransactionalRfcDestinationEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapTRfcDestinationModel}. + */ +public class V2CamelSapSRfcDestinationModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-trfc-destination-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.TRFC_DESTINATION; + private static final String DESTINATION_NAME = "nplHost"; + private static final String RFC_NAME = "BAPI_FLTRIP_GETLIST"; + private static final Boolean TRANSACTED = Boolean.TRUE; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + DESTINATION_NAME + ":" + RFC_NAME + + "?transacted=" + TRANSACTED; + + public V2CamelSapSRfcDestinationModelTest() { + super(SapTransactionalRfcDestinationEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2CamelSapBindingModel binding = + new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()) { + @Override + public boolean isReferenceBinding() { + return true; + } + }; + V2RfcDestinationModel endpoint = new V2RfcDestinationModel(CamelSapNamespace.V_2_0.uri(), + Constants.TRFC_DESTINATION); + endpoint.setDestinationName(DESTINATION_NAME); + endpoint.setRfcName(RFC_NAME); + endpoint.setTransacted(TRANSACTED); + return binding.setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2RfcDestinationModel.class, endpoint.getClass()); + V2RfcDestinationModel rfcDest = V2RfcDestinationModel.class.cast(endpoint); + assertEquals(DESTINATION_NAME, rfcDest.getDestinationName()); + assertEquals(RFC_NAME, rfcDest.getRfcName()); + assertEquals(TRANSACTED, rfcDest.isTransacted()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapSRfcServerModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapSRfcServerModelTest.java new file mode 100644 index 000000000..f82ed21e4 --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapSRfcServerModelTest.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapSynchronousRfcServerEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapSRfcServerModel}. + */ +public class V2CamelSapSRfcServerModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-srfc-server-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.SRFC_SERVER; + private static final String SERVER_NAME = "nplserver"; + private static final String RFC_NAME = "BOOK_FLIGHT"; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + SERVER_NAME + ":" + RFC_NAME; + + public V2CamelSapSRfcServerModelTest() { + super(SapSynchronousRfcServerEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2RfcServerModel endpoint = new V2RfcServerModel(CamelSapNamespace.V_2_0.uri(), Constants.SRFC_SERVER); + endpoint.setServerName(SERVER_NAME); + endpoint.setRfcName(RFC_NAME); + return new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()).setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2RfcServerModel.class, endpoint.getClass()); + V2RfcServerModel rfcServer = V2RfcServerModel.class.cast(endpoint); + assertEquals(SERVER_NAME, rfcServer.getServerName()); + assertEquals(RFC_NAME, rfcServer.getRfcName()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapTRfcDestinationModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapTRfcDestinationModelTest.java new file mode 100644 index 000000000..683a4bfc1 --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapTRfcDestinationModelTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapSynchronousRfcDestinationEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapSRfcDestinationModel}. + */ +public class V2CamelSapTRfcDestinationModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-srfc-destination-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.SRFC_DESTINATION; + private static final String DESTINATION_NAME = "nplHost"; + private static final String RFC_NAME = "BAPI_FLTRIP_GETLIST"; + private static final Boolean TRANSACTED = Boolean.TRUE; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + DESTINATION_NAME + ":" + RFC_NAME + + "?transacted=" + TRANSACTED; + + public V2CamelSapTRfcDestinationModelTest() { + super(SapSynchronousRfcDestinationEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2CamelSapBindingModel binding = + new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()) { + @Override + public boolean isReferenceBinding() { + return true; + } + }; + V2RfcDestinationModel endpoint = new V2RfcDestinationModel(CamelSapNamespace.V_2_0.uri(), + Constants.SRFC_DESTINATION); + endpoint.setDestinationName(DESTINATION_NAME); + endpoint.setRfcName(RFC_NAME); + endpoint.setTransacted(TRANSACTED); + return binding.setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2RfcDestinationModel.class, endpoint.getClass()); + V2RfcDestinationModel rfcDest = V2RfcDestinationModel.class.cast(endpoint); + assertEquals(DESTINATION_NAME, rfcDest.getDestinationName()); + assertEquals(RFC_NAME, rfcDest.getRfcName()); + assertEquals(TRANSACTED, rfcDest.isTransacted()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapTRfcServerModelTest.java b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapTRfcServerModelTest.java new file mode 100644 index 000000000..5f167fac2 --- /dev/null +++ b/components/camel/camel-sap/src/test/java/org/switchyard/component/camel/sap/model/v2/V2CamelSapTRfcServerModelTest.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sap.model.v2; + +import static org.junit.Assert.assertEquals; + +import org.fusesource.camel.component.sap.SapTransactionalRfcServerEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelServiceBindingModelTest; +import org.switchyard.component.camel.sap.model.CamelSapNamespace; +import org.switchyard.component.camel.sap.model.EndpointModel; + +/** + * Test for {@link V2CamelSapTRfcServerModel}. + */ +public class V2CamelSapTRfcServerModelTest extends V1BaseCamelServiceBindingModelTest { + + private static final String CAMEL_XML = "/v2/switchyard-sap-trfc-server-beans.xml"; + private static final String ENDPOINT_TYPE = Constants.TRFC_SERVER; + private static final String SERVER_NAME = "nplserver"; + private static final String RFC_NAME = "BOOK_FLIGHT"; + private static final String CAMEL_URI = "sap-" + ENDPOINT_TYPE + ":" + SERVER_NAME + ":" + RFC_NAME; + + public V2CamelSapTRfcServerModelTest() { + super(SapTransactionalRfcServerEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V2CamelSapBindingModel createTestModel() { + V2RfcServerModel endpoint = new V2RfcServerModel(CamelSapNamespace.V_2_0.uri(), Constants.TRFC_SERVER); + endpoint.setServerName(SERVER_NAME); + endpoint.setRfcName(RFC_NAME); + return new V2CamelSapBindingModel(CamelSapNamespace.V_2_0.uri()).setEndpointModel(endpoint); + } + + @Override + protected void createModelAssertions(V2CamelSapBindingModel model) { + EndpointModel endpoint = model.getEndpointModel(); + assertEquals(ENDPOINT_TYPE, endpoint.getName()); + assertEquals(V2RfcServerModel.class, endpoint.getClass()); + V2RfcServerModel rfcServer = V2RfcServerModel.class.cast(endpoint); + assertEquals(SERVER_NAME, rfcServer.getServerName()); + assertEquals(RFC_NAME, rfcServer.getRfcName()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoc-destination-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoc-destination-beans.xml new file mode 100644 index 000000000..e73be1064 --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoc-destination-beans.xml @@ -0,0 +1,32 @@ + + + + + + + + + nplHost + BAPI_FLTRIP_GETLIST + IDOC_TYPE_EXTENSION + SYSTEM_RELEASE + APPLICATION_RELEASE + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoclist-destination-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoclist-destination-beans.xml new file mode 100644 index 000000000..92de6eafc --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoclist-destination-beans.xml @@ -0,0 +1,31 @@ + + + + + + + + + nplHost + BAPI_FLTRIP_GETLIST + IDOC_TYPE_EXTENSION + SYSTEM_RELEASE + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoclist-server-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoclist-server-beans.xml new file mode 100644 index 000000000..f2739e22e --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-idoclist-server-beans.xml @@ -0,0 +1,32 @@ + + + + + + + + + nplserver + BOOK_FLIGHT + IDOC_TYPE_EXTENSION + SYSTEM_RELEASE + APPLICATION_RELEASE + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qidoc-destination-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qidoc-destination-beans.xml new file mode 100644 index 000000000..827da731a --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qidoc-destination-beans.xml @@ -0,0 +1,31 @@ + + + + + + + + + nplHost + QUEUE_NAME + BAPI_FLTRIP_GETLIST + IDOC_TYPE_EXTENSION + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qidoclist-destination-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qidoclist-destination-beans.xml new file mode 100644 index 000000000..bc3b208e6 --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qidoclist-destination-beans.xml @@ -0,0 +1,30 @@ + + + + + + + + + nplHost + QUEUE_NAME + BAPI_FLTRIP_GETLIST + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qrfc-destination-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qrfc-destination-beans.xml new file mode 100644 index 000000000..061e019d2 --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-qrfc-destination-beans.xml @@ -0,0 +1,31 @@ + + + + + + + + + nplHost + QUEUE_NAME + BAPI_FLTRIP_GETLIST + true + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-srfc-destination-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-srfc-destination-beans.xml new file mode 100644 index 000000000..a6d145ae0 --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-srfc-destination-beans.xml @@ -0,0 +1,30 @@ + + + + + + + + + nplHost + BAPI_FLTRIP_GETLIST + true + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-srfc-server-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-srfc-server-beans.xml new file mode 100644 index 000000000..4f326ca1c --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-srfc-server-beans.xml @@ -0,0 +1,29 @@ + + + + + + + + + nplserver + BOOK_FLIGHT + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-trfc-destination-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-trfc-destination-beans.xml new file mode 100644 index 000000000..0e8d3a07a --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-trfc-destination-beans.xml @@ -0,0 +1,30 @@ + + + + + + + + + nplHost + BAPI_FLTRIP_GETLIST + true + + + + + diff --git a/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-trfc-server-beans.xml b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-trfc-server-beans.xml new file mode 100644 index 000000000..29e60df4f --- /dev/null +++ b/components/camel/camel-sap/src/test/resources/v2/switchyard-sap-trfc-server-beans.xml @@ -0,0 +1,29 @@ + + + + + + + + + nplserver + BOOK_FLIGHT + + + + + diff --git a/components/camel/camel-sql/pom.xml b/components/camel/camel-sql/pom.xml new file mode 100644 index 000000000..4e4435fa8 --- /dev/null +++ b/components/camel/camel-sql/pom.xml @@ -0,0 +1,71 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-sql + bundle + SwitchYard: Camel Component :: SQL Binding + http://switchyard.org + + + org.switchyard.component.camel.sql.* + + + org.apache.camel.component.sql, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.apache.camel + camel-core + + + org.apache.camel + camel-sql + + + org.switchyard.components + switchyard-component-camel-test + test + + + diff --git a/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/CamelSqlComponent.java b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/CamelSqlComponent.java new file mode 100644 index 000000000..1a7771f04 --- /dev/null +++ b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/CamelSqlComponent.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sql.deploy; + +import org.switchyard.component.camel.common.deploy.BaseBindingComponent; +import org.switchyard.component.camel.sql.model.v1.V1CamelSqlBindingModel; + +/** + * Sql binding component. + */ +public class CamelSqlComponent extends BaseBindingComponent { + + /** + * Creates new component. + */ + public CamelSqlComponent() { + super("CamelSqlComponent", V1CamelSqlBindingModel.SQL); + } + +} diff --git a/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/SQLCamelComponentLogger.java b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/SQLCamelComponentLogger.java new file mode 100644 index 000000000..624c41bee --- /dev/null +++ b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/SQLCamelComponentLogger.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sql.deploy; + +import static org.jboss.logging.Logger.Level.ERROR; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 33800-33899 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface SQLCamelComponentLogger { + /** + * A root logger with the category of the package name. + */ + SQLCamelComponentLogger ROOT_LOGGER = Logger.getMessageLogger(SQLCamelComponentLogger.class, SQLCamelComponentLogger.class.getPackage().getName()); + + /** + * cannotLookupOperation method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 33400, value = "Cannot lookup operation using custom operation selector. Returning empty name") + void cannotLookupOperation(@Cause Exception e); +} diff --git a/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/SQLCamelComponentMessages.java b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/SQLCamelComponentMessages.java new file mode 100644 index 000000000..08d80bae6 --- /dev/null +++ b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/deploy/SQLCamelComponentMessages.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sql.deploy; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 34000-34100 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface SQLCamelComponentMessages { + /** + * The default messages. + */ + SQLCamelComponentMessages MESSAGES = Messages.getBundle(SQLCamelComponentMessages.class); + + /** + * periodAttributeMandatory method definition. + * + * @return SwitchYardException + */ + @Message(id = 34000, value = "Period attribute is mandatory for SQL service bindings") + SwitchYardException periodAttributeMandatory(); + + +} diff --git a/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/CamelSqlBindingModel.java b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/CamelSqlBindingModel.java new file mode 100644 index 000000000..b359bf561 --- /dev/null +++ b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/CamelSqlBindingModel.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sql.model; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Represents the configuration settings for a SQL endpoint in Camel. + */ +public interface CamelSqlBindingModel extends CamelBindingModel { + + /** + * Get SQL query to be executed. + * + * @return SQL query. + */ + String getQuery(); + + /** + * Specify sql query to execute. + * + * @param query SQL query. + * @return a reference to this Camel binding model + */ + CamelSqlBindingModel setQuery(String query); + + /** + * Reference to a DataSource to look up in the registry. + * + * @return Data source bean name. + */ + String getDataSourceRef(); + + /** + * Specify data source bean name. + * + * @param dataSourceRef Bean name. + * @return a reference to this Camel binding model + */ + CamelSqlBindingModel setDataSourceRef(String dataSourceRef); + + /** + * Execute SQL batch update statements. + * + * @return True if jdbc batch update should be performed. + */ + Boolean isBatch(); + + /** + * Turn on/off JDBC batching support. + * + * @param batch Batch flag. + * @return a reference to this Camel binding model + */ + CamelSqlBindingModel setBatch(Boolean batch); + + /** + * Get placeholder character. + * + * @return Paceholder character. + */ + String getPlaceholder(); + + /** + * Specifies a character that will be replaced to ? in SQL query. + * Notice, that it is simple String.replaceAll() operation and no SQL parsing is + * involved (quoted strings will also change). + * + * @param placeholder Placeholder in query. + * @return a reference to this Camel binding model + */ + CamelSqlBindingModel setPlaceholder(String placeholder); + + /** + * Period between polls. + * + * @return Period between polls. + */ + String getPeriod(); + + /** + * Specifies delays between pools. Possible values are long (millis) and string, eg: 1s, 1m. + * + * @param period Period between polls. + * @return a reference to this Camel binding model + */ + CamelSqlBindingModel setPeriod(String period); + + /** + * Specifies delay in millis before first poll. + * + * @param initialDelay First poll delay. + * @return a reference to this Camel binding model + */ + CamelSqlBindingModel setInitialDelay(Long initialDelay); + + /** + * Get first poll delay. + * + * @return First poll delay. + */ + Long getInitialDelay(); + + +} diff --git a/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/CamelSqlNamespace.java b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/CamelSqlNamespace.java new file mode 100644 index 000000000..b608b9c54 --- /dev/null +++ b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/CamelSqlNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sql.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel Sql config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelSqlNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final transient Util _util; + + /** + * Constructs a new CamelSqlNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelSqlNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelSqlNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelSqlNamespace + */ + public static CamelSqlNamespace fromUri(String uri) { + return Util.fromUri(CamelSqlNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelSqlNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel-sql:config", version); + } + } + +} diff --git a/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlBindingModel.java b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlBindingModel.java new file mode 100644 index 000000000..a3ad21f77 --- /dev/null +++ b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlBindingModel.java @@ -0,0 +1,166 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sql.model.v1; +import java.net.URI; +import java.util.List; + +import org.apache.camel.util.UnsafeUriCharactersEncoder; +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.sql.model.CamelSqlBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of sql configuration binding. + * + * @author Lukasz Dywicki + */ +public class V1CamelSqlBindingModel extends V1BaseCamelBindingModel + implements CamelSqlBindingModel { + /** + * Camel component prefix. + */ + public static final String SQL = "sql"; + private static final String QUERY = "query"; + private static final String DATA_SOURCE_REF = "dataSourceRef"; + private static final String BATCH = "batch"; + private static final String PLACEHOLDER = "placeholder"; + // timer related attributes + private static final String PERIOD = "period"; + private static final String INITIAL_DELAY = "initialDelay"; + + /** + * Create a new CamelSqlBindingModel. + * + * @param namespace + * namespace + */ + public V1CamelSqlBindingModel(String namespace) { + super(SQL, namespace); + setModelChildrenOrder(QUERY, DATA_SOURCE_REF, BATCH, PLACEHOLDER); + } + + /** + * Create a V1CamelSqlBindingModel from the specified configuration and + * descriptor. + * + * @param config + * The switchyard configuration instance. + * @param desc + * The switchyard descriptor instance. + */ + public V1CamelSqlBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getQuery() { + return getConfig(QUERY); + } + + @Override + public V1CamelSqlBindingModel setQuery(String query) { + return setConfig(QUERY, query); + } + + @Override + public String getDataSourceRef() { + return getConfig(DATA_SOURCE_REF); + } + + @Override + public V1CamelSqlBindingModel setDataSourceRef(String dataSourceRef) { + return setConfig(DATA_SOURCE_REF, dataSourceRef); + } + + @Override + public Boolean isBatch() { + return getBooleanConfig(BATCH); + } + + @Override + public V1CamelSqlBindingModel setBatch(Boolean batch) { + return setConfig(BATCH, batch); + } + + @Override + public String getPlaceholder() { + return getConfig(PLACEHOLDER); + } + + @Override + public V1CamelSqlBindingModel setPlaceholder(String placeholder) { + return setConfig(PLACEHOLDER, placeholder); + } + + @Override + public String getPeriod() { + return getModelAttribute(PERIOD); + } + + @Override + public V1CamelSqlBindingModel setPeriod(String schedule) { + setModelAttribute(PERIOD, schedule); + return this; + } + + @Override + public V1CamelSqlBindingModel setInitialDelay(Long initialDelay) { + setModelAttribute(INITIAL_DELAY, Long.toString(initialDelay)); + return this; + } + + @Override + public Long getInitialDelay() { + String value = getModelAttribute(INITIAL_DELAY); + return value == null ? null : Long.valueOf(value); + } + + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + String baseUri = SQL + "://" + getQuery(); + QueryString queryStr = new QueryString(); + queryStr.add("consumer.delay", getPeriod()); + queryStr.add("consumer.initialDelay", getInitialDelay()); + traverseConfiguration(children, queryStr, QUERY); + return URI.create(UnsafeUriCharactersEncoder.encode(baseUri + queryStr.toString())); + } + + + protected Long convertPeriodToLongMilliseconds(String period) { + if (isLong(period)) { + return new Long(period); + } else if (period.endsWith("s")) { + if (isLong(period.substring(0, period.length() - 1))) { + return new Long(period.substring(0, period.length() - 1) + "000"); + } + } + return null; + } + + protected boolean isLong(String s) { + try { + Long.parseLong(s); + } catch (NumberFormatException e) { + return false; + } + // only got here if we didn't return false + return true; + } +} + diff --git a/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlModelMarshaller.java b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlModelMarshaller.java new file mode 100644 index 000000000..a02ee23a4 --- /dev/null +++ b/components/camel/camel-sql/src/main/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sql.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Sql model marshaller. + */ +public class V1CamelSqlModelMarshaller extends V1BaseCamelMarshaller { + + private static final String BINDING_SQL = BindingModel.BINDING + '.' + V1CamelSqlBindingModel.SQL; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelSqlModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (BINDING_SQL.equals(name)) { + return new V1CamelSqlBindingModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/camel-sql/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/camel-sql/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..e144be253 --- /dev/null +++ b/components/camel/camel-sql/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.sql.deploy.CamelSqlComponent diff --git a/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v1/camel-sql_1_0.xsd b/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v1/camel-sql_1_0.xsd new file mode 100644 index 000000000..596b60cca --- /dev/null +++ b/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v1/camel-sql_1_0.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v1/camel-sql_1_1.xsd b/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v1/camel-sql_1_1.xsd new file mode 100644 index 000000000..94fad967f --- /dev/null +++ b/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v1/camel-sql_1_1.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v2/camel-sql_2_0.xsd b/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v2/camel-sql_2_0.xsd new file mode 100644 index 000000000..186cf3f0c --- /dev/null +++ b/components/camel/camel-sql/src/main/resources/org/switchyard/component/camel/sql/model/v2/camel-sql_2_0.xsd @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/camel/camel-sql/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/camel-sql/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..8bd49f7bc --- /dev/null +++ b/components/camel/camel-sql/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_sql_1_0.section=urn:switchyard-component-camel-sql:config +camel_sql_1_0.version=1.0 +camel_sql_1_0.namespace=urn:switchyard-component-camel-sql:config:1.0 +camel_sql_1_0.schema=camel-sql_1_0.xsd +camel_sql_1_0.location=/org/switchyard/component/camel/sql/model/v1/ +camel_sql_1_0.marshaller=org.switchyard.component.camel.sql.model.v1.V1CamelSqlModelMarshaller + +camel_sql_1_1.section=urn:switchyard-component-camel-sql:config +camel_sql_1_1.version=1.1 +camel_sql_1_1.namespace=urn:switchyard-component-camel-sql:config:1.1 +camel_sql_1_1.schema=camel-sql_1_1.xsd +camel_sql_1_1.location=/org/switchyard/component/camel/sql/model/v1/ +camel_sql_1_1.marshaller=org.switchyard.component.camel.sql.model.v1.V1CamelSqlModelMarshaller + +camel_sql_2_0.section=urn:switchyard-component-camel-sql:config +camel_sql_2_0.version=2.0 +camel_sql_2_0.namespace=urn:switchyard-component-camel-sql:config:2.0 +camel_sql_2_0.schema=camel-sql_2_0.xsd +camel_sql_2_0.location=/org/switchyard/component/camel/sql/model/v2/ +camel_sql_2_0.marshaller=org.switchyard.component.camel.sql.model.v1.V1CamelSqlModelMarshaller \ No newline at end of file diff --git a/components/camel/camel-sql/src/test/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlBindingModelTest.java b/components/camel/camel-sql/src/test/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlBindingModelTest.java new file mode 100644 index 000000000..6f5179d49 --- /dev/null +++ b/components/camel/camel-sql/src/test/java/org/switchyard/component/camel/sql/model/v1/V1CamelSqlBindingModelTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.sql.model.v1; + +import static junit.framework.Assert.assertEquals; + +import org.apache.camel.component.sql.SqlEndpoint; +import org.switchyard.component.camel.config.test.v1.V1BaseCamelReferenceBindingModelTest; +import org.switchyard.component.camel.sql.model.CamelSqlNamespace; + +/** + * Test for {@link V1CamelSqlBindingModel}. + * + * @author Lukasz Dywicki + */ +public class V1CamelSqlBindingModelTest extends V1BaseCamelReferenceBindingModelTest { + + private static final String CAMEL_XML = "/v1/switchyard-sql-binding-beans.xml"; + private static final String CAMEL_URI = "sql://INSERT INTO events VALUES(?, ?, ?)?dataSourceRef=myDS&batch=false&placeholder=?"; + + private static final String QUERY = "INSERT INTO events VALUES(?, ?, ?)"; + private static final String DATA_SOURCE_REF = "myDS"; + private static final Boolean BATCH = false; + private static final String PLACEHOLDER = "?"; + + public V1CamelSqlBindingModelTest() { + super(SqlEndpoint.class, CAMEL_XML); + + setSkipCamelEndpointTesting(true); + } + + @Override + protected V1CamelSqlBindingModel createTestModel() { + return new V1CamelSqlBindingModel(CamelSqlNamespace.V_1_0.uri()) + .setQuery(QUERY) + .setDataSourceRef(DATA_SOURCE_REF) + .setBatch(BATCH) + .setPlaceholder(PLACEHOLDER); + } + + @Override + protected void createModelAssertions(V1CamelSqlBindingModel model) { + assertEquals(QUERY, model.getQuery()); + assertEquals(DATA_SOURCE_REF, model.getDataSourceRef()); + assertEquals(BATCH, model.isBatch()); + assertEquals(PLACEHOLDER, model.getPlaceholder()); + } + + @Override + protected String createEndpointUri() { + return CAMEL_URI; + } + +} \ No newline at end of file diff --git a/components/camel/camel-sql/src/test/resources/v1/switchyard-sql-binding-beans.xml b/components/camel/camel-sql/src/test/resources/v1/switchyard-sql-binding-beans.xml new file mode 100644 index 000000000..aa1b8e541 --- /dev/null +++ b/components/camel/camel-sql/src/test/resources/v1/switchyard-sql-binding-beans.xml @@ -0,0 +1,30 @@ + + + + + + + + INSERT INTO events VALUES(?, ?, ?) + myDS + false + ? + + + + + diff --git a/components/camel/camel-switchyard/pom.xml b/components/camel/camel-switchyard/pom.xml new file mode 100644 index 000000000..3a57f0f0e --- /dev/null +++ b/components/camel/camel-switchyard/pom.xml @@ -0,0 +1,91 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-switchyard + bundle + SwitchYard: Camel Component :: Camel Component + http://switchyard.org + + + org.switchyard.component.camel.switchyard.* + + + + + org.apache.camel + camel-core + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-extensions-java + test + + + org.switchyard + switchyard-security + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-bean + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.hamcrest + hamcrest-core + test + + + org.mockito + mockito-all + test + + + org.apache.camel + camel-test + test + + + diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/CamelResponseHandler.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/CamelResponseHandler.java new file mode 100644 index 000000000..96dd350f4 --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/CamelResponseHandler.java @@ -0,0 +1,114 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import org.apache.camel.ExchangePattern; +import org.apache.camel.Message; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.HandlerException; +import org.switchyard.ServiceReference; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.common.composer.MessageComposer; + +/** + * A CamelResponseHandler is responsible for passing back result data from Apache Camel to + * SwitchYard. + * + * By given access to the CamelExchange this ExchangeHandler can extract the SwitchYard payload + * and set in into the Camel Exchange. + * + * @author Daniel Bevenius + */ +public class CamelResponseHandler implements ExchangeHandler { + + private final org.apache.camel.Exchange _camelExchange; + private final MessageComposer _messageComposer; + + /** + * Sole constructor. + * + * @param camelExchange The Camel {@link org.apache.camel.Exchange} + * @param reference The SwitchYard ServiceReference. + * @param messageComposer the MessageComposer to use + */ + public CamelResponseHandler(final org.apache.camel.Exchange camelExchange, final ServiceReference reference, final MessageComposer messageComposer) { + if (camelExchange == null) { + throw SwitchYardCamelComponentMessages.MESSAGES.camelExchangeArgumentMustNotBeNull(); + } + if (reference == null) { + throw SwitchYardCamelComponentMessages.MESSAGES.referenceArgumentMustNotBeNull(); + } + _camelExchange = camelExchange; + _messageComposer = messageComposer; + } + + /** + * Will extract the message content from the SwitchYard exchange and insert + * it into the Camel Exchange's In body. + * + * @param switchYardExchange SwitchYards Exchange from which the payload will be extracted. + * @throws HandlerException If there was an exception while trying to extract the payload from + * the SwitchYard Exchange. + */ + @Override + public void handleMessage(final Exchange switchYardExchange) throws HandlerException { + try { + compose(switchYardExchange); + } catch (Exception e) { + throw new HandlerException(e); + } + } + + private Message getCamelMessage() { + return isInOnly() ? _camelExchange.getIn() : _camelExchange.getOut(); + } + + private boolean isInOnly() { + return _camelExchange.getPattern().equals(ExchangePattern.InOnly); + } + + @Override + public void handleFault(final Exchange exchange) { + final Object content = exchange.getMessage().getContent(); + + if (content instanceof Throwable) { + _camelExchange.setException((Throwable) content); + return; + } + + try { + Message camelMsg = compose(exchange); + camelMsg.setFault(true); + } catch (Exception e) { + _camelExchange.setException(e); + } + } + + private Message compose(Exchange exchange) throws Exception { + Message camelMsg; + if (_messageComposer != null) { + camelMsg = getCamelMessage(); + _messageComposer.decompose(exchange, new CamelBindingData(camelMsg)); + } else { + camelMsg = ExchangeMapper.mapSwitchYardToCamel(exchange, _camelExchange); + if (isInOnly()) { + _camelExchange.setIn(camelMsg); + } else { + _camelExchange.setOut(camelMsg); + } + } + return camelMsg; + } +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/ComponentNameComposer.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/ComponentNameComposer.java new file mode 100644 index 000000000..497a536c0 --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/ComponentNameComposer.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.switchyard.component.camel.common.CamelConstants.SWITCHYARD_COMPONENT_NAME; + +import java.net.URI; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.deploy.ComponentNames; + +/** + * Utility class that takes care of creating Camel component uris for + * SwitchYard services. + * + * @author Daniel Bevenius + */ +public final class ComponentNameComposer { + + private ComponentNameComposer() { + } + + /** + * Creates a Camel endpoint URI based on the component and service name. + * Returns a String that has the format: + *

+     * {@value #SWITCHYARD_COMPONENT_NAME}://serviceName.getLocalPart()
+     * 
+ * @param serviceName SwitchYard service name + * @return camel endpoint URI based on component and service name + */ + public static String composeComponentUri(final QName serviceName) { + final StringBuilder sb = new StringBuilder(); + sb.append(SWITCHYARD_COMPONENT_NAME).append("://").append(serviceName.getLocalPart()); + return sb.toString(); + } + + /** + * Composes a SwitchYard service name, a QName, from the passed-in string uri. + * + * @param namespace the service namespace + * @param uri a string uri. + * @param componentName service componentName + * @return QName a SwitchYard service name + */ + public static QName composeSwitchYardServiceName( + final String namespace, final String uri, final QName componentName) { + final URI create = URI.create(uri); + final String path = create.getAuthority(); + if (componentName != null) { + return ComponentNames.qualify(componentName.getLocalPart(), path, namespace); + } else { + return XMLHelper.createQName(namespace, path); + } + + } + + /** + * Parses the passed-in URI's query for parameters and returns the as + * a Map. + * + * @param uri The URI to parse + * @return Map Containing the query parameters or an empty map if there were no query parameters. + */ + public static Map getQueryParamMap(final URI uri) { + final Map map = new HashMap(); + for (final String param : uri.getQuery().split("&")) { + final String[] nameValue = param.split("="); + if (nameValue.length == 2) { + map.put(nameValue[0], nameValue[1]); + } + } + return map; + } + +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/ExchangeMapper.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/ExchangeMapper.java new file mode 100644 index 000000000..5233f84ef --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/ExchangeMapper.java @@ -0,0 +1,149 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.activation.DataHandler; + +import org.apache.camel.impl.DefaultMessage; +import org.switchyard.ExchangePhase; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.common.camel.ContextPropertyUtil; +import org.switchyard.common.camel.HandlerDataSource; +import org.switchyard.common.camel.SwitchYardMessage; +import org.switchyard.label.BehaviorLabel; + +/** + * ExchangeMapper handles the mapping between SwitchYard and Camel exchanges when used from a Camel + * implementation. This mapping is distinct from what message composers do with gateways for two + * reasons: + * 1) Gateway composers are configurable by users. Internal mapping between exchanges + * within a camel implementation should not be configurable. + * 2) The mapping rules for gateways and implementations can differ in subtle ways. For example, + * transient context properties propagate from gateway routes with SwitchYardProducer, but this should + * not happen in implementation routes as it allows exchange properties to leak between multiple + * switchyard:// endpoint invocations. + */ +public final class ExchangeMapper { + + /** + * Name of List exchange property with names of properties to include in mapping. By + * default, all Camel* exchange properties are excluded. + */ + public static final String CAMEL_PROPERTY_INCLUDES = "org.switchyard.includedCamelProperties"; + private static final String CAMEL_PROPERTY_PREFIX = "Camel"; + + private ExchangeMapper() { + + } + + /** + * Map from a camel exchange to a SwitchYard exchange. + * @param camelExchange the camel exchange + * @param syExchange the switchyard exchange + * @param phase ExchangePhase.IN to target camelExchange.getIn(), ExchangePhase.OUT to + * target camelExchange.getIn(). + * @return the + */ + public static org.switchyard.Message mapCamelToSwitchYard( + org.apache.camel.Exchange camelExchange, + org.switchyard.Exchange syExchange, + ExchangePhase phase) { + + // Associate the correct Camel message with the SY exchange + org.switchyard.Message message = syExchange.createMessage(); + org.apache.camel.Message camelMessage; + if (phase.equals(ExchangePhase.OUT) && camelExchange.hasOut()) { + camelMessage = camelExchange.getOut(); + } else { + camelMessage = camelExchange.getIn(); + } + message.setContent(camelMessage.getBody()); + + for (String property : camelExchange.getProperties().keySet()) { + if (ContextPropertyUtil.isReservedProperty(property, Scope.EXCHANGE)) { + continue; + } + // skip the implementation route property as we don't want that propagated + if (SwitchYardConsumer.IMPLEMENTATION_ROUTE.equals(property)) { + continue; + } + // skip Camel* properties unless they have been explicitly included + List propertyIncludes = camelExchange.getProperty(CAMEL_PROPERTY_INCLUDES, List.class); + if (property.startsWith(CAMEL_PROPERTY_PREFIX) + && (propertyIncludes == null || !propertyIncludes.contains(property))) { + continue; + } + + message.getContext().setProperty(property, camelExchange.getProperty(property), Scope.EXCHANGE); + } + + Set> entrySet = camelMessage.getHeaders().entrySet(); + Iterator> iter = entrySet.iterator(); + while (iter.hasNext()) { + String header = iter.next().getKey(); + if (ContextPropertyUtil.isReservedProperty(header, Scope.MESSAGE)) { + continue; + } + message.getContext().setProperty(header, camelMessage.getHeader(header), Scope.MESSAGE); + } + + for (String attachmentName : camelMessage.getAttachmentNames()) { + message.addAttachment(attachmentName, new HandlerDataSource(camelMessage.getAttachment(attachmentName))); + } + + return message; + } + + /** + * Maps a SwitchYard exchange to a Camel exchange. Keep in mind that the camel message created + * during mapping is *not* associate with the exchange. You need to call setIn() or setOut() + * with the returned reference depending on your use case. + * @param syExchange switchyard exchange + * @param camelExchange camel exchange + * @return mapped camel message + */ + public static DefaultMessage mapSwitchYardToCamel( + org.switchyard.Exchange syExchange, + org.apache.camel.Exchange camelExchange) { + + DefaultMessage camelMessage = new SwitchYardMessage(); + camelMessage.setBody(syExchange.getMessage().getContent()); + + for (Property property : syExchange.getContext().getProperties()) { + if (property.hasLabel(BehaviorLabel.TRANSIENT.label()) + || ContextPropertyUtil.isReservedProperty(property.getName(), property.getScope())) { + continue; + } + + if (Scope.EXCHANGE.equals(property.getScope())) { + camelExchange.setProperty(property.getName(), property.getValue()); + } else { + camelMessage.setHeader(property.getName(), property.getValue()); + } + } + + for (String attachmentName : syExchange.getMessage().getAttachmentMap().keySet()) { + camelMessage.addAttachment(attachmentName, + new DataHandler(syExchange.getMessage().getAttachment(attachmentName))); + } + + return camelMessage; + } +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardCamelComponentLogger.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardCamelComponentLogger.java new file mode 100644 index 000000000..0192ecb91 --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardCamelComponentLogger.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.jboss.logging.Logger.Level.ERROR; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 33800-33899 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface SwitchYardCamelComponentLogger { + /** + * A root logger with the category of the package name. + */ + SwitchYardCamelComponentLogger ROOT_LOGGER = Logger.getMessageLogger(SwitchYardCamelComponentLogger.class, SwitchYardCamelComponentLogger.class.getPackage().getName()); + + /** + * cannotLookupOperation method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 33400, value = "Cannot lookup operation using custom operation selector. Returning empty name") + void cannotLookupOperation(@Cause Exception e); +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardCamelComponentMessages.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardCamelComponentMessages.java new file mode 100644 index 000000000..00f7134c2 --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardCamelComponentMessages.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; + +import org.switchyard.HandlerException; + +/** + *

+ * This file is using the subset 33900-33999 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface SwitchYardCamelComponentMessages { + /** + * The default messages. + */ + SwitchYardCamelComponentMessages MESSAGES = Messages.getBundle(SwitchYardCamelComponentMessages.class); + + /** + * noServiceReferenceFoundForURI method definition. + * @param uri uri + * @return NullPointerException + */ + @Message(id = 33900, value = "No ServiceReference was found for uri [%s]") + NullPointerException noServiceReferenceFoundForURI(String uri); + + /** + * unableToDetermineOperation method definition. + * @return String + */ + @Message(id = 33901, value = "Unable to determine operation as the target service contains more than one operation") + String unableToDetermineOperation(); + + /** + * camelExchangeFailedWithoutException method definition. + * @param camelFault camel fault + * @return HandlerException + */ + @Message(id = 33902, value = "camel exchange failed without an exception: %s") + HandlerException camelExchangeFailedWithoutException(String camelFault); + + /** + * camelExchangeFailed method definition. + * @return HandlerException + */ + @Message(id = 33903, value = "camel exchange failed without an exception") + HandlerException camelExchangeFailed(); + + /** + * invalidHandlerState method definition. + * @return SwitchYardException + */ + @Message(id = 33904, value = "Invalid handler state.") + SwitchYardException invalidHandlerState(); + + /** + * stateCannotBeNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 33905, value = "State cannot be null.") + IllegalArgumentException stateCannotBeNull(); + + /** + * camelExchangeArgumentMustNotBeNull method definition. + * @return SwitchYardException + */ + @Message(id = 33906, value = "[camelExchange] argument must not be null") + SwitchYardException camelExchangeArgumentMustNotBeNull(); + + /** + * referenceArgumentMustNotBeNull method definition. + * @return SwitchYardException + */ + @Message(id = 33907, value = "[reference] argument must not be null") + SwitchYardException referenceArgumentMustNotBeNull(); + + +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardComponent.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardComponent.java new file mode 100644 index 000000000..d64cec9bc --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardComponent.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import java.util.Map; + +import org.apache.camel.Endpoint; +import org.apache.camel.impl.DefaultComponent; +import org.switchyard.component.camel.common.composer.BindingDataCreatorResolver; + +/** + * SwitchYardComponent enable Switchyard services to be exposed through Apache Camel. + *

+ * This classes {@link #createEndpoint(String, String, Map)} creates a {@link SwitchYardEndpoint}. + * + * Example usage using Camel's Java DSL: + *

+ * from("switchyard://someIncomingService")
+ * ...
+ * .to("switchyard://mySwitchyardService")
+ * 
+ * + * @author Daniel Bevenius + */ +public class SwitchYardComponent extends DefaultComponent { + + private BindingDataCreatorResolver _bindingDataCreatorResolver = new BindingDataCreatorResolver(); + + @Override + protected Endpoint createEndpoint(final String uri, final String path, final Map parameters) throws Exception { + final String operationName = (String) parameters.remove("operationName"); + return new SwitchYardEndpoint(uri, this, operationName); + } + + /** + * Returns binding data creator resolver. + * + * @return An instance of binding data creator. + */ + public BindingDataCreatorResolver getBindingDataCreatorResolver() { + return _bindingDataCreatorResolver; + } + + /** + * Setter which allows to specify custom bindingDataCreator. + * + * @param bindingDataCreatorResolver Binding data creator to use. + */ + public void setBindingDataCreatorResolver(BindingDataCreatorResolver bindingDataCreatorResolver) { + this._bindingDataCreatorResolver = bindingDataCreatorResolver; + } + +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardConsumer.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardConsumer.java new file mode 100644 index 000000000..61ce59bad --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardConsumer.java @@ -0,0 +1,214 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.switchyard.Exchange.FAULT_TYPE; +import static org.switchyard.Exchange.OPERATION_NAME; +import static org.switchyard.Exchange.SERVICE_NAME; + +import java.util.concurrent.atomic.AtomicReference; + +import javax.xml.namespace.QName; + +import org.apache.camel.Endpoint; +import org.apache.camel.Processor; +import org.apache.camel.impl.DefaultConsumer; +import org.apache.camel.impl.DefaultMessage; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.component.camel.common.CamelConstants; +import org.switchyard.deploy.ServiceHandler; +import org.switchyard.SwitchYardException; +import org.switchyard.metadata.ServiceOperation; +import org.w3c.dom.Node; + +/** + * A SwitchYardConsumer is both a Camel Consumer and an SwitchYard ExchangeHandler. + *

+ * A Camel event driven consumer that is able to receive events, SwitchYard Exchanges, + * and invoke the Camel processors. + * + * @author Daniel Bevenius + */ +public class SwitchYardConsumer extends DefaultConsumer implements ServiceHandler { + + private AtomicReference _state = new AtomicReference(State.NONE); + + private QName _componentName; + private String _namespace; + + /** + * Used to flag an exchange as originating from a service implementation route. + */ + public static final String IMPLEMENTATION_ROUTE = + "org.switchyard.component.camel.implementation"; + + /** + * The name of the service component containing this camel route. + */ + public static final String COMPONENT_NAME = + "org.switchyard.component.camel.componentName"; + + /** + * Sole constructor. + * + * @param endpoint The Camel endpoint that this consumer was created by. + * @param processor The Camel processor that this consumer will delegate to. + */ + public SwitchYardConsumer(final Endpoint endpoint, final Processor processor) { + super(endpoint, processor); + } + + @Override + public void handleMessage(final Exchange switchyardExchange) throws HandlerException { + org.apache.camel.Exchange camelExchange = getEndpoint().createExchange( + isInOut(switchyardExchange) ? org.apache.camel.ExchangePattern.InOut : org.apache.camel.ExchangePattern.InOnly); + DefaultMessage targetMessage = ExchangeMapper.mapSwitchYardToCamel(switchyardExchange, camelExchange); + + // mark this as an exchange for a camel implementation service + camelExchange.setProperty(IMPLEMENTATION_ROUTE, true); + camelExchange.setProperty(COMPONENT_NAME, _componentName); + + // set the application namespace property in case producer endpoints are used in the route + camelExchange.setProperty(CamelConstants.APPLICATION_NAMESPACE, _namespace); + + ServiceOperation operation = switchyardExchange.getContract().getProviderOperation(); + camelExchange.setProperty(OPERATION_NAME, operation.getName()); + camelExchange.setProperty(FAULT_TYPE, operation.getFaultType()); + camelExchange.setProperty(SERVICE_NAME, switchyardExchange.getProvider().getName()); + camelExchange.setIn(targetMessage); + + invokeCamelProcessor(camelExchange); + Exception camelException = camelExchange.getException(); + + if (camelExchange.isFailed()) { + QName faultName = switchyardExchange.getContract().getProviderOperation().getFaultType(); + Class declaredFault = faultName != null && QNameUtil.isJavaMessageType(faultName) ? QNameUtil.toJavaMessageType(faultName) : null; + + Object camelFault = camelException; + if (camelFault == null) { + if (camelExchange.hasOut() && camelExchange.getOut().isFault()) { + // Use Out body as a fault content if camelExchange.getException() returns null + camelFault = camelExchange.getOut().getBody(); + } + } + + if (camelFault != null && declaredFault != null && declaredFault.isAssignableFrom(camelFault.getClass())) { + Message msg = switchyardExchange.createMessage().setContent(camelFault); + switchyardExchange.sendFault(msg); + } else if (camelFault instanceof Throwable) { + throw new HandlerException(Throwable.class.cast(camelFault)); + } else if (camelFault instanceof Node) { + Message msg = switchyardExchange.createMessage().setContent((Node)camelFault); + switchyardExchange.sendFault(msg); + } else { + String faultMessage = (camelFault == null) ? null : camelFault.toString(); + throw SwitchYardCamelComponentMessages.MESSAGES.camelExchangeFailedWithoutException(faultMessage); + } + } else if (isInOut(switchyardExchange)) { + sendResponse(camelExchange, switchyardExchange); + } + } + + @Override + public synchronized void start() { + if (getState() == State.STARTED) { + // already started + return; + } else if (getState() != State.NONE) { + throw SwitchYardCamelComponentMessages.MESSAGES.invalidHandlerState(); + } + setState(State.STARTING); + try { + super.start(); + setState(State.STARTED); + } catch (Exception ex) { + setState(State.NONE); + throw new SwitchYardException(ex); + } + } + + @Override + public synchronized void stop() { + if (getState() == State.NONE) { + // already stopped + return; + } else if (getState() != State.STARTED) { + throw SwitchYardCamelComponentMessages.MESSAGES.invalidHandlerState(); + } + setState(State.STOPPING); + try { + super.stop(); + setState(State.NONE); + } catch (Exception ex) { + setState(State.STARTED); + throw new SwitchYardException(ex); + } + } + + /** + * Set the service component name for this camel route implementation. + * @param componentName service component name + */ + public void setComponentName(QName componentName) { + _componentName = componentName; + } + + /** + * Set the application namespace for this camel route implementation. + * @param namespace namespace URI + */ + public void setNamespace(String namespace) { + _namespace = namespace; + } + + private void invokeCamelProcessor(final org.apache.camel.Exchange camelExchange) throws HandlerException { + try { + getProcessor().process(camelExchange); + } catch (final Exception e) { + throw new HandlerException(e); + } + } + + private void sendResponse(org.apache.camel.Exchange camelExchange, final Exchange switchyardExchange) throws HandlerException { + Message message = ExchangeMapper.mapCamelToSwitchYard( + camelExchange, switchyardExchange, ExchangePhase.OUT); + switchyardExchange.send(message); + } + + private boolean isInOut(final Exchange exchange) { + return exchange.getContract().getProviderOperation().getExchangePattern() == ExchangePattern.IN_OUT; + } + + @Override + public void handleFault(final Exchange exchange) { + //TODO: Implement error handling. + } + + @Override + public State getState() { + return _state.get(); + } + + private void setState(State newState) { + if (newState == null) { + throw SwitchYardCamelComponentMessages.MESSAGES.stateCannotBeNull(); + } + _state.set(newState); + } +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardEndpoint.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardEndpoint.java new file mode 100644 index 000000000..59bbe1805 --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardEndpoint.java @@ -0,0 +1,137 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.impl.DefaultEndpoint; +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.composer.BindingDataCreatorResolver; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.composer.CamelComposition; +import org.switchyard.component.common.composer.MessageComposer; + +/** + * A Camel Endpoint that is a simple ProcessorEndpoint. + * + * @author Daniel Bevenius + */ +public class SwitchYardEndpoint extends DefaultEndpoint { + + /** + * Producer property. + */ + private String _operationName; + + /** + * Producer property. + */ + private MessageComposer _messageComposer; + + /** + * SwitchYard Consumer that handles events from SwitchYard and delegates + * to the Camel processors. + */ + private SwitchYardConsumer _consumer; + + /** + * Sole constructor. + * + * @param endpointUri The uri of the Camel endpoint. + * @param component The {@link SwitchYardComponent}. + * @param operationName The operation name that a Producer requires + */ + public SwitchYardEndpoint(final String endpointUri, final SwitchYardComponent component, final String operationName) { + super(endpointUri, component); + _operationName = operationName; + } + + /** + * Sets the message composer this endpoint should pass along to producers and consumers. + * @param messageComposer the message composer + * @return this endpoint (useful for chaining) + */ + public synchronized SwitchYardEndpoint setMessageComposer(MessageComposer messageComposer) { + _messageComposer = messageComposer; + return this; + } + + /** + * Gets the message composer this endpoint should pass along to producers and consumers. + * @return the message composer + */ + public synchronized MessageComposer getMessageComposer() { + if (_messageComposer == null) { + _messageComposer = CamelComposition.getMessageComposer(); + } + return _messageComposer; + } + + /** + * Creates a event driven consumer as opposed to a polling consumer. + * @param processor processor used by consumer + * @return event-driven consumer + * @throws Exception error creating consumer + */ + @Override + public Consumer createConsumer(final Processor processor) throws Exception { + _consumer = new SwitchYardConsumer(this, processor); + return _consumer; + } + + /** + * Gets the consumer for this endpoint. + * + * @return {@link SwitchYardConsumer} + */ + public SwitchYardConsumer getConsumer() { + return _consumer; + } + + /** + * {@inheritDoc} + */ + @Override + public Producer createProducer() throws Exception { + return new SwitchYardProducer(this, _operationName, getMessageComposer()); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isSingleton() { + return true; + } + + /** + * Returns component binding data creator resolver. + * + * @return Component binding data creator resolver. + */ + public BindingDataCreatorResolver getBindingDataCreatorResolver() { + return ((SwitchYardComponent) getComponent()).getBindingDataCreatorResolver(); + } + + /** + * Returns the ServiceDomain used for this endpoint. + * + * @return ServiceDomain used for this endpoint. + */ + public ServiceDomain getServiceDomain() { + return ((SwitchYardCamelContext) getCamelContext()).getServiceDomain(); + } +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardProducer.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardProducer.java new file mode 100644 index 000000000..35c4b9bca --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardProducer.java @@ -0,0 +1,231 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.switchyard.component.camel.switchyard.ComponentNameComposer.composeSwitchYardServiceName; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.camel.Endpoint; +import org.apache.camel.impl.DefaultProducer; +import org.switchyard.Exchange; +import org.switchyard.ExchangePhase; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.SwitchYardException; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.CamelConstants; +import org.switchyard.component.camel.common.composer.BindingDataCreator; +import org.switchyard.component.camel.common.composer.BindingDataCreatorResolver; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.SecurityBindingData; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.policy.PolicyUtil; +import org.switchyard.policy.TransactionPolicy; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.security.context.SecurityContextManager; +import org.switchyard.selector.OperationSelector; + +/** + * A Camel producer that is capable of calling SwitchYard services from a Camel route. + *

+ * + * A SwitchYardProducer is created by Camel when a 'to' route contains the switchyard component. + * For example: + *
+ *    from("direct://input).
+ *    to("switchyard://serviceName?operationName=print");
+ * 
+ * + * @author Daniel Bevenius + * + */ +public class SwitchYardProducer extends DefaultProducer { + + private String _operationName; + private final MessageComposer _messageComposer; + + /** + * Sole constructor. + * + * @param endpoint the Camel Endpoint that this Producer belongs to. + * @param operationName the operation name of the target SwitchYard service. + * @param messageComposer the MessageComposer to use + */ + public SwitchYardProducer(final Endpoint endpoint, final String operationName, final MessageComposer messageComposer) { + super(endpoint); + _operationName = operationName; + _messageComposer = messageComposer; + } + + @Override + public void process(final org.apache.camel.Exchange camelExchange) throws Exception { + final String namespace = camelExchange.getProperty(CamelConstants.APPLICATION_NAMESPACE, String.class); + final String targetUri = camelExchange.getProperty(org.apache.camel.Exchange.TO_ENDPOINT, String.class); + ServiceDomain domain = ((SwitchYardCamelContext) camelExchange.getContext()).getServiceDomain(); + final ServiceReference serviceRef = lookupServiceReference(targetUri, namespace, domain, + camelExchange.getProperty(SwitchYardConsumer.COMPONENT_NAME, QName.class)); + + // set a flag to indicate whether this producer endpoint is used within a service route + boolean isGatewayRoute = camelExchange.getProperty(SwitchYardConsumer.IMPLEMENTATION_ROUTE) == null; + + // the composer is not used for switchyard:// endpoints invoked from service routes + MessageComposer composer = + isGatewayRoute ? getMessageComposer(camelExchange) : null; + final Exchange switchyardExchange = createSwitchyardExchange(camelExchange, serviceRef, composer); + + // Set appropriate policy based on Camel exchange properties + if (camelExchange.isTransacted()) { + PolicyUtil.provide(switchyardExchange, TransactionPolicy.PROPAGATES_TRANSACTION); + PolicyUtil.provide(switchyardExchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + } + + // Message composition depends on whether this switchyard:// endpoint is called from + // a Camel service implementation or a Camel gateway + Message switchyardMessage; + if (isGatewayRoute) { + switchyardMessage = composeForGateway(composer, camelExchange, switchyardExchange); + } else { + switchyardMessage = ExchangeMapper.mapCamelToSwitchYard( + camelExchange, switchyardExchange, ExchangePhase.IN); + } + + switchyardExchange.send(switchyardMessage); + } + + private Message composeForGateway(MessageComposer composer, + org.apache.camel.Exchange camelExchange, Exchange switchyardExchange) throws Exception { + + BindingDataCreator bindingCreator = getBindingDataCreator(camelExchange); + CamelBindingData bindingData = bindingCreator.createBindingData(camelExchange.getIn()); + if (bindingData instanceof SecurityBindingData) { + // returned binding is contains some security bindings, let's move them to security context + ServiceDomain serviceDomain = ((SwitchYardCamelContext)camelExchange.getContext()).getServiceDomain(); + SecurityContextManager securityContextManager = new SecurityContextManager(serviceDomain); + securityContextManager.addCredentials(switchyardExchange, ((SecurityBindingData)bindingData).extractCredentials()); + } + + /* + * initialize the gateway name on the context. this was most likely not + * mapped by the message composer/context mapper. + */ + final String gatewayName = camelExchange.getProperty(ExchangeCompletionEvent.GATEWAY_NAME, String.class); + if (gatewayName != null) { + switchyardExchange.getContext() + .setProperty(ExchangeCompletionEvent.GATEWAY_NAME, gatewayName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } + + return composer.compose(bindingData, switchyardExchange); + } + + /** + * Helper method which lookup for BindingDataCreatorResolver and uses returned + * instance to create new CamelBindingData. + * + * @param camelExchange Camel exchange. + * @return Binding data creator. + */ + private BindingDataCreator getBindingDataCreator(org.apache.camel.Exchange camelExchange) { + BindingDataCreatorResolver resolver = ((SwitchYardEndpoint) getEndpoint()).getBindingDataCreatorResolver(); + String resolverKey = camelExchange.getFromEndpoint().getClass().getSimpleName(); + return resolver.resolveBindingCreator(resolverKey, getEndpoint().getCamelContext()); + } + + @SuppressWarnings("unchecked") + private String getOperationName(org.apache.camel.Exchange exchange) { + String operationName = null; + + OperationSelector selector = exchange.getIn().getHeader(CamelConstants.OPERATION_SELECTOR_HEADER, OperationSelector.class); + if (selector != null) { + try { + operationName = selector.selectOperation(new CamelBindingData(exchange.getIn())).getLocalPart(); + } catch (Exception e) { + SwitchYardCamelComponentLogger.ROOT_LOGGER.cannotLookupOperation(e); + } + } + return operationName; + } + + @SuppressWarnings("unchecked") + private MessageComposer getMessageComposer(org.apache.camel.Exchange exchange) { + MessageComposer composer = exchange.getIn().getHeader(CamelConstants.MESSAGE_COMPOSER_HEADER, MessageComposer.class); + return composer == null ? _messageComposer : composer; + } + + private ServiceReference lookupServiceReference( + final String targetUri, final String namespace, ServiceDomain domain, QName componentName) { + final QName serviceName = composeSwitchYardServiceName(namespace, targetUri, componentName); + final ServiceReference serviceRef = domain.getServiceReference(serviceName); + if (serviceRef == null) { + throw SwitchYardCamelComponentMessages.MESSAGES.noServiceReferenceFoundForURI(targetUri); + } + return serviceRef; + } + + private Exchange createSwitchyardExchange(final org.apache.camel.Exchange camelExchange, final ServiceReference serviceRef, + MessageComposer messageComposer) { + String opName = lookupOperationNameFor(camelExchange, serviceRef); + CamelResponseHandler handler = new CamelResponseHandler(camelExchange, serviceRef, messageComposer); + + + if (opName != null) { + return serviceRef.createExchange(opName, handler); + } else { + return serviceRef.createExchange(handler); + } + } + + private String lookupOperationNameFor(final org.apache.camel.Exchange camelExchange, final ServiceReference serviceRef) { + + // Initialize operation name to whatever is specified in endpoint URI + String operationName = _operationName; + + // See if an operation selector has been specified + if (operationName == null) { + operationName = getOperationName(camelExchange); + } + + // If we still haven't found an operation and the target service only has one operation, + // then just use that + if (operationName == null) { + Set ops = serviceRef.getInterface().getOperations(); + if (ops.size() == 1) { + operationName = ops.iterator().next().getName(); + } else { + // See if the existing camel operation exists on the target service + String camelOp = camelExchange.getProperty(Exchange.OPERATION_NAME, String.class); + if (serviceRef.getInterface().getOperation(camelOp) != null) { + operationName = camelOp; + } + } + } + + // Still haven't found it? Houston, we have a problem. + if (operationName == null) { + final StringBuilder msg = new StringBuilder(); + msg.append(SwitchYardCamelComponentMessages.MESSAGES.unableToDetermineOperation()); + msg.append(serviceRef.getInterface().getOperations()); + throw new SwitchYardException(msg.toString()); + } + return operationName; + } + +} diff --git a/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardPropertiesParser.java b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardPropertiesParser.java new file mode 100644 index 000000000..89cb1cc9d --- /dev/null +++ b/components/camel/camel-switchyard/src/main/java/org/switchyard/component/camel/switchyard/SwitchYardPropertiesParser.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import java.util.Properties; + +import org.apache.camel.component.properties.DefaultPropertiesParser; +import org.switchyard.common.property.PropertyResolver; + +/** + * A custom Camel PropertiesParser which resolves SwitchYard implementation properties. + */ +public class SwitchYardPropertiesParser extends DefaultPropertiesParser { + + private PropertyResolver _resolver; + + /** + * Constructor. + * @param pr PropertyResolver which resolves SwitchYard implementation properties + */ + public SwitchYardPropertiesParser(PropertyResolver pr) { + _resolver = pr; + } + + @Override + public String parseProperty(String key, String value, Properties properties) { + if (_resolver != null) { + Object response = _resolver.resolveProperty(key); + if (response != null) { + return response.toString(); + } + } + + return super.parseProperty(key, value, properties); + } +} diff --git a/components/camel/camel-switchyard/src/main/resources/META-INF/services/org/apache/camel/component/switchyard b/components/camel/camel-switchyard/src/main/resources/META-INF/services/org/apache/camel/component/switchyard new file mode 100644 index 000000000..652790305 --- /dev/null +++ b/components/camel/camel-switchyard/src/main/resources/META-INF/services/org/apache/camel/component/switchyard @@ -0,0 +1 @@ +class=org.switchyard.component.camel.switchyard.SwitchYardComponent diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/CamelResponseHandlerTest.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/CamelResponseHandlerTest.java new file mode 100644 index 000000000..2ad5f5b4a --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/CamelResponseHandlerTest.java @@ -0,0 +1,178 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.xml.namespace.QName; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.Service; +import org.switchyard.ServiceReference; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.composer.CamelComposition; +import org.switchyard.component.camel.switchyard.CamelResponseHandler; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.internal.DefaultContext; +import org.switchyard.metadata.ExchangeContract; +import org.switchyard.metadata.ServiceOperation; + +/** + * Unit test for {@link org.switchyard.component.camel.switchyard.CamelResponseHandler} + * + * @author Daniel Bevenius + */ +public class CamelResponseHandlerTest { + + private static final QName JAVA_STRING_QNAME = new QName("java:java.lang.String"); + private static final QName SERVICE_QNAME = new QName("java:" + MockService.class.getName()); + + private MessageComposer _messageComposer; + + @Before + public void before() { + _messageComposer = CamelComposition.getMessageComposer(); + } + + @Test (expected = RuntimeException.class) + public void constructor() throws Exception { + final CamelResponseHandler responseHandler = new CamelResponseHandler(null, null, _messageComposer); + responseHandler.handleMessage(null); + } + + @Test + public void handleMessageWithOutputType() throws HandlerException { + final Exchange camelExchange = createCamelExchange(); + final ServiceReference serviceReference = createMockServiceRef(); + final org.switchyard.Exchange switchYardExchange = createMockExchangeWithBody(new MessageCreator() { + @Override + public Message create() { + Message message = mock(Message.class); + when(message.getContext()).thenReturn(new DefaultContext(Scope.MESSAGE)); + when(message.getContent(Integer.class)).thenReturn(10); + return message; + } + }); + final CamelResponseHandler responseHandler = new CamelResponseHandler(camelExchange, serviceReference, _messageComposer); + + responseHandler.handleMessage(switchYardExchange); + + assertThat(switchYardExchange.getMessage().getContent(Integer.class), is(equalTo(new Integer(10)))); + } + + @Test + public void fault() throws HandlerException { + final String fault = "some fault"; + final Exchange camelExchange = createCamelExchange(); + final ServiceReference serviceReference = createMockServiceRef(); + final org.switchyard.Exchange switchYardExchange = createMockExchangeWithBody(new MessageCreator() { + @Override + public Message create() { + Message message = mock(Message.class); + when(message.getContext()).thenReturn(new DefaultContext(Scope.MESSAGE)); + when(message.getContent()).thenReturn(fault); + return message; + } + }); + final CamelResponseHandler responseHandler = new CamelResponseHandler(camelExchange, serviceReference, _messageComposer); + + responseHandler.handleFault(switchYardExchange); + + assertTrue(camelExchange.getIn().isFault()); + assertSame(fault, camelExchange.getIn().getBody()); + } + + @Test + public void exception() throws HandlerException { + final IllegalArgumentException exception = new IllegalArgumentException(); + final Exchange camelExchange = createCamelExchange(); + final ServiceReference serviceReference = createMockServiceRef(); + final org.switchyard.Exchange switchYardExchange = createMockExchangeWithBody(new MessageCreator() { + @Override + public Message create() { + Message message = mock(Message.class); + when(message.getContent()).thenReturn(exception); + return message; + } + }); + final CamelResponseHandler responseHandler = new CamelResponseHandler(camelExchange, serviceReference, _messageComposer); + + responseHandler.handleFault(switchYardExchange); + assertSame(exception, camelExchange.getException()); + } + + private Exchange createCamelExchange() { + return new DefaultExchange((CamelContext) null); + } + + private ServiceReference createMockServiceRef() { + final ServiceReference serviceReference = mock(ServiceReference.class); + when(serviceReference.getInterface()).thenReturn(JavaService.fromClass(MockService.class)); + return serviceReference; + } + + private org.switchyard.Exchange createMockExchangeWithBody(MessageCreator creator) { + final org.switchyard.Exchange switchYardExchange = mock(org.switchyard.Exchange.class); + final org.switchyard.Context switchYardContext = mock(org.switchyard.Context.class); + final ExchangeContract exchangeContract = mock(ExchangeContract.class); + final ServiceOperation serviceOperation = mock(ServiceOperation.class); + final ServiceOperation referenceOperation = mock(ServiceOperation.class); + final Service provider = mock(Service.class); + + final Message message = creator.create(); + when(switchYardExchange.getMessage()).thenReturn(message); + + when(provider.getName()).thenReturn(SERVICE_QNAME); + when(switchYardExchange.getProvider()).thenReturn(provider); + when(switchYardExchange.getContext()).thenReturn(switchYardContext); + when(referenceOperation.getOutputType()).thenReturn(JAVA_STRING_QNAME); + when(exchangeContract.getProviderOperation()).thenReturn(serviceOperation); + when(serviceOperation.getInputType()).thenReturn(JAVA_STRING_QNAME); + when(serviceOperation.getOutputType()).thenReturn(null); + when(serviceOperation.getFaultType()).thenReturn(null); + when(exchangeContract.getConsumerOperation()).thenReturn(referenceOperation); + when(switchYardExchange.getContract()).thenReturn(exchangeContract); + + return switchYardExchange; + } + + private class MockService { + @SuppressWarnings("unused") + public void print(final String msg) { + } + } + + /** + * Interface which let populate mock message. + */ + interface MessageCreator { + Message create(); + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/ComponentNameComposerTest.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/ComponentNameComposerTest.java new file mode 100644 index 000000000..4e9a62813 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/ComponentNameComposerTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; + +import org.junit.Test; +import org.switchyard.component.camel.switchyard.ComponentNameComposer; + +/** + * Tests for {@link org.switchyard.component.camel.switchyard.ComponentNameComposer}. + * + * @author Daniel Bevenius + */ +public class ComponentNameComposerTest { + + @Test + public void getQueryParamMap() throws Exception { + final Map map = getQueryParamMap("switchyard://SomeService?foo=bar&bar=baz"); + assertThat(map.size(), is(2)); + assertThat(map.get("foo"), equalTo("bar")); + assertThat(map.get("bar"), equalTo("baz")); + } + + @Test + public void getQueryParamMap_no_params() throws Exception { + assertThat(getQueryParamMap("switchyard://SomeService?foo").isEmpty(), is(true)); + } + + private Map getQueryParamMap(final String uri) throws URISyntaxException { + return ComponentNameComposer.getQueryParamMap(new URI(uri)); + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/ExchangeMapperTests.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/ExchangeMapperTests.java new file mode 100644 index 000000000..80f77f130 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/ExchangeMapperTests.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; +import org.apache.camel.impl.DefaultMessage; + +import org.switchyard.ExchangePhase; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.ServiceReference; +import org.switchyard.Scope; + +import org.switchyard.internal.DefaultContext; +import org.switchyard.internal.ExchangeImpl; +import org.switchyard.component.camel.switchyard.ExchangeMapper; +import org.switchyard.component.camel.common.composer.CamelContextMapper; +import org.switchyard.component.camel.common.handler.OutboundHandler; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * ExchangeMapperTests + * + * Tests to support ExchangeMapper. + */ +public class ExchangeMapperTests { + @Before + public void setUp() throws Exception { + } + + /** + * Test to confirm fixes for SWITCHYARD-2252, where message headers were unexpectedly + * changed to lower case in Camel services. + * @throws Exception exception + */ + @Test + public void testMapCamelToSwitchYard() throws Exception { + org.apache.camel.Exchange exchange = createCamelExchange(); + org.apache.camel.Message in = exchange.getIn(); + exchange.getIn().setBody("bar", java.lang.String.class); + in.setHeader("CamelFileName", "foobar"); + + org.switchyard.Exchange syExchange = createSwitchYardExchange(); + + org.switchyard.Message message = ExchangeMapper.mapCamelToSwitchYard(exchange, syExchange, + ExchangePhase.IN); + + Property property = message.getContext().getProperty("CamelFileName"); + assertTrue(property != null); + assertTrue("foobar".equals(property.getValue())); + } + + /** + * Create a mocked SwitchYard exchange + * @return exchange + */ + private org.switchyard.Exchange createSwitchYardExchange() { + org.switchyard.Exchange switchYardExchange = mock(org.switchyard.Exchange.class); + Message message = mock(org.switchyard.Message.class); + when(message.getContext()).thenReturn(new DefaultContext(Scope.MESSAGE)); + when(message.getContent(Integer.class)).thenReturn(10); + when(switchYardExchange.getMessage()).thenReturn(message); + when(switchYardExchange.createMessage()).thenReturn(message); + return switchYardExchange; + } + + /** + * Create a camel exchange + * @return exchange + */ + private Exchange createCamelExchange() { + DefaultMessage message = new DefaultMessage(); + message.setBody("foobar"); + message.setExchange(new DefaultExchange(new SwitchYardCamelContextImpl(false))); + return message.getExchange(); + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SendFromSwitchYardTest.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SendFromSwitchYardTest.java new file mode 100644 index 000000000..40acd5d0e --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SendFromSwitchYardTest.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; + +import javax.xml.namespace.QName; + +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.composer.CamelContextMapper; +import org.switchyard.component.camel.common.composer.CamelMessageComposer; +import org.switchyard.component.camel.common.handler.OutboundHandler; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.switchyard.util.Composer; +import org.switchyard.component.camel.switchyard.util.Mapper; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class SendFromSwitchYardTest extends SwitchYardComponentTestBase { + + private static final String ENDPOINT_URI = "mock:output"; + private static final String PAYLOAD = "Test Payload"; + private static final String OPERATION_NAME = "foo"; + private MockEndpoint _mock; + private CamelBindingModel _bindingModel; + private CompositeReferenceModel _referenceModel = mock(CompositeReferenceModel.class); + + @Before + public void startUp() { + _mock = getMockEndpoint(ENDPOINT_URI); + _bindingModel = mock(CamelBindingModel.class); + when(_bindingModel.getComponentURI()).thenReturn(URI.create(ENDPOINT_URI)); + when(_bindingModel.getName()).thenReturn("testGateway"); + when(_bindingModel.getReference()).thenReturn(_referenceModel); + } + + @Test + public void messageComposerComposeTest() throws InterruptedException { + _mock.expectedBodiesReceived(Composer.DECOMPOSE_PREFIX + PAYLOAD); + Exchange exchange = createExchange(new Composer().setContextMapper(new CamelContextMapper())); + exchange.send(exchange.createMessage().setContent(PAYLOAD)); + _mock.assertIsSatisfied(); + } + + @Test + public void contextMapperMapToTest() throws InterruptedException { + _mock.expectedBodiesReceived(PAYLOAD); + _mock.expectedHeaderReceived(Mapper.PROPERTY, Mapper.VALUE); + + Exchange exchange = createExchange(new CamelMessageComposer().setContextMapper(new Mapper())); + exchange.send(exchange.createMessage().setContent(PAYLOAD)); + _mock.assertIsSatisfied(); + } + + public Exchange createExchange(MessageComposer messageComposer) { + QName serviceName = new QName("urn:test", "Service"); + ServiceInterface metadata = new InOnlyService(OPERATION_NAME); + + OutboundHandler handler = new OutboundHandler(_bindingModel, _camelContext, messageComposer, null) { + { + setState(State.STARTED); + } + }; + _serviceDomain.registerService(serviceName, metadata, handler); + return _serviceDomain.registerServiceReference(serviceName, metadata).createExchange(OPERATION_NAME); + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SendToSwitchYardTest.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SendToSwitchYardTest.java new file mode 100644 index 000000000..0b9205044 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SendToSwitchYardTest.java @@ -0,0 +1,176 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.Property; +import org.switchyard.component.camel.common.handler.InboundHandler; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.switchyard.util.Composer; +import org.switchyard.component.camel.switchyard.util.Mapper; +import org.switchyard.component.camel.switchyard.util.TestService; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.config.Configuration; +import org.switchyard.config.ConfigurationPuller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.composer.v1.V1ContextMapperModel; +import org.switchyard.config.model.composer.v1.V1MessageComposerModel; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1StaticOperationSelectorModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class SendToSwitchYardTest extends SwitchYardComponentTestBase { + + private static final String OPERATION_NAME = "foo"; + private static final String PAYLOAD = "Test Payload"; + private Configuration _configuration = new ConfigurationPuller().pull(new QName("urn:camel", "binding")); + private QName _serviceName = new QName("urn:test", "Service"); + private ServiceInterface _metadata = new InOnlyService(OPERATION_NAME); + + @Test + public void messageComposerComposeTest() { + MockHandler mock = new MockHandler().forwardInToOut(); + _serviceDomain.registerService(_serviceName, _metadata, mock); + _serviceDomain.registerServiceReference(_serviceName, _metadata); + InboundHandler handler = createInboundHandler(_serviceName, "direct:input", "input", + new V1MessageComposerModel(SwitchYardNamespace.DEFAULT.uri()).setClazz(Composer.class.getName())); + handler.start(); + + sendBody("direct:input", PAYLOAD); + mock.waitForOKMessage(); + List exchanges = new ArrayList(); + mock.getMessages().drainTo(exchanges); + assertEquals(1, exchanges.size()); + assertEquals(Composer.COMPOSE_PREFIX + PAYLOAD, exchanges.get(0).getMessage().getContent()); + + handler.stop(); + } + + @Test + public void contextMapperMapToTest() { + MockHandler mock = new MockHandler().forwardInToOut(); + _serviceDomain.registerService(_serviceName, _metadata, mock); + _serviceDomain.registerServiceReference(_serviceName, _metadata); + InboundHandler handler = createInboundHandler(_serviceName, "direct:input", "direct", + new V1ContextMapperModel(SwitchYardNamespace.DEFAULT.uri()).setClazz(Mapper.class.getName())); + handler.start(); + + sendBody("direct:input", PAYLOAD); + mock.waitForOKMessage(); + List exchanges = new ArrayList(); + mock.getMessages().drainTo(exchanges); + assertEquals(1, exchanges.size()); + Exchange exchange = exchanges.get(0); + Property property = exchange.getContext().getProperty(Mapper.PROPERTY); + assertNotNull(property); + assertEquals(Mapper.VALUE, property.getValue()); + + handler.stop(); + } + + @Test + public void operationSelectorTest() { + MockHandler mock = new MockHandler().forwardInToOut(); + _serviceDomain.registerService(_serviceName, _metadata, mock); + _serviceDomain.registerServiceReference(_serviceName, _metadata); + InboundHandler handler = createInboundHandler(_serviceName, "direct:input", "input", + new V1StaticOperationSelectorModel(SwitchYardNamespace.DEFAULT.uri()).setOperationName(OPERATION_NAME)); + handler.start(); + + sendBody("direct:input", PAYLOAD); + mock.waitForOKMessage(); + List exchanges = new ArrayList(); + mock.getMessages().drainTo(exchanges); + assertEquals(1, exchanges.size()); + assertEquals(OPERATION_NAME, exchanges.get(0).getContract().getProviderOperation().getName()); + + handler.stop(); + } + + @Test + public void wrongOperationSelectorTest() { + MockHandler mock = new MockHandler().forwardInToOut(); + JavaService metadata = JavaService.fromClass(TestService.class); + _serviceDomain.registerService(_serviceName, metadata, mock); + _serviceDomain.registerServiceReference(_serviceName, metadata); + InboundHandler handler = createInboundHandler(_serviceName, "direct:input", "input", + new V1StaticOperationSelectorModel(SwitchYardNamespace.DEFAULT.uri()).setOperationName("missing")); + handler.start(); + + sendBody("direct:input", PAYLOAD); + assertTrue(mock.getMessages().isEmpty()); + handler.stop(); + } + + protected InboundHandler createInboundHandler(QName serviceName, String uri, final String name) { + return createInboundHandler(serviceName, uri, name, null, null, null); + } + + protected InboundHandler createInboundHandler(QName serviceName, String uri, final String name, OperationSelectorModel selectorModel) { + return createInboundHandler(serviceName, uri, name, selectorModel, null, null); + } + + protected InboundHandler createInboundHandler(QName serviceName, String uri, final String name, MessageComposerModel composerModel) { + return createInboundHandler(serviceName, uri, name, null, composerModel, null); + } + + protected InboundHandler createInboundHandler(QName serviceName, String uri, final String name, ContextMapperModel mapperModel) { + return createInboundHandler(serviceName, uri, name, null, null, mapperModel); + } + + protected InboundHandler createInboundHandler(QName serviceName, final String uri, final String name, final OperationSelectorModel selectorModel, + final MessageComposerModel composerModel, final ContextMapperModel mapperModel) { + V1BaseCamelBindingModel camelBindingModel = new V1BaseCamelBindingModel(_configuration, new Descriptor()) { + @Override + public String getName() { + return name; + } + @Override + public URI getComponentURI() { + return URI.create(uri); + } + @Override + public OperationSelectorModel getOperationSelector() { + return selectorModel; + } + @Override + public MessageComposerModel getMessageComposer() { + return composerModel; + } + @Override + public ContextMapperModel getContextMapper() { + return mapperModel; + } + }; + return new InboundHandler(camelBindingModel, _camelContext, serviceName, null); + } +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SwitchYardComponentTest.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SwitchYardComponentTest.java new file mode 100644 index 000000000..288bf6932 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SwitchYardComponentTest.java @@ -0,0 +1,154 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.LinkedBlockingQueue; + +import javax.xml.namespace.QName; + +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.deploy.Binding; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceMetadataBuilder; +import org.switchyard.policy.Policy; +import org.switchyard.policy.PolicyUtil; +import org.switchyard.policy.SecurityPolicy; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/** + * Test for {@link org.switchyard.component.camel.switchyard.SwitchYardComponent}. + * + * @author Daniel Bevenius + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class SwitchYardComponentTest extends SwitchYardComponentTestBase { + + protected String _serviceName = "testServiceName"; + + @Test + public void sendToSwitchyardInOut() throws Exception { + final String expectedResponse = "replacedContent"; + final String payload = "bajja"; + + _serviceDomain.registerService(new QName(_serviceName), new InOutService(), + new ResponseService(expectedResponse)); + _serviceDomain.registerServiceReference(new QName(_serviceName), new InOutService("process")); + + final String response = (String) template.requestBody("direct:input", payload); + assertThat(response, is(equalTo(expectedResponse))); + } + + @Test + public void sendToSwitchyardInOnly() throws Exception { + final String payload = "bajja"; + final MockHandler mockService = new MockHandler(); + _serviceDomain.registerService(new QName(_serviceName), new InOnlyService(), mockService); + _serviceDomain.registerServiceReference(new QName(_serviceName), new InOnlyService("process")); + + template.sendBody("direct:input", payload); + + assertThat(mockService.getMessages().size(), is(1)); + final String actualPayload = mockService.getMessages().iterator().next().getMessage().getContent(String.class); + assertThat(actualPayload, is(equalTo(payload))); + } + + + @Test + public void sendToSwitchyardInOnlyFault() throws Exception { + final String payload = "bajja"; + + MockEndpoint endpoint = getMockEndpoint("mock:result"); + endpoint.expectedBodiesReceived(payload); + final MockHandler mockService = new MockHandler().forwardInToOut(); + _serviceDomain.registerService(new QName(_serviceName), new InOnlyService(), mockService); + _serviceDomain.registerServiceReference(new QName(_serviceName), new InOnlyService("process")); + + template.sendBody("direct:input", payload); + + assertThat(mockService.getMessages().size(), is(1)); + final String actualPayload = mockService.getMessages().iterator().next().getMessage().getContent(String.class); + assertThat(actualPayload, is(equalTo(payload))); + endpoint.assertIsSatisfied(); + } + + @Test + public void customBindingData() throws Exception { + List policies = Arrays.asList(SecurityPolicy.CONFIDENTIALITY); + final MockHandler mockService = new MockHandler(); + _serviceDomain.registerService( + new QName(_serviceName), + new InOnlyService(), + mockService, + ServiceMetadataBuilder.create().security(_serviceDomain.getServiceSecurity(null)) + .requiredPolicies(policies).registrant(new Binding(new ArrayList())).build()); + _serviceDomain.registerServiceReference(new QName(_serviceName), new InOnlyService("process")); + _camelContext.addRoutes(new RouteBuilder() { + @Override + public void configure() throws Exception { + from("netty://foo").to("switchyard://" + _serviceName + "?operationName=process"); + } + }); + _camelContext.createProducerTemplate().sendBody("netty://foo", "baja"); + + LinkedBlockingQueue msgs = mockService.getMessages(); + Exchange exchange = msgs.iterator().next(); + assertTrue(PolicyUtil.isProvided(exchange, SecurityPolicy.CONFIDENTIALITY)); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + public void configure() throws Exception { + from("direct:input") + .to("switchyard://" + _serviceName + "?operationName=process") + .to("mock:result"); + } + }; + } + + private static class ResponseService extends BaseHandler { + private final String _response; + + public ResponseService(final String response) { + this._response = response; + + } + + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + final Message responseMessage = exchange.createMessage().setContent(_response); + exchange.send(responseMessage); + } + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SwitchYardComponentTestBase.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SwitchYardComponentTestBase.java new file mode 100644 index 000000000..bb0633e91 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/SwitchYardComponentTestBase.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard; + +import org.apache.camel.CamelContext; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.component.camel.common.CamelConstants; + +/** + * Base class for switchyard-camel integration. + */ +public abstract class SwitchYardComponentTestBase extends CamelTestSupport { + + protected ServiceDomain _serviceDomain; + + protected SwitchYardCamelContextImpl _camelContext; + + @Override + protected CamelContext createCamelContext() throws Exception { + _camelContext = new SwitchYardCamelContextImpl(false); + _camelContext.setServiceDomain(_serviceDomain); + return _camelContext; + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyBindingDataCreator.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyBindingDataCreator.java new file mode 100644 index 000000000..8210c189e --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyBindingDataCreator.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard.test; + +import org.apache.camel.Message; +import org.switchyard.component.camel.common.composer.BindingDataCreator; +import org.switchyard.component.camel.common.composer.CamelBindingData; + +/** + * Dedicated binding creator which handles NettyEndpoint exchanges. + */ +public class NettyBindingDataCreator implements BindingDataCreator { + + @Override + public CamelBindingData createBindingData(Message message) { + return new SecureBindingData(message); + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyComponent.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyComponent.java new file mode 100644 index 000000000..661fe57f6 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyComponent.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard.test; + +import java.util.Map; + +import org.apache.camel.Endpoint; +import org.apache.camel.component.direct.DirectComponent; + +/** + * Dummy component for test purposes. + */ +public class NettyComponent extends DirectComponent { + + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + Endpoint endpoint = new NettyEndpoint(uri, this); + setProperties(endpoint, parameters); + return endpoint; + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyEndpoint.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyEndpoint.java new file mode 100644 index 000000000..6a3c743e5 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/NettyEndpoint.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard.test; + +import org.apache.camel.component.direct.DirectEndpoint; + +/** + * Dummy endpoint for testing purposes. + */ +public class NettyEndpoint extends DirectEndpoint { + + public NettyEndpoint(String uri, NettyComponent component) { + super(uri, component); + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/SecureBindingData.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/SecureBindingData.java new file mode 100644 index 000000000..ea3d36b18 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/test/SecureBindingData.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard.test; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.camel.Message; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.common.composer.SecurityBindingData; +import org.switchyard.security.credential.ConfidentialityCredential; +import org.switchyard.security.credential.Credential; + +/** + * Secure binding data for test endpoint. + */ +public class SecureBindingData extends CamelBindingData implements SecurityBindingData { + + public SecureBindingData(Message message) { + super(message); + } + + @Override + public Set extractCredentials() { + Set credentials = new HashSet(); + credentials.add(new ConfidentialityCredential(true)); + return credentials; + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/Composer.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/Composer.java new file mode 100644 index 000000000..c90a37ffe --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/Composer.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard.util; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.composer.CamelMessageComposer; + +/** + * Dummy message composer. + */ +public class Composer extends CamelMessageComposer { + + public static final String COMPOSE_PREFIX = "Composer compose "; + public static final String DECOMPOSE_PREFIX = "Composer decompose "; + + @Override + public Message compose(CamelBindingData source, Exchange exchange) throws Exception { + Message message = super.compose(source, exchange); + message.setContent(COMPOSE_PREFIX + message.getContent(String.class)); + return message; + } + + @Override + public CamelBindingData decompose(Exchange exchange, CamelBindingData target) throws Exception { + CamelBindingData decompose = super.decompose(exchange, target); + decompose.getMessage().setBody(DECOMPOSE_PREFIX + decompose.getMessage().getBody(String.class)); + return decompose; + } +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/Mapper.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/Mapper.java new file mode 100644 index 000000000..644d02c95 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/Mapper.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard.util; + +import org.switchyard.Context; +import org.switchyard.Scope; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.composer.CamelContextMapper; + +public class Mapper extends CamelContextMapper { + + public static final String PROPERTY = "TestProperty"; + public static final String VALUE = "TestValue"; + + @Override + public void mapFrom(CamelBindingData source, Context context) throws Exception { + super.mapFrom(source, context); + context.setProperty(PROPERTY, VALUE); + } + + @Override + public void mapTo(Context context, CamelBindingData target) throws Exception { + super.mapTo(context, target); + target.getMessage().setHeader(PROPERTY, VALUE); + } + +} diff --git a/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/TestService.java b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/TestService.java new file mode 100644 index 000000000..3dd092f14 --- /dev/null +++ b/components/camel/camel-switchyard/src/test/java/org/switchyard/component/camel/switchyard/util/TestService.java @@ -0,0 +1,24 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.switchyard.util; + +/** + * Simple service interface for test purposes. + * + */ +public interface TestService { + + void foo(String payload); + +} diff --git a/components/camel/camel-switchyard/src/test/resources/META-INF/services/org/apache/camel/component/netty b/components/camel/camel-switchyard/src/test/resources/META-INF/services/org/apache/camel/component/netty new file mode 100644 index 000000000..5f609ed8d --- /dev/null +++ b/components/camel/camel-switchyard/src/test/resources/META-INF/services/org/apache/camel/component/netty @@ -0,0 +1 @@ +class=org.switchyard.component.camel.switchyard.test.NettyComponent \ No newline at end of file diff --git a/components/camel/camel-switchyard/src/test/resources/META-INF/services/org/switchyard/component/camel/NettyEndpoint b/components/camel/camel-switchyard/src/test/resources/META-INF/services/org/switchyard/component/camel/NettyEndpoint new file mode 100644 index 000000000..b529488ca --- /dev/null +++ b/components/camel/camel-switchyard/src/test/resources/META-INF/services/org/switchyard/component/camel/NettyEndpoint @@ -0,0 +1 @@ +class=org.switchyard.component.camel.switchyard.test.NettyBindingDataCreator \ No newline at end of file diff --git a/components/camel/camel-switchyard/src/test/resources/log4j.properties b/components/camel/camel-switchyard/src/test/resources/log4j.properties new file mode 100644 index 000000000..625c0e2ed --- /dev/null +++ b/components/camel/camel-switchyard/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +# The logging properties used during tests.. +# +log4j.rootLogger=INFO, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d %-5p %-30.30c{1} - %m%n diff --git a/components/camel/camel-test/pom.xml b/components/camel/camel-test/pom.xml new file mode 100644 index 000000000..8b2180100 --- /dev/null +++ b/components/camel/camel-test/pom.xml @@ -0,0 +1,48 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel-test + jar + SwitchYard: Camel Component :: Binding Test framework + http://switchyard.org + + + org.switchyard + switchyard-common + + + org.switchyard.components + switchyard-component-common-camel + + + org.apache.camel + camel-core + + + junit + junit + + + xmlunit + xmlunit + + + diff --git a/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelModelTest.java b/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelModelTest.java new file mode 100644 index 000000000..e2fe61a0f --- /dev/null +++ b/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelModelTest.java @@ -0,0 +1,130 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.config.test.v1; + +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.BeforeClass; +import org.switchyard.common.type.Classes; +import org.switchyard.component.camel.common.model.AdditionalUriParametersModel; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.common.model.v1.V1AdditionalUriParametersModel; +import org.switchyard.component.camel.common.model.v1.V1ParameterModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Base class for camel model bindings. Contains common code, mostly related to + * model parsing and resource lookups. + * + * @author Lukasz Dywicki + * + * @param Model type. + */ +public abstract class V1BaseCamelModelTest { + + /** + * Static instance of context used to create endpoint instances. + */ + private static CamelContext context; + + /** + * Prepare test environment. + */ + @BeforeClass + public static void setUpClass() { + context = new DefaultCamelContext(); + } + + /** + * Lookup camel binding model in SCA configuration and use Switchard model + * as root and return first element from it. + * + * @param config Configuration location. + * @return Camel binding. + * @throws Exception In case of any problems exception is not handled. + */ + @SuppressWarnings("unchecked") + protected T getFirstCamelBinding(final String config) throws Exception { + final InputStream in = Classes.getResourceAsStream(config, getClass()); + final SwitchYardModel model = new ModelPuller().pull(in); + final List services = model.getComposite().getServices(); + final CompositeServiceModel compositeServiceModel = services.get(0); + final List bindings = compositeServiceModel.getBindings(); + return (T) bindings.get(0); + } + + /** + * Lookup camel reference binding model in SCA configuration and use Switchard + * model as root and return first element from it. + * + * @param config Configuration location. + * @return Camel binding. + * @throws Exception In case of any problems exception is not handled. + */ + @SuppressWarnings("unchecked") + protected T getFirstCamelReferenceBinding(final String config) throws Exception { + final InputStream in = Classes.getResourceAsStream(config, getClass()); + final SwitchYardModel model = new ModelPuller().pull(in); + final List services = model.getComposite().getReferences(); + final CompositeReferenceModel compositeServiceModel = services.get(0); + final List bindings = compositeServiceModel.getBindings(); + return (T) bindings.get(0); + } + + /** + * Lookup camel binding model without usage of SCA parser. + * + * @param config Configuration location. + * @return Camel binding. + * @throws Exception In case of any problems exception is not handled. + */ + @SuppressWarnings("unchecked") + protected T getFirstCamelModelBinding(final String config) throws Exception { + final InputStream in = Classes.getResourceAsStream(config, getClass()); + final CamelBindingModel model = new ModelPuller().pull(in); + return (T) model; + } + + /** + * Creates endpoint instance from given model. + * + * @param model Endpoint configuration model (will be used to obtain uri). + * @param enpointType Expected endpoint type. + * @return Endpoint instance created with model URI. + */ + protected E getEndpoint(CamelBindingModel model, Class enpointType) { + String configUri = model.getComponentURI().toString(); + return context.getEndpoint(configUri, enpointType); + } + + protected static AdditionalUriParametersModel createAdditionalUriParametersModel(String namespace, + Map parameters) { + final AdditionalUriParametersModel retVal = new V1AdditionalUriParametersModel(namespace); + for (Entry entry : parameters.entrySet()) { + retVal.addParameter(new V1ParameterModel(namespace).setName(entry.getKey()).setValue(entry.getValue())); + } + return retVal; + + } +} diff --git a/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelReferenceBindingModelTest.java b/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelReferenceBindingModelTest.java new file mode 100644 index 000000000..30aae5ad9 --- /dev/null +++ b/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelReferenceBindingModelTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.config.test.v1; + +import org.apache.camel.Endpoint; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; + +/** + * Base class for camel bindings which uses reference elements. + * + * @param Type of model + * @param Type of endpoint. + */ +public abstract class V1BaseCamelReferenceBindingModelTest + extends V1BaseCamelServiceBindingModelTest { + + protected V1BaseCamelReferenceBindingModelTest(Class endpointType, String fileName) { + this(endpointType, fileName, true); + } + + protected V1BaseCamelReferenceBindingModelTest(Class endpointType, String fileName, boolean valid) { + super(endpointType, fileName, valid); + } + + @Override + protected T getFirstBinding() throws Exception { + return getFirstCamelReferenceBinding(getFileName()); + } + +} diff --git a/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelServiceBindingModelTest.java b/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelServiceBindingModelTest.java new file mode 100644 index 000000000..149af1674 --- /dev/null +++ b/components/camel/camel-test/src/main/java/org/switchyard/component/camel/config/test/v1/V1BaseCamelServiceBindingModelTest.java @@ -0,0 +1,218 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.config.test.v1; + +import static junit.framework.Assert.assertTrue; +import static org.apache.camel.util.URISupport.normalizeUri; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.UnsupportedEncodingException; +import java.net.URISyntaxException; + +import org.apache.camel.Endpoint; +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Test; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; + +/** + * Base test class for camel bindings. + * + * @author Lukasz Dywicki + * + * @param Type of model + * @param Type of endpoint. + */ +public abstract class V1BaseCamelServiceBindingModelTest + extends V1BaseCamelModelTest { + + private String _fileName; + private boolean _valid; + private Class _endpointType; + private boolean _skipCamelEndpointTesting; + + protected V1BaseCamelServiceBindingModelTest(Class endpointType, String fileName, boolean valid) { + _endpointType = endpointType; + _fileName = fileName; + _valid = valid; + } + + protected V1BaseCamelServiceBindingModelTest(Class endpointType, String fileName) { + this(endpointType, fileName, true); + } + + /** + * Force test to don't resolve endpoint during the test during 3rd party dependencies + * ie. registry entries or environment dependencies. + * + * @param skip True if camel context shouldn't create endpoint. + */ + public void setSkipCamelEndpointTesting(boolean skip) { + _skipCamelEndpointTesting = skip; + } + + /** + * Verify correctness of model read from file. + * + * @throws Exception If model can not be read + */ + @Test + public void testFileIsValid() throws Exception { + validModel(getFirstBinding()); + } + + /** + * Verify correctness of model created by test. + * + * @throws Exception If model can not be read + */ + @Test + public void testModelIsValid() throws Exception { + validModel(createTestModel()); + } + + /** + * Verify assertions with file binding. + * + * @throws Exception If model from file can not be read. + */ + @Test + public void testModelAssertionsFromFile() throws Exception { + createModelAssertions(getFirstBinding()); + } + + /** + * Verify assertions with model binding. + */ + @Test + public void testModelAssertionsFromModel() { + createModelAssertions(createTestModel()); + } + + /** + * Verify if model from file is similar to model created by test. + * + * @throws Exception If model from file can not be read. + */ + @Test + public void testSimilarityBetweenFileAndModel() throws Exception { + String refXml = getFirstBinding().toString(); + String newXml = createTestModel().toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(refXml, newXml); + if (!diff.similar()) { + System.out.println("Expected\n" + refXml); + System.out.println("Generated\n" + newXml); + } + assertTrue(diff.toString(), diff.similar()); + } + + /** + * This test verify if uri reported by test is same as generated by camel + * endpoint. + * + * To avoid problems with parameter order in query string uri is normalized + * before comparision. + * + * @throws Exception An exception might be thrown when test is failing. + */ + @Test + public void testCamelEndpointUriFromModel() throws Exception { + verifyCamelEndpointUri(createTestModel()); + } + + /** + * This test verify if uri of binding read from file is same as generated by camel + * endpoint. + * + * To avoid problems with parameter order in query string uri is normalized + * before comparision. + * + * @throws Exception An exception might be thrown when test is failing. + */ + @Test + public void testCamelEndpointUriFromFile() throws Exception { + verifyCamelEndpointUri(getFirstBinding()); + } + + /** + * Verify if uri generated by model binding is equals to uri produced by test. + * + * @throws Exception Any exception can be thrown from uri normalization code. + */ + @Test + public void verifyModelUri() throws Exception { + String componentURI = createTestModel().getComponentURI().toString(); + + assertUriEquals(createEndpointUri(), normalizeUri(componentURI)); + } + + protected void validModel(T model) { + if (_valid) { + model.assertModelValid(); + } else { + try { + model.assertModelValid(); + fail("Expected invalid model, but validation framework did not report any problems"); + } catch (Exception e) { + e.getMessage(); // everything ok - model is invalid + } + } + } + + protected void verifyCamelEndpointUri(T model) { + if (_skipCamelEndpointTesting) { + return; + } + + assertUriEquals(createEndpointUri(), getEndpoint(model, _endpointType).getEndpointUri()); + } + + /** + * Verify if given parameter is equals to expected value. + * + * NOTE: expected uri is normalized before comparision, given uri should be + * normalized by caller. + * + * @param expected Expected uri. + * @param given Given uri, after normalization done by camel. + */ + protected void assertUriEquals(String expected, String given) { + try { + assertEquals(normalizeUri(expected), given); + } catch (UnsupportedEncodingException e) { + throw new Error("Unsuported encoding", e); + } catch (URISyntaxException e) { + throw new Error("Uri syntax is invalid", e); + } + } + + protected T getFirstBinding() throws Exception { + return getFirstCamelBinding(_fileName); + } + + protected abstract String createEndpointUri(); + protected abstract void createModelAssertions(T model); + protected abstract T createTestModel(); + + protected Class getEndpointType() { + return _endpointType; + } + + protected String getFileName() { + return _fileName; + } + +} diff --git a/components/camel/component/pom.xml b/components/camel/component/pom.xml new file mode 100644 index 000000000..f109099cd --- /dev/null +++ b/components/camel/component/pom.xml @@ -0,0 +1,185 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-camel-parent + 2.1.0-SNAPSHOT + + switchyard-component-camel + bundle + SwitchYard: Camel Component :: SwitchYard component + http://switchyard.org + + ${project.build.directory}/dependency/camel/resources + + org.switchyard.component.camel, + org.switchyard.component.camel.deploy, + org.switchyard.component.camel.model, + org.switchyard.component.camel.model.v1, + org.switchyard.component.camel.transformer, + + + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.apache.camel.spring.*;resolution:=optional, + org.springframework.transaction*;resolution:=optional, + * + + + + + org.apache.camel + camel-core + + + org.apache.camel + camel-script + + + org.beanshell + bsh + test + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-transform + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-camel-switchyard + + + org.switchyard.components + switchyard-component-camel-core + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + org.switchyard.components + switchyard-component-bean + test + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + org.apache.camel + camel-jms + test + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + test + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + include-camel-spring-schema + generate-sources + + unpack + + + + + org.apache.camel + camel-spring + sources + jar + camel-spring.xsd + ${directory.camel.resources}/org/apache/camel/schema/spring + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-resource + generate-resources + + add-resource + + + + + ${directory.camel.resources} + + + + + + + + + diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/CamelComponentLogger.java b/components/camel/component/src/main/java/org/switchyard/component/camel/CamelComponentLogger.java new file mode 100644 index 000000000..af295a2af --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/CamelComponentLogger.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.MessageLogger; + + +/** + *

+ * This file is using the subset 33400-33799 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface CamelComponentLogger { + /** + * A root logger with the category of the package name. + */ + CamelComponentLogger ROOT_LOGGER = Logger.getMessageLogger(CamelComponentLogger.class, CamelComponentLogger.class.getPackage().getName()); + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/CamelComponentMessages.java b/components/camel/component/src/main/java/org/switchyard/component/camel/CamelComponentMessages.java new file mode 100644 index 000000000..aac4ec63c --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/CamelComponentMessages.java @@ -0,0 +1,124 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 33000-33399 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface CamelComponentMessages { + /** + * The default messages. + */ + CamelComponentMessages MESSAGES = Messages.getBundle(CamelComponentMessages.class); + + /** + * noRoutesFoundInXMLFile method definition. + * @param xmlPath xmlPath + * @return SwitchYardException + */ + @Message(id = 33000, value = "No routes found in XML file %s") + SwitchYardException noRoutesFoundInXMLFile(String xmlPath); + + /** + * javaDSLClassMustExtend method definition. + * @param javaDSLClassName Java DSL class name + * @param className class Name + * @return SwitchYardException + */ + @Message(id = 33001, value = "Java DSL class %s must extend %s") + SwitchYardException javaDSLClassMustExtend(String javaDSLClassName, String className); + + /** + * noRoutesFoundinJavaDSLClass method definition. + * @param className class name + * @return SwitchYardException + */ + @Message(id = 33002, value = "No routes found in Java DSL class %s") + SwitchYardException noRoutesFoundinJavaDSLClass(String className); + + /** + * failedToInitializeDSLClass method definition. + * @param className class name + * @param ex exception + * @return SwitchYardException + */ + @Message(id = 33003, value = "Failed to initialize Java DSL class %s") + SwitchYardException failedToInitializeDSLClass(String className, @Cause Exception ex); + + /** + * mustHaveAtLeastOneInput method definition. + * @return SwitchYardException + */ + @Message(id = 33004, value = "Every route must have at least one input") + SwitchYardException mustHaveAtLeastOneInput(); + + /** + * onlyOneSwitchYardInputPerImpl method definition. + * @return SwitchYardException + */ + @Message(id = 33005, value = "Only one switchyard input per implementation is allowed") + SwitchYardException onlyOneSwitchYardInputPerImpl(); + + /** + * implementationConsumerDoesNotMatchService method definition. + * @param serviceName service name + * @return SwitchYardException + */ + @Message(id = 33006, value = "The implementation consumer doesn't match expected service %s") + SwitchYardException implementationConsumerDoesNotMatchService(String serviceName); + + /** + * couldNotFindServiceReference method definition. + * @param referenceName reference name + * @param to to + * @return SwitchYardException + */ + @Message(id = 33007, value = "Could not find the service reference for '%s' which is referenced in %s") + SwitchYardException couldNotFindServiceReference(String referenceName, String to); + + /** + * couldNotFindServiceName method definition. + * @param qualifiedRefName qualified reference name + * @param to to + * @return SwitchYardException + */ + @Message(id = 33008, value = "Could not find the service name '%s' which is referenced in %s") + SwitchYardException couldNotFindServiceName(String qualifiedRefName, String to); + + /** + * cannotCreateComponentImpl method definition. + * @return SwitchYardException + */ + @Message(id = 33009, value = "Can not create camel based component implementation without consuming from switchyard service") + SwitchYardException cannotCreateComponentImpl(); + + /** + * noServiceReferenceFoundForURI method definition. + * @param uri uri + * @return NullPointerException + */ + @Message(id = 33015, value = "No ServiceReference was found for uri [%s]") + NullPointerException noServiceReferenceFoundForURI(String uri); + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/Route.java b/components/camel/component/src/main/java/org/switchyard/component/camel/Route.java new file mode 100644 index 000000000..192dc4b69 --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/Route.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.switchyard.component.camel; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Designates a class as a Camel route provider. A required value element + * of type java.lang.Class is required to identify the service interface for the + * route service. An optional name element of type java.lang.String is used to + * define the service name. + */ +@Target({TYPE}) +@Retention(RUNTIME) +@Documented +public @interface Route { + + /** + * Service interface for the route. + */ + Class value(); + + /** + * Optional Service name. + */ + String name() default EMPTY; + + /** + * Constant representing a null (i.e. unassigned) value. + * Annotations are not allowed to have empty values, so a default + * representation for an empty value is used. + */ + public static final String EMPTY = ""; +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/RouteFactory.java b/components/camel/component/src/main/java/org/switchyard/component/camel/RouteFactory.java new file mode 100644 index 000000000..6f48a204d --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/RouteFactory.java @@ -0,0 +1,201 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.Binder; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.camel.CamelContext; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.builder.xml.Namespaces; +import org.apache.camel.model.Constants; +import org.apache.camel.model.RouteDefinition; +import org.apache.camel.model.RoutesDefinition; +import org.apache.camel.spi.NamespaceAware; +import org.switchyard.common.type.Classes; +import org.switchyard.component.camel.model.CamelComponentImplementationModel; +import org.switchyard.SwitchYardException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Creates RouteDefinition instances based off of a class containing @Route + * methods and Java DSL route definitions. + */ +public final class RouteFactory { + + /** + * JAXB context for reading XML definitions. + */ + private static JAXBContext JAXB_CONTEXT; + + static { + try { + JAXB_CONTEXT = JAXBContext.newInstance(Constants.JAXB_CONTEXT_PACKAGES, CamelContext.class.getClassLoader()); + } catch (JAXBException e) { + throw new SwitchYardException(e); + } + } + + /** + * Utility class - so no need to directly instantiate. + */ + private RouteFactory() { + + } + + /** + * Returns a list of route definitions referenced by a camel implementation. + * @param model implementation config model + * @return list of route definitions + */ + public static List getRoutes(CamelComponentImplementationModel model) { + if (model.getJavaClass() != null) { + return createRoute(model.getJavaClass(), model.getComponent().getTargetNamespace()); + } + return loadRoute(model.getXMLPath()); + } + + /** + * Loads a set of route definitions from an XML file. + * @param xmlPath path to the file containing one or more route definitions + * @return list of route definitions + */ + public static List loadRoute(String xmlPath) { + List routes = null; + + try { + InputSource source = new InputSource(Classes.getResourceAsStream(xmlPath)); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(source); + Element element = document.getDocumentElement(); + Binder binder = JAXB_CONTEXT.createBinder(); + Object obj = binder.unmarshal(element); + injectNamespaces(element, binder); + + // Look for or as top-level element + if (obj instanceof RoutesDefinition) { + routes = ((RoutesDefinition)obj).getRoutes(); + } else if (obj instanceof RouteDefinition) { + routes = new ArrayList(1); + routes.add((RouteDefinition)obj); + } + + // If we couldn't find a or definition, throw an error + if (routes == null) { + CamelComponentMessages.MESSAGES.noRoutesFoundInXMLFile(xmlPath); + } + return routes; + } catch (SAXException e) { + throw new SwitchYardException(e); + } catch (ParserConfigurationException e) { + throw new SwitchYardException(e); + } catch (JAXBException e) { + throw new SwitchYardException(e); + } catch (IOException e) { + throw new SwitchYardException(e); + } + } + + private static void injectNamespaces(Element element, Binder binder) { + NodeList list = element.getChildNodes(); + Namespaces namespaces = null; + int size = list.getLength(); + for (int i = 0; i < size; i++) { + Node child = list.item(i); + if (child instanceof Element) { + Element childElement = (Element) child; + Object object = binder.getJAXBNode(child); + if (object instanceof NamespaceAware) { + NamespaceAware namespaceAware = (NamespaceAware) object; + if (namespaces == null) { + namespaces = new Namespaces(element); + } + namespaces.configure(namespaceAware); + } + injectNamespaces(childElement, binder); + } + } + } + + /** + * Create a new route from the given class name and service name. + * @param className name of the class containing an @Route definition + * @return the route definition + */ + public static List createRoute(String className) { + return createRoute(className, null); + } + + /** + * Create a new route from the given class name and service name. + * @param className name of the class containing an @Route definition + * @param namespace the namespace to append to switchyard:// service URIs + * @return the route definition + */ + public static List createRoute(String className, String namespace) { + return createRoute(Classes.forName(className), namespace); + } + + /** + * Create a new route from the given class and service name. + * @param routeClass class containing an @Route definition + * @return the route definition + */ + public static List createRoute(Class routeClass) { + return createRoute(routeClass, null); + } + + /** + * Create a new route from the given class and service name. + * @param routeClass class containing an @Route definition + * @param namespace the namespace to append to switchyard:// service URIs + * @return the route definition + */ + public static List createRoute(Class routeClass, String namespace) { + if (!RouteBuilder.class.isAssignableFrom(routeClass)) { + throw CamelComponentMessages.MESSAGES.javaDSLClassMustExtend(routeClass.getName(), + RouteBuilder.class.getName()); + } + + // Create the route and tell it to create a route + RouteBuilder builder; + try { + builder = (RouteBuilder) routeClass.newInstance(); + builder.configure(); + List routes = builder.getRouteCollection().getRoutes(); + if (routes.isEmpty()) { + throw CamelComponentMessages.MESSAGES.noRoutesFoundinJavaDSLClass(routeClass.getName()); + } + return routes; + } catch (Exception ex) { + throw CamelComponentMessages.MESSAGES.failedToInitializeDSLClass(routeClass.getName(), ex); + } + } + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/deploy/CamelActivator.java b/components/camel/component/src/main/java/org/switchyard/component/camel/deploy/CamelActivator.java new file mode 100644 index 000000000..fa77f47cc --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/deploy/CamelActivator.java @@ -0,0 +1,181 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import java.net.URI; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.apache.camel.component.properties.PropertiesComponent; +import org.apache.camel.model.FromDefinition; +import org.apache.camel.model.ProcessorDefinition; +import org.apache.camel.model.RouteDefinition; +import org.apache.camel.model.ToDefinition; +import org.switchyard.ServiceReference; +import org.switchyard.SwitchYardException; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.component.camel.CamelComponentMessages; +import org.switchyard.component.camel.switchyard.ComponentNameComposer; +import org.switchyard.component.camel.RouteFactory; +import org.switchyard.component.camel.switchyard.SwitchYardConsumer; +import org.switchyard.component.camel.switchyard.SwitchYardEndpoint; +import org.switchyard.component.camel.switchyard.SwitchYardPropertiesParser; +import org.switchyard.component.camel.common.CamelConstants; +import org.switchyard.component.camel.common.composer.CamelComposition; +import org.switchyard.component.camel.common.deploy.BaseCamelActivator; +import org.switchyard.component.camel.model.CamelComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.deploy.ComponentNames; +import org.switchyard.deploy.ServiceHandler; + +/** + * Activates Camel bindings, references and implementations in SwitchYard. + * + * @author Daniel Bevenius + */ +public class CamelActivator extends BaseCamelActivator { + + /** + * Creates a new activator for Camel endpoint types. + * + * @param context Camel context to use. + * @param types Activation types. + */ + public CamelActivator(SwitchYardCamelContext context, String ... types) { + super(context, types); + } + + @Override + public ServiceHandler activateService(QName serviceName, ComponentModel config) { + ServiceHandler handler = null; + + // add switchyard property parser to camel PropertiesComponent + PropertiesComponent propertiesComponent = getCamelContext().getComponent("properties", PropertiesComponent.class); + PropertyResolver pr = config.getModelConfiguration().getPropertyResolver(); + propertiesComponent.setPropertiesParser(new SwitchYardPropertiesParser(pr)); + + // process service + for (ComponentServiceModel service : config.getServices()) { + if (service.getQName().equals(serviceName)) { + handler = handleImplementation(service, serviceName); + break; + } + } + + return handler; + } + + @Override + public void deactivateService(QName name, ServiceHandler handler) { + // nothing to do here ... + } + + private ServiceHandler handleImplementation(final ComponentServiceModel config, final QName serviceName) { + final CamelComponentImplementationModel ccim = + (CamelComponentImplementationModel)config.getComponent().getImplementation(); + try { + final String endpointUri = ComponentNameComposer.composeComponentUri(serviceName); + final List routeDefinitions = getRouteDefinition(ccim); + verifyRouteDefinitions(routeDefinitions, ccim); + getCamelContext().addRouteDefinitions(routeDefinitions); + final SwitchYardEndpoint endpoint = getCamelContext().getEndpoint(endpointUri, SwitchYardEndpoint.class); + endpoint.setMessageComposer(CamelComposition.getMessageComposer()); + final SwitchYardConsumer consumer = endpoint.getConsumer(); + consumer.setComponentName(config.getComponent().getQName()); + consumer.setNamespace(serviceName.getNamespaceURI()); + return consumer; + } catch (final Exception e) { + throw new SwitchYardException(e.getMessage(), e); + } + } + + private boolean containsServiceRef(final List refs, final String serviceName) { + for (ComponentReferenceModel refModel : refs) { + if (refModel.getName().equals(serviceName)) { + return true; + } + } + return false; + } + + private void verifyRouteDefinitions(List routeDefinitions, CamelComponentImplementationModel ccim) throws Exception { + // service name & namespace + // TODO what happens when we have multiple services? + String serviceName = ccim.getComponent().getServices().get(0).getName(); + String compositeNs = ccim.getComponent().getComposite().getTargetNamespace(); + + // number of switchyard:// consumers/from statements + int serviceConsumer = 0; + for (RouteDefinition routeDefinition : routeDefinitions) { + if (routeDefinition.getInputs().isEmpty()) { + throw CamelComponentMessages.MESSAGES.mustHaveAtLeastOneInput(); + } + for (FromDefinition fromDefinition : routeDefinition.getInputs()) { + URI from = URI.create(fromDefinition.getUri()); + if (from.getScheme().equals(CamelConstants.SWITCHYARD_COMPONENT_NAME)) { + if (serviceConsumer > 0) { + throw CamelComponentMessages.MESSAGES.onlyOneSwitchYardInputPerImpl(); + } + String authority = from.getAuthority(); + + if (!serviceName.equals(authority)) { + throw CamelComponentMessages.MESSAGES.implementationConsumerDoesNotMatchService(serviceName); + } + serviceConsumer++; + } + } + + List> outputs = routeDefinition.getOutputs(); + for (ProcessorDefinition processorDefinition : outputs) { + if (processorDefinition instanceof ToDefinition) { + ToDefinition to = (ToDefinition) processorDefinition; + final URI componentUri = URI.create(to.getUri()); + if (componentUri.getScheme().equals(CamelConstants.SWITCHYARD_COMPONENT_NAME)) { + final String referenceName = componentUri.getAuthority(); + final QName refServiceName = new QName(compositeNs, referenceName); + if (!containsServiceRef(ccim.getComponent().getReferences(), referenceName)) { + throw CamelComponentMessages.MESSAGES.couldNotFindServiceReference(referenceName, to.toString()); + } + + QName qualifiedRefName = ComponentNames.qualify( + ccim.getComponent().getQName(), refServiceName); + final ServiceReference service = getServiceDomain().getServiceReference(qualifiedRefName); + if (service == null) { + throw CamelComponentMessages.MESSAGES.couldNotFindServiceName(qualifiedRefName.toString(), to.toString()); + } + } + } + } + } + if (serviceConsumer != 1) { + throw CamelComponentMessages.MESSAGES.cannotCreateComponentImpl(); + } + } + + + /** + * There are two options for Camel implementation : Spring XML or Java DSL. + * This method figures out which one were dealing with and returns the + * corresponding RouteDefinition. + */ + private List getRouteDefinition(CamelComponentImplementationModel model) { + List routes = RouteFactory.getRoutes(model); + return routes; + } + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/deploy/CamelComponent.java b/components/camel/component/src/main/java/org/switchyard/component/camel/deploy/CamelComponent.java new file mode 100644 index 000000000..8485a6e72 --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/deploy/CamelComponent.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.deploy.BaseCamelComponent; +import org.switchyard.component.camel.model.v1.V1CamelImplementationModel; + +/** + * An implementation of Camel component. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class CamelComponent extends BaseCamelComponent { + + /** + * Default constructor. + */ + public CamelComponent() { + super("CamelComponent", V1CamelImplementationModel.CAMEL); + } + + @Override + protected CamelActivator createActivator(SwitchYardCamelContext context, String... types) { + return new CamelActivator(context, types); + } + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/model/CamelComponentImplementationModel.java b/components/camel/component/src/main/java/org/switchyard/component/camel/model/CamelComponentImplementationModel.java new file mode 100644 index 000000000..274cd534a --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/model/CamelComponentImplementationModel.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.model; + +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * Definition of a Camel implementation model (implementation.camel). + *

+ * This allows for the usage of Camel DSL for routing between SwichYard + * Services. + * + * @author Daniel Bevenius + * + */ +public interface CamelComponentImplementationModel extends ComponentImplementationModel { + + /** + * The 'camel' implementation type. + */ + String CAMEL = "camel"; + + /** + * The name of the Camel java element. + */ + String JAVA = "java"; + + /** + * The name of the Camel xml element. + */ + String XML = "xml"; + + /** + * Name of a Class containing one or more @Route definitions. + * @return reference to the route class + */ + String getJavaClass(); + + /** + * Path to a file containing an XML route definition. + * @return path to the route definition + */ + String getXMLPath(); + + /** + * Set the name of a Class with one ore more @Route definitions. + * @param className name of the class + * @return reference to this config model + */ + CamelComponentImplementationModel setJavaClass(String className); + + /** + * Set the path to a file containing an XML route definition. + * @param path path to a route definition + * @return reference to this config model + */ + CamelComponentImplementationModel setXMLPath(String path); + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/model/CamelNamespace.java b/components/camel/component/src/main/java/org/switchyard/component/camel/model/CamelNamespace.java new file mode 100644 index 000000000..4bbc7075b --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/model/CamelNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Camel config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum CamelNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final transient Util _util; + + /** + * Constructs a new CamelNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + CamelNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the CamelNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the CamelNamespace + */ + public static CamelNamespace fromUri(String uri) { + return Util.fromUri(CamelNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(CamelNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-camel:config", version); + } + } + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/model/RouteScanner.java b/components/camel/component/src/main/java/org/switchyard/component/camel/model/RouteScanner.java new file mode 100644 index 000000000..70537e278 --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/model/RouteScanner.java @@ -0,0 +1,139 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.model; + +import java.io.IOException; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.util.List; + +import org.switchyard.common.type.classpath.AbstractTypeFilter; +import org.switchyard.common.type.classpath.ClasspathScanner; +import org.switchyard.component.camel.Route; +import org.switchyard.component.camel.model.v1.V1CamelImplementationModel; +import org.switchyard.config.model.Scannable; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.v1.V1ComponentModel; +import org.switchyard.config.model.composite.v1.V1ComponentServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeModel; +import org.switchyard.config.model.composite.v1.V1InterfaceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; + +/** + * Scans for classes with @Route methods and creates a Camel Route definition + * for each. + * @author eduardo.devera + */ +public class RouteScanner implements Scanner { + + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + SwitchYardNamespace switchyardNamespace = input.getSwitchyardNamespace(); + SwitchYardModel switchyardModel = new V1SwitchYardModel(switchyardNamespace.uri()); + CompositeModel compositeModel = new V1CompositeModel(); + compositeModel.setName(input.getCompositeName()); + + CamelNamespace camelNamespace = CamelNamespace.DEFAULT; + for (CamelNamespace value : CamelNamespace.values()) { + if (value.versionMatches(switchyardNamespace)) { + camelNamespace = value; + break; + } + } + + List> routeClasses = scanForRoutes(input.getURLs()); + + // Create a Camel component model for each class + for (Class routeClass : routeClasses) { + // Top-level component definition + ComponentModel componentModel = new V1ComponentModel(); + componentModel.setName(routeClass.getSimpleName()); + + // Component implementation definition + CamelComponentImplementationModel camelModel = new V1CamelImplementationModel(camelNamespace.uri()); + camelModel.setJavaClass(routeClass.getName()); + componentModel.setImplementation(camelModel); + compositeModel.addComponent(componentModel); + + // Component service definition + ComponentServiceModel serviceModel = new V1ComponentServiceModel(switchyardNamespace.uri()); + InterfaceModel csiModel = new V1InterfaceModel(InterfaceModel.JAVA); + Class serviceInterface = routeClass.getAnnotation(Route.class).value(); + serviceModel.setName(getServiceName(routeClass)); + csiModel.setInterface(serviceInterface.getName()); + serviceModel.setInterface(csiModel); + componentModel.addService(serviceModel); + + // Component reference definition(s) + // Need to add these! + } + + if (!compositeModel.getModelChildren().isEmpty()) { + switchyardModel.setComposite(compositeModel); + } + + return new ScannerOutput().setModel(switchyardModel); + } + + private String getServiceName(Class routeClass) { + return routeClass.getAnnotation(Route.class).name().equals(Route.EMPTY) + ? routeClass.getAnnotation(Route.class).value().getSimpleName() + : routeClass.getAnnotation(Route.class).name(); + } + + private List> scanForRoutes(List urls) throws IOException { + AbstractTypeFilter filter = new RouteFilter(); + ClasspathScanner scanner = new ClasspathScanner(filter); + + for (URL url : urls) { + scanner.scan(url); + } + + return filter.getMatchedTypes(); + } + + private class RouteFilter extends AbstractTypeFilter { + @Override + public boolean matches(Class clazz) { + // Check to see if it's been excluded from scans + Scannable scannable = clazz.getAnnotation(Scannable.class); + if (scannable != null && !scannable.value()) { + return false; + } + + // Can't be an interface or abstract class + if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { + return false; + } + + // Must have a no-arg constructor + try { + clazz.getConstructor(); + } catch (NoSuchMethodException e) { + return false; + } + + // Check for @Route definitions + return clazz.isAnnotationPresent(Route.class); + } + } +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/model/v1/V1CamelComponentModelMarshaller.java b/components/camel/component/src/main/java/org/switchyard/component/camel/model/v1/V1CamelComponentModelMarshaller.java new file mode 100644 index 000000000..b4035e817 --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/model/v1/V1CamelComponentModelMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.model.v1; + +import org.switchyard.component.camel.common.model.v1.V1BaseCamelMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * Camel component marshaller. + */ +public class V1CamelComponentModelMarshaller extends V1BaseCamelMarshaller { + + private static final String IMPLEMENTATION_CAMEL = ComponentImplementationModel.IMPLEMENTATION + '.' + V1CamelImplementationModel.CAMEL; + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1CamelComponentModelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1BaseCamelMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (IMPLEMENTATION_CAMEL.equals(name)) { + return new V1CamelImplementationModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/model/v1/V1CamelImplementationModel.java b/components/camel/component/src/main/java/org/switchyard/component/camel/model/v1/V1CamelImplementationModel.java new file mode 100644 index 000000000..3902283e9 --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/model/v1/V1CamelImplementationModel.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.model.v1; + +import org.switchyard.component.camel.common.model.v1.NameValueModel; +import org.switchyard.component.camel.model.CamelComponentImplementationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1ComponentImplementationModel; + +/** + * Version 1 implementation. + * + * @author Daniel Bevenius + */ +public class V1CamelImplementationModel extends V1ComponentImplementationModel + implements CamelComponentImplementationModel { + + // The class attribute for Java DSL routes + private static final String CLASS = "class"; + + // The path attribute for XML DSL routes + private static final String PATH = "path"; + + /** + * Create a new CamelImplementationModel. + * @param namespace namespace + */ + public V1CamelImplementationModel(String namespace) { + super(CAMEL, namespace); + } + + /** + * Create a CamelImplementationModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(); + } + + @Override + public String getJavaClass() { + Configuration classConfig = getModelConfiguration().getFirstChild(JAVA); + return classConfig != null ? classConfig.getAttribute(CLASS) : null; + } + + @Override + public V1CamelImplementationModel setJavaClass(String className) { + Configuration classConfig = getModelConfiguration().getFirstChild(JAVA); + if (classConfig == null) { + NameValueModel model = new NameValueModel(getNamespaceURI(), JAVA); + model.getModelConfiguration().setAttribute(CLASS, className); + setChildModel(model); + } else { + classConfig.setAttribute(CLASS, className); + } + return this; + } + + @Override + public String getXMLPath() { + Configuration classConfig = getModelConfiguration().getFirstChild(XML); + return classConfig != null ? classConfig.getAttribute(PATH) : null; + } + + @Override + public CamelComponentImplementationModel setXMLPath(String path) { + Configuration pathConfig = getModelConfiguration().getFirstChild(XML); + if (pathConfig == null) { + NameValueModel model = new NameValueModel(getNamespaceURI(), XML); + model.getModelConfiguration().setAttribute(PATH, path); + setChildModel(model); + } else { + pathConfig.setAttribute(PATH, path); + } + return this; + } + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelConverter.java b/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelConverter.java new file mode 100644 index 000000000..af33ae529 --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelConverter.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.transformer; + +import org.apache.camel.TypeConverter; +import org.apache.camel.impl.DefaultCamelContext; + +/** + * A singleton converter that can be used by Switchyard Transformers + * that need to delegate to Camel's TypeConverters. + * + * @author Daniel Bevenius + * + */ +public final class CamelConverter { + + private static final CamelConverter INSTANCE = new CamelConverter(); + + private TypeConverter _typeConverter; + + private CamelConverter() { + final DefaultCamelContext camelContext = new DefaultCamelContext(); + +// PackageScanClassResolver packageScanClassResolver = CamelActivator.getPackageScanClassResolver(); +// if (packageScanClassResolver != null) { +// camelContext.setPackageScanClassResolver(packageScanClassResolver); +// } + + _typeConverter = camelContext.getTypeConverter(); + } + + /** + * Delegates to Camel's TypeConverter. + * + * @param toType the type to convert to + * @param from the object to convert from + * @return Object the converted object + */ + public Object convert(final Class toType, final Object from) { + return _typeConverter.convertTo(toType, from); + } + + /** + * Gets the singleton instance. + * @return CamelConverter the singleton instance. + */ + public static CamelConverter instance() { + return INSTANCE; + } + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelTransformer.java b/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelTransformer.java new file mode 100644 index 000000000..1f059be87 --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelTransformer.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.transformer; + +import javax.xml.namespace.QName; + +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.transform.BaseTransformer; + +/** + * A SwitchYard transformer that delegates to Apache Camel's converter framework. + *

+ * + * This gives SwitchYard components that use the SwitchYard Camel component to have + * access to all converters that are provided by Camel and at the same time enables + * the from and to types to be explicitely declared on the SwitchYard contracts. + * + * @author Daniel Bevenius + * + */ +public class CamelTransformer extends BaseTransformer { + + private CamelConverter _camelConverter = CamelConverter.instance(); + + /** + * No-args constructor. + */ + public CamelTransformer() { + } + + /** + * + * @param from The QName of the type that this transformer is capable of transforming from + * @param to The QName of the type that this transformer is capable of transforming to + */ + public CamelTransformer(final QName from, final QName to) { + super(from, to); + } + + @Override + public Object transform(final Object from) { + if (from == null) { + return null; + } + + final Class toType = QNameUtil.toJavaMessageType(getTo()); + return _camelConverter.convert(toType, from); + } + +} diff --git a/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelTypeConverterExtractor.java b/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelTypeConverterExtractor.java new file mode 100644 index 000000000..16da08786 --- /dev/null +++ b/components/camel/component/src/main/java/org/switchyard/component/camel/transformer/CamelTypeConverterExtractor.java @@ -0,0 +1,136 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.transformer; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.camel.CamelContext; +import org.apache.camel.TypeConverter; +import org.apache.camel.impl.converter.DefaultTypeConverter; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.model.transform.v1.V1TransformsModel; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.transform.config.model.JavaTransformModel; +import org.switchyard.transform.config.model.TransformNamespace; +import org.switchyard.transform.config.model.v1.V1JavaTransformModel; + +/** + * Extracts the types that have been registered in Camel with a corresponding {@link TypeConverter}. + * This is simply a way to find out what converters are available in Camel and make this information + * available to SwitchYard. + * + * @author Daniel Bevenius + * + */ +public class CamelTypeConverterExtractor extends DefaultTypeConverter { + + private Map> _transformTypes = new HashMap>(); + private CamelContext _camelContext; + + /** + * Sole constuctor. + * + * @param camelContext the CamelContext to be used. + */ + public CamelTypeConverterExtractor(final CamelContext camelContext) { + super(camelContext.getPackageScanClassResolver(), camelContext.getInjector(), camelContext.getDefaultFactoryFinder()); + _camelContext = camelContext; + } + + /** + * Initializes Camel's type converters by loading default type converters and annotated converters. + * + * @throws Exception if an error occurs while loading the type converters. + */ + public void init() throws Exception { + _camelContext.addService(this); + } + + /** + * Will return the SwitchYard representations (QName) for the 'from and 'to' types + * registered within Camel's TypeConverter registry. + * + * @return Map where the key is the fromType and the value a set of toTypes. + */ + public Map> getTransformTypes() { + for (Entry entry : typeMappings.entrySet()) + { + final TypeMapping mapping = entry.getKey(); + final QName fromType = JavaTypes.toMessageType(mapping.getFromType()); + final QName toType = JavaTypes.toMessageType(mapping.getToType()); + getToTypesFor(fromType).add(toType); + } + + return Collections.unmodifiableMap(_transformTypes); + } + + private Set getToTypesFor(final QName fromType) { + if (!_transformTypes.containsKey(fromType)) { + _transformTypes.put(fromType, new HashSet()); + } + return _transformTypes.get(fromType); + } + + /** + * Returns a TransformsModel which will not include transformers are already registered in + * the {@link TransformerRegistry} in SwitchYard. + * + * @param transformerRegistry SwitchYard's {@link TransformerRegistry}. + * + * @return {@link TransformsModel} the populated TransformsModel + */ + public TransformsModel getTransformsModel(final TransformerRegistry transformerRegistry) { + final TransformsModel transforms = new V1TransformsModel(TransformNamespace.DEFAULT.uri()); + for (Entry> entry : getTransformTypes().entrySet()) { + final QName from = entry.getKey(); + final Set toTypes = entry.getValue(); + for (QName to : toTypes) { + final V1JavaTransformModel transform = new V1JavaTransformModel(TransformNamespace.DEFAULT.uri()); + transform.setFrom(from); + transform.setTo(to); + transform.setClazz(CamelTransformer.class.getName()); + if (!isTransformRegistred(transform, transformerRegistry)) { + transforms.addTransform(transform); + } + } + } + return transforms; + } + + private boolean isTransformRegistred(final JavaTransformModel transform, final TransformerRegistry transformerRegistry) { + if (transformerRegistry == null) { + return false; + } + + return transformerRegistry.hasTransformer(transform.getFrom(), transform.getTo()); + } + + /** + * Returns a TransformsModel that does not check if transformers are already registered within + * the {@link TransformerRegistry} in SwitchYard. + * + * @return {@link TransformsModel} populated with the passed in types. + */ + public TransformsModel getTransformsModel() { + return getTransformsModel(null); + } +} diff --git a/components/camel/component/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/camel/component/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..c7a614da4 --- /dev/null +++ b/components/camel/component/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.camel.deploy.CamelComponent diff --git a/components/camel/component/src/main/resources/META-INF/switchyard/transforms.xml b/components/camel/component/src/main/resources/META-INF/switchyard/transforms.xml new file mode 100644 index 000000000..4333e0b3f --- /dev/null +++ b/components/camel/component/src/main/resources/META-INF/switchyard/transforms.xml @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/main/resources/OSGI-INF/blueprint/transformers.xml b/components/camel/component/src/main/resources/OSGI-INF/blueprint/transformers.xml new file mode 100644 index 000000000..d7c903944 --- /dev/null +++ b/components/camel/component/src/main/resources/OSGI-INF/blueprint/transformers.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v1/camel-component_1_0.xsd b/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v1/camel-component_1_0.xsd new file mode 100644 index 000000000..05c1fc305 --- /dev/null +++ b/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v1/camel-component_1_0.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v1/camel-component_1_1.xsd b/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v1/camel-component_1_1.xsd new file mode 100644 index 000000000..a9ba961f8 --- /dev/null +++ b/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v1/camel-component_1_1.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v2/camel-component_2_0.xsd b/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v2/camel-component_2_0.xsd new file mode 100644 index 000000000..620d81329 --- /dev/null +++ b/components/camel/component/src/main/resources/org/switchyard/component/camel/model/v2/camel-component_2_0.xsd @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/camel/component/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..46424c7e6 --- /dev/null +++ b/components/camel/component/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,44 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_1_0.section=urn:switchyard-component-camel:config +camel_1_0.version=1.0 +camel_1_0.namespace=urn:switchyard-component-camel:config:1.0 +camel_1_0.schema=camel-component_1_0.xsd +camel_1_0.location=/org/switchyard/component/camel/model/v1/ +camel_1_0.marshaller=org.switchyard.component.camel.model.v1.V1CamelComponentModelMarshaller + +camel_1_1.section=urn:switchyard-component-camel:config +camel_1_1.version=1.1 +camel_1_1.namespace=urn:switchyard-component-camel:config:1.1 +camel_1_1.schema=camel-component_1_1.xsd +camel_1_1.location=/org/switchyard/component/camel/model/v1/ +camel_1_1.marshaller=org.switchyard.component.camel.model.v1.V1CamelComponentModelMarshaller + +camel_2_0.section=urn:switchyard-component-camel:config +camel_2_0.version=2.0 +camel_2_0.namespace=urn:switchyard-component-camel:config:2.0 +camel_2_0.schema=camel-component_2_0.xsd +camel_2_0.location=/org/switchyard/component/camel/model/v2/ +camel_2_0.marshaller=org.switchyard.component.camel.model.v1.V1CamelComponentModelMarshaller + +camel_spring_1_0.section=http://camel.apache.org/schema/spring +camel_spring_1_0.version=1.0 +camel_spring_1_0.namespace=http://camel.apache.org/schema/spring +camel_spring_1_0.schema=camel-spring.xsd +camel_spring_1_0.location=/org/apache/camel/schema/spring/ + +spring_beans_2_0.section=http://www.springframework.org/schema/beans +spring_beans_2_0.version=2.0 +spring_beans_2_0.namespace=http://www.springframework.org/schema/beans +spring_beans_2_0.schema=spring-beans-2.0.xsd +spring_beans_2_0.location=/org/springframework/beans/factory/xml/ diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/ExceptionHandlingTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/ExceptionHandlingTest.java new file mode 100644 index 000000000..28a3b3017 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/ExceptionHandlingTest.java @@ -0,0 +1,125 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.HandlerException; +import org.switchyard.Scope; +import org.switchyard.test.InvocationFaultException; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardTestKit; + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-exception-test.xml") +public class ExceptionHandlingTest { + + private SwitchYardTestKit testKit; + @ServiceOperation("UnhandledExceptionService") + private Invoker unhandledException; + @ServiceOperation("OnExceptionService") + private Invoker onException; + @ServiceOperation("TryCatchService") + private Invoker tryCatch; + + @Test + public void testUnhandledException() { + final String exMsg = "Service1 Exception"; + + testKit.registerInOutService("Service1") + .replyWithFault(new Exception(exMsg)); + + try { + unhandledException.operation("process").sendInOut("test"); + Assert.fail("Exception from Service1 not propagated"); + } catch (InvocationFaultException ifEx) { + Assert.assertEquals(exMsg, ifEx.getCause().getCause().getMessage()); + } + } + + @Test + public void testOnExceptionFailurePath() { + final String exMsg = "Service1 Exception"; + + testKit.registerInOutService("Service1") + .replyWithFault(new Exception(exMsg)); + + try { + String result = onException.operation("process") + .sendInOut("test").getContent(String.class); + Assert.assertEquals("handled:" + exMsg, result); + + } catch (Exception ex) { + Assert.fail("Exception from Service1 not handled"); + } + } + + /** + * Make sure that happy path is not impacted by updated logic to screen + * off "Camel*" exchange properties. + */ + @Test + public void testOnExceptionHappyPath() { + testKit.registerInOutService("Service1", new ExchangeHandler() { + public void handleFault(Exchange exchange) { } + public void handleMessage(Exchange exchange) throws HandlerException { + // check to make sure that when Service1 is called, the correct properties were passed + Assert.assertEquals("Camel-abc", exchange.getContext().getPropertyValue("Camel-abc")); + Assert.assertNull(exchange.getContext().getProperty("Camel-123")); + + // now set two properties, one of which should flow back + exchange.getContext().setProperty("Camel-xyz", "Camel-xyz", Scope.EXCHANGE); + exchange.getContext().setProperty("Camel-456", "Camel-456", Scope.EXCHANGE); + } + }); + String result = onException.operation("process") + .sendInOut("test").getContent(String.class); + Assert.assertEquals("happy path", result); + } + + @Test + public void testTryCatchFailurePath() { + final String exMsg = "Service1 Exception"; + + testKit.registerInOutService("Service1") + .replyWithFault(new Exception(exMsg)); + + try { + String result = tryCatch.operation("process") + .sendInOut("test").getContent(String.class); + Assert.assertEquals("handled:" + exMsg, result); + + } catch (Exception ex) { + Assert.fail("Exception from Service1 not handled"); + } + } + + /** + * Make sure that happy path is not impacted by updated logic to screen + * off "Camel*" exchange properties. + */ + @Test + public void testTryCatchHappyPath() { + testKit.registerInOutService("Service1").forwardInToOut(); + String result = tryCatch.operation("process") + .sendInOut("test").getContent(String.class); + Assert.assertEquals("happy path", result); + } +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/OnExceptionRoute.java b/components/camel/component/src/test/java/org/switchyard/component/camel/OnExceptionRoute.java new file mode 100644 index 000000000..c582d102b --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/OnExceptionRoute.java @@ -0,0 +1,52 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.builder.RouteBuilder; +import org.switchyard.component.camel.switchyard.ExchangeMapper; + +public class OnExceptionRoute extends RouteBuilder { + + /** + * The Camel route is configured via this method. The from endpoint is required to be a SwitchYard service. + */ + public void configure() { + from("switchyard://OnExceptionService") + .onException(Exception.class) + .handled(true) + .setBody().simple("handled:${exception.message}") + .end() + .process(new Processor() { + public void process(Exchange exchange) throws Exception { + // List of propagated Camel properties + List includeProps = new ArrayList(); + includeProps.add("Camel-abc"); + includeProps.add("Camel-xyz"); + exchange.setProperty(ExchangeMapper.CAMEL_PROPERTY_INCLUDES, includeProps); + + // Set two properties, one of which should be propagated + exchange.setProperty("Camel-abc", "Camel-abc"); + exchange.setProperty("Camel-123", "Camel-123"); + } + }) + .to("switchyard://Service1") + .setBody().simple("happy path"); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/Process.java b/components/camel/component/src/test/java/org/switchyard/component/camel/Process.java new file mode 100644 index 000000000..96b752003 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/Process.java @@ -0,0 +1,18 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + +public interface Process { + String process(String msg); +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/RouteFactoryTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/RouteFactoryTest.java new file mode 100644 index 000000000..a3b62e0b6 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/RouteFactoryTest.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + +import java.util.List; + +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.model.RouteDefinition; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.component.camel.scanner.ServiceInterface; +import org.switchyard.component.camel.scanner.SingleRouteService; +import org.switchyard.SwitchYardException; + +public class RouteFactoryTest { + + @Test + public void createRouteFromClass() { + List routes = RouteFactory.createRoute(SingleRouteService.class.getName()); + + Assert.assertNotNull(routes); + Assert.assertEquals(1, routes.size()); + RouteDefinition route = routes.get(0); + Assert.assertEquals(1, route.getInputs().size()); + Assert.assertEquals(2, route.getOutputs().size()); + } + + @Test + public void doesntExtendRouteBuilder() { + try { + RouteFactory.createRoute(DoesntExtendRouteBuilder.class.getName()); + Assert.fail("Java DSL class does not extend RouteBuilder " + DoesntExtendRouteBuilder.class.getName()); + } catch (RuntimeException ex) { + System.err.println("Route class that does not extend RouteBuilder was rejected: " + ex.toString()); + } + } + + @Test + public void noRoutesDefined() { + try { + RouteFactory.createRoute(NoRoutesDefined.class.getName()); + Assert.fail("No routes defined in Java DSL class " + NoRoutesDefined.class.getName()); + } catch (RuntimeException ex) { + System.err.println("Java DSL class without a route was rejected: " + ex.toString()); + } + } + + @Test + public void noRoutesDefinedXML() { + try { + RouteFactory.loadRoute("org/switchyard/component/camel/deploy/not-a-route.xml"); + } catch (SwitchYardException syEx) { + System.err.println("Invalid Camel XML definition rejected: " + syEx.toString()); + } + } + + @Test + public void singleRouteXML() { + List routes = + RouteFactory.loadRoute("org/switchyard/component/camel/deploy/route.xml"); + Assert.assertEquals(1, routes.size()); + } + + @Test + public void multiRouteXML() { + List routes = + RouteFactory.loadRoute("org/switchyard/component/camel/deploy/routes.xml"); + Assert.assertEquals(2, routes.size()); + } +} + +class NoRouteAnnotation extends RouteBuilder { + public void configure() { + from("direct://foo") + .to("mock:test"); + } +} + +@Route(ServiceInterface.class) +class DoesntExtendRouteBuilder { + public void configure() { + } +} + +@Route(ServiceInterface.class) +class NoRoutesDefined extends RouteBuilder { + public void configure() { + } +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/TryCatchRoute.java b/components/camel/component/src/test/java/org/switchyard/component/camel/TryCatchRoute.java new file mode 100644 index 000000000..183e7b0d4 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/TryCatchRoute.java @@ -0,0 +1,32 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + +import org.apache.camel.builder.RouteBuilder; + +public class TryCatchRoute extends RouteBuilder { + + /** + * The Camel route is configured via this method. The from endpoint is required to be a SwitchYard service. + */ + public void configure() { + from("switchyard://TryCatchService") + .doTry() + .to("switchyard://Service1") + .setBody(simple("happy path")) + .doCatch(Exception.class) + .setBody(simple("handled:${exception.message}")); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/UnhandledExceptionRoute.java b/components/camel/component/src/test/java/org/switchyard/component/camel/UnhandledExceptionRoute.java new file mode 100644 index 000000000..5a64ff603 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/UnhandledExceptionRoute.java @@ -0,0 +1,29 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel; + +import org.apache.camel.builder.RouteBuilder; + +public class UnhandledExceptionRoute extends RouteBuilder { + + /** + * The Camel route is configured via this method. The from endpoint is required to be a SwitchYard service. + */ + public void configure() { + // TODO Auto-generated method stub + from("switchyard://UnhandledExceptionService") + .to("switchyard://Service1"); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelActivatorTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelActivatorTest.java new file mode 100644 index 000000000..aaecfe74e --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelActivatorTest.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.apache.camel.CamelContext; +import org.apache.camel.CamelExecutionException; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.spi.PackageScanClassResolver; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.camel.deploy.support.CustomPackageScanResolver; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardTestKit; + +/** + * Test for {@link CamelActivator}. + * + * @author Daniel Bevenius + * + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-test.xml", mixins = CDIMixIn.class) +public class CamelActivatorTest { + + private SwitchYardTestKit _testKit; + private CamelContext _camelContext; + + @Test + public void sendOneWayMessageThroughCamelToSwitchYardService() throws Exception { + // remove the currently registered service for SimpleCamelService + _testKit.removeService("SimpleCamelService"); + final MockHandler mockHandler = _testKit.registerInOnlyService("SimpleCamelService"); + final ProducerTemplate producerTemplate = _camelContext.createProducerTemplate(); + + producerTemplate.sendBody("direct://input", "dummy payload"); + assertOneMessage(mockHandler, "dummy payload"); + + producerTemplate.sendBody("direct://input2", "dummy payload"); + assertOneMessage(mockHandler, "dummy payload"); + } + + @Test + public void setCustomClassPathResolver() { + final PackageScanClassResolver p = _camelContext.getPackageScanClassResolver(); + assertThat(p, is(instanceOf(CustomPackageScanResolver.class))); + } + + @Ignore + @Test + public void startStop() throws Exception { + final MockHandler mockHandler = _testKit.registerInOnlyService("SimpleCamelService"); + final ProducerTemplate producerTemplate = _camelContext.createProducerTemplate(); + + producerTemplate.sendBody("direct://input", "dummy payload"); + assertOneMessage(mockHandler, "dummy payload"); + + // Stop the camel components for the service... + + try { + producerTemplate.sendBody("direct://input2", "dummy payload"); + Assert.fail("Expected CamelExecutionException."); + } catch (CamelExecutionException e) { + // Expected.... + } + + // Restart the camel components for the service... + producerTemplate.sendBody("direct://input", "dummy payload"); + assertOneMessage(mockHandler, "dummy payload"); + } + + private void assertOneMessage(final MockHandler mockHandler, final String expectedPayload) { + mockHandler.waitForOKMessage(); + assertThat(mockHandler.getMessages().size(), is(1)); + final String content = mockHandler.getMessages().poll().getMessage().getContent(String.class); + assertThat(content, is(equalTo("dummy payload"))); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationDeclaredFaultHandlingTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationDeclaredFaultHandlingTest.java new file mode 100644 index 000000000..56dbd2e20 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationDeclaredFaultHandlingTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.camel.deploy.support.CustomException; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/** + * Test for {@link CamelActivator} that uses a implementation.camel and + * test error handling. + * + * @author Daniel Bevenius + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-impl-declared-fault.xml", mixins = CDIMixIn.class) +public class CamelImplementationDeclaredFaultHandlingTest { + + @ServiceOperation("OrderService.getTitleForItem") + private Invoker _getTitleForItem; + + @Rule + public SwitchYardExpectedException thrown = SwitchYardExpectedException.none(); + + private CamelContext _camelContext; + + @Before + public void setupMockEndpoint() { + final MockEndpoint endpoint = _camelContext.getEndpoint("mock://throw", MockEndpoint.class); + endpoint.whenAnyExchangeReceived(new ExceptionThrowingProcesor()); + } + + @Test + public void shouldThrowDeclaredExceptionFromCamelRoute() throws Exception { + thrown.expect(CustomException.class); + thrown.expectMessage("dummy exception"); + _getTitleForItem.sendInOut("10"); + } + + private class ExceptionThrowingProcesor implements Processor { + @Override + public void process(Exchange exchange) throws Exception { + throw new CustomException("dummy exception"); + } + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationDotUnderscoreTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationDotUnderscoreTest.java new file mode 100644 index 000000000..9e93ff150 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationDotUnderscoreTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import javax.activation.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.TestDataSource; + +/** + * Test for {@link CamelActivator} where the service name contains dot(.) and underscore(_). + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-impl-dot-underscore.xml", mixins = CDIMixIn.class) +public class CamelImplementationDotUnderscoreTest { + + @ServiceOperation("Order.Service_1.getTitleForItem") + private Invoker _getTitleForItem; + + @ServiceOperation("Warehouse.Service_1.getDataForItem") + private Invoker _getDataForItem; + + @Test + public void sendOneWayMessageThroughCamelToSwitchYardService() throws Exception { + final String title = _getTitleForItem.sendInOut("10").getContent(String.class); + assertThat(title, is(equalTo("Fletch"))); + } + + @Test + public void sendOneWayMessageThroughCamelToTestAttachment() throws Exception { + DataSource ds = new TestDataSource("10", "text/plain", "Fletch-Data"); + _getDataForItem.attachment(ds.getName(), ds); + final String data = _getDataForItem.sendInOut(ds.getName()).getContent(String.class); + assertThat(data, is(equalTo("Fletch-Data"))); + } +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationErrorHandlingTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationErrorHandlingTest.java new file mode 100644 index 000000000..38d81967f --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationErrorHandlingTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.camel.deploy.support.CustomException; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/** + * Test for {@link CamelActivator} that uses a implementation.camel and + * test error handling. + * + * @author Daniel Bevenius + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-impl-error.xml", mixins = CDIMixIn.class) +public class CamelImplementationErrorHandlingTest { + + @ServiceOperation("OrderService.getTitleForItem") + private Invoker _getTitleForItem; + + @Rule + public SwitchYardExpectedException thrown = SwitchYardExpectedException.none(); + + private CamelContext _camelContext; + + @Before + public void setupMockEndpoint() { + final MockEndpoint endpoint = _camelContext.getEndpoint("mock://throw", MockEndpoint.class); + endpoint.whenAnyExchangeReceived(new ExceptionThrowingProcesor()); + } + + @Test + public void shouldThrowRuntimeExceptionFromCamelRoute() throws Exception { + thrown.expect(CustomException.class); + thrown.expectMessage("dummy exception"); + _getTitleForItem.sendInOut("10"); + } + + private class ExceptionThrowingProcesor implements Processor { + @Override + public void process(Exchange exchange) throws Exception { + throw new CustomException("dummy exception"); + } + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationMissingRefTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationMissingRefTest.java new file mode 100644 index 000000000..a3ed628f4 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationMissingRefTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.switchyard.deploy.ServiceDomainManager.ROOT_DOMAIN; + +import java.util.List; + +import org.junit.Test; +import org.switchyard.ServiceDomain; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.ActivatorLoader; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.internal.Deployment; +import org.switchyard.SwitchYardException; + +/** + * Test for {@link CamelActivator} and verifies that an exception is thrown during + * the initalization phase if a service is referenced in a Camel route but a + * sca:reference is missing from the SwitchYard component configuration. + * + * @author Daniel Bevenius + */ +public class CamelImplementationMissingRefTest { + + private static final String SWITCHYARD_CONFIG = "switchyard-activator-impl-missing-ref.xml"; + + @Test (expected = SwitchYardException.class) + public void should_throw_if_serviceReference_is_missing() throws Exception { + final SwitchYardModel model = pullSwitchYardModel(); + final Deployment deployment = new Deployment(model); + final ServiceDomain domain = new ServiceDomainManager().createDomain(ROOT_DOMAIN, deployment.getConfig()); + final List activators = ActivatorLoader.createActivators(domain); + deployment.init(domain, activators); + deployment.start(); + } + + private SwitchYardModel pullSwitchYardModel() throws Exception { + return new ModelPuller().pull(getClass().getResourceAsStream(SWITCHYARD_CONFIG)); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationNonJavaTypeTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationNonJavaTypeTest.java new file mode 100644 index 000000000..c16765c4e --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationNonJavaTypeTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/** + * Test for camel component chain with named in/out + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-impl-type.xml", mixins = CDIMixIn.class) +public class CamelImplementationNonJavaTypeTest { + + @ServiceOperation("EchoProxyService.echo") + private Invoker _proxy; + + @Test + public void sendInOutMessageThroughCamelToSwitchYardService() throws Exception { + final String output = _proxy.sendInOut("hello").getContent(String.class); + assertThat(output, is(equalTo("hello"))); + } +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationTest.java new file mode 100644 index 000000000..fe261f3ac --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelImplementationTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import javax.activation.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.TestDataSource; + +/** + * Test for {@link CamelActivator}. + * + * @author Daniel Bevenius + * + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-impl.xml", mixins = CDIMixIn.class) +public class CamelImplementationTest { + + @ServiceOperation("OrderService.getTitleForItem") + private Invoker _getTitleForItem; + + @ServiceOperation("WarehouseService.getDataForItem") + private Invoker _getDataForItem; + + @Test + public void sendOneWayMessageThroughCamelToSwitchYardService() throws Exception { + final String title = _getTitleForItem.sendInOut("10").getContent(String.class); + assertThat(title, is(equalTo("Fletch"))); + } + + @Test + public void sendOneWayMessageThroughCamelToTestAttachment() throws Exception { + DataSource ds = new TestDataSource("10", "text/plain", "Fletch-Data"); + _getDataForItem.attachment(ds.getName(), ds); + final String data = _getDataForItem.sendInOut(ds.getName()).getContent(String.class); + assertThat(data, is(equalTo("Fletch-Data"))); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelJMSTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelJMSTest.java new file mode 100644 index 000000000..82d0ca110 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelJMSTest.java @@ -0,0 +1,128 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.concurrent.LinkedBlockingQueue; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.Destination; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.naming.InitialContext; + +import org.apache.camel.CamelContext; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; + +/** + * Test using Camel's JMS Component in SwitchYard. + * + * @author Daniel Bevenius + */ +@SwitchYardTestCaseConfig(config = "switchyard-jms-test.xml", mixins = {CDIMixIn.class, HornetQMixIn.class}) +@RunWith(SwitchYardRunner.class) +public class CamelJMSTest { + + private ServiceDomain _domain; + + private SwitchYardTestKit _testKit; + + @Test + public void sendOneWayTextMessageToJMSQueue() throws Exception { + sendAndAssertOneMessage(); + } + + @Test + public void stopAndStartCamelActivator() throws Exception { + sendAndAssertOneMessage(); + stopCamelActivator(); + + Thread.sleep(2000); + + startCamelActivator(); + sendAndAssertOneMessage(); + } + + private void stopCamelActivator() throws Exception { + CamelContext context = (CamelContext) _domain.getProperty(SwitchYardCamelContext.CAMEL_CONTEXT_PROPERTY); + context.suspend(); + } + + private void startCamelActivator() throws Exception { + CamelContext context = (CamelContext) _domain.getProperty(SwitchYardCamelContext.CAMEL_CONTEXT_PROPERTY); + context.resume(); + } + + private void sendAndAssertOneMessage() throws Exception, InterruptedException { + final String payload = "dummy payload"; + // remove the currently registered service for SimpleCamelService + _testKit.removeService("SimpleCamelService"); + final MockHandler simpleCamelService = _testKit.registerInOnlyService("SimpleCamelService"); + + sendTextToQueue(payload, "testQueue"); + // Allow for the JMS Message to be processed. + Thread.sleep(3000); + + final LinkedBlockingQueue recievedMessages = simpleCamelService.getMessages(); + assertThat(recievedMessages, is(notNullValue())); + final Exchange recievedExchange = recievedMessages.iterator().next(); + assertThat(recievedExchange.getMessage().getContent(String.class), is(equalTo(payload))); + } + + private void sendTextToQueue(final String text, final String destinationName) throws Exception { + InitialContext initialContext = null; + Connection connection = null; + Session session = null; + MessageProducer producer = null; + try { + initialContext = new InitialContext(); + final ConnectionFactory connectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory"); + final Destination destination = (Destination) initialContext.lookup(destinationName); + connection = connectionFactory.createConnection(); + connection.start(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + producer = session.createProducer(destination); + producer.send(session.createTextMessage(text)); + } finally { + if (producer != null) { + producer.close(); + } + if (session != null) { + session.close(); + } + if (connection != null) { + connection.close(); + } + if (initialContext != null) { + initialContext.close(); + } + } + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelJavaDSLImplementationTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelJavaDSLImplementationTest.java new file mode 100644 index 000000000..3ea8b5f36 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelJavaDSLImplementationTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/** + * Test for Java DSL routes in Camel component + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-impl-java-dsl.xml", mixins = CDIMixIn.class) +public class CamelJavaDSLImplementationTest { + + @ServiceOperation("OrderService.getTitleForItem") + private Invoker _getTitleForItem; + + @Test + public void sendOneWayMessageThroughCamelToSwitchYardService() throws Exception { + final String title = _getTitleForItem.sendInOut("10").getContent(String.class); + assertThat(title, is(equalTo("Fletch"))); + } +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelMathTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelMathTest.java new file mode 100644 index 000000000..3c714c7ba --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelMathTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.junit.Assert.assertNotNull; + +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/** + * Test header presence populated by CamelMessageComposer in camel messages. + * + * @author Lukasz Dywicki + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-math-test.xml", mixins = CDIMixIn.class) +public class CamelMathTest { + + private final static String SERVICE_NAMESPACE = "{urn:camel-core:test:1.0}"; + + private final static String MATH_ALL_SERVICE_NS = SERVICE_NAMESPACE + "MathAll"; + private final static String MATH_COS_SERVICE_NS = SERVICE_NAMESPACE + "MathCos"; + private final static String MATH_ABS_SERVICE_NS = SERVICE_NAMESPACE + "MathAbs"; + private final static String MATH_SERVICE = "CamelMathService"; + private final static String MATH_SERVICE_NS = SERVICE_NAMESPACE + MATH_SERVICE; + + private SwitchYardCamelContext _camelContext; + + @ServiceOperation(MATH_SERVICE) + private Invoker invoker; + + @Before + public void verifyContext() { + assertNotNull(_camelContext.getServiceDomain()); + } + + @Test + public void shouldInvokeDifferentOperations() throws Exception { + MockEndpoint unknown = _camelContext.getEndpoint("mock:unknown", MockEndpoint.class); + unknown.expectedMessageCount(0); + + MockEndpoint all = _camelContext.getEndpoint("mock:all", MockEndpoint.class); + all.expectedMessageCount(2); + all.expectedBodiesReceived(100.0, 101.0); + // in this case + all.expectedPropertyReceived(Exchange.SERVICE_NAME, MATH_ALL_SERVICE_NS); + all.expectedPropertyReceived(Exchange.SERVICE_NAME, MATH_ALL_SERVICE_NS); + + MockEndpoint cos = _camelContext.getEndpoint("mock:cos", MockEndpoint.class); + cos.expectedMessageCount(1); + cos.expectedBodiesReceived(101.0); + cos.expectedPropertyReceived(Exchange.SERVICE_NAME, MATH_COS_SERVICE_NS); + + MockEndpoint abs = _camelContext.getEndpoint("mock:abs", MockEndpoint.class); + abs.expectedMessageCount(1); + abs.expectedBodiesReceived(100.0); + abs.expectedPropertyReceived(Exchange.SERVICE_NAME, MATH_ABS_SERVICE_NS); + + invoker.operation("abs").sendInOut(100.0); + invoker.operation("cos").sendInOut(101.0); + + unknown.assertIsSatisfied(); + all.assertIsSatisfied(); + abs.assertIsSatisfied(); + cos.assertIsSatisfied(); + } + + @Test + public void shouldReahUnknown() throws Exception { + MockEndpoint unknown = _camelContext.getEndpoint("mock:unknown", MockEndpoint.class); + unknown.expectedBodiesReceived(10.1); + unknown.expectedPropertyReceived(Exchange.OPERATION_NAME, "pow"); + unknown.expectedPropertyReceived(Exchange.SERVICE_NAME, MATH_SERVICE_NS); + unknown.expectedPropertyReceived(Exchange.FAULT_TYPE, "java:" + IllegalArgumentException.class.getName()); + + invoker.operation("pow").sendInOut(10.1); + + unknown.assertIsSatisfied(); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelProxyTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelProxyTest.java new file mode 100644 index 000000000..6a67bb3cc --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelProxyTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.junit.Assert.assertNotNull; + +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/** + * Test header presence populated by CamelMessageComposer in camel messages. + * + * @author Lukasz Dywicki + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-proxy-test.xml", mixins = CDIMixIn.class) +public class CamelProxyTest { + + private final static String MATH_SERVICE = "CamelMathService"; + + private SwitchYardCamelContext _camelContext; + + @ServiceOperation(MATH_SERVICE) + private Invoker invoker; + + @Before + public void verifyContext() { + assertNotNull(_camelContext.getServiceDomain()); + } + + @Test + public void shouldInvokeDifferentOperations() throws Exception { + MockEndpoint all = _camelContext.getEndpoint("mock:all", MockEndpoint.class); + + all.expectedBodiesReceived(100.0); + all.expectedPropertyReceived(Exchange.OPERATION_NAME, "pow"); + invoker.operation("pow").sendInOut(100.0); + all.assertIsSatisfied(); + + all.reset(); + + all.expectedBodiesReceived(101.0); + all.expectedPropertyReceived(Exchange.OPERATION_NAME, "cos"); + invoker.operation("cos").sendInOut(101.0); + all.assertIsSatisfied(); + + all.reset(); + + all.expectedBodiesReceived(11.0); + all.expectedPropertyReceived(Exchange.OPERATION_NAME, "pow"); + invoker.operation("pow").sendInOut(11.0); + all.assertIsSatisfied(); + } + +} \ No newline at end of file diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelReferenceTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelReferenceTest.java new file mode 100644 index 000000000..aae3461be --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/CamelReferenceTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.apache.camel.CamelContext; +import org.apache.camel.builder.RouteBuilder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/** + * Test for {@link CamelActivator} using a Camel reference binding. + * + * @author Daniel Bevenius + * + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-activator-ref.xml", mixins = CDIMixIn.class) +public class CamelReferenceTest { + + @ServiceOperation("OrderService.getTitleForItem") + private Invoker _getTitleForItem; + + private CamelContext _camelContext; + + @Test + public void invokeCamelEndpointViaInjection() throws Exception { + _camelContext.addRoutes(new RouteBuilder() { + @Override + public void configure() throws Exception { + from("vm://warehouseStatusService").inOut().setBody(constant("Fletch")); + } + }); + final String itemId = "1"; + final String title = (String) _getTitleForItem.sendInOut(itemId).getContent(); + + assertThat(title, is(equalTo("Fletch"))); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/SwitchYardExpectedException.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/SwitchYardExpectedException.java new file mode 100644 index 000000000..528ecd519 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/SwitchYardExpectedException.java @@ -0,0 +1,101 @@ +package org.switchyard.component.camel.deploy; + +import static org.junit.matchers.JUnitMatchers.containsString; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.junit.internal.matchers.TypeSafeMatcher; +import org.junit.rules.ExpectedException; +import org.junit.rules.TestRule; +import org.junit.runners.model.Statement; +import org.switchyard.HandlerException; +import org.switchyard.test.InvocationFaultException; + +public class SwitchYardExpectedException implements TestRule { + + private final ExpectedException _delegate = ExpectedException.none(); + + private SwitchYardExpectedException() { + } + + public static SwitchYardExpectedException none() { + return new SwitchYardExpectedException(); + } + + public Statement apply(Statement base, org.junit.runner.Description desc) { + return _delegate.apply(base, desc); + } + + public void expect(Class type) { + _delegate.expect(new ExceptionCauseMatcher(type)); + } + + public void expectMessage(String message) { + expectMessage(containsString(message)); + } + + /** + * Adds {@code matcher} to the list of requirements for the message + * returned from any thrown exception. + */ + public void expectMessage(Matcher matcher) { + _delegate.expect(hasMessage(matcher)); + } + + private Matcher hasMessage(final Matcher matcher) { + return new TypeSafeMatcher() { + public void describeTo(Description description) { + description.appendText("exception with message "); + description.appendDescriptionOf(matcher); + } + + @Override + public boolean matchesSafely(Throwable item) { + final Throwable throwable = getCauseFromHandlerException(item); + return matcher.matches(throwable.getMessage()); + } + }; + } + + private class ExceptionCauseMatcher extends BaseMatcher { + + private Class expectedClass; + + public ExceptionCauseMatcher(final Class expectedClass) { + this.expectedClass = expectedClass; + } + + @Override + public void describeTo(final Description description) { + description.appendText("Exception.getCause() should be [" + expectedClass.toString() + "]"); + } + + @Override + public boolean matches(final Object obj) { + if (!(obj instanceof Exception)) { + return false; + } + + final Exception e = (Exception) obj; + final Throwable thrown = getCauseFromHandlerException(e); + return expectedClass.equals(thrown.getClass()); + } + + } + + public static Throwable getCauseFromHandlerException(final Throwable thrown) { + Throwable cause = thrown; + if (thrown instanceof InvocationFaultException) { + final InvocationFaultException faultException = (InvocationFaultException) thrown; + if (faultException.getCause() instanceof HandlerException) { + HandlerException handlerEx = (HandlerException)faultException.getCause(); + cause = handlerEx.isWrapper() ? handlerEx.getCause() : handlerEx; + } else if (faultException.getFaultMessage().getContent() instanceof Exception) { + cause = faultException.getFaultMessage().getContent(Throwable.class); + } + } + return cause; + } + +} \ No newline at end of file diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/CustomException.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/CustomException.java new file mode 100644 index 000000000..8fefe2323 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/CustomException.java @@ -0,0 +1,22 @@ +package org.switchyard.component.camel.deploy.support; + +public class CustomException extends Exception { + private static final long serialVersionUID = 1L; + + public CustomException() { + super(); + } + + public CustomException(String message, Throwable cause) { + super(message, cause); + } + + public CustomException(String message) { + super(message); + } + + public CustomException(Throwable cause) { + super(cause); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/CustomPackageScanResolver.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/CustomPackageScanResolver.java new file mode 100644 index 000000000..e623b7150 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/CustomPackageScanResolver.java @@ -0,0 +1,19 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +import org.apache.camel.impl.DefaultPackageScanClassResolver; + +public class CustomPackageScanResolver extends DefaultPackageScanClassResolver { +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/EchoService.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/EchoService.java new file mode 100644 index 000000000..48faf9437 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/EchoService.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +import org.switchyard.annotations.OperationTypes; + +/** + * Simple interface intended for testing. + */ +public interface EchoService { + + @OperationTypes(in="{urn:camel-core:test:1.0}input", out="{urn:camel-core:test:1.0}output") + String echo(String string); + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/MathService.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/MathService.java new file mode 100644 index 000000000..b620edee7 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/MathService.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +/** + * Simple service with two operations. + * + * @author Lukasz Dywicki + */ +public interface MathService { + + Double abs(Double value); + Double cos(Double value); + Double pow(Double value) throws IllegalArgumentException; + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderService.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderService.java new file mode 100644 index 000000000..cb0a58593 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderService.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +/** + * Simple interface intended for testing. + * + * @author Daniel Bevenius + */ +public interface OrderService { + + String getTitleForItem(String itemId); + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceImpl.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceImpl.java new file mode 100644 index 000000000..422ffb1d5 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceImpl.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +import javax.inject.Inject; + +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; + +@Service(OrderService.class) +public class OrderServiceImpl implements OrderService { + + @Inject @Reference + WarehouseService _warehouseService; + + @Override + public String getTitleForItem(String itemId) { + return _warehouseService.hasItem(Integer.parseInt(itemId)); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceRoute.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceRoute.java new file mode 100644 index 000000000..cbb73d1cb --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceRoute.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +import org.apache.camel.builder.RouteBuilder; +import org.switchyard.component.camel.Route; + +/** + * Java DSL route equivalent to: + * + * + * + * + * + */ +@Route(OrderService.class) +public class OrderServiceRoute extends RouteBuilder { + + public void configure() { + from("switchyard://OrderService") + .log("ItemId [${body}]") + .to("switchyard://WarehouseService?operationName=hasItem") + .log("Title Name [${body}]"); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceWithFault.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceWithFault.java new file mode 100644 index 000000000..3b20495e2 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/OrderServiceWithFault.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +/** + * Simple interface intended for testing. + * + * @author Daniel Bevenius + */ +public interface OrderServiceWithFault { + + String getTitleForItem(String itemId) throws CustomException; + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/SimpleCamelService.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/SimpleCamelService.java new file mode 100644 index 000000000..6f0800c0d --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/SimpleCamelService.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +/** + * Simple interface intended for testing. + * + * @author Daniel Bevenius + */ +public interface SimpleCamelService { + + /** + * Simple print method. + * + * @param msg The message to be printed. + * @return String A return message from the service. + */ + String print(String msg); + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/SimpleCamelServiceImpl.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/SimpleCamelServiceImpl.java new file mode 100644 index 000000000..de8d94b3b --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/SimpleCamelServiceImpl.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +import org.switchyard.component.bean.Service; + +/** + * Test implementation of SimpleCamelService. + */ +@Service(SimpleCamelService.class) +public class SimpleCamelServiceImpl implements SimpleCamelService { + + @Override + public String print(String msg) { + System.out.println("SimpleCamelServiceImpl: " + msg); + return "SimpleCamelService: " + msg; + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseService.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseService.java new file mode 100644 index 000000000..c2eb6cc60 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseService.java @@ -0,0 +1,22 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.deploy.support; + +public interface WarehouseService { + + String hasItem(Integer id); + + String getDataForItem(String itemId); + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseServiceImpl.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseServiceImpl.java new file mode 100644 index 000000000..62c8d2a40 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseServiceImpl.java @@ -0,0 +1,31 @@ +package org.switchyard.component.camel.deploy.support; + +import java.io.IOException; + +import javax.inject.Inject; + +import org.switchyard.Message; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.bean.Service; + +@Service(WarehouseService.class) +public class WarehouseServiceImpl implements WarehouseService { + + @Override + public String hasItem(Integer id) { + return "Fletch"; + } + + @Inject + Message _message; + + @Override + public String getDataForItem(String itemId) { + try { + return new StringPuller().pull(_message.getAttachment(itemId).getInputStream()); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseServiceImplDotUnderscore.java b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseServiceImplDotUnderscore.java new file mode 100644 index 000000000..6f0dd3f7b --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/deploy/support/WarehouseServiceImplDotUnderscore.java @@ -0,0 +1,31 @@ +package org.switchyard.component.camel.deploy.support; + +import java.io.IOException; + +import javax.inject.Inject; + +import org.switchyard.Message; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.bean.Service; + +@Service(name="Warehouse.Service_1") +public class WarehouseServiceImplDotUnderscore implements WarehouseService { + + @Override + public String hasItem(Integer id) { + return "Fletch"; + } + + @Inject + Message _message; + + @Override + public String getDataForItem(String itemId) { + try { + return new StringPuller().pull(_message.getAttachment(itemId).getInputStream()); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationService.java b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationService.java new file mode 100644 index 000000000..a911f3472 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationService.java @@ -0,0 +1,11 @@ +package org.switchyard.component.camel.model; + +/** + * @author: Eduardo de Vera + * Date: 7/13/12 + * Time: 12:34 AM + */ +public interface RouteAnnotationService { + + public void noOp(String ignored); +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationServiceCustomNameBean.java b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationServiceCustomNameBean.java new file mode 100644 index 000000000..0823202a0 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationServiceCustomNameBean.java @@ -0,0 +1,15 @@ +package org.switchyard.component.camel.model; + +import org.switchyard.component.camel.Route; + +/** + * @author: Eduardo de Vera + * Date: 7/13/12 + * Time: 12:36 AM + */ +@Route(value = RouteAnnotationService.class, name="CustomRouteAnnotationServiceName") +public class RouteAnnotationServiceCustomNameBean implements RouteAnnotationService { + + @Override + public void noOp(String ignored) {} +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationServiceEmptyNameBean.java b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationServiceEmptyNameBean.java new file mode 100644 index 000000000..9a1139a3c --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationServiceEmptyNameBean.java @@ -0,0 +1,15 @@ +package org.switchyard.component.camel.model; + +import org.switchyard.component.camel.Route; + +/** + * @author: Eduardo de Vera + * Date: 7/13/12 + * Time: 12:35 AM + */ +@Route(value = RouteAnnotationService.class) +public class RouteAnnotationServiceEmptyNameBean implements RouteAnnotationService { + + @Override + public void noOp(String ignored) {} +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationTest.java new file mode 100644 index 000000000..f7b97b92d --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteAnnotationTest.java @@ -0,0 +1,60 @@ +package org.switchyard.component.camel.model; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.component.camel.model.RouteScanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Unit test used to prove the feature described in ticket. + * + * @author: Eduardo de Vera + */ +public class RouteAnnotationTest { + + private SwitchYardModel _scannedModel; + + @Before + public void setUp() throws IOException { + RouteScanner scanner = new RouteScanner(); + List urls = new ArrayList(); + urls.add(new File("./target/test-classes").toURI().toURL()); + ScannerInput input = new ScannerInput().setURLs(urls); + _scannedModel = scanner.scan(input).getModel(); + } + + @Test + public void testRouteAnnnotationServiceNaming() { + List components = _scannedModel.getComposite().getComponents(); + boolean customServiceNameFound = false; + boolean emptyServiceNameFound = false; + + for (ComponentModel componentModel : components) { + List services = componentModel.getServices(); + for (ComponentServiceModel serviceModel : services) { + if (serviceModel.getName().equals("CustomRouteAnnotationServiceName")) { + customServiceNameFound = true; + } + if (serviceModel.getName().equals("")) { + emptyServiceNameFound = true; + } + } + } + + assertTrue("The custom name service must be found.", customServiceNameFound); + assertFalse("The empty name service should have the name of the interface.", emptyServiceNameFound); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteScannerTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteScannerTest.java new file mode 100644 index 000000000..2e7497bd2 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/model/RouteScannerTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.component.camel.model.CamelComponentImplementationModel; +import org.switchyard.component.camel.model.RouteScanner; +import org.switchyard.component.camel.scanner.SingleRouteService; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Test scanner looking for @Route methods and generating appropriate config. + * + * NOTE: I lifted a fair bit of this code from the Bean scanner test - it would + * probably be a good idea to create a base Scanner test class so that additional + * scanner implementations can reuse the same code. + */ +public class RouteScannerTest { + + private SwitchYardModel _scannedModel; + private RouteScanner _scanner; + private List _scannedURLs; + + @Before + public void setUp() throws Exception { + _scanner = new RouteScanner(); + _scannedURLs = new ArrayList(); + _scannedURLs.add(new File("./target/test-classes").toURI().toURL()); + } + + @Test + public void componentImplementationCreated() throws Exception { + scan(new URL(new File("./target/test-classes").toURI().toURL(), "#org/switchyard/component/camel/scanner")); + List components = _scannedModel.getComposite().getComponents(); + for(ComponentModel component : components) { + System.out.println("RouteScanner found component: " + component.getName()); + // Verify component details + assertEquals(SingleRouteService.class.getSimpleName(), component.getName()); + assertTrue(component.getServices().size() == 1); + ComponentImplementationModel implementation = component.getImplementation(); + assertTrue(implementation instanceof CamelComponentImplementationModel); + checkCamelImplementation((CamelComponentImplementationModel)implementation); + } + } + + // verify an empty model is created + @Test + public void testEmptyScan() throws Exception { + scan(); + assertNull("Composite element should not be created if no components were found.", + _scannedModel.getComposite()); + } + + private void checkCamelImplementation(CamelComponentImplementationModel model) throws Exception { + // Load the class + Class routeClass = Classes.forName(model.getJavaClass(), getClass()); + // make sure the class itself is valid + assertFalse(routeClass.isInterface()); + assertFalse(Modifier.isAbstract(routeClass.getModifiers())); + + } + + // Takes a list of URLs to scan *instead* of what's defined in @Before. + private void scan(URL ... urls) throws Exception { + _scannedURLs.clear(); + if (urls != null && urls.length > 0) { + _scannedURLs.addAll(Arrays.asList(urls)); + } + ScannerInput input = new ScannerInput().setURLs(_scannedURLs); + _scannedModel = _scanner.scan(input).getModel(); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/model/v1/V1CamelComponentImplementationModelTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/model/v1/V1CamelComponentImplementationModelTest.java new file mode 100644 index 000000000..ba469a1d2 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/model/v1/V1CamelComponentImplementationModelTest.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.model.v1; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import junit.framework.Assert; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.camel.core.model.v1.V1CamelUriBindingModel; +import org.switchyard.component.camel.model.CamelComponentImplementationModel; +import org.switchyard.component.camel.model.CamelNamespace; +import org.switchyard.component.camel.scanner.SingleRouteService; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Test for {@link V1CamelUriBindingModel}. + * + * @author Daniel Bevenius + */ +public class V1CamelComponentImplementationModelTest { + + private static boolean oldIgnoreWhitespace; + + private static final String XML_ROUTE_PATH = "org/switchyard/component/camel/model/v1/SingleRouteService.xml"; + + @BeforeClass + public static void setup() { + oldIgnoreWhitespace = XMLUnit.getIgnoreWhitespace(); + XMLUnit.setIgnoreWhitespace(true); + } + + @AfterClass + public static void cleanup() { + XMLUnit.setIgnoreWhitespace(oldIgnoreWhitespace); + } + + @Test + public void programmaticConfig() { + assertThat(createModel().getJavaClass(), is(equalTo(SingleRouteService.class.getName()))); + } + + @Test + public void validateModelWithJavaElement() throws Exception { + final V1CamelImplementationModel implModel = getCamelImplementation("switchyard-implementation-java.xml"); + + validateModel(implModel); + assertThat(SingleRouteService.class.getName(), is(equalTo(implModel.getJavaClass()))); + } + + @Test + public void validateModelWithXMLElement() throws Exception { + final V1CamelImplementationModel implModel = getCamelImplementation("switchyard-implementation-xml.xml"); + + validateModel(implModel); + assertThat(XML_ROUTE_PATH, is(equalTo(implModel.getXMLPath()))); + } + + @Test + public void addXMLPath() throws Exception { + V1CamelImplementationModel camelConfig = new V1CamelImplementationModel(CamelNamespace.V_1_0.uri()); + camelConfig.setXMLPath(XML_ROUTE_PATH); + validateModel(camelConfig); + Assert.assertEquals(XML_ROUTE_PATH, camelConfig.getXMLPath()); + } + + @Test + public void writeConfig() throws Exception { + final String control = getCamelImplementation("switchyard-implementation-java.xml").toString(); + final String test = createModel().toString(); + XMLAssert.assertXMLEqual(control, test); + } + + private V1CamelImplementationModel createModel() { + return new V1CamelImplementationModel(CamelNamespace.V_1_0.uri()).setJavaClass(SingleRouteService.class.getName()); + } + + private void validateModel(final CamelComponentImplementationModel model) { + assertThat(model.validateModel().isValid(), is(true)); + } + + private V1CamelImplementationModel getCamelImplementation(final String config) throws Exception { + V1CamelImplementationModel implementation = null; + final SwitchYardModel model = new ModelPuller().pull(config, getClass()); + for (ComponentModel componentModel : model.getComposite().getComponents()) { + if (CamelComponentImplementationModel.CAMEL.equals(componentModel.getImplementation().getType())) { + implementation = (V1CamelImplementationModel) componentModel.getImplementation(); + break; + } + } + return implementation; + } +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/scanner/ServiceInterface.java b/components/camel/component/src/test/java/org/switchyard/component/camel/scanner/ServiceInterface.java new file mode 100644 index 000000000..5a247fdc9 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/scanner/ServiceInterface.java @@ -0,0 +1,19 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.scanner; + +public interface ServiceInterface { + + String doStuff(Object input); +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/scanner/SingleRouteService.java b/components/camel/component/src/test/java/org/switchyard/component/camel/scanner/SingleRouteService.java new file mode 100644 index 000000000..c8164ee6e --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/scanner/SingleRouteService.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.scanner; + +import org.apache.camel.builder.RouteBuilder; +import org.switchyard.component.camel.Route; + +/** + * Defines a Camel route using Java DSL and the @Route annotation in SwitchYard. + */ +@Route(ServiceInterface.class) +public class SingleRouteService extends RouteBuilder { + + public void configure() { + from("direct://in") + .log("Inside of @Route service") + .to("mock:SingleRouteService"); + } +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/transformer/CamelTransformerTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/transformer/CamelTransformerTest.java new file mode 100644 index 000000000..f7d411786 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/transformer/CamelTransformerTest.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.transformer; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.io.File; + +import javax.xml.namespace.QName; + +import org.apache.camel.component.file.GenericFile; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.switchyard.metadata.JavaTypes; + +/** + * Unit test for {@link CamelTransformer}. + * + * @author Daniel Bevenius + * + */ +public class CamelTransformerTest { + + @Rule + public TemporaryFolder tmpFolder = new TemporaryFolder(); + + @Test + public void genericFileToString() throws Exception { + final QName genericFileType = new QName("java:org.apache.camel.component.file.GenericFile"); + final QName stringType = JavaTypes.toMessageType(String.class); + + final CamelTransformer camelTransformer = new CamelTransformer(); + camelTransformer.setFrom(genericFileType); + camelTransformer.setTo(stringType); + + final GenericFile genericFile = new GenericFile(); + genericFile.setBody("dummy file content"); + + final Object transform = camelTransformer.transform(genericFile); + assertThat(transform, is(instanceOf(String.class))); + } + +} diff --git a/components/camel/component/src/test/java/org/switchyard/component/camel/transformer/CamelTypeConverterExtractorTest.java b/components/camel/component/src/test/java/org/switchyard/component/camel/transformer/CamelTypeConverterExtractorTest.java new file mode 100644 index 000000000..373043b15 --- /dev/null +++ b/components/camel/component/src/test/java/org/switchyard/component/camel/transformer/CamelTypeConverterExtractorTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.transformer; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasItems; + +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.internal.TransformerRegistryLoader; + +/** + * Test for {@link CamelTypeConverterExtractor} + * + * @author Daniel Bevenius + * + */ +public class CamelTypeConverterExtractorTest +{ + private static CamelTypeConverterExtractor _extractor; + private static BaseTransformerRegistry _transformerRegistry; + + @BeforeClass + public static void init() throws Exception { + final DefaultCamelContext camelContext = new DefaultCamelContext(); + _extractor = new CamelTypeConverterExtractor(camelContext); + _extractor.init(); + + _transformerRegistry = new BaseTransformerRegistry(); + new TransformerRegistryLoader(_transformerRegistry).loadOOTBTransforms(); + } + + @Test + public void extractTypeConverterTypes() throws Exception { + final Map> transformTypes = _extractor.getTransformTypes(); + final Set toTypes = transformTypes.get(JavaTypes.toMessageType(String.class)); + + assertThat(toTypes, hasItems( + new QName("java:java.io.InputStream"), + new QName("java:java.io.StringReader"), + new QName("java:java.io.File"), + new QName("java:java.nio.ByteBuffer"), + new QName("java:long"), + new QName("java:char"), + new QName("java:byte[]"), + new QName("java:char[]"), + new QName("java:javax.xml.transform.Source"), + new QName("java:javax.xml.transform.dom.DOMSource"), + new QName("java:javax.xml.transform.sax.SAXSource"), + new QName("java:org.w3c.dom.Document"), + new QName("java:org.apache.camel.StringSource"))); + } + + @Test + public void generateTransformsModel() { + final TransformsModel v1TransformsModel = _extractor.getTransformsModel(); + + assertThat(v1TransformsModel, is(not(nullValue()))); + assertThat(v1TransformsModel.getTransforms().size(), is(greaterThan(161))); + } + + @Ignore ("This method can be enabled to manually genereate a transforms.xml file in the output directory") + public void generateTransformsModelFile() throws FileNotFoundException, IOException { + FileOutputStream fileOut = null; + try { + fileOut = new FileOutputStream("target/classes/new-transforms.xml"); + final TransformsModel transformsModel = _extractor.getTransformsModel(_transformerRegistry); + transformsModel.write(fileOut); + } finally { + if (fileOut != null) { + fileOut.close(); + } + } + } + + +} diff --git a/components/camel/component/src/test/resources/META-INF/beans.xml b/components/camel/component/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/camel/component/src/test/resources/META-INF/services/org.apache.camel.spi.PackageScanClassResolver b/components/camel/component/src/test/resources/META-INF/services/org.apache.camel.spi.PackageScanClassResolver new file mode 100644 index 000000000..ec2d54456 --- /dev/null +++ b/components/camel/component/src/test/resources/META-INF/services/org.apache.camel.spi.PackageScanClassResolver @@ -0,0 +1 @@ +org.switchyard.component.camel.deploy.support.CustomPackageScanResolver \ No newline at end of file diff --git a/components/camel/component/src/test/resources/hornetq-configuration.xml b/components/camel/component/src/test/resources/hornetq-configuration.xml new file mode 100644 index 000000000..7f71c4964 --- /dev/null +++ b/components/camel/component/src/test/resources/hornetq-configuration.xml @@ -0,0 +1,32 @@ + + + target/data/paging + target/data/bindings + false + target/data/journal + 10 + target/data/large-messages + false + + + + org.hornetq.core.remoting.impl.invm.InVMConnectorFactory + + + org.hornetq.core.remoting.impl.netty.NettyConnectorFactory + + + + + + + org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory + + + org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory + + + + + + \ No newline at end of file diff --git a/components/camel/component/src/test/resources/hornetq-jms.xml b/components/camel/component/src/test/resources/hornetq-jms.xml new file mode 100644 index 000000000..5598b5b1d --- /dev/null +++ b/components/camel/component/src/test/resources/hornetq-jms.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + true + + + + false + + + diff --git a/components/camel/component/src/test/resources/log4j.properties b/components/camel/component/src/test/resources/log4j.properties new file mode 100644 index 000000000..dd3bcd83d --- /dev/null +++ b/components/camel/component/src/test/resources/log4j.properties @@ -0,0 +1,22 @@ +# The logging properties used during tests.. +# +log4j.rootLogger=INFO, stdout, stdout + +log4j.logger.org.apache.camel=DEBUG +log4j.logger.org.milyn=DEBUG + + +#log4j.logger.org.apache.camel.impl.converter=DEBUG + + +# 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.file=org.apache.log4j.FileAppender +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n +log4j.appender.file.file=target/camel-smooks-test.log +log4j.appender.file.append=true diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/convert2string-route-1.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/convert2string-route-1.xml new file mode 100644 index 000000000..006173b49 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/convert2string-route-1.xml @@ -0,0 +1,26 @@ + + + + + + + + /input:input[text()='hello'] + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/convert2string-route-2.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/convert2string-route-2.xml new file mode 100644 index 000000000..2a78453e0 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/convert2string-route-2.xml @@ -0,0 +1,26 @@ + + + + + + + + /input:input[text()='hello'] + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/error-route.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/error-route.xml new file mode 100644 index 000000000..3d43bee41 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/error-route.xml @@ -0,0 +1,22 @@ + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/impl-dot-underscore-route.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/impl-dot-underscore-route.xml new file mode 100644 index 000000000..faf9cf59d --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/impl-dot-underscore-route.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/impl-route.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/impl-route.xml new file mode 100644 index 000000000..cd3a0d0d8 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/impl-route.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/math-proxy-route.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/math-proxy-route.xml new file mode 100644 index 000000000..cf638f620 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/math-proxy-route.xml @@ -0,0 +1,20 @@ + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/math-route.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/math-route.xml new file mode 100644 index 000000000..55100890d --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/math-route.xml @@ -0,0 +1,51 @@ + + + + + + + + + ${property.org.switchyard.operationName} == 'cos' + + + + ${property.org.switchyard.operationName} == 'abs' + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/missing-ref-route.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/missing-ref-route.xml new file mode 100644 index 000000000..3438a92b2 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/missing-ref-route.xml @@ -0,0 +1,21 @@ + + + + + + + + + \ No newline at end of file diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/not-a-route.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/not-a-route.xml new file mode 100644 index 000000000..c1a039f01 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/not-a-route.xml @@ -0,0 +1,15 @@ + + +test diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/route.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/route.xml new file mode 100644 index 000000000..d803aa9cf --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/route.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/routes.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/routes.xml new file mode 100644 index 000000000..2798287cc --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/routes.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-declared-fault.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-declared-fault.xml new file mode 100644 index 000000000..64dfea899 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-declared-fault.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-dot-underscore.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-dot-underscore.xml new file mode 100644 index 000000000..840b869b3 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-dot-underscore.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-error.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-error.xml new file mode 100644 index 000000000..530bb0f24 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-error.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-java-dsl.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-java-dsl.xml new file mode 100644 index 000000000..c189b138a --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-java-dsl.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-missing-ref.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-missing-ref.xml new file mode 100644 index 000000000..d57de3041 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-missing-ref.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-type.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-type.xml new file mode 100644 index 000000000..911ed69ed --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl-type.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl.xml new file mode 100644 index 000000000..b970e449a --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-impl.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-math-test.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-math-test.xml new file mode 100644 index 000000000..fdbcdb084 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-math-test.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + all + + + + + + abs + + + + + + cos + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-proxy-test.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-proxy-test.xml new file mode 100644 index 000000000..19ce5f778 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-proxy-test.xml @@ -0,0 +1,50 @@ + + + + + + + + + input + + + + + + + + + + + + + + + + + + + + + all + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-ref.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-ref.xml new file mode 100644 index 000000000..103805647 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-ref.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-test.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-test.xml new file mode 100644 index 000000000..448b4589f --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-activator-test.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-jms-test.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-jms-test.xml new file mode 100644 index 000000000..d84bb0795 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/deploy/switchyard-jms-test.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/SingleRouteService.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/SingleRouteService.xml new file mode 100644 index 000000000..7ab1b414a --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/SingleRouteService.xml @@ -0,0 +1,30 @@ + + + + + + + $foo = 'bar' + + + + $foo = 'cheese' + + + + + + + \ No newline at end of file diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/switchyard-implementation-java.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/switchyard-implementation-java.xml new file mode 100644 index 000000000..7aea31bb8 --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/switchyard-implementation-java.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/switchyard-implementation-xml.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/switchyard-implementation-xml.xml new file mode 100644 index 000000000..44305595b --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/model/v1/switchyard-implementation-xml.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + diff --git a/components/camel/component/src/test/resources/org/switchyard/component/camel/switchyard-exception-test.xml b/components/camel/component/src/test/resources/org/switchyard/component/camel/switchyard-exception-test.xml new file mode 100644 index 000000000..0292a3cfe --- /dev/null +++ b/components/camel/component/src/test/resources/org/switchyard/component/camel/switchyard-exception-test.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/camel/pom.xml b/components/camel/pom.xml new file mode 100644 index 000000000..090cc26cb --- /dev/null +++ b/components/camel/pom.xml @@ -0,0 +1,60 @@ + + + + 4.0.0 + switchyard-component-camel-parent + pom + SwitchYard: Component Camel Parent + The parent for SwitchYard component camel modules + http://switchyard.org + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + + + component + camel-switchyard + camel-amqp + camel-atom + camel-core + camel-cxf + camel-file + camel-ftp + camel-jms + camel-jpa + camel-mail + camel-mqtt + camel-netty + camel-quartz + camel-rss + camel-sap + camel-sql + camel-test + + + + + junit + junit + test + + + org.slf4j + slf4j-log4j12 + test + + + diff --git a/components/clojure/Readme.md b/components/clojure/Readme.md new file mode 100644 index 000000000..79558997c --- /dev/null +++ b/components/clojure/Readme.md @@ -0,0 +1,72 @@ +# Switchyard Clojure Component +This project provides an implementation.clojure enabling the usage of the Clojure language in a SwitchYard service implementation. + +_ _ _ + +## Using Clojure script "inlined" in SwitchYard + + + + + + + + + + + + + + + + + + +The Clojure function is passed the SwitchYard Exchange and is required to import that class. It then as access to the complete content of the Exchange to operate on. + +Calling this service is done in the same way as calling any other SwitchYard service, for example: + + String title = (String) newInvoker("OrderService").operation("getTitleForItem").sendInOut(10).getContent(String.class); + +_ _ _ + +## Using external Clojure script + + + + + + + + + + + + + + + + +The Clojure script can be located on the classpath or in an external file. + +_ _ _ + +## Message content/Exchange injection +The Clojure function can be injected with the content on the SwitchYard Message object or with the complete Exchange. By default, the Message content is injected but you can specify the attribute +_injectExchange_ to inject the complete Exchange. For example: + + + +_ _ _ diff --git a/components/clojure/pom.xml b/components/clojure/pom.xml new file mode 100644 index 000000000..9b8684735 --- /dev/null +++ b/components/clojure/pom.xml @@ -0,0 +1,94 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-clojure + bundle + SwitchYard: Clojure Component + http://switchyard.org + + + org.switchyard.component.clojure.* + + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + src/test/resources + + **/*.xml + **/*.clj + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.clojure + clojure + + + org.switchyard.components + switchyard-component-bean + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.mockito + mockito-all + test + + + diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureComponentImplementationModel.java b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureComponentImplementationModel.java new file mode 100644 index 000000000..2799ef669 --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureComponentImplementationModel.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.config.model; + +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * A definition of an 'implementation.clojure' element. + * + * @author Daniel Bevenius + * + */ +public interface ClojureComponentImplementationModel extends ComponentImplementationModel { + + /** + * The 'clojure' implementation type. + */ + String CLOJURE = "clojure"; + + /** + * The 'script' element name. + */ + String SCRIPT = "script"; + + /** + * The 'scriptFile' attribute name. + */ + String SCRIPT_FILE = "scriptFile"; + + /** + * The 'injectMessageOnly' attribute name. + */ + String INJECT_EXCHANGE = "injectExchange"; + + /** + * Gets the clojure script that is the actual Clojure code. + * @return {@link ClojureScriptModel} the clojure script configuration model. + */ + ClojureScriptModel getScriptModel(); + + /** + * Sets the clojure script model. + * @param scriptModel The script configuration model. + * @return {@link ClojureComponentImplementationModel} to enable method chaining. + */ + ClojureComponentImplementationModel setScriptModel(final ClojureScriptModel scriptModel); + + /** + * Gets the clojure script that is the actual Clojure code. + * @return String the clojure script to execute. + */ + String getScriptFile(); + + /** + * Sets the scriptFile. + * + * @param scriptFile The script file. + * @return {@link ClojureComponentImplementationModel} to enable method chaining. + */ + ClojureComponentImplementationModel setScriptFile(final String scriptFile); + + /** + * Determines whether the complete Exchange should be injected into the Clojure script. + * + * @return true If the Exchange should be injected. + */ + Boolean injectExchange(); + + /** + * Sets the 'injectExchange' property whether the complete Exchange should be injected into the Clojure script. + * + * @param enable The value to 'injectExchange to. + * @return {@link ClojureComponentImplementationModel} to enable method chaining. + */ + ClojureComponentImplementationModel setInjectExchange(final Boolean enable); + + +} diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureNamespace.java b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureNamespace.java new file mode 100644 index 000000000..eea4b4e0d --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.config.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Clojure config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum ClojureNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new ClojureNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + ClojureNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the ClojureNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the ClojureNamespace + */ + public static ClojureNamespace fromUri(String uri) { + return Util.fromUri(ClojureNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(ClojureNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-clojure:config", version); + } + } + +} diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureScriptModel.java b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureScriptModel.java new file mode 100644 index 000000000..0167128b9 --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/ClojureScriptModel.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.config.model; + +import org.switchyard.config.model.NamedModel; + +/** + * Configuration model for a 'script' element containing an 'inline' clojure script. + * + * @author Daniel Bevenius + * + */ +public interface ClojureScriptModel extends NamedModel { + + /** + * The script element name. + */ + String SCRIPT = "script"; + + /** + * Gets the script content from the 'script' element. + * + * @return String The clojure script. + */ + public abstract String getScript(); + + /** + * Sets the Clojure script. + * + * @param script The Clojure script to set. + * @return {@link V1ClojureScriptModel} this object ref to support method chaining. + */ + public abstract ClojureScriptModel setScript(final String script); + +} diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureComponentImplementationModel.java b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureComponentImplementationModel.java new file mode 100644 index 000000000..001289a3b --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureComponentImplementationModel.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.config.model.v1; + +import org.switchyard.component.clojure.config.model.ClojureComponentImplementationModel; +import org.switchyard.component.clojure.config.model.ClojureScriptModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1ComponentImplementationModel; + +/** + * Version 1 implementation of a {@link ClojureComponentImplementationModel}. + * + * @author Daniel Bevenius + * + */ +public class V1ClojureComponentImplementationModel extends V1ComponentImplementationModel implements ClojureComponentImplementationModel { + + private Boolean _injectExchange; + private String _scriptFile; + private ClojureScriptModel _scriptModel; + + /** + * Constructor. + * @param namespace namespace + */ + public V1ClojureComponentImplementationModel(String namespace) { + super(CLOJURE, namespace); + } + + /** + * Constructor. + * + * @param config The configuration model. + * @param desc The descriptor for the model. + */ + public V1ClojureComponentImplementationModel(final Configuration config, final Descriptor desc) { + super(config, desc); + } + + @Override + public ClojureScriptModel getScriptModel() { + if (_scriptModel != null) { + return _scriptModel; + } + + _scriptModel = (ClojureScriptModel) getFirstChildModel(SCRIPT); + return _scriptModel; + } + + @Override + public V1ClojureComponentImplementationModel setScriptModel(final ClojureScriptModel scriptModel) { + setChildModel(scriptModel); + _scriptModel = scriptModel; + return this; + } + + @Override + public String getScriptFile() { + if (_scriptFile != null) { + return _scriptFile; + } + + _scriptFile = getModelAttribute(SCRIPT_FILE); + return _scriptFile; + } + + @Override + public V1ClojureComponentImplementationModel setScriptFile(final String scriptFile) { + setModelAttribute(SCRIPT_FILE, scriptFile); + _scriptFile = scriptFile; + return this; + } + + @Override + public Boolean injectExchange() { + if (_injectExchange != null) { + return _injectExchange; + } + + _injectExchange = Boolean.valueOf(getModelAttribute(INJECT_EXCHANGE)); + return _injectExchange; + } + + @Override + public ClojureComponentImplementationModel setInjectExchange(final Boolean enable) + { + setModelAttribute(INJECT_EXCHANGE, enable.toString()); + _injectExchange = enable; + return this; + } +} diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureModelMarshaller.java b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureModelMarshaller.java new file mode 100644 index 000000000..2f5a6b05d --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureModelMarshaller.java @@ -0,0 +1,41 @@ +package org.switchyard.component.clojure.config.model.v1; + +import org.switchyard.component.clojure.config.model.ClojureComponentImplementationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * Version 1 marshaller for a Clojure model. + * + * @author Daniel Bevenius + * + */ +public class V1ClojureModelMarshaller extends BaseMarshaller { + + /** + * Sole constructor. + * + * @param desc The descriptor for this model. + */ + public V1ClojureModelMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(final Configuration config) { + final String name = config.getName(); + if (name.startsWith(ComponentImplementationModel.IMPLEMENTATION)) { + return new V1ClojureComponentImplementationModel(config, getDescriptor()); + } + + if (name.startsWith(ClojureComponentImplementationModel.SCRIPT)) { + return new V1ClojureScriptModel(config, getDescriptor()); + } + + return null; + } + +} diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureScriptModel.java b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureScriptModel.java new file mode 100644 index 000000000..6e13c121a --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/config/model/v1/V1ClojureScriptModel.java @@ -0,0 +1,59 @@ +package org.switchyard.component.clojure.config.model.v1; + +import org.switchyard.component.clojure.config.model.ClojureScriptModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 implementation of a ScriptModel. + * + * @author Daniel Bevenius + * + */ +public class V1ClojureScriptModel extends BaseNamedModel implements ClojureScriptModel { + + private String _script; + + /** + * Constructor. + * @param namespace namespace + */ + public V1ClojureScriptModel(String namespace) { + super(namespace, SCRIPT); + } + + /** + * Constructor. + * + * @param config The configuration model. + * @param desc The descriptor for this model. + */ + public V1ClojureScriptModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /* (non-Javadoc) + * @see org.switchyard.component.clojure.config.model.v1.ClojureScriptModel#getScript() + */ + @Override + public String getScript() { + if (_script != null) { + return _script; + } + + _script = getModelValue(); + return _script; + } + + /* (non-Javadoc) + * @see org.switchyard.component.clojure.config.model.v1.ClojureScriptModel#setScript(java.lang.String) + */ + @Override + public ClojureScriptModel setScript(final String script) { + setModelValue(script); + _script = script; + return this; + } + +} diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureActivator.java b/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureActivator.java new file mode 100644 index 000000000..3e91e095e --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureActivator.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.component.clojure.config.model.ClojureComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; + +/** + * Activator for implemenations.clojure. + * + * @author Daniel Bevenius + * + */ +public class ClojureActivator extends BaseActivator { + + static final String[] TYPES = new String[] {"clojure"}; + + /** + * Sole constructor . + */ + public ClojureActivator() { + super(TYPES); + } + + @Override + public ServiceHandler activateService(QName name, ComponentModel config) { + return new ClojureHandler((ClojureComponentImplementationModel)config.getImplementation()); + } + + @Override + public void deactivateService(QName name, ServiceHandler handler) { + // Nothing to do here + } +} diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureComponent.java b/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureComponent.java new file mode 100644 index 000000000..2835ab84d --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureComponent.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.deploy; + +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * An implementation of Clojure component. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class ClojureComponent extends BaseComponent { + + /** + * Default constructor. + */ + public ClojureComponent() { + super(ClojureActivator.TYPES); + setName("ClojureComponent"); + } + + /* (non-Javadoc) + * @see org.switchyard.deploy.Component#createActivator(org.switchyard.ServiceDomain) + */ + @Override + public Activator createActivator(ServiceDomain domain) { + ClojureActivator activator = new ClojureActivator(); + activator.setServiceDomain(domain); + return activator; + } + +} diff --git a/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureHandler.java b/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureHandler.java new file mode 100644 index 000000000..5db8abd3e --- /dev/null +++ b/components/clojure/src/main/java/org/switchyard/component/clojure/deploy/ClojureHandler.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.deploy; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.common.type.Classes; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.component.clojure.config.model.ClojureComponentImplementationModel; +import org.switchyard.component.clojure.config.model.ClojureScriptModel; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.SwitchYardException; + +import clojure.lang.Var; + +/** + * An ExchangeHandle that can load and invoke a Clojure script. + * + * @author Daniel Bevenius + * + */ +public class ClojureHandler extends BaseServiceHandler { + + private final ClojureComponentImplementationModel _implModel; + private Var _var; + + /** + * Sole constructor. + * + * @param implModel The configuration model. + */ + public ClojureHandler(final ClojureComponentImplementationModel implModel) { + _implModel = implModel; + } + + /** + * Loads the Clojure script. + */ + @Override + protected void doStart() { + try { + final ClojureScriptModel scriptModel = _implModel.getScriptModel(); + _var = scriptModel != null + ? (Var) clojure.lang.Compiler.load(new StringReader(scriptModel.getScript())) + : (Var) clojure.lang.Compiler.load(loadInputStream(_implModel.getScriptFile())); + } catch (final Exception e) { + throw new SwitchYardException(e); + } + } + + @Override + public void stop() { + // Nothing to do here + // leave state alone + } + + private InputStreamReader loadInputStream(final String scriptFile) throws IOException { + final InputStream in = Classes.getResourceAsStream(scriptFile); + if (in != null) { + return new InputStreamReader(in); + } else { + return new InputStreamReader(new FileInputStream(scriptFile)); + } + } + + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + try { + Object response =_implModel.injectExchange() + ? _var.invoke(exchange) + : _var.invoke(exchange.getMessage().getContent()); + if (response != null) { + Message message = exchange.createMessage().setContent(response); + exchange.send(message); + } + + } catch (final Exception e) { + QName declaredFault = exchange.getContract().getProviderOperation().getFaultType(); + if (declaredFault != null && QNameUtil.isJavaMessageType(declaredFault) + && QNameUtil.toJavaMessageType(declaredFault).isAssignableFrom(e.getClass())) { + Message msg = exchange.createMessage().setContent(e); + exchange.sendFault(msg); + } else { + throw new HandlerException(e); + } + } + } + + @Override + public void handleFault(final Exchange exchange) { + } + +} diff --git a/components/clojure/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/clojure/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..5abc734b7 --- /dev/null +++ b/components/clojure/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.clojure.deploy.ClojureComponent diff --git a/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v1/clojure_1_0.xsd b/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v1/clojure_1_0.xsd new file mode 100644 index 000000000..5430c181a --- /dev/null +++ b/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v1/clojure_1_0.xsd @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v1/clojure_1_1.xsd b/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v1/clojure_1_1.xsd new file mode 100644 index 000000000..0b4f1f807 --- /dev/null +++ b/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v1/clojure_1_1.xsd @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v2/clojure_2_0.xsd b/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v2/clojure_2_0.xsd new file mode 100644 index 000000000..acba951dd --- /dev/null +++ b/components/clojure/src/main/resources/org/switchyard/component/clojure/config/model/v2/clojure_2_0.xsd @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/clojure/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/clojure/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..bb4645975 --- /dev/null +++ b/components/clojure/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +clojure_1_0.section=urn:switchyard-component-clojure:config +clojure_1_0.version=1.0 +clojure_1_0.namespace=urn:switchyard-component-clojure:config:1.0 +clojure_1_0.schema=clojure_1_0.xsd +clojure_1_0.location=/org/switchyard/component/clojure/config/model/v1/ +clojure_1_0.marshaller=org.switchyard.component.clojure.config.model.v1.V1ClojureModelMarshaller + +clojure_1_1.section=urn:switchyard-component-clojure:config +clojure_1_1.version=1.1 +clojure_1_1.namespace=urn:switchyard-component-clojure:config:1.1 +clojure_1_1.schema=clojure_1_1.xsd +clojure_1_1.location=/org/switchyard/component/clojure/config/model/v1/ +clojure_1_1.marshaller=org.switchyard.component.clojure.config.model.v1.V1ClojureModelMarshaller + +clojure_2_0.section=urn:switchyard-component-clojure:config +clojure_2_0.version=2.0 +clojure_2_0.namespace=urn:switchyard-component-clojure:config:2.0 +clojure_2_0.schema=clojure_2_0.xsd +clojure_2_0.location=/org/switchyard/component/clojure/config/model/v2/ +clojure_2_0.marshaller=org.switchyard.component.clojure.config.model.v1.V1ClojureModelMarshaller diff --git a/components/clojure/src/test/java/org/switchyard/component/clojure/config/model/v1/V1ClojureComponentImplementationModelTest.java b/components/clojure/src/test/java/org/switchyard/component/clojure/config/model/v1/V1ClojureComponentImplementationModelTest.java new file mode 100644 index 000000000..e8757e63b --- /dev/null +++ b/components/clojure/src/test/java/org/switchyard/component/clojure/config/model/v1/V1ClojureComponentImplementationModelTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.config.model.v1; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.component.clojure.config.model.ClojureNamespace; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.Validation; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Unit test for {@link V1ClojureComponentImplementationModel}. + * + * @author Daniel Bevenius + * + */ +public class V1ClojureComponentImplementationModelTest { + + @Test + public void inlineScript() throws Exception { + final V1ClojureComponentImplementationModel implModel = getImplModel("switchyard-clojure-impl.xml"); + final Validation validateModel = implModel.validateModel(); + + assertThat(validateModel.isValid(), is(true)); + final String script = implModel.getScriptModel().getScript(); + assertThat(script, is(equalTo("(ns printer)(defn print-string [arg] (println arg))"))); + } + + @Test + public void externalFileScript() throws Exception { + final V1ClojureComponentImplementationModel implModel = getImplModel("switchyard-clojure-impl-file.xml"); + final Validation validateModel = implModel.validateModel(); + + assertThat(validateModel.isValid(), is(true)); + assertThat(implModel.injectExchange(), is(true)); + assertThat(implModel.getScriptFile(), is(equalTo("sample.clj"))); + assertThat(Classes.getResourceAsStream(implModel.getScriptFile(), getClass()), is(notNullValue())); + } + + @Test + public void programmaticCreationWithInlineScript() { + final V1ClojureComponentImplementationModel implModel = new V1ClojureComponentImplementationModel(ClojureNamespace.DEFAULT.uri()); + implModel.setInjectExchange(true); + final V1ClojureScriptModel scriptModel = new V1ClojureScriptModel(ClojureNamespace.DEFAULT.uri()); + scriptModel.setScript("bogus script"); + implModel.setScriptModel(scriptModel); + + assertThat(implModel.getScriptModel().getScript(), is(equalTo("bogus script"))); + assertThat(implModel.injectExchange(), is(true)); + } + + @Test + public void programmaticCreationWithScriptFile() { + final V1ClojureComponentImplementationModel implModel = new V1ClojureComponentImplementationModel(ClojureNamespace.DEFAULT.uri()); + implModel.setScriptFile("bogusScript.clj"); + + assertThat(implModel.getScriptFile(), is(equalTo("bogusScript.clj"))); + assertThat(implModel.injectExchange(), is(false)); + } + + private V1ClojureComponentImplementationModel getImplModel(final String config) throws Exception { + final SwitchYardModel model = new ModelPuller().pull(config, getClass()); + final ComponentModel componentModel = model.getComposite().getComponents().get(0); + final ComponentImplementationModel implementation = componentModel.getImplementation(); + return (V1ClojureComponentImplementationModel) implementation; + } + +} diff --git a/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/ClojureActivatorTest.java b/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/ClojureActivatorTest.java new file mode 100644 index 000000000..6a99563fa --- /dev/null +++ b/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/ClojureActivatorTest.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/** + * Functional test for ClojureActivator. + * + * @author Daniel Bevenius + * + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-clojure.xml", mixins = CDIMixIn.class) +public class ClojureActivatorTest { + + @ServiceOperation("OrderService.getTitleForItem") + private Invoker _getTitleForItem; + + @Test + public void activtor() { + final String title = _getTitleForItem.sendInOut(10).getContent(String.class); + assertThat(title, is(equalTo("Fletch"))); + } + + +} diff --git a/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/ClojureScriptFileTest.java b/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/ClojureScriptFileTest.java new file mode 100644 index 000000000..935a40e07 --- /dev/null +++ b/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/ClojureScriptFileTest.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.deploy; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/** + * Functional test for ClojureActivator. + * + * @author Daniel Bevenius + * + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-clojure-scriptFile.xml", mixins = CDIMixIn.class) +public class ClojureScriptFileTest { + + @ServiceOperation("OrderService.getTitleForItem") + private Invoker _getTitleForItem; + + @Test + public void executeClojureScriptFromFileOnClasspath() { + final String title = _getTitleForItem.sendInOut(10).getContent(String.class); + assertThat(title, is(equalTo("Fletch"))); + } + + +} diff --git a/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/support/OrderService.java b/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/support/OrderService.java new file mode 100644 index 000000000..761152c0a --- /dev/null +++ b/components/clojure/src/test/java/org/switchyard/component/clojure/deploy/support/OrderService.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.clojure.deploy.support; + +/** + * Simple interface intended for testing. + * + * @author Daniel Bevenius + * + */ +public interface OrderService { + + public String getTitleForItem(String itemId); + +} diff --git a/components/clojure/src/test/resources/META-INF/beans.xml b/components/clojure/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/sample.clj b/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/sample.clj new file mode 100644 index 000000000..249f77b74 --- /dev/null +++ b/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/sample.clj @@ -0,0 +1,3 @@ +(ns org.switchyard (:import org.switchyard.Exchange)) +(defn process [ex] (.setContent (.getMessage ex) "Fletch") + (.getContent (.getMessage ex))) \ No newline at end of file diff --git a/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/switchyard-clojure-impl-file.xml b/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/switchyard-clojure-impl-file.xml new file mode 100644 index 000000000..907e19f40 --- /dev/null +++ b/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/switchyard-clojure-impl-file.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + diff --git a/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/switchyard-clojure-impl.xml b/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/switchyard-clojure-impl.xml new file mode 100644 index 000000000..c4a5aabe1 --- /dev/null +++ b/components/clojure/src/test/resources/org/switchyard/component/clojure/config/model/v1/switchyard-clojure-impl.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + diff --git a/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/sample.clj b/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/sample.clj new file mode 100644 index 000000000..382c27e60 --- /dev/null +++ b/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/sample.clj @@ -0,0 +1,3 @@ +(ns org.switchyard.component.clojure.deploy.sample) + (defn process [content] "Fletch") + diff --git a/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/switchyard-clojure-scriptFile.xml b/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/switchyard-clojure-scriptFile.xml new file mode 100644 index 000000000..3a54924bc --- /dev/null +++ b/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/switchyard-clojure-scriptFile.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + diff --git a/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/switchyard-clojure.xml b/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/switchyard-clojure.xml new file mode 100644 index 000000000..f513defce --- /dev/null +++ b/components/clojure/src/test/resources/org/switchyard/component/clojure/deploy/switchyard-clojure.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + diff --git a/components/common/camel/pom.xml b/components/common/camel/pom.xml new file mode 100644 index 000000000..25d87efa3 --- /dev/null +++ b/components/common/camel/pom.xml @@ -0,0 +1,91 @@ + + + + 4.0.0 + switchyard-component-common-camel + bundle + SwitchYard: Camel Component Common Library + The SwitchYard Camel Component Common Library. + http://switchyard.org + + org.switchyard.components + switchyard-component-common-parent + 2.1.0-SNAPSHOT + ../pom.xml + + + + org.switchyard.component.camel.common.* + + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + org.apache.camel.spring.spi*;resolution:=optional, + org.springframework.transaction*;resolution:=optional, + * + + + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-config + + + org.switchyard.components + switchyard-component-common + + + org.springframework + spring-tx + + + org.apache.camel + camel-core + + + org.apache.camel + camel-spring + + + org.apache.camel + camel-test + test + + + org.mockito + mockito-all + test + + + org.switchyard.components + switchyard-component-bean + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + io.netty + netty + test + + + diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/CamelConstants.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/CamelConstants.java new file mode 100644 index 000000000..3b4a9e487 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/CamelConstants.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common; + +/** + * Constants used by Camel component. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public interface CamelConstants { + + /** + * SwitchYard component scheme. + */ + String SWITCHYARD_COMPONENT_NAME = "switchyard"; + + /** + * Name of message header where operation selector is stored. + */ + String OPERATION_SELECTOR_HEADER = "org.switchyard.operationSelector"; + + /** + * Name of message header where message composer is stored. + */ + String MESSAGE_COMPOSER_HEADER = "org.switchyard.messageComposer"; + + /** + * Namespace of the application. + */ + String APPLICATION_NAMESPACE = "org.switchyard.component.camel.namespace"; + + /** + * Name of Spring SPI transaction policy bean. + */ + String TRANSACTED_REF = "transactionPolicy"; + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/CommonCamelLogger.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/CommonCamelLogger.java new file mode 100644 index 000000000..2303471a5 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/CommonCamelLogger.java @@ -0,0 +1,32 @@ +package org.switchyard.component.camel.common; + +import org.jboss.logging.Cause; +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 34200-34299 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface CommonCamelLogger { + /** + * A root logger with the category of the package name. + */ + CommonCamelLogger ROOT_LOGGER = Logger.getMessageLogger(CommonCamelLogger.class, CommonCamelLogger.class.getPackage().getName()); + + /** + * failedToRemoveRouteForService method definition. + * @param serviceName the serviceName + * @param ex the ex + */ + @LogMessage(level = Level.WARN) + @Message(id = 34200, value = "Failed to remove route for service %s") + void failedToRemoveRouteForService(String serviceName, @Cause Exception ex); + +} + diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/CommonCamelMessages.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/CommonCamelMessages.java new file mode 100644 index 000000000..c3d045e13 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/CommonCamelMessages.java @@ -0,0 +1,158 @@ +package org.switchyard.component.camel.common; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; +/** + *

+ * This file is using the subset 34300-33999 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface CommonCamelMessages { + /** + * The default messages. + */ + CommonCamelMessages MESSAGES = Messages.getBundle(CommonCamelMessages.class); + + /** + * invalidURINoBindingDataCreatorRegisteredForScheme method definition. + * @param name the name + * @param e the e + * @return IllegalArgumentException + */ + @Message(id = 34300, value = "Invalid URI, no BindingDataCreator registered for scheme: %s") + IllegalArgumentException invalidURINoBindingDataCreatorRegisteredForScheme(String name, @Cause Exception e); + + /** + * resolvingBindingDataCreatorForEndpointOfType method definition. + * @param name the name + * @param typeName typeName + * @return IllegalArgumentException + */ + @Message(id = 34301, value = "Resolving binding data creator for endpoint of type : %s detected type conflict: Not a BindingDataCreator implementation. Found: %s") + IllegalArgumentException resolvingBindingDataCreatorForEndpointOfType(String name, String typeName); + + /** + * failedToStartRouteForService method definition. + * @param serviceName serviceName + * @param ex the ex + * @return SwitchYardException + */ + @Message(id = 34303, value = "Failed to start route for service %s") + SwitchYardException failedToStartRouteForService(String serviceName, @Cause Exception ex); + + /** + * failedToStopRouteForService method definition. + * @param serviceName serviceName + * @param ex the ex + * @return SwitchYardException + */ + @Message(id = 34304, value = "Failed to stop route for service %s") + SwitchYardException failedToStopRouteForService(String serviceName, @Cause Exception ex); + + /** + * bindingArgumentMustNotBeNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 34305, value = "binding argument must not be null") + IllegalArgumentException bindingArgumentMustNotBeNull(); + + /** + * camelContextArgumentMustNotBeNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 34306, value = "camelContext argument must not be null") + IllegalArgumentException camelContextArgumentMustNotBeNull(); + + /** + * bindingUriMustNotBeNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 34307, value = "binding uri must not be null") + IllegalArgumentException bindingUriMustNotBeNull(); + + /** + * failedToStartCamelProducerTemplateFor method definition. + * @param uri uri + * @param e the e + * @return SwitchYardException + */ + @Message(id = 34308, value = "Failed to start Camel producer template for %s") + SwitchYardException failedToStartCamelProducerTemplateFor(String uri, @Cause Exception e); + + /** + * failedToStopCamelProducerTemplateFor method definition. + * @param uri uri + * @param e the e + * @return SwitchYardException + */ + @Message(id = 34309, value = "Failed to stop Camel producer template for %s") + SwitchYardException failedToStopCamelProducerTemplateFor(String uri, @Cause Exception e); + + /** + * referenceBindingIsNotStarted method definition. + * @param referenceName the referenceName + * @param bindingName the bindingName + * @return HandlerException + */ + @Message(id = 34310, value = "Reference binding \"%s/%s\" is not started.") + HandlerException referenceBindingIsNotStarted(String referenceName, String bindingName); + + /** + * camelExchangeFailedWithoutAnException method definition. + * @param camelFault the camelFault + * @return HandlerException + */ + @Message(id = 34313, value = "camel exchange failed without an exception: %s") + HandlerException camelExchangeFailedWithoutAnException(String camelFault); + + /** + * configurationProvidesPasswordButDoNotSpecifyUser method definition. + * @return IllegalArgumentException + */ + @Message(id = 34314, value = "Configuration provides password but do not specify user") + IllegalArgumentException configurationProvidesPasswordButDoNotSpecifyUser(); + + /** + * failedToParse method definition. + * @param configName the configName + * @param parseEx the parseEx + * @return IllegalArgumentException + */ + @Message(id = 34315, value = "Failed to parse %s as a date.") + IllegalArgumentException failedToParse(String configName, @Cause java.text.ParseException parseEx); + + /** + * couldNotCreateAJtaTransactionManagerAsNoTransactionManagerWasFoundJBOSSUSERTRANSACTION method definition. + * @param userTransaction userTransaction + * @param osgitm OSGi TransactionManager name + * @param defaultUserTransaction defaultUserTransaction + * @return SwitchYardException + */ + @Message(id = 34318, value = "Could not create a JtaTransactionManager as no TransactionManager was found in JNDI. Tried [%s, %s, %s]") + SwitchYardException couldNotCreateAJtaTransactionManagerAsNoTransactionManagerWasFoundJBOSSUSERTRANSACTION(String userTransaction, String osgitm, String defaultUserTransaction); + + /** + * unexpectedExceptionRetrieving method definition. + * @param name the name + * @param e the e + * @return SwitchYardException + */ + @Message(id = 34319, value = "Unexpected Exception retrieving '%s' from JNDI namespace.") + SwitchYardException unexpectedExceptionRetrieving(String name, @Cause Exception e); + + /** + * unexpectedErrorClosingInitialContext method definition. + * @param e the e + * @return SwitchYardException + */ + @Message(id = 34320, value = "Unexpected error closing InitialContext.") + SwitchYardException unexpectedErrorClosingInitialContext(@Cause Exception e); + +} + diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/QueryString.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/QueryString.java new file mode 100644 index 000000000..7ee76666c --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/QueryString.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common; + +/** + * Represents the query string portion of a URI. The query string is built + * by adding name value pairs. Calling toString() produces a + * string which can be appended to the root (scheme + host) portion of a URI. + */ +public class QueryString { + + private StringBuilder _uriStr; + + /** + * Creates a new QueryString. + */ + public QueryString() { + _uriStr = new StringBuilder(); + } + + /** + * Add a name/value pair to the query string. + * @param name parameter name + * @param value parameter value + * @return a reference to this QueryString to promote fluent builder + */ + public QueryString add(String name, Object value) { + if (name != null && value != null) { + if (_uriStr.length() > 0) { + // we already have a query parameter, so add a separator + _uriStr.append('&'); + } + _uriStr.append(name + "=" + value); + } + return this; + } + + /** + * Returns a String representation of the query string. If no parameters + * have been added then an empty string is returned. + * @return string version of a URI + */ + public String toString() { + if (_uriStr.length() == 0) { + return ""; + } else { + return "?" + _uriStr.toString(); + } + } +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/BindingDataCreator.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/BindingDataCreator.java new file mode 100644 index 000000000..83aafe72a --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/BindingDataCreator.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import org.apache.camel.Message; + +/** + * BindingDataCreator interface is an extension point which allows 3rd party endpoints + * decide what kind of {@link CamelBindingData} instance should be created. This SPI + * point allows implement SecurityBindingData for these endpoints who support secure + * exchanges. + * + * @param Type of binding data. + */ +public interface BindingDataCreator { + + /** + * Creates new camel binding data for given input message. + * + * @param message Message instance. + * @return Camel binding data. + */ + T createBindingData(Message message); + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/BindingDataCreatorResolver.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/BindingDataCreatorResolver.java new file mode 100644 index 000000000..b054da3dd --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/BindingDataCreatorResolver.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import org.apache.camel.CamelContext; +import org.apache.camel.NoFactoryAvailableException; +import org.apache.camel.spi.FactoryFinder; +import org.switchyard.component.camel.common.CommonCamelMessages; + +/** + * Resolver which allows to plug-in custom {@link BindingDataCreator} injection. + */ +public class BindingDataCreatorResolver { + + private final static String BINDING_DATA_CREATOR_RESOURCE_PATH = "META-INF/services/org/switchyard/component/camel/"; + private FactoryFinder _bindingDataCreatorFactory; + + /** + * Try resolve binding creator for given endpoint name. + * + * @param name Name of endpoint, eg. DirectEndpoint. + * @param context Camel context instance. + * @return Dedicated BindingDataCreator or default if none found. + */ + public BindingDataCreator resolveBindingCreator(String name, CamelContext context) { + Class type = null; + try { + if (_bindingDataCreatorFactory == null) { + _bindingDataCreatorFactory = context.getFactoryFinder(BINDING_DATA_CREATOR_RESOURCE_PATH); + } + type = _bindingDataCreatorFactory.findClass(name); + } catch (NoFactoryAvailableException e) { + e.getMessage(); // ignore + } catch (Exception e) { + throw CommonCamelMessages.MESSAGES.invalidURINoBindingDataCreatorRegisteredForScheme(name, e); + } + + if (type != null) { + if (BindingDataCreator.class.isAssignableFrom(type)) { + return (BindingDataCreator) context.getInjector().newInstance(type); + } else { + throw CommonCamelMessages.MESSAGES.resolvingBindingDataCreatorForEndpointOfType(name, type.getName()); + } + } + return new DefaultBindingDataCreator(); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelBindingData.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelBindingData.java new file mode 100644 index 000000000..a78906002 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelBindingData.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import org.apache.camel.Message; +import org.switchyard.component.common.composer.BindingData; + +/** + * Camel binding data. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class CamelBindingData implements BindingData { + + private final Message _message; + + /** + * Constructs a new Camel binding data with the specified message. + * @param message the specified message + */ + public CamelBindingData(Message message) { + _message = message; + } + + /** + * Gets the message. + * @return the message + */ + public Message getMessage() { + return _message; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelComposition.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelComposition.java new file mode 100644 index 000000000..600f4438c --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelComposition.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.common.composer.Composition; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; + +/** + * Utility class for Camel-specific Composition. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class CamelComposition { + + /** + * Uses the {@link Composition} class to create a Camel-specific MessageComposer. + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer() { + return Composition.getMessageComposer(CamelBindingData.class); + } + + /** + * Uses the {@link Composition} class to create a Camel-specific MessageComposer. + * @param cbm a CamelBindingModel to get configuration details from + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer(CamelBindingModel cbm) { + ContextMapperModel cmm = cbm != null ? cbm.getContextMapper() : null; + MessageComposerModel mcm = cbm != null ? cbm.getMessageComposer() : null; + return Composition.getMessageComposer(CamelBindingData.class, cmm, mcm); + } + + private CamelComposition() {} + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelContextMapper.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelContextMapper.java new file mode 100644 index 000000000..91063ff5e --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelContextMapper.java @@ -0,0 +1,128 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.common.camel.ContextPropertyUtil; +import org.switchyard.component.common.composer.BaseRegexContextMapper; +import org.switchyard.component.common.label.ComponentLabel; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composite.BindingModel; + +/** + * CamelContextMapper. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class CamelContextMapper extends BaseRegexContextMapper { + + private String[] _camelLabels = null; + + private String[] getCamelLabels() { + if (_camelLabels == null) { + List list = new ArrayList(); + list.add(ComponentLabel.CAMEL.label()); + ContextMapperModel cm_model = getModel(); + if (cm_model != null) { + BindingModel b_model = cm_model.getBindingModel(); + if (b_model != null) { + String e_label = EndpointLabel.toLabel(b_model.getType()); + if (e_label != null) { + list.add(e_label); + } + } + } + _camelLabels = list.toArray(new String[list.size()]); + } + return _camelLabels; + } + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(CamelBindingData source, Context context) throws Exception { + Message message = source.getMessage(); + Exchange exchange = message.getExchange(); + + for (Map.Entry header : message.getHeaders().entrySet()) { + String name = header.getKey(); + if (matches(name) && !ContextPropertyUtil.isReservedProperty(name, Scope.MESSAGE)) { + Object value = header.getValue(); + if (value != null) { + context.setProperty(name, value, Scope.MESSAGE).addLabels(getCamelLabels()); + } + } + } + if (exchange != null) { + for (Map.Entry property : exchange.getProperties().entrySet()) { + String name = property.getKey(); + if (matches(name) && !ContextPropertyUtil.isReservedProperty(name, Scope.EXCHANGE)) { + Object value = property.getValue(); + if (value != null) { + context.setProperty(name, value, Scope.EXCHANGE).addLabels(getCamelLabels()); + } + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mapTo(Context context, CamelBindingData target) throws Exception { + Message message = target.getMessage(); + Exchange exchange = message.getExchange(); + + for (Property property : context.getProperties(Scope.MESSAGE)) { + String name = property.getName(); + if (matches(name) && !ContextPropertyUtil.isReservedProperty(name, Scope.MESSAGE)) { + Object value = property.getValue(); + if (value != null) { + message.setHeader(name, value); + } + } + } + if (exchange != null) { + for (Property property : context.getProperties(Scope.EXCHANGE)) { + String name = property.getName(); + if (matches(name) && !ContextPropertyUtil.isReservedProperty(name, Scope.EXCHANGE)) { + Object value = property.getValue(); + if (value != null) { + exchange.setProperty(name, value); + } + } + } + } + } + + @Override + public void setModel(ContextMapperModel model) { + super.setModel(model); + // reinitialize camel labels. prevent accessing the model outside of initialization. + _camelLabels = null; + getCamelLabels(); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelContextMapperFactory.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelContextMapperFactory.java new file mode 100644 index 000000000..5a66d626c --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelContextMapperFactory.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.ContextMapperFactory; + +/** + * CamelContextMapperFactory. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class CamelContextMapperFactory extends ContextMapperFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return CamelBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper newContextMapperDefault() { + return new CamelContextMapper(); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelMessageComposer.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelMessageComposer.java new file mode 100644 index 000000000..8db31d812 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelMessageComposer.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import static org.switchyard.Exchange.FAULT_TYPE; +import static org.switchyard.Exchange.OPERATION_NAME; +import static org.switchyard.Exchange.SERVICE_NAME; + +import java.io.InputStream; +import java.util.Map.Entry; +import java.util.Set; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.xml.namespace.QName; +import javax.xml.transform.Source; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.component.common.composer.BaseMessageComposer; +import org.switchyard.metadata.ServiceOperation; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +/** + * The Camel implementation of MessageComposer. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class CamelMessageComposer extends BaseMessageComposer { + + /** + * {@inheritDoc} + */ + @Override + public Message compose(CamelBindingData source, Exchange exchange) throws Exception { + Message message = exchange.createMessage(); + + // map context properties + getContextMapper().mapFrom(source, exchange.getContext(message)); + + org.apache.camel.Message sourceMessage = source.getMessage(); + + // map content + QName msgType = getMessageType(exchange); + Object content; + if (msgType == null) { + content = sourceMessage.getBody(); + } else if (QNameUtil.isJavaMessageType(msgType)) { + content = sourceMessage.getBody(QNameUtil.toJavaMessageType(msgType)); + } else { + content = sourceMessage.getBody(); + if (!(content instanceof String) && !(content instanceof Node) + && !(content instanceof InputSource) && !(content instanceof Source)) { + // named binary content - content is not String nor XML, but has type name other than "java:*" + content = sourceMessage.getBody(InputStream.class); + } + } + message.setContent(content); + + Set attachements = sourceMessage.getAttachmentNames(); + if (!attachements.isEmpty()) { + for (Entry entry : sourceMessage.getAttachments().entrySet()) { + message.addAttachment(entry.getKey(), entry.getValue().getDataSource()); + } + } + + return message; + } + + /** + * {@inheritDoc} + */ + @Override + public CamelBindingData decompose(Exchange exchange, CamelBindingData target) throws Exception { + Message sourceMessage = exchange.getMessage(); + getContextMapper().mapTo(exchange.getContext(), target); + + org.apache.camel.Message targetMessage = target.getMessage(); + + if (!sourceMessage.getAttachmentMap().isEmpty()) { + for (Entry entry : sourceMessage.getAttachmentMap().entrySet()) { + targetMessage.addAttachment(entry.getKey(), new DataHandler(entry.getValue())); + } + } + + ServiceOperation operation = exchange.getContract().getProviderOperation(); + target.getMessage().getExchange().setProperty(OPERATION_NAME, operation.getName()); + target.getMessage().getExchange().setProperty(FAULT_TYPE, operation.getFaultType()); + target.getMessage().getExchange().setProperty(SERVICE_NAME, exchange.getProvider().getName()); + + targetMessage.setBody(sourceMessage.getContent()); + return target; + } +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelMessageComposerFactory.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelMessageComposerFactory.java new file mode 100644 index 000000000..4f902c99e --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/CamelMessageComposerFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.MessageComposerFactory; + + +/** + * CamelMessageComposerFactory. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class CamelMessageComposerFactory extends MessageComposerFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return CamelBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer newMessageComposerDefault() { + return new CamelMessageComposer(); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/DefaultBindingDataCreator.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/DefaultBindingDataCreator.java new file mode 100644 index 000000000..6431a6864 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/composer/DefaultBindingDataCreator.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.composer; + +import org.apache.camel.Message; + +/** + * Default binding data creator which creates unsecured binding data. + */ +public class DefaultBindingDataCreator implements BindingDataCreator { + + @Override + public CamelBindingData createBindingData(Message message) { + return new CamelBindingData(message); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseBindingActivator.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseBindingActivator.java new file mode 100644 index 000000000..82acad992 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseBindingActivator.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.composer.CamelComposition; +import org.switchyard.component.camel.common.handler.InboundHandler; +import org.switchyard.component.camel.common.handler.OutboundHandler; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.deploy.ServiceHandler; + +/** + * Activator for handling camel bindings on both, service and reference, sides. + * + * @author Lukasz Dywicki + */ +public class BaseBindingActivator extends BaseCamelActivator { + + protected BaseBindingActivator(SwitchYardCamelContext context, String ... types) { + super(context, types); + } + + @Override + public ServiceHandler activateBinding(QName serviceName, BindingModel config) { + CamelBindingModel binding = (CamelBindingModel) config; + binding.setEnvironment(getEnvironment()); + + if (binding.isServiceBinding()) { + return createInboundHandler(serviceName, binding); + } else { + return createOutboundHandler(binding); + } + } + + protected InboundHandler createInboundHandler(QName serviceName, T binding) { + return new InboundHandler(binding, getCamelContext(), serviceName, getServiceDomain()); + } + + protected OutboundHandler createOutboundHandler(T binding) { + return new OutboundHandler(binding, getCamelContext(), CamelComposition + .getMessageComposer(binding), getServiceDomain()); + } + + @Override + public void deactivateBinding(QName name, ServiceHandler handler) { + // anything to do here? + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseBindingComponent.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseBindingComponent.java new file mode 100644 index 000000000..b100002a5 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseBindingComponent.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.deploy; + +import org.switchyard.common.camel.SwitchYardCamelContext; + +/** + * Base class for camel binding components. + */ +public abstract class BaseBindingComponent extends BaseCamelComponent { + + /** + * Default constructor. + * + * @param name Component name. + * @param types Names of supported elements. + */ + protected BaseBindingComponent(String name, String ... types) { + super(name, types); + } + + @Override + protected BaseBindingActivator createActivator(SwitchYardCamelContext context, String ... types) { + return new BaseBindingActivator(context, types); + } + +} + diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseCamelActivator.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseCamelActivator.java new file mode 100644 index 000000000..8ffdce318 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseCamelActivator.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.deploy; + +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.config.Configuration; +import org.switchyard.deploy.BaseActivator; + +/** + * Activator for handling camel bindings on both, service and reference, sides. + * + * @author Lukasz Dywicki + */ +public class BaseCamelActivator extends BaseActivator { + + private Configuration _environment; + private SwitchYardCamelContext _camelContext; + + protected BaseCamelActivator(SwitchYardCamelContext context, String ... types) { + super(types); + _camelContext = context; + } + + /** + * Specify environment configuration for binding. + * + * @param config Environment settings. + */ + public void setEnvironment(Configuration config) { + _environment = config; + } + + /** + * Gets the {@ling Configuration} used by this Activator. + * + * @return Configuration of the Activator. + */ + public Configuration getEnvironment() { + return _environment; + } + + /** + * Gets the {@link SwitchYardCamelContext} used by this Activator. + * + * @return The CamelContext used by this Activator. + */ + public SwitchYardCamelContext getCamelContext() { + return _camelContext; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseCamelComponent.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseCamelComponent.java new file mode 100644 index 000000000..cd445d7b9 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/deploy/BaseCamelComponent.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.deploy; + +import java.util.List; + +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * Base class for camel binding components. + */ +public abstract class BaseCamelComponent extends BaseComponent { + + /** + * Default constructor. + * + * @param name Component name. + * @param types Names of supported elements. + */ + protected BaseCamelComponent(String name, String ... types) { + super(types); + setName(name); + } + + /** + * {@inheritDoc} + */ + @Override + public Activator createActivator(ServiceDomain domain) { + List activationTypes = getActivationTypes(); + String[] types = activationTypes.toArray(new String[activationTypes.size()]); + + SwitchYardCamelContext camelContext = (SwitchYardCamelContext) domain + .getProperty(SwitchYardCamelContext.CAMEL_CONTEXT_PROPERTY); + BaseCamelActivator activator = createActivator(camelContext, types); + activator.setServiceDomain(domain); + activator.setEnvironment(getConfig()); + return activator; + } + + /** + * Creates activator for component. + * + * @param camelContext Camel context. + * @param types Activation types supported by component. + * @return Activator instance. + */ + protected abstract BaseCamelActivator createActivator(SwitchYardCamelContext camelContext, String ... types); + +} + diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/DefaultProcessor.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/DefaultProcessor.java new file mode 100644 index 000000000..3651d62e5 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/DefaultProcessor.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import org.apache.camel.Processor; +import org.switchyard.Exchange; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.common.composer.MessageComposer; + +/** + * A default Camel Processor. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class DefaultProcessor implements Processor { + + private final MessageComposer _messageComposer; + private Exchange _exchange; + + /** + * Create a DefaultProcessor that handles all generic outbound routes. + * + * @param composer the message composer to be used + * @param exchange the switchayrd exchange + */ + public DefaultProcessor(MessageComposer composer, Exchange exchange) { + _messageComposer = composer; + _exchange = exchange; + } + + /** + * {@inheritDoc} + */ + @Override + public void process(org.apache.camel.Exchange camelExchange) throws Exception { + _messageComposer.decompose(_exchange, new CamelBindingData(camelExchange.getIn())); + } + + /** + * Returns the SwitchYard exchange associated with this processor. + * + * @return the SwicthYard exchange + */ + public Exchange getExchange() { + return _exchange; + } + + /** + * Returns the composer associated with this processor. + * + * @return the message composer + */ + public MessageComposer getComposer() { + return _messageComposer; + } +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/InboundHandler.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/InboundHandler.java new file mode 100644 index 000000000..71b2d945e --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/InboundHandler.java @@ -0,0 +1,239 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import java.net.URI; + +import javax.xml.namespace.QName; + +import org.apache.camel.model.RouteDefinition; +import org.switchyard.Exchange; +import org.switchyard.ServiceDomain; +import org.switchyard.SwitchYardException; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.CamelConstants; +import org.switchyard.component.camel.common.CommonCamelLogger; +import org.switchyard.component.camel.common.CommonCamelMessages; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.common.transaction.TransactionHelper; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * An ExchangeHandler that acts as a gateway/entrypoint for Camel Components. + * + * This gives access to all component of Apache Camel and works by creating a + * Camel route that looks something like this + *

+ * from("CamelComponentURI").to("switchyard://serviceName"); 
+ * 
+ * + * @author Daniel Bevenius + * + * @param Type of the binding. + */ +public class InboundHandler extends BaseServiceHandler { + + private static final String NAMESPACE_POLICY_REF = "org.switchyard.namespaceContextPolicy"; + + private final T _camelBindingModel; + private final SwitchYardCamelContext _camelContext; + private final QName _serviceName; + + /** + * Sole constructor. + * + * @param camelBindingModel The {@link CamelBindingModel}. + * @param camelContext The camel context instance. + * @param serviceName The target service name. + * @param domain the service domain. + */ + public InboundHandler(final T camelBindingModel, final SwitchYardCamelContext camelContext, final QName serviceName, final ServiceDomain domain) { + super(domain); + _camelBindingModel = camelBindingModel; + _camelContext = camelContext; + _serviceName = serviceName; + + try { + _camelContext.addRouteDefinition(createRouteDefinition()); + } catch (final Exception e) { + throw new SwitchYardException(e); + } + } + + /** + * Creates route definition applicable for actual camel binding model. + * + * @return Route definition handling given binding. + */ + protected RouteDefinition createRouteDefinition() { + final RouteDefinition route = new RouteDefinition(); + + route.routeId(getRouteId()).from(getComponentUri().toString()); + addTransactionPolicy(route); + addNamespacePolicy(route); + + route.setProperty(ExchangeCompletionEvent.GATEWAY_NAME).simple(getBindingModel().getName(), String.class) + .setProperty(CamelConstants.APPLICATION_NAMESPACE).constant(_serviceName.getNamespaceURI()) + .process(new MessageComposerProcessor(getBindingModel())) + .process(new OperationSelectorProcessor(getServiceName(), getBindingModel())) + .to(getSwitchyardEndpointUri()); + + return route; + } + + /** + * Get route id for given binding. + * + * @return Camel route id. + */ + public String getRouteId() { + return getBindingModel().getClass().getSimpleName() + "/" + getServiceName().getLocalPart() + "@" + + getBindingModel().getName() + "#" + getBindingModel().getComponentURI().hashCode(); + } + + protected QName getServiceName() { + return _serviceName; + } + + /** + * Add transacted DSL element to route if necessary. + * + * This method checks if component uri contains transaction manager reference + * and puts + * + * @param route Route definition. + * @param componentURI Component uri. + * @return + */ + protected RouteDefinition addTransactionPolicy(final RouteDefinition route) { + if (TransactionHelper.useTransactionManager(getComponentUri(), _camelContext)) { + route.transacted(CamelConstants.TRANSACTED_REF); + } + + return route; + } + + /** + * Only add a namespace policy if the policy ref can be resolved, which will + * be the case on EAP but not on Karaf. + */ + protected RouteDefinition addNamespacePolicy(final RouteDefinition route) { + if (_camelContext.getRegistry().lookupByName(NAMESPACE_POLICY_REF) != null) { + route.routePolicyRef(NAMESPACE_POLICY_REF); + } + return route; + } + + protected URI getComponentUri() { + return getBindingModel().getComponentURI(); + } + + protected String getSwitchyardEndpointUri() { + return CamelConstants.SWITCHYARD_COMPONENT_NAME + "://" + getServiceName().getLocalPart(); + } + + protected T getBindingModel() { + return _camelBindingModel; + } + + protected SwitchYardCamelContext getSwitchYardCamelContext() { + return _camelContext; + } + + /** + * Will create the Camel route and add it to the camel context. + */ + @Override + protected void doStart() { + try { + RouteDefinition route = _camelContext.getRouteDefinition(getRouteId()); + if (route == null) { + // may have been removed if this was stopped + route = createRouteDefinition(); + _camelContext.addRouteDefinition(route); + } + if (route.isStartable(_camelContext)) { + _camelContext.startRoute(getRouteId()); + } + } catch (Exception ex) { + throw CommonCamelMessages.MESSAGES.failedToStartRouteForService(_serviceName.toString(), ex); + } + } + + /** + * Suspends the route. + */ + @Override + protected void doStop() { + try { + _camelContext.stopRoute(getRouteId()); + } catch (Exception ex) { + throw CommonCamelMessages.MESSAGES.failedToStopRouteForService(_serviceName.toString(), ex); + } + try { + _camelContext.removeRoute(getRouteId()); + } catch (Exception ex) { + CommonCamelLogger.ROOT_LOGGER.failedToRemoveRouteForService(_serviceName.toString(), ex); + } + } + + /** + * This is a noop for this handler. This handler is only responsible for setting up + * a route in camel and the {@link SwitchyardComponent} will take care of calling + * the configured SwitchYard service. + * + * @param switchYardExchange Message exchange. + */ + @Override + public void handleMessage(final Exchange switchYardExchange) { + } + + @Override + public void handleFault(final Exchange exchange) { + System.out.println(exchange.getMessage().getContent()); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_camelBindingModel == null) ? 0 : _camelBindingModel.getComponentURI().hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + + final InboundHandler other = (InboundHandler) obj; + if (_camelBindingModel == null) { + if (other._camelBindingModel != null) { + return false; + } + } else if (!_camelBindingModel.getComponentURI().equals(other._camelBindingModel.getComponentURI())) { + return false; + } + return true; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/MessageComposerProcessor.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/MessageComposerProcessor.java new file mode 100644 index 000000000..40d7de35b --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/MessageComposerProcessor.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import static org.switchyard.component.camel.common.CamelConstants.MESSAGE_COMPOSER_HEADER; + +import org.apache.camel.Message; +import org.apache.camel.Processor; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.composer.CamelComposition; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.common.composer.MessageComposer; + +/** + * Processor used to choose operation from binding model. + */ +public class MessageComposerProcessor implements Processor { + + private final MessageComposer _composer; + + /** + * Creates new processor. + * + * @param bindingModel Camel binding model bound to service interface. + */ + public MessageComposerProcessor(CamelBindingModel bindingModel) { + _composer = CamelComposition.getMessageComposer(bindingModel); + } + + @Override + public void process(org.apache.camel.Exchange exchange) throws Exception { + Message in = exchange.getIn(); + in.setHeader(MESSAGE_COMPOSER_HEADER, _composer); + exchange.setOut(in.copy()); + } + +} + diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/OperationSelectorProcessor.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/OperationSelectorProcessor.java new file mode 100644 index 000000000..4d25d1e6f --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/OperationSelectorProcessor.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import static org.switchyard.component.camel.common.CamelConstants.OPERATION_SELECTOR_HEADER; + +import javax.xml.namespace.QName; + +import org.apache.camel.Message; +import org.apache.camel.Processor; +import org.switchyard.common.lang.Strings; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.common.selector.OperationSelectorFactory; +import org.switchyard.selector.OperationSelector; + +/** + * Processor used to choose operation from binding model. + */ +public class OperationSelectorProcessor implements Processor { + + private final QName _serviceName; + private final CamelBindingModel _bindingModel; + private final OperationSelector _selector; + + /** + * Creates new processor. + * + * @param serviceName Service name. + * @param bindingModel Camel binding model bound to service interface. + */ + public OperationSelectorProcessor(QName serviceName, CamelBindingModel bindingModel) { + this._serviceName = serviceName; + this._bindingModel = bindingModel; + + OperationSelectorFactory selectorFactory = OperationSelectorFactory.getOperationSelectorFactory(CamelBindingData.class); + _selector = selectorFactory.newOperationSelector(_bindingModel.getOperationSelector()); + if (_selector != null) { + _selector.setDefaultNamespace(Strings.trimToNull(_serviceName.getNamespaceURI())); + } + } + + @Override + public void process(org.apache.camel.Exchange exchange) throws Exception { + Message in = exchange.getIn(); + in.setHeader(OPERATION_SELECTOR_HEADER, _selector); + exchange.setOut(in.copy()); + } + +} + diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/OutboundHandler.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/OutboundHandler.java new file mode 100644 index 000000000..a4130b7a2 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/handler/OutboundHandler.java @@ -0,0 +1,243 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import javax.xml.namespace.QName; + +import org.apache.camel.CamelContext; +import org.apache.camel.CamelExecutionException; +import org.apache.camel.Processor; +import org.apache.camel.ProducerTemplate; +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.component.camel.common.CommonCamelMessages; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.common.transaction.TransactionHelper; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * A handler that is capable of calling Apache Camel components and returning responses + * from Camel to SwitchYard. + *

+ * The typical usage would be when a POJO has a field with a reference annotation. SwitchYard + * can inject a proxy instance which will invoke a Camel endpoint. It is an instance of this + * class that will handle the invocation of the Camel endpoint. + * + * @author Daniel Bevenius + * + */ +public class OutboundHandler extends BaseServiceHandler { + + private static Logger _logger = Logger.getLogger(OutboundHandler.class); + + private final MessageComposer _messageComposer; + private final ProducerTemplate _producerTemplate; + private final SwitchYardCamelContext _camelContext; + private final String _bindingName; + private final String _referenceName; + private final String _uri; + private final ServiceDomain _domain; + + /** + * Constructor that will create a default {@link ProducerTemplate}. + * + * @param binding The Camel binding. + * @param context The {@link CamelContext}. + * @param messageComposer the MessageComposer this handler should use + * @param domain the service domain + */ + public OutboundHandler(final CamelBindingModel binding, final SwitchYardCamelContext context, MessageComposer messageComposer, ServiceDomain domain) { + this(binding, context, messageComposer, null, domain); + } + + /** + * Constructor that allows for specifying a specific {@link ProducerTemplate}. + * + * @param binding The Camel binding. + * @param context The {@link CamelContext}. + * @param messageComposer the MessageComposer this handler should use. + * @param producerTemplate The {@link ProducerTemplate} to be used by this handler. + * @param domain the service domain + */ + public OutboundHandler(final CamelBindingModel binding, final SwitchYardCamelContext context, MessageComposer messageComposer, ProducerTemplate producerTemplate, ServiceDomain domain) { + super(domain); + _domain = domain; + if (binding == null) { + throw CommonCamelMessages.MESSAGES.bindingArgumentMustNotBeNull(); + } + if (context == null) { + throw CommonCamelMessages.MESSAGES.camelContextArgumentMustNotBeNull(); + } + if (binding.getComponentURI() == null) { + throw CommonCamelMessages.MESSAGES.bindingUriMustNotBeNull(); + } + _uri = binding.getComponentURI().toString(); + _bindingName = binding.getName(); + _referenceName = binding.getReference().getName(); + _camelContext = context; + _messageComposer = messageComposer; + _producerTemplate = producerTemplate == null ? _camelContext.createProducerTemplate() : producerTemplate; + + TransactionHelper.useTransactionManager(_uri, context); + } + + /** + * Starts the {@link ProducerTemplate}. + */ + @Override + protected void doStart() { + try { + _producerTemplate.start(); + _logger.debug("Started producer template for " + _uri); + } catch (Exception e) { + throw CommonCamelMessages.MESSAGES.failedToStartCamelProducerTemplateFor(_uri, e); + } + } + + /** + * Stops the {@link ProducerTemplate}. + */ + @Override + protected void doStop() { + try { + _producerTemplate.stop(); + _logger.debug("Stopped producer template for " + _uri); + } catch (Exception ex) { + throw CommonCamelMessages.MESSAGES.failedToStopCamelProducerTemplateFor(_uri.toString(), ex); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + // identify ourselves + exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + + if (getState() != State.STARTED) { + throw CommonCamelMessages.MESSAGES.referenceBindingIsNotStarted(_referenceName, _bindingName); + } + if (isInOnly(exchange)) { + handleInOnly(exchange); + } else { + handleInOut(exchange); + } + } + + private boolean isInOnly(final Exchange exchange) { + return exchange.getContract().getConsumerOperation().getExchangePattern() == ExchangePattern.IN_ONLY; + } + + private void handleInOnly(final Exchange exchange) throws HandlerException { + try { + final org.apache.camel.Exchange camelExchange = _producerTemplate.send(_uri, createProcessor(exchange)); + Object propagateException = _domain.getProperty(Exchange.PROPAGATE_EXCEPTION_ON_IN_ONLY); + if ((propagateException == null || Boolean.parseBoolean(propagateException.toString())) + && camelExchange.isFailed()) { + Exception camelException = camelExchange.getException(); + if (camelException != null) { + throw new HandlerException(camelException); + } else { + throw CommonCamelMessages.MESSAGES.camelExchangeFailedWithoutAnException(""); + } + } + } catch (final CamelExecutionException e) { + throw new HandlerException(e); + } + } + + private void handleInOut(final Exchange switchyardExchange) throws HandlerException { + final org.apache.camel.Exchange camelExchange = _producerTemplate.request(_uri, createProcessor(switchyardExchange)); + CamelBindingData bindingData = new CamelBindingData(camelExchange.getOut()); + Exception camelException = camelExchange.getException(); + + if (!camelExchange.isFailed()) { + sendResponseToSwitchyard(switchyardExchange, bindingData); + + } else { + QName faultName = switchyardExchange.getContract().getProviderOperation().getFaultType(); + Class declaredFault = faultName != null && QNameUtil.isJavaMessageType(faultName) ? QNameUtil.toJavaMessageType(faultName) : null; + + Object camelFault = camelException; + if (camelFault == null) { + if (camelExchange.hasOut() && bindingData.getMessage().isFault()) { + // Use Out body as a fault content if camelExchange.getException() returns null + camelFault = bindingData.getMessage().getBody(); + } + } + + if (camelFault != null && declaredFault != null && declaredFault.isAssignableFrom(camelFault.getClass())) { + Message msg = null; + try { + msg = _messageComposer.compose(bindingData, switchyardExchange); + } catch (Exception e) { + throw new HandlerException(e); + } + switchyardExchange.sendFault(msg); + } else if (camelFault instanceof Throwable) { + throw new HandlerException(Throwable.class.cast(camelFault)); + } else { + if (camelFault == null) { + throw CommonCamelMessages.MESSAGES.camelExchangeFailedWithoutAnException(""); + } else { + throw CommonCamelMessages.MESSAGES.camelExchangeFailedWithoutAnException(camelFault.toString()); + } + } + } + } + + private void sendResponseToSwitchyard(final Exchange switchyardExchange, CamelBindingData bindingData) throws HandlerException { + Message msg = null; + try { + msg = _messageComposer.compose(bindingData, switchyardExchange); + } catch (Exception e) { + throw new HandlerException(e); + } + switchyardExchange.send(msg); + } + + private Processor createProcessor(final Exchange switchyardExchange) { + return new DefaultProcessor(_messageComposer, switchyardExchange); + } + + /** + * Return the CamelContext used by this handler. + * @return CamelContext + */ + public CamelContext getCamelContext() { + return _camelContext; + } + + /** + * Return the Camel endpoint URI used by this handler. + * @return Camel endpoint URI + */ + public String getUri() { + return _uri; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/AdditionalUriParametersModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/AdditionalUriParametersModel.java new file mode 100644 index 000000000..ae328ba28 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/AdditionalUriParametersModel.java @@ -0,0 +1,61 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @author tags. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.switchyard.component.camel.common.model; + +import java.util.List; +import java.util.Map; + +import org.switchyard.config.model.Model; + +/** + * "additionalUriParameters" configuration model. + */ +public interface AdditionalUriParametersModel extends Model { + + /** The "additionalUriParameters" name. */ + public static final String ADDITIONAL_URI_PARAMETERS = "additionalUriParameters"; + + /** + * Gets the child parameter models. + * @return the child parameter models + */ + public List getParameters(); + + /** + * Adds a child parameter model. + * @param parameter the child parameter model to add + * @return this AdditionalUriParametersModel (useful for chaining) + */ + public AdditionalUriParametersModel addParameter(ParameterModel parameter); + + /** + * Remove a parameter model by name. + * @param name name of the parameter + * @return parameter with the specified name, or null if no such parameter exists + */ + public ParameterModel removeParameter(String name); + + /** + * Converts this ParametersModel to a Map. + * @return the Map + */ + public Map toMap(); + + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/CamelBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/CamelBindingModel.java new file mode 100644 index 000000000..d93c6489c --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/CamelBindingModel.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model; + +import java.net.URI; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.composite.BindingModel; + +/** + * A binding definition that specifies how communication between Apache Camel + * and SwitchYard components is done. + * + * Example of a binding implementation: + *

{
+ *  
+ *     
+ *        
+ *     
+ *  
+ * }
+ * + *
    + *
  • The operationsSelector can be used to specify an operation name of the target + * service. + * This is required when you have components are consumers where there is + * no way for the the operation name to be derived. For example, this might be the case when + * you are using the file component. This way you can specify the target operation name statically. + * This is an option element as there can be case when the target service can be derived. An example + * of this could be an webservice component where the operation name can be derived from the incoming + * SOAPMessage and the WSDL. + *
  • + *
+ * + * @author Daniel Bevenius + */ +public interface CamelBindingModel extends BindingModel { + + /** + * Name of 'produce' element. + */ + String PRODUCE = "produce"; + + /** + * Name of 'consume' element. + */ + String CONSUME = "consume"; + + /** + * Gets the component URI from the underlying model. + * Implementations are responsible for building an uri from the elements and attributes + * of the configuration in question. + * + * @return URI The Camel components URI. + */ + URI getComponentURI(); + + /** + * Sets the global configuration. + * + * @param config the environment/global config + */ + void setEnvironment(Configuration config); + + /** + * Additional URI parameters not declared in the configuration model. + * @return an instance of the additional URI parameters. + */ + AdditionalUriParametersModel getAdditionalUriParameters(); + + /** + * Specify additional URI parameters not declared in the configuration model. + * @param parameters the additional URI parameters + * @return a reference to the binding model + */ + CamelBindingModel setAdditionalUriParameters(AdditionalUriParametersModel parameters); +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/ParameterModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/ParameterModel.java new file mode 100644 index 000000000..ee5b6acfe --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/ParameterModel.java @@ -0,0 +1,63 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @author tags. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.switchyard.component.camel.common.model; + +import org.switchyard.config.model.Model; + +/** + * "parameter" configuration model. + */ +public interface ParameterModel extends Model { + + /** The "parameter" name. */ + public static final String PARAMETER = "parameter"; + + /** + * Gets the parent parameters model. + * @return the parent parameters model. + */ + public AdditionalUriParametersModel getAdditionalUriParameters(); + + /** + * Gets the name attribute. + * @return the name attribute + */ + public String getName(); + + /** + * Sets the name attribute. + * @param name the name attribute + * @return this ParameterModel (useful for chaining) + */ + public ParameterModel setName(String name); + + /** + * Gets the value attribute. + * @return the value attribute + */ + public String getValue(); + + /** + * Sets the value attribute. + * @param value the value attribute + * @return this ParameterModel (useful for chaining) + */ + public ParameterModel setValue(String value); + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledBatchPollConsumer.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledBatchPollConsumer.java new file mode 100644 index 000000000..301f6435f --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledBatchPollConsumer.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.consumer; + +/** + * Scheduled batch poll consumer interface. Allows to limit number of elements + * in one poll. + * + * @author Lukasz Dywicki + */ +public interface CamelScheduledBatchPollConsumer extends CamelScheduledPollConsumer { + + /** + * An integer that defines the maximum number of messages to gather per poll. + * + * @return maximum number of messages per poll. + */ + Integer getMaxMessagesPerPoll(); + + /** + * Specify the maximum number of messages to gather per poll. + * + * @param maxMessagesPerPoll the maximum number of messages to gather per poll + * @return a reference to this binding model. + */ + CamelScheduledBatchPollConsumer setMaxMessagesPerPoll(Integer maxMessagesPerPoll); + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledPollConsumer.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledPollConsumer.java new file mode 100644 index 000000000..8b2371ef1 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledPollConsumer.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.consumer; + +import java.util.concurrent.TimeUnit; + +/** + * Scheduled poll consumer interface. Defines common properties for schedule + * based consumers. + * + * @author Lukasz Dywicki + */ +public interface CamelScheduledPollConsumer { + + /** + * Delay before the next poll. + * + * @return the delay setting or null if it has not been specified. + */ + Integer getDelay(); + + /** + * Specify the time before next poll. + * + * @param delay the time in configured time unit. + * @return a reference to this binding model. + */ + CamelScheduledPollConsumer setDelay(Integer delay); + + /** + * Delay before polling starts in given time unit. + * + * @return the initial delay setting or null if it has not been specified. + */ + Integer getInitialDelay(); + + /** + * Specify the time before polling starts. + * + * @param initialDelay the time in configured time unit. + * @return a reference to this binding model. + */ + CamelScheduledPollConsumer setInitialDelay(Integer initialDelay); + + /** + * Time unit used to count delay and initial delay. By default it is millisecond. + * + * @return Time unit of initial delay/delay. + */ + TimeUnit getTimeUnit(); + + /** + * Specify the time unit of initial delay/delay parameters. + * + * @param timeUnit Time unit to use. + * @return a reference to this binding model + */ + CamelScheduledPollConsumer setTimeUnit(String timeUnit); + + /** + * Controls if fixed delay or fixed rate is used. + * + * @return True if fixed rate is used. + */ + Boolean isUseFixedDelay(); + + /** + * Specify whether to use fixed delay between pools, otherwise fixed rate is + * used. + * + * @param useFixedDelay true: fixed delay between pools. False: fixed rate is used + * @return a reference to this binding model. + */ + CamelScheduledPollConsumer setUseFixedDelay(Boolean useFixedDelay); + + /** + * If the polling consumer did not poll any message, you can enable this option + * to send an empty message (no body) instead. + * + * @return Should empty message be sent when there is nothing to poll. + */ + Boolean isSendEmptyMessageWhenIdle(); + + /** + * Specify whether to use empty messages if there is nothing to poll. + * + * @param sendEmptyMessageWhenIdle True - empty message will be sent. + * @return a reference to this binding model. + */ + CamelScheduledPollConsumer setSendEmptyMessageWhenIdle(Boolean sendEmptyMessageWhenIdle); + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileBindingModel.java new file mode 100644 index 000000000..54d278a73 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileBindingModel.java @@ -0,0 +1,109 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.file; + +import org.switchyard.component.camel.common.model.CamelBindingModel; + +/** + * Binding model for file endpoints. + * + * @author Lukasz Dywicki + */ +public interface GenericFileBindingModel extends CamelBindingModel { + + /** + * The endpoint directory. + * @return the directory + */ + String getDirectory(); + + /** + * Specify the endpoint consume/produce directory. + * @param directory the target directory + * @return a reference to this Camel binding model + */ + GenericFileBindingModel setDirectory(String directory); + + /** + * Whether missing directories in the file's pathname will be created or not. + * For the file consumer, that means creating the starting directory. + * For the file producer, it means the directory to where the files should be written. + * @return the auto-create setting or null if it has not been specified + */ + Boolean isAutoCreate(); + + /** + * Specify whether missing directories in the file's pathname will be created or not. + * @param autoCreate true if directories will be created, false otherwise + * @return a reference to this Camel binding model + */ + GenericFileBindingModel setAutoCreate(Boolean autoCreate); + + /** + * Buffer sized in bytes. + * @return the buffer size setting or null if it has not been specified + */ + Integer getBufferSize(); + + /** + * Specify buffer size in bytes. + * @param bufferSize buffer size in bytes + * @return a reference to this Camel binding model + */ + GenericFileBindingModel setBufferSize(Integer bufferSize); + + /** + * Expression such as File Language to dynamically set the filename. + * For consumers, it's used as a filename filter. + * For producers, it's used to evaluate the filename to write + * @return the file name setting or null if it has not been specified + */ + String getFileName(); + + /** + * Specify expression such as File Language to dynamically set the filename. + * @param fileName expression to dynamically set the filename + * @return a reference to this Camel binding model + */ + GenericFileBindingModel setFileName(String fileName); + + /** + * Whether the file name path will get leading paths stripped; so it's just the file name. + * @return the flatten setting or null if it has not been specified + */ + Boolean isFlatten(); + + /** + * Specify whether the file name will be stripped. + * @param flatten true to get it flattened, false otherwise + * @return a reference to this Camel binding model + */ + GenericFileBindingModel setFlatten(Boolean flatten); + + /** + * This option is used to specify the encoding of the file, and camel will + * set the Exchange property with Exchange.CHARSET_NAME with the value of this option. + * @return the charset setting or null if it has not been specified + */ + String getCharset(); + + /** + * Specify the encoding of the file. + * + * @param charset the encoding of the file + * @return a reference to this Camel binding model + */ + GenericFileBindingModel setCharset(String charset); + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileConsumerBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileConsumerBindingModel.java new file mode 100644 index 000000000..bb01d412c --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileConsumerBindingModel.java @@ -0,0 +1,409 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.file; + +import org.switchyard.component.camel.common.model.consumer.CamelScheduledBatchPollConsumer; + +/** + * Binding model for file based consumers. + * + * @author Lukasz Dywicki + */ +public interface GenericFileConsumerBindingModel extends CamelScheduledBatchPollConsumer { + + /** + * If a directory, will look for files in all the sub-directories as well. + * + * @return true if recursive; false otherwise + */ + Boolean isRecursive(); + + /** + * Specify whether to look for files in all the sub-directories as well. + * + * @param recursive + * true to look for files in all the sub-directories; false + * otherwise + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setRecursive(Boolean recursive); + + /** + * Whether the file will be deleted after it is processed. + * + * @return true if to be deleted; false otherwise + */ + Boolean isDelete(); + + /** + * Specify whether the file will be deleted after it is processed. + * + * @param delete + * true to get the file deleted; false otherwise + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setDelete(Boolean delete); + + /** + * If true, the file is not moved or deleted in any way. This option is good + * for readonly data, or for ETL type requirements. If noop=true, Camel will + * set idempotent=true as well, to avoid consuming the same files over and + * over again. + * + * @return true if no operation is to be performed; false otherwise + */ + Boolean isNoop(); + + /** + * Specify whether the file is not to be moved or deleted in any way. This + * option is good for readonly data, or for ETL type requirements. If + * noop=true, Camel will set idempotent=true as well, to avoid consuming the + * same files over and over again. + * + * @param noop + * true to avoid moving or deleting the file; false otherwise + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setNoop(Boolean noop); + + /** + * Expression used to dynamically set the filename when moving it before + * processing. + * + * @return the expression to be used + */ + String getPreMove(); + + /** + * Specify the expression used to dynamically set the filename when moving + * it before processing. + * + * @param preMove + * the expression + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setPreMove(String preMove); + + /** + * Expression used to dynamically set the filename when moving it after + * processing. + * + * @return the expression to be used + */ + String getMove(); + + /** + * Specify the expression used to dynamically set the filename when moving + * it after processing. + * + * @param move + * the expression + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setMove(String move); + + /** + * Expression used to dynamically set a different target directory when + * moving files after processing failed. + * + * @return the expression to be used + */ + String getMoveFailed(); + + /** + * Specify expression used to dynamically set a different target directory + * when moving files after. + * + * @param moveFailed + * the expression + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setMoveFailed(String moveFailed); + + /** + * Used to include files, if filename matches the regex pattern. + * + * @return the expression to be used + */ + String getInclude(); + + /** + * Specify the expression used to include files, if filename matches the + * regex pattern. + * + * @param include + * the expression + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setInclude(String include); + + /** + * Used to exclude files, if filename matches the regex pattern. + * + * @return the expression to be used + */ + String getExclude(); + + /** + * Specify the expression used to exclude files, if filename matches the + * regex pattern. + * + * @param exclude + * the expression + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setExclude(String exclude); + + /** + * Option to use the Idempotent Consumer EIP pattern to let Camel skip + * already processed files. + * + * @return whether idempotent is enabled or not + */ + Boolean isIdempotent(); + + /** + * Specify to use the Idempotent Consumer EIP pattern to let Camel skip + * already processed files. + * + * @param idempotent + * whether to use Idempotent Consumer EIP pattern or not + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setIdempotent(Boolean idempotent); + + /** + * Pluggable repository. + * + * @return the repository + */ + String getIdempotentRepository(); + + /** + * Specify the Pluggable repository. + * + * @param idempotentRepository + * the repository + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setIdempotentRepository(String idempotentRepository); + + /** + * Pluggable in-progress repository. + * + * @return the in-progress repository + */ + String getInProgressRepository(); + + /** + * Specify the Pluggable in-progress repository. + * + * @param inProgressRepository + * the in-progress repository + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setInProgressRepository(String inProgressRepository); + + /** + * Pluggable filter. + * + * @return the filter + */ + String getFilter(); + + /** + * Specify the Pluggable filter. + * + * @param filter + * the filter + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setFilter(String filter); + + /** + * Pluggable sorter. + * + * @return the sorter + */ + String getSorter(); + + /** + * Specify the Pluggable sorter. + * + * @param sorter + * the sorter + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setSorter(String sorter); + + /** + * Built-in sort. group sort by modified date. + * + * @return the sort + */ + String getSortBy(); + + /** + * Specify the built-in sort to use. Supports nested sorts, so you can have + * a sort by file name and as a 2nd group sort by modified date. + * + * @param sortBy + * the built-in sort + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setSortBy(String sortBy); + + /** + * Used by consumer, to only poll the files if it has exclusive read-lock on + * the file. + * + * @return the read lock + */ + String getReadLock(); + + /** + * Used by consumer, to specify only polling the files if it has exclusive + * read-lock on the file (i.e. the file is not in-progress or being + * written). Camel will wait until the file lock is granted. + * + * @param readLock + * the read lock + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setReadLock(String readLock); + + /** + * Optional timeout in milliseconds for the read-lock, if supported by the + * read-lock. + * + * @return the timeout in milliseconds + */ + Long getReadLockTimeout(); + + /** + * Specify an optional timeout in milliseconds for the read-lock, if + * supported by the read-lock. + * + * @param readLockTimeout + * the timeout + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setReadLockTimeout(Long readLockTimeout); + + /** + * Camel 2.6: Interval in millis for the read-lock, if supported by the read + * lock. This interval is used for sleeping between attempts to acquire the + * read lock. + * + * @return the interval in millis + */ + Integer getReadLockCheckInterval(); + + /** + * Specify the interval in millis for the read-lock, if supported by the + * read lock. + * + * @param readLockCheckInterval + * the interval in millis + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setReadLockCheckInterval(Integer readLockCheckInterval); + + /** + * Pluggable read-lock. + * + * @return the read-lock + */ + String getExclusiveReadLockStrategy(); + + /** + * Specify the Pluggable read-lock. + * + * @param exclusiveReadLockStrategy + * the read-lock + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setExclusiveReadLockStrategy(String exclusiveReadLockStrategy); + + /** + * A pluggable File Process Strategy allowing you to implement your own + * readLock option or similar. + * + * @return file process strategy + */ + String getProcessStrategy(); + + /** + * Specify a pluggable File Process Strategy allowing you to implement your + * own readLock option or similar. + * + * @param processStrategy + * the process strategy + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setProcessStrategy(String processStrategy); + + /** + * Camel 2.5: Whether the starting directory must exist. + * + * @return true if the starting directory must exist; false otherwise + */ + Boolean isStartingDirectoryMustExist(); + + /** + * Specify whether the starting directory must exist. + * + * @param startingDirectoryMustExist + * true if the directory must exist; false otherwise + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setStartingDirectoryMustExist(Boolean startingDirectoryMustExist); + + /** + * Camel 2.5: Similar to startingDirectoryMustExist but this applies during + * polling recursive sub directories. + * + * @return true if the starting directory must exist; false otherwise + */ + Boolean isDirectoryMustExist(); + + /** + * Camel 2.5: Similar to startingDirectoryMustExist but this applies during + * polling recursive sub directories. + * + * @param directoryMustExist + * true if the directory must exist; false otherwise + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setDirectoryMustExist(Boolean directoryMustExist); + + /** + * Camel 2.6: If provided, Camel will only consume files if a done file + * exists. + * + * @return the file name to use + */ + String getDoneFileName(); + + /** + * Camel 2.6: If provided, Camel will only consume files if a done file + * exists. + * + * @param doneFileName + * the file name to use + * @return a reference to this Camel File binding model + */ + GenericFileConsumerBindingModel setDoneFileName(String doneFileName); + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileProducerBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileProducerBindingModel.java new file mode 100644 index 000000000..5efaee12a --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/GenericFileProducerBindingModel.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.file; + +/** + * Binding model for file based producers. + * + * @author Lukasz Dywicki + */ +public interface GenericFileProducerBindingModel { + + /** + * What to do if a file already exists with the same name. The following + * values can be obtained: Override, Append, Fail and Ignore. + * + * @return the fileExist value + */ + String getFileExist(); + + /** + * Specify what to do if a file already exists with the same name. + * + * @param fileExist one of these: Override, Append, Fail or Ignore + * @return a reference to this Camel File binding model + */ + GenericFileProducerBindingModel setFileExist(String fileExist); + + /** + * This option is used to write the file using a temporary name and then, + * after the write is complete, rename it to the real name. + * + * @return the tempPrefix value + */ + String getTempPrefix(); + + /** + * Specify the name of the temporary name when writting it. After the write + * is complete, it will be renamed to the real name. + * + * @param tempPrefix the temporary file name + * @return a reference to this Camel File binding model + */ + GenericFileProducerBindingModel setTempPrefix(String tempPrefix); + + /** + * Camel 2.1: The same as tempPrefix option but offering a more fine grained + * control on the naming of the temporary filename. + * + * @return the temporary file name value + */ + String getTempFileName(); + + /** + * Camel 2.1: The same as tempPrefix option but offering a more fine grained + * control on the naming of the temporary filename. + * + * @param tempFileName + * the temporary file name + * @return a reference to this Camel File binding model + */ + GenericFileProducerBindingModel setTempFileName(String tempFileName); + + /** + * Camel 2.2: Will keep the last modified timestamp from the source file (if any). + * + * @return true to keep the last modified timestamp; false otherwise + */ + Boolean isKeepLastModified(); + + /** + * Camel 2.2: Will keep the last modified timestamp from the source file (if any). + * + * @param keepLastModified whether to keep the last modified timestamp (true), or not (false) + * @return a reference to this Camel File binding model + */ + GenericFileProducerBindingModel setKeepLastModified(Boolean keepLastModified); + + /** + * Camel 2.3: Whether or not to eagerly delete any existing target file. + * + * @return true if eagerly delete existing target file; false otherwise + */ + Boolean isEagerDeleteTargetFile(); + + /** + * Camel 2.3: Whether or not to eagerly delete any existing target file. + * + * @param eagerDeleteTargetFile true if eagerly delete existing target file; false otherwise + * @return a reference to this Camel File binding model + */ + GenericFileProducerBindingModel setEagerDeleteTargetFile(Boolean eagerDeleteTargetFile); + + /** + * Camel 2.6: If provided, then Camel will write a 2nd done file when the + * original file has been written. + * + * @return the file name to use + */ + String getDoneFileName(); + + /** + * If provided, then Camel will write a 2nd done file when the original file + * has been written. + * + * @param doneFileName the file name to use + * @return a reference to this Camel File binding model + */ + GenericFileProducerBindingModel setDoneFileName(String doneFileName); + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileBindingModel.java new file mode 100644 index 000000000..225c9e6d7 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileBindingModel.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.file.v1; + +import org.switchyard.component.camel.common.model.file.GenericFileBindingModel; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Base class for bindings of file based endpoints. + * + * @author Lukasz Dywicki + */ +public abstract class V1GenericFileBindingModel extends V1BaseCamelBindingModel + implements GenericFileBindingModel { + + /** + * The name of the 'targetDir' element. + */ + public static final String DIRECTORY = "directory"; + + /** + * The name of the 'autoCreate' element. + */ + private static final String AUTO_CREATE = "autoCreate"; + + /** + * The name of the 'bufferSize' element. + */ + private static final String BUFFER_SIZE = "bufferSize"; + + /** + * The name of the 'fileName' element. + */ + private static final String FILE_NAME = "fileName"; + + /** + * The name of the 'flatten' element. + */ + private static final String FLATTEN = "flatten"; + + /** + * The name of the 'charset' element. + */ + private static final String CHARSET = "charset"; + + /** + * Creates a binding with specified type. + * + * @param type Type of binding. + * @param namespace Namespace of the binding + */ + protected V1GenericFileBindingModel(String type, String namespace) { + super(type, namespace); + + setModelChildrenOrder(DIRECTORY, AUTO_CREATE, BUFFER_SIZE, FILE_NAME, FLATTEN, CHARSET); + } + + /** + * Create a binding from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + protected V1GenericFileBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getDirectory() { + return getConfig(DIRECTORY); + } + + @Override + public V1GenericFileBindingModel setDirectory(String targetDir) { + return setConfig(DIRECTORY, targetDir); + } + + @Override + public Boolean isAutoCreate() { + return getBooleanConfig(AUTO_CREATE); + } + + @Override + public V1GenericFileBindingModel setAutoCreate(Boolean autoCreate) { + return setConfig(AUTO_CREATE, autoCreate); + } + + @Override + public Integer getBufferSize() { + return getIntegerConfig(BUFFER_SIZE); + } + + @Override + public V1GenericFileBindingModel setBufferSize(Integer bufferSize) { + return setConfig(BUFFER_SIZE, bufferSize); + } + + @Override + public String getFileName() { + return getConfig(FILE_NAME); + } + + @Override + public V1GenericFileBindingModel setFileName(String fileName) { + return setConfig(FILE_NAME, fileName); + } + + @Override + public Boolean isFlatten() { + return getBooleanConfig(FLATTEN); + } + + @Override + public V1GenericFileBindingModel setFlatten(Boolean flatten) { + return setConfig(FLATTEN, flatten); + } + + @Override + public String getCharset() { + return getConfig(CHARSET); + } + + @Override + public V1GenericFileBindingModel setCharset(String charset) { + return setConfig(CHARSET, charset); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileConsumerBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileConsumerBindingModel.java new file mode 100644 index 000000000..868b6d978 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileConsumerBindingModel.java @@ -0,0 +1,388 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.file.v1; + +import org.switchyard.component.camel.common.model.file.GenericFileConsumerBindingModel; +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledBatchPollConsumer; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of 1st version for file consumer bindings. + * + * @author Lukasz Dywicki + */ +public class V1GenericFileConsumerBindingModel extends V1CamelScheduledBatchPollConsumer + implements GenericFileConsumerBindingModel { + + /** + * The name of the 'recursive' element. + */ + public static final String RECURSIVE = "recursive"; + + /** + * The name of the 'delete' element. + */ + public static final String DELETE = "delete"; + + /** + * The name of the 'noop' element. + */ + public static final String NOOP = "noop"; + + /** + * The name of the 'preMove' element. + */ + public static final String PRE_MOVE = "preMove"; + + /** + * The name of the 'move' element. + */ + public static final String MOVE = "move"; + + /** + * The name of the 'moveFailed' element. + */ + public static final String MOVE_FAILED = "moveFailed"; + + /** + * The name of the 'include' element. + */ + public static final String INCLUDE = "include"; + + /** + * The name of the 'exclude' element. + */ + public static final String EXCLUDE = "exclude"; + + /** + * The name of the 'idempotent' element. + */ + public static final String IDEMPOTENT = "idempotent"; + + /** + * The name of the 'idempotentRepository' element. + */ + public static final String IDEMPOTENT_REPOSITORY = "idempotentRepository"; + + /** + * The name of the 'inProgressRepository' element. + */ + public static final String IN_PROGRESS_REPOSITORY = "inProgressRepository"; + + /** + * The name of the 'filter' element. + */ + public static final String FILTER = "filter"; + + /** + * The name of the 'sorter' element. + */ + public static final String SORTER = "sorter"; + + /** + * The name of the 'sortBy' element. + */ + public static final String SORT_BY = "sortBy"; + + /** + * The name of the 'readLock' element. + */ + public static final String READ_LOCK = "readLock"; + + /** + * The name of the 'readLockTimeout' element. + */ + public static final String READ_LOCK_TIMEOUT = "readLockTimeout"; + + /** + * The name of the 'readLockCheckInterval' element. + */ + public static final String READ_LOCK_CHECK_INTERVAL = "readLockCheckInterval"; + + /** + * The name of the 'exclusiveReadLockStrategy' element. + */ + public static final String EXCLUSIVE_READ_LOCK_STRATEGY = "exclusiveReadLockStrategy"; + + /** + * The name of the 'processStrategy' element. + */ + public static final String PROCESS_STRATEGY = "processStrategy"; + + /** + * The name of the 'startingDirectoryMustExist' element. + */ + public static final String STARTING_DIRECTORY_MUST_EXIST = "startingDirectoryMustExist"; + + /** + * The name of the 'directoryMustExist' element. + */ + public static final String DIRECTORY_MUST_EXIST = "directoryMustExist"; + + /** + * The name of the 'doneFileName' element. + */ + public static final String DONE_FILE_NAME = "doneFileName"; + + /** + * Creates model bound to given namespace. + * + * @param namespace Namespace to bound. + * @param name Name of element. + */ + public V1GenericFileConsumerBindingModel(String namespace, String name) { + super(namespace, name); + + setModelChildrenOrder( + DELETE, RECURSIVE, NOOP, PRE_MOVE, MOVE, MOVE_FAILED, INCLUDE, EXCLUDE, + IDEMPOTENT, IDEMPOTENT_REPOSITORY, IN_PROGRESS_REPOSITORY, + FILTER, SORTER, SORT_BY, READ_LOCK, READ_LOCK_TIMEOUT, + READ_LOCK_CHECK_INTERVAL, EXCLUSIVE_READ_LOCK_STRATEGY, + PROCESS_STRATEGY, + STARTING_DIRECTORY_MUST_EXIST, DIRECTORY_MUST_EXIST, + DONE_FILE_NAME); + } + + /** + * Create a binding model from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1GenericFileConsumerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public Boolean isRecursive() { + return getBooleanConfig(RECURSIVE); + } + + @Override + public V1GenericFileConsumerBindingModel setRecursive(Boolean recursive) { + return setConfig(RECURSIVE, recursive); + } + + @Override + public Boolean isDelete() { + return getBooleanConfig(DELETE); + } + + @Override + public V1GenericFileConsumerBindingModel setDelete(Boolean delete) { + return setConfig(DELETE, delete); + } + + @Override + public Boolean isNoop() { + return getBooleanConfig(NOOP); + } + + @Override + public V1GenericFileConsumerBindingModel setNoop(Boolean noop) { + return setConfig(NOOP, noop); + } + + @Override + public String getPreMove() { + return getConfig(PRE_MOVE); + } + + @Override + public V1GenericFileConsumerBindingModel setPreMove(String preMove) { + return setConfig(PRE_MOVE, preMove); + } + + @Override + public String getMove() { + return getConfig(MOVE); + } + + @Override + public V1GenericFileConsumerBindingModel setMove(String move) { + return setConfig(MOVE, move); + } + + @Override + public String getMoveFailed() { + return getConfig(MOVE_FAILED); + } + + @Override + public V1GenericFileConsumerBindingModel setMoveFailed(String moveFailed) { + return setConfig(MOVE_FAILED, moveFailed); + } + + @Override + public String getInclude() { + return getConfig(INCLUDE); + } + + @Override + public V1GenericFileConsumerBindingModel setInclude(String include) { + return setConfig(INCLUDE, include); + } + + @Override + public String getExclude() { + return getConfig(EXCLUDE); + } + + @Override + public V1GenericFileConsumerBindingModel setExclude(String exclude) { + return setConfig(EXCLUDE, exclude); + } + + @Override + public Boolean isIdempotent() { + return getBooleanConfig(IDEMPOTENT); + } + + @Override + public V1GenericFileConsumerBindingModel setIdempotent(Boolean idempotent) { + return setConfig(IDEMPOTENT, idempotent); + } + + @Override + public String getIdempotentRepository() { + return getConfig(IDEMPOTENT_REPOSITORY); + } + + @Override + public V1GenericFileConsumerBindingModel setIdempotentRepository(String idempotentRepository) { + return setConfig(IDEMPOTENT_REPOSITORY, idempotentRepository); + } + + @Override + public String getInProgressRepository() { + return getConfig(IN_PROGRESS_REPOSITORY); + } + + @Override + public V1GenericFileConsumerBindingModel setInProgressRepository(String inProgressRepository) { + return setConfig(IN_PROGRESS_REPOSITORY, inProgressRepository); + } + + @Override + public String getFilter() { + return getConfig(FILTER); + } + + @Override + public V1GenericFileConsumerBindingModel setFilter(String filter) { + return setConfig(FILTER, filter); + } + + @Override + public String getSorter() { + return getConfig(SORTER); + } + + @Override + public V1GenericFileConsumerBindingModel setSorter(String sorter) { + return setConfig(SORTER, sorter); + } + + @Override + public String getSortBy() { + return getConfig(SORT_BY); + } + + @Override + public V1GenericFileConsumerBindingModel setSortBy(String sortBy) { + return setConfig(SORT_BY, sortBy); + } + + @Override + public String getReadLock() { + return getConfig(READ_LOCK); + } + + @Override + public V1GenericFileConsumerBindingModel setReadLock(String readLock) { + return setConfig(READ_LOCK, readLock); + } + + @Override + public Long getReadLockTimeout() { + return getLongConfig(READ_LOCK_TIMEOUT); + } + + @Override + public V1GenericFileConsumerBindingModel setReadLockTimeout(Long readLockTimeout) { + return setConfig(READ_LOCK_TIMEOUT, readLockTimeout); + } + + @Override + public Integer getReadLockCheckInterval() { + return getIntegerConfig(READ_LOCK_CHECK_INTERVAL); + } + + @Override + public V1GenericFileConsumerBindingModel setReadLockCheckInterval(Integer readLockCheckInterval) { + return setConfig(READ_LOCK_CHECK_INTERVAL, readLockCheckInterval); + } + + @Override + public String getExclusiveReadLockStrategy() { + return getConfig(EXCLUSIVE_READ_LOCK_STRATEGY); + } + + @Override + public V1GenericFileConsumerBindingModel setExclusiveReadLockStrategy(String exclusiveReadLockStrategy) { + return setConfig(EXCLUSIVE_READ_LOCK_STRATEGY, exclusiveReadLockStrategy); + } + + @Override + public String getProcessStrategy() { + return getConfig(PROCESS_STRATEGY); + } + + @Override + public V1GenericFileConsumerBindingModel setProcessStrategy(String processStrategy) { + return setConfig(PROCESS_STRATEGY, processStrategy); + } + + @Override + public Boolean isStartingDirectoryMustExist() { + return getBooleanConfig(STARTING_DIRECTORY_MUST_EXIST); + } + + @Override + public V1GenericFileConsumerBindingModel setStartingDirectoryMustExist(Boolean startingDirectoryMustExist) { + return setConfig(STARTING_DIRECTORY_MUST_EXIST, startingDirectoryMustExist); + } + + @Override + public Boolean isDirectoryMustExist() { + return getBooleanConfig(DIRECTORY_MUST_EXIST); + } + + @Override + public V1GenericFileConsumerBindingModel setDirectoryMustExist(Boolean directoryMustExist) { + return setConfig(DIRECTORY_MUST_EXIST, directoryMustExist); + } + + @Override + public String getDoneFileName() { + return getConfig(DONE_FILE_NAME); + } + + @Override + public V1GenericFileConsumerBindingModel setDoneFileName(String doneFileName) { + return setConfig(DONE_FILE_NAME, doneFileName); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileProducerBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileProducerBindingModel.java new file mode 100644 index 000000000..cfa69cf23 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/file/v1/V1GenericFileProducerBindingModel.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.file.v1; + +import org.switchyard.component.camel.common.model.file.GenericFileProducerBindingModel; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Base implementation for file producers (both filesystem and remote). + * + * @author Lukasz Dywicki + */ +public abstract class V1GenericFileProducerBindingModel extends V1BaseCamelModel + implements GenericFileProducerBindingModel { + + /** + * The name of the 'fileExist' element. + */ + public static final String FILE_EXIST = "fileExist"; + + /** + * The name of the 'tempPrefix' element. + */ + public static final String TEMP_PREFIX = "tempPrefix"; + + /** + * The name of the 'tempFileName' element. + */ + public static final String TEMP_FILENAME = "tempFileName"; + + /** + * The name of the 'keepLastModified' element. + */ + public static final String KEEP_LAST_MODIFIED = "keepLastModified"; + + /** + * The name of the 'eagerDeleteTargetFile' element. + */ + public static final String EAGER_DELETE_TARGET_FILE = "eagerDeleteTargetFile"; + + /** + * The name of the 'doneFileName' element. + */ + public static final String DONE_FILE_NAME = "doneFileName"; + + /** + * Create a binding model bound to given namespace. + * + * @param namespace Namespace to bound. + * @param name Element name. + */ + public V1GenericFileProducerBindingModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(FILE_EXIST, TEMP_PREFIX, TEMP_FILENAME, + KEEP_LAST_MODIFIED, EAGER_DELETE_TARGET_FILE, DONE_FILE_NAME); + } + + /** + * Create a binding model from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1GenericFileProducerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getFileExist() { + return getConfig(FILE_EXIST); + } + + @Override + public V1GenericFileProducerBindingModel setFileExist(String fileExist) { + return setConfig(FILE_EXIST, fileExist); + } + + @Override + public String getTempPrefix() { + return getConfig(TEMP_PREFIX); + } + + @Override + public V1GenericFileProducerBindingModel setTempPrefix(String tempPrefix) { + return setConfig(TEMP_PREFIX, tempPrefix); + } + + @Override + public String getTempFileName() { + return getConfig(TEMP_FILENAME); + } + + @Override + public V1GenericFileProducerBindingModel setTempFileName(String tempFileName) { + return setConfig(TEMP_FILENAME, tempFileName); + } + + @Override + public Boolean isKeepLastModified() { + return getBooleanConfig(KEEP_LAST_MODIFIED); + } + + @Override + public V1GenericFileProducerBindingModel setKeepLastModified(Boolean keepLastModified) { + return setConfig(KEEP_LAST_MODIFIED, keepLastModified); + } + + @Override + public Boolean isEagerDeleteTargetFile() { + return getBooleanConfig(EAGER_DELETE_TARGET_FILE); + } + + @Override + public V1GenericFileProducerBindingModel setEagerDeleteTargetFile(Boolean eagerDeleteTargetFile) { + return setConfig(EAGER_DELETE_TARGET_FILE, eagerDeleteTargetFile); + } + + @Override + public String getDoneFileName() { + return getConfig(DONE_FILE_NAME); + } + + @Override + public V1GenericFileProducerBindingModel setDoneFileName(String doneFileName) { + return setConfig(DONE_FILE_NAME, doneFileName); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileBindingModel.java new file mode 100644 index 000000000..637983ba1 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileBindingModel.java @@ -0,0 +1,262 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.remote; + +import org.switchyard.component.camel.common.model.file.GenericFileBindingModel; + +/** + * Remote file endpoint configuration. + * + * @author Lukasz Dywicki + */ +public interface CamelRemoteFileBindingModel extends GenericFileBindingModel { + + /** + * Path separator enumeration. + */ + public enum PathSeparator { + /** + * Unix style path separator. + */ + UNIX, + /** + * Windows style path separator. + */ + Windows, + /** + * Enables auto detection of path separator. + */ + Auto + }; + + /** + * Gets host name / ip. + * + * @return Host name. + */ + String getHost(); + + /** + * Sets host name. + * + * @param host Host name. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setHost(String host); + + /** + * Gets connection port. + * + * @return Port number used to connect remote server. + */ + Integer getPort(); + + /** + * Sets port to use during connection. + * + * @param port Port number. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setPort(int port); + + /** + * Gets user name. + * + * @return Username used to authenticate connection. + */ + String getUsername(); + + /** + * Specifies the username to use to log in to the remote file system. + * + * @param username Username. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setUsername(String username); + + /** + * Gets password. + * + * @return Password used to authenticate connection. + */ + String getPassword(); + + /** + * Specifies the password to use to log in to the remote file system. + * + * @param password Password. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setPassword(String password); + + /** + * Should transfer be treat as binary? + * + * @return Binary transfer. + */ + Boolean isBinary(); + + /** + * Specifies the file transfer mode, BINARY or ASCII. Default is ASCII (false). + * + * @param binary Should transfer be binary. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setBinary(boolean binary); + + /** + * Gets connect timeout. + * + * @return Connect timeout (in milliseconds). + */ + Integer getConnectTimeout(); + + /** + * Sets connect timeout (in milliseconds). + * + * @param timeout Timeout. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setConnectionTimeout(int timeout); + + /** + * Should exception be thrown when connection is failed? + * + * @return Throw exception if value is set to true. Skip otherwise. + */ + Boolean isThrowExceptionOnConnectFailed(); + + /** + * Sets endpoint behavior during connection problems. + * + * @param throwException Throw exception when connection is failed. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setThrowExceptionOnConnectFailed(boolean throwException); + + /** + * Gets stepwise flag value. + * + * @return True if camel consumer is configured in stepwise mode. + */ + Boolean isStepwise(); + + /** + * Whether or not stepwise traversing directories should be used or not. + * Stepwise means that it will CD one directory at a time. See more details below. + * You can disable this in case you can't use this approach. + * + * @param stepwise Should camel do CD every time. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setStepwise(boolean stepwise); + + /** + * Gets path separator. + * + * @return Path separator. + */ + PathSeparator getSeparator(); + + /** + * Dictates what path separator char to use when uploading files. + * Auto = Use the path provided without altering it. + * UNIX = Use unix style path separators. + * Windows = Use Windows style path separators. + * + * @param separator Directory separator. + * @return a reference to this binding model + */ + CamelRemoteFileBindingModel setSeparator(String separator); + + /** + * Specifies the maximum reconnect attempts Camel performs when it tries to + * connect to the remote server. Use 0 to disable this behavior. + * + * @return Number of maximum reconnect attempts. + */ + Integer getMaximumReconnectAttempts(); + + /** + * Sets number of reconnect attempts. By default it is 3. + * + * @param maximumReconnectAttempts Number of attempts. 0 to do not try again. + * @return a reference to this binding model. + */ + CamelRemoteFileBindingModel setMaximumReconnectAttempts(Integer maximumReconnectAttempts); + + /** + * Delay in millis Camel will wait before performing a reconnect attempt. + * + * @return delay between reconnect attempts. + */ + Integer getReconnectDelay(); + + /** + * Specifies delay in milliseconds between reconnect attempts. + * + * @param reconnectDelay Delay. + * @return a reference to this binding model. + */ + CamelRemoteFileBindingModel setReconnectDelay(Integer reconnectDelay); + + /** + * Whether or not to disconnect from remote FTP server right after use. + * Can be used for both consumer and producer. Disconnect will only disconnect + * the current connection to the FTP server. If you have a consumer which you want to stop, + * then you need to stop the consumer/route instead. + * + * @return Should producer/consumer be disconnected every time. + */ + Boolean getDisconnect(); + + /** + * Specifies if producer/consumer should close connection after operation. + * + * @param disconnect Should connection be closed after operation? + * @return a reference to this binding model. + */ + CamelRemoteFileBindingModel setDisconnect(Boolean disconnect); + + /** + * The consumer's configurations. + * + * @return an instance of the camel remote file consumer binding model + */ + public CamelRemoteFileConsumerBindingModel getConsumer(); + + /** + * Specify the consumer binding model. + * + * @param consumer The consumer binding model + * @return a reference to this binding model + */ + public CamelRemoteFileBindingModel setConsumer(CamelRemoteFileConsumerBindingModel consumer); + + /** + * The producer's configurations. + * + * @return an instance of the camel remote file producer binding model + */ + public CamelRemoteFileProducerBindingModel getProducer(); + + /** + * Specify the producer binding model. + * + * @param producer The producer binding model + * @return a reference to this binding model + */ + public CamelRemoteFileBindingModel setProducer(CamelRemoteFileProducerBindingModel producer); + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileConsumerBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileConsumerBindingModel.java new file mode 100644 index 000000000..d2e50d639 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileConsumerBindingModel.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.remote; + +import org.switchyard.component.camel.common.model.file.GenericFileConsumerBindingModel; + +/** + * Camel remote file consumer binding. + * + * @author Lukasz Dywicki + */ +public interface CamelRemoteFileConsumerBindingModel extends GenericFileConsumerBindingModel { + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileProducerBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileProducerBindingModel.java new file mode 100644 index 000000000..55361572a --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/CamelRemoteFileProducerBindingModel.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.remote; + +import org.switchyard.component.camel.common.model.file.GenericFileProducerBindingModel; + +/** + * Remote file producer model. + * + * @author Lukasz Dywicki + */ +public interface CamelRemoteFileProducerBindingModel extends GenericFileProducerBindingModel { + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileBindingModel.java new file mode 100644 index 000000000..95fb60072 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileBindingModel.java @@ -0,0 +1,343 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.remote.v1; + +import java.net.URI; +import java.util.List; + +import org.switchyard.component.camel.common.CommonCamelMessages; +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.file.v1.V1GenericFileBindingModel; +import org.switchyard.component.camel.common.model.remote.CamelRemoteFileBindingModel; +import org.switchyard.component.camel.common.model.remote.CamelRemoteFileConsumerBindingModel; +import org.switchyard.component.camel.common.model.remote.CamelRemoteFileProducerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Base class for remote file endpoint configurations. + * + * @author Lukasz Dywicki + */ +public abstract class V1CamelRemoteFileBindingModel extends V1GenericFileBindingModel + implements CamelRemoteFileBindingModel { + + /** + * Name of 'directory' element. + */ + private static final String DIRECTORY = "directory"; + + /** + * Name of 'host' element. + */ + private static final String HOST = "host"; + + /** + * Name of 'port' element. + */ + private static final String PORT = "port"; + + /** + * Name of 'username' element. + */ + private static final String USERNAME = "username"; + + /** + * Name of 'password' element. + */ + private static final String PASSWORD = "password"; + + /** + * Name of 'binary' element. + */ + private static final String BINARY = "binary"; + + /** + * Name of 'connectTimeout' element. + */ + private static final String CONNECTION_TIMEOUT = "connectTimeout"; + + /** + * Name of 'throwExceptionOnConnectFailed' element. + */ + private static final String THROW_EXCEPTION_ON_CONNECT_FAILED = "throwExceptionOnConnectFailed"; + + /** + * Name of 'stepwise' element. + */ + private static final String STEPWISE = "stepwise"; + + /** + * Name of 'separator' element. + */ + private static final String SEPARATOR = "separator"; + + /** + * Name of 'separator' element. + */ + private static final String RECONNECT_DELAY = "reconnectDelay"; + + /** + * Name of 'separator' element. + */ + private static final String MAXIMUM_RECONNECT_ATTEMPTS = "maximumReconnectAttempts"; + + /** + * Name of 'separator' element. + */ + private static final String DISCONNECT = "disconnect"; + + /** + * Remote file consumer. + */ + private CamelRemoteFileConsumerBindingModel _consume; + + /** + * Remote file producer. + */ + private CamelRemoteFileProducerBindingModel _produce; + + /** + * Create a CamelRemoteBindingModel from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param descriptor The switchyard descriptor instance. + */ + public V1CamelRemoteFileBindingModel(Configuration config, Descriptor descriptor) { + super(config, descriptor); + } + + /** + * Creates CamelRemoteBindingModel with given protocol name. + * + * @param protocol Protocol prefix in uri. + * @param namespace Namespace prefix. + */ + protected V1CamelRemoteFileBindingModel(String protocol, String namespace) { + super(protocol, namespace); + + setModelChildrenOrder( + HOST, PORT, USERNAME, PASSWORD, BINARY, CONNECTION_TIMEOUT, DISCONNECT, + MAXIMUM_RECONNECT_ATTEMPTS, RECONNECT_DELAY, SEPARATOR, STEPWISE, + THROW_EXCEPTION_ON_CONNECT_FAILED + ); + } + + @Override + public String getUsername() { + return getConfig(USERNAME); + } + + @Override + public V1CamelRemoteFileBindingModel setUsername(String username) { + return setConfig(USERNAME, username); + } + + @Override + public String getHost() { + return getConfig(HOST); + } + + @Override + public V1CamelRemoteFileBindingModel setHost(String host) { + return setConfig(HOST, host); + } + + @Override + public Integer getPort() { + return getIntegerConfig(PORT); + } + + @Override + public V1CamelRemoteFileBindingModel setPort(int port) { + return setConfig(PORT, (port)); + } + + @Override + public String getDirectory() { + return getConfig(DIRECTORY); + } + + @Override + public V1CamelRemoteFileBindingModel setDirectory(String directory) { + return setConfig(DIRECTORY, directory); + } + + @Override + public String getPassword() { + return getConfig(PASSWORD); + } + + @Override + public V1CamelRemoteFileBindingModel setPassword(String password) { + return setConfig(PASSWORD, password); + } + + @Override + public Boolean isBinary() { + return getBooleanConfig(BINARY); + } + + @Override + public V1CamelRemoteFileBindingModel setBinary(boolean binary) { + return setConfig(BINARY, binary); + } + + @Override + public Integer getConnectTimeout() { + return getIntegerConfig(CONNECTION_TIMEOUT); + } + + @Override + public V1CamelRemoteFileBindingModel setConnectionTimeout(int timeout) { + return setConfig(CONNECTION_TIMEOUT, timeout); + } + + @Override + public Boolean isThrowExceptionOnConnectFailed() { + return getBooleanConfig(THROW_EXCEPTION_ON_CONNECT_FAILED); + } + + @Override + public V1CamelRemoteFileBindingModel setThrowExceptionOnConnectFailed(boolean throwException) { + return setConfig(THROW_EXCEPTION_ON_CONNECT_FAILED, throwException); + } + + @Override + public Boolean isStepwise() { + return getBooleanConfig(STEPWISE); + } + + @Override + public V1CamelRemoteFileBindingModel setStepwise(boolean stepwise) { + return setConfig(STEPWISE, stepwise); + } + + @Override + public PathSeparator getSeparator() { + return getEnumerationConfig(SEPARATOR, PathSeparator.class); + } + + @Override + public V1CamelRemoteFileBindingModel setSeparator(String separator) { + return setConfig(SEPARATOR, separator); + } + + @Override + public Integer getMaximumReconnectAttempts() { + return getIntegerConfig(MAXIMUM_RECONNECT_ATTEMPTS); + } + + @Override + public V1CamelRemoteFileBindingModel setMaximumReconnectAttempts(Integer maximumReconnectAttempts) { + return setConfig(MAXIMUM_RECONNECT_ATTEMPTS, maximumReconnectAttempts); + } + + @Override + public Integer getReconnectDelay() { + return getIntegerConfig(RECONNECT_DELAY); + } + + @Override + public V1CamelRemoteFileBindingModel setReconnectDelay(Integer reconnectDelay) { + return setConfig(RECONNECT_DELAY, reconnectDelay); + } + + @Override + public Boolean getDisconnect() { + return getBooleanConfig(DISCONNECT); + } + + @Override + public V1CamelRemoteFileBindingModel setDisconnect(Boolean disconnect) { + return setConfig(DISCONNECT, disconnect); + } + + @Override + public CamelRemoteFileConsumerBindingModel getConsumer() { + if (_consume == null) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + _consume = new V1CamelRemoteFileConsumerBindingModel(config, + getModelDescriptor()); + } + return _consume; + } + + @Override + public V1CamelRemoteFileBindingModel setConsumer(CamelRemoteFileConsumerBindingModel consumer) { + Configuration config = getModelConfiguration().getFirstChild(CONSUME); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(CONSUME); + getModelConfiguration().addChild(((V1CamelRemoteFileConsumerBindingModel) consumer) + .getModelConfiguration()); + } else { + setChildModel((V1CamelRemoteFileConsumerBindingModel) consumer); + } + _consume = consumer; + return this; + } + + @Override + public CamelRemoteFileProducerBindingModel getProducer() { + if (_produce == null) { + Configuration config = getModelConfiguration().getFirstChild(PRODUCE); + _produce = new V1CamelRemoteFileProducerBindingModel(config, + getModelDescriptor()); + } + return _produce; + } + + @Override + public V1CamelRemoteFileBindingModel setProducer(CamelRemoteFileProducerBindingModel producer) { + Configuration config = getModelConfiguration().getFirstChild(PRODUCE); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(PRODUCE); + getModelConfiguration().addChild(((V1CamelRemoteFileProducerBindingModel) producer) + .getModelConfiguration()); + } else { + setChildModel((V1CamelRemoteFileProducerBindingModel) producer); + } + _produce = producer; + return this; + } + + @Override + public URI getComponentURI() { + Configuration modelConfiguration = getModelConfiguration(); + List children = modelConfiguration.getChildren(); + + String username = ""; + if (getUsername() != null && getPassword() != null) { + username = getUsername() + ":" + getPassword() + "@"; + } else if (getUsername() != null && getPassword() == null) { + username = getUsername() + "@"; + } else if (getUsername() == null && getPassword() != null) { + throw CommonCamelMessages.MESSAGES.configurationProvidesPasswordButDoNotSpecifyUser(); + } + + String baseUri = getEndpointProtocol() + "://" + username + getHost(); + baseUri += getPort() != null ? ":" + getPort() : ""; + baseUri += getDirectory() != null ? "/" + getDirectory() : ""; + + QueryString queryStr = new QueryString(); + traverseConfiguration(children, queryStr, HOST, PORT, USERNAME, PASSWORD, DIRECTORY); + + return URI.create(baseUri + queryStr.toString()); + } + + protected abstract String getEndpointProtocol(); + protected abstract void enrichQueryString(QueryString queryString); +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileConsumerBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileConsumerBindingModel.java new file mode 100644 index 000000000..fb8ba57a7 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileConsumerBindingModel.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.remote.v1; + +import org.switchyard.component.camel.common.model.file.v1.V1GenericFileConsumerBindingModel; +import org.switchyard.component.camel.common.model.remote.CamelRemoteFileConsumerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Consumer binding model for remote file. + * + * @author Lukasz Dywicki + */ +public class V1CamelRemoteFileConsumerBindingModel extends V1GenericFileConsumerBindingModel + implements CamelRemoteFileConsumerBindingModel { + + /** + * Creates consumer binding model. + * + * @param config Configuration. + * @param desc Descriptor. + */ + public V1CamelRemoteFileConsumerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Creates model bound to given namespace. + * + * @param namespace Namespace to bound. + * @param name Name of element. + */ + public V1CamelRemoteFileConsumerBindingModel(String namespace, String name) { + super(namespace, name); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileProducerBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileProducerBindingModel.java new file mode 100644 index 000000000..8577e0deb --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/remote/v1/V1CamelRemoteFileProducerBindingModel.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.remote.v1; + +import org.switchyard.component.camel.common.model.file.v1.V1GenericFileProducerBindingModel; +import org.switchyard.component.camel.common.model.remote.CamelRemoteFileProducerBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Binding model for remote producers. + * + * @author Lukasz Dywicki + */ +public class V1CamelRemoteFileProducerBindingModel extends V1GenericFileProducerBindingModel + implements CamelRemoteFileProducerBindingModel { + + /** + * Creates model bound to given namespace. + * + * @param namespace Namespace to bound. + * @param name Name of element. + */ + public V1CamelRemoteFileProducerBindingModel(String namespace, String name) { + super(namespace, name); + } + + /** + * Create a binding model from the specified configuration and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelRemoteFileProducerBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/NameValueModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/NameValueModel.java new file mode 100644 index 000000000..dc803cd93 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/NameValueModel.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; + +/** + * Generic configuration interface used to represent a basic name to value mapping + * for a child configuration, e.g. + *

+ *
+ *    value
+ * 
+ *
+ */ +public class NameValueModel extends BaseModel { + + /** + * Create a new NameValueModel with the specified name. + * + * @param namespace Config namespace. + * @param name Config name + */ + public NameValueModel(String namespace, String name) { + super(new QName(namespace, name)); + } + + /** + * Create a new NameValueModel based on an existing config element. + * @param config configuration element + */ + public NameValueModel(Configuration config) { + super(config); + } + + /** + * Get the config value. + * @return config value + */ + public String getValue() { + return super.getModelValue(); + } + + /** + * Set the config value. + * @param value config value + */ + public void setValue(String value) { + super.setModelValue(value); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1AdditionalUriParametersModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1AdditionalUriParametersModel.java new file mode 100644 index 000000000..f504d8a49 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1AdditionalUriParametersModel.java @@ -0,0 +1,117 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @author tags. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.switchyard.component.camel.common.model.v1; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.component.camel.common.model.AdditionalUriParametersModel; +import org.switchyard.component.camel.common.model.ParameterModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 AdditionalUriParametersModel. + */ +public class V1AdditionalUriParametersModel extends BaseModel implements AdditionalUriParametersModel { + + private List _parameters = new ArrayList(); + + /** + * + * Create a new AdditionalUriParametersModel. + * + * @param namespace Namespace name + */ + public V1AdditionalUriParametersModel(String namespace) { + super(namespace, ADDITIONAL_URI_PARAMETERS); + } + + /** + * Create a AdditionalUriParametersModel from the specified configuration + * and descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1AdditionalUriParametersModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration parameter_config : config.getChildren(ParameterModel.PARAMETER)) { + ParameterModel parameter = new V1ParameterModel(parameter_config, desc); + if (parameter != null) { + _parameters.add(parameter); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getParameters() { + return Collections.unmodifiableList(_parameters); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized AdditionalUriParametersModel addParameter(ParameterModel parameter) { + addChildModel(parameter); + _parameters.add(parameter); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ParameterModel removeParameter(String parameterName) { + ParameterModel removed = null; + + for (ParameterModel parameter : _parameters) { + if (parameter.getName().equals(parameterName)) { + removed = parameter; + _parameters.remove(parameter); + } + } + return removed; + } + + /** + * {@inheritDoc} + */ + @Override + public Map toMap() { + Map map = new HashMap(); + for (ParameterModel pm : getParameters()) { + String name = pm.getName(); + String value = pm.getValue(); + if (name != null && value != null) { + map.put(name, value); + } + } + return map; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelBindingModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelBindingModel.java new file mode 100644 index 000000000..066e84cc7 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelBindingModel.java @@ -0,0 +1,261 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.v1; + +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.apache.camel.util.UnsafeUriCharactersEncoder; +import org.switchyard.component.camel.common.CommonCamelMessages; +import org.switchyard.component.camel.common.QueryString; +import org.switchyard.component.camel.common.model.AdditionalUriParametersModel; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.common.model.ParameterModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.Configurations; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.v1.V1BindingModel; + +/** + * Version 1.0 implementation of a {@link CamelBindingModel}. + * + * @author Daniel Bevenius + */ +public abstract class V1BaseCamelBindingModel extends V1BindingModel + implements CamelBindingModel { + + /** + * Camel endpoint type. + */ + public static final String CAMEL = "camel"; + + private Configuration _environment = Configurations.newConfiguration(); + private AdditionalUriParametersModel _additionalUriParameters; + + /** + * + * Create a new CamelBindingModel. + * + * @param type Binding type + * @param namespace Namespace name + */ + public V1BaseCamelBindingModel(String type, String namespace) { + super(type, namespace); + } + + /** + * Create a CamelBindingModel from the specified configuration and + * descriptor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1BaseCamelBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * Returns the global configuration. + * + * @return the environment/global config + */ + public Configuration getEnvironment() { + return _environment; + } + + /** + * Sets the global configuration. + * + * @param config the environment/global config + */ + public void setEnvironment(Configuration config) { + _environment = config; + } + + @Override + protected Model setModelChildrenOrder(String... childrenOrder) { + Set mco = new LinkedHashSet(); + mco.add(AdditionalUriParametersModel.ADDITIONAL_URI_PARAMETERS); + if (childrenOrder != null) { + mco.addAll(Arrays.asList(childrenOrder)); + } + super.setModelChildrenOrder(mco.toArray(new String[mco.size()])); + return this; + } + + @Override + public AdditionalUriParametersModel getAdditionalUriParameters() { + if (_additionalUriParameters == null) { + Configuration config = getModelConfiguration().getFirstChild( + AdditionalUriParametersModel.ADDITIONAL_URI_PARAMETERS); + if (config == null) { + return null; + } + _additionalUriParameters = new V1AdditionalUriParametersModel(config, getModelDescriptor()); + } + return _additionalUriParameters; + } + + @Override + public CamelBindingModel setAdditionalUriParameters(AdditionalUriParametersModel parameters) { + Configuration config = getModelConfiguration().getFirstChild( + AdditionalUriParametersModel.ADDITIONAL_URI_PARAMETERS); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(AdditionalUriParametersModel.ADDITIONAL_URI_PARAMETERS); + getModelConfiguration().addChild(((V1AdditionalUriParametersModel) parameters).getModelConfiguration()); + } else { + setChildModel((V1AdditionalUriParametersModel) parameters); + } + _additionalUriParameters = parameters; + return this; + } + + protected final void traverseConfiguration(List parent, QueryString queryString, + String ... excludes) { + + if (parent.size() != 0) { + List excludeParameters = new ArrayList(Arrays.asList(excludes)); + + // ignore additional URI parameters + excludeParameters.add(AdditionalUriParametersModel.ADDITIONAL_URI_PARAMETERS); + + traverseConfigurationInternal(parent, queryString, excludeParameters); + + // add additional URI parameters + final AdditionalUriParametersModel additionalParametersModel = getAdditionalUriParameters(); + if (additionalParametersModel != null) { + for (ParameterModel parameter : additionalParametersModel.getParameters()) { + if (parameter == null || parameter.getName() == null || excludeParameters.contains(parameter.getName())) { + continue; + } + queryString.add(parameter.getName(), UnsafeUriCharactersEncoder.encode(parameter.getValue())); + excludeParameters.add(parameter.getName()); + } + } + } + } + + private void traverseConfigurationInternal(List parent, QueryString queryString, + List excludes) { + + if (parent.size() != 0) { + Iterator parentIterator = parent.iterator(); + while (parentIterator.hasNext()) { + Configuration child = parentIterator.next(); + + if (child == null || child.getName() == null || excludes.contains(child.getName())) { + continue; + } + + if (child.getChildren().size() == 0) { + queryString.add(child.getName(), UnsafeUriCharactersEncoder.encode(child.getValue())); + excludes.add(child.getName()); + } else { + traverseConfigurationInternal(child.getChildren(), queryString, excludes); + } + } + } + } + + protected T replaceChildren(String children, T model) { + Configuration config = getModelConfiguration().getFirstChild(children); + if (config != null) { + // set an existing config value + getModelConfiguration().removeChildren(children); + getModelConfiguration().addChild(model.getModelConfiguration()); + } else { + setChildModel(model); + } + return model; + } + + protected Configuration getFirstChild(String name) { + return getModelConfiguration().getFirstChild(name); + } + + protected final Integer getIntegerConfig(String configName) { + String value = getConfig(configName); + return value != null ? Integer.parseInt(value) : null; + } + + protected final Double getDoubleConfig(String configName) { + String value = getConfig(configName); + return value != null ? Double.parseDouble(value) : null; + } + + protected final Boolean getBooleanConfig(String configName) { + String value = getConfig(configName); + return value != null ? Boolean.valueOf(value) : null; + } + + protected final Long getLongConfig(String configName) { + String value = getConfig(configName); + return value != null ? Long.parseLong(value) : null; + } + + protected final Date getDateConfig(String configName, DateFormat format) { + String value = getConfig(configName); + if (value == null) { + return null; + } else { + try { + return format.parse(value); + } catch (java.text.ParseException parseEx) { + throw CommonCamelMessages.MESSAGES.failedToParse(configName, parseEx); + } + } + } + + protected final String getConfig(String configName) { + Configuration config = getModelConfiguration().getFirstChild(configName); + if (config != null) { + return config.getValue(); + } else { + return null; + } + } + + protected final > T getEnumerationConfig(String configName, Class type) { + String constantName = getConfig(configName); + if (constantName != null) { + return Enum.valueOf(type, constantName); + } + return null; + } + + @SuppressWarnings("unchecked") + protected X setConfig(String name, Object value) { + String modelValue = String.valueOf(value); + Configuration config = getModelConfiguration().getFirstChild(name); + if (config != null) { + // set an existing config value + config.setValue(modelValue); + } else { + // create the config model and set the value + NameValueModel model = new NameValueModel(getNamespaceURI(), name); + model.setValue(modelValue); + setChildModel(model); + } + return (X) this; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelMarshaller.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelMarshaller.java new file mode 100644 index 000000000..71b8cf789 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelMarshaller.java @@ -0,0 +1,47 @@ +package org.switchyard.component.camel.common.model.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.composer.v1.V1ContextMapperModel; +import org.switchyard.config.model.composer.v1.V1MessageComposerModel; +import org.switchyard.config.model.composite.v1.V1CompositeMarshaller; + +/** + * Base class for camel marshallers. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public abstract class V1BaseCamelMarshaller extends V1CompositeMarshaller { + + /** + * Creates new marshaller. + * + * @param desc Descriptor + */ + public V1BaseCamelMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1CompositeMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(ContextMapperModel.CONTEXT_MAPPER)) { + return new V1ContextMapperModel(config, desc); + } else if (name.equals(MessageComposerModel.MESSAGE_COMPOSER)) { + return new V1MessageComposerModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelModel.java new file mode 100644 index 000000000..99e881ae4 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1BaseCamelModel.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.v1; + +import java.text.DateFormat; +import java.util.Date; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.component.camel.common.CommonCamelMessages; + +/** + * Base class for all camel models which are not related to binding. + * + * @author Lukasz Dywicki + */ +public abstract class V1BaseCamelModel extends BaseModel { + + protected V1BaseCamelModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + protected V1BaseCamelModel(String namespace, String name) { + super(namespace, name); + } + + protected V1BaseCamelModel(Configuration config) { + super(config); + } + + protected final Integer getIntegerConfig(String configName) { + String value = getConfig(configName); + return value != null ? Integer.parseInt(value) : null; + } + + protected final Boolean getBooleanConfig(String configName) { + String value = getConfig(configName); + return value != null ? Boolean.valueOf(value) : Boolean.FALSE; + } + + protected final Long getLongConfig(String configName) { + String value = getConfig(configName); + return value != null ? Long.parseLong(value) : null; + } + + protected final Date getDateConfig(String configName, DateFormat format) { + String value = getConfig(configName); + if (value == null) { + return null; + } else { + try { + return format.parse(value); + } catch (java.text.ParseException parseEx) { + throw CommonCamelMessages.MESSAGES.failedToParse(configName, parseEx); + } + } + } + + protected final String getConfig(String configName) { + Configuration config = getModelConfiguration().getFirstChild(configName); + if (config != null) { + return config.getValue(); + } else { + return null; + } + } + + protected final > T getEnumerationConfig(String configName, Class type) { + String constantName = getConfig(configName); + if (constantName != null) { + return Enum.valueOf(type, constantName); + } + return null; + } + + @SuppressWarnings("unchecked") + protected X setConfig(String name, Object value) { + String modelValue = String.valueOf(value); + Configuration config = getModelConfiguration().getFirstChild(name); + if (config != null) { + // set an existing config value + config.setValue(modelValue); + } else { + // create the config model and set the value + NameValueModel model = new NameValueModel(getNamespaceURI(), name); + model.setValue(modelValue); + setChildModel(model); + } + return (X) this; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1CamelScheduledBatchPollConsumer.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1CamelScheduledBatchPollConsumer.java new file mode 100644 index 000000000..d5121841a --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1CamelScheduledBatchPollConsumer.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.v1; + +import org.switchyard.component.camel.common.model.consumer.CamelScheduledBatchPollConsumer; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Implementation of 1st batching poll consumer interface. + * + * @author Lukasz Dywicki + */ +public class V1CamelScheduledBatchPollConsumer extends V1CamelScheduledPollConsumer + implements CamelScheduledBatchPollConsumer { + + /** + * The name of the 'maxMessagesPerPoll' element. + */ + private static final String MAX_MESSAGES_PER_POLL = "maxMessagesPerPoll"; + + /** + * Creates model bound to given namespace. + * + * @param namespace Namespace to bound. + * @param name Name of element. + */ + public V1CamelScheduledBatchPollConsumer(String namespace, String name) { + super(namespace, name); + + setModelChildrenOrder(MAX_MESSAGES_PER_POLL); + } + + /** + * Constructor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelScheduledBatchPollConsumer(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public Integer getMaxMessagesPerPoll() { + return getIntegerConfig(MAX_MESSAGES_PER_POLL); + } + + @Override + public V1CamelScheduledBatchPollConsumer setMaxMessagesPerPoll(Integer maxMessagesPerPoll) { + return setConfig(MAX_MESSAGES_PER_POLL, maxMessagesPerPoll); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1CamelScheduledPollConsumer.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1CamelScheduledPollConsumer.java new file mode 100644 index 000000000..d374b8ef0 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1CamelScheduledPollConsumer.java @@ -0,0 +1,128 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.v1; + +import java.util.concurrent.TimeUnit; + +import org.switchyard.component.camel.common.model.consumer.CamelScheduledPollConsumer; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * Base class for scheduled consumers. + * + * @author Lukasz Dywicki + */ +public class V1CamelScheduledPollConsumer extends V1BaseCamelModel + implements CamelScheduledPollConsumer { + + /** + * The name of the 'initialDelay' element. + */ + public static final String INITIAL_DELAY = "initialDelay"; + /** + * The name of the 'delay' element. + */ + public static final String DELAY = "delay"; + /** + * The name of the 'useFixedDelay' element. + */ + public static final String USE_FIXED_DELAY = "useFixedDelay"; + + /** + * The name of the 'timeUnit' element. + */ + private static final String TIME_UNIT = "timeUnit"; + + /** + * The name of the 'sendEmptyMessageWhenIdle' element. + */ + private static final String SEND_EMPTY_MESSAGE_WHEN_IDLE = "sendEmptyMessageWhenIdle"; + + /** + * Creates model bound to given namespace. + * + * @param namespace Namespace to bound. + * @param name Name of element. + */ + public V1CamelScheduledPollConsumer(String namespace, String name) { + super(namespace, name); + + setModelChildrenOrder(INITIAL_DELAY, DELAY, USE_FIXED_DELAY, + TIME_UNIT, SEND_EMPTY_MESSAGE_WHEN_IDLE + ); + } + + /** + * Constructor. + * + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1CamelScheduledPollConsumer(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public Integer getInitialDelay() { + return getIntegerConfig(INITIAL_DELAY); + } + + @Override + public V1CamelScheduledPollConsumer setInitialDelay(Integer initialDelay) { + return setConfig(INITIAL_DELAY, initialDelay); + } + + @Override + public Integer getDelay() { + return getIntegerConfig(DELAY); + } + + @Override + public V1CamelScheduledPollConsumer setDelay(Integer delay) { + return setConfig(DELAY, delay); + } + + @Override + public Boolean isUseFixedDelay() { + return getBooleanConfig(USE_FIXED_DELAY); + } + + @Override + public V1CamelScheduledPollConsumer setUseFixedDelay(Boolean useFixedDelay) { + setConfig(USE_FIXED_DELAY, String.valueOf(useFixedDelay)); + return this; + } + + @Override + public TimeUnit getTimeUnit() { + return getEnumerationConfig(TIME_UNIT, TimeUnit.class); + } + + @Override + public V1CamelScheduledPollConsumer setTimeUnit(String timeUnit) { + return setConfig(TIME_UNIT, timeUnit); + } + + @Override + public Boolean isSendEmptyMessageWhenIdle() { + return getBooleanConfig(SEND_EMPTY_MESSAGE_WHEN_IDLE); + } + + @Override + public V1CamelScheduledPollConsumer setSendEmptyMessageWhenIdle(Boolean sendEmptyMessageWhenIdle) { + return setConfig(SEND_EMPTY_MESSAGE_WHEN_IDLE, sendEmptyMessageWhenIdle); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1ParameterModel.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1ParameterModel.java new file mode 100644 index 000000000..d0dc11963 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/model/v1/V1ParameterModel.java @@ -0,0 +1,96 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @author tags. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.switchyard.component.camel.common.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.component.camel.common.model.AdditionalUriParametersModel; +import org.switchyard.component.camel.common.model.ParameterModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 AdditionalUriParametersModel. + */ +public class V1ParameterModel extends BaseModel implements ParameterModel { + + /** + * Creates a new ParameterModel in the specified namespace. + * + * @param namespace the specified namespace + */ + public V1ParameterModel(String namespace) { + super(new QName(namespace, PARAMETER)); + } + + /** + * Creates a new ParameterModel with the specified configuration and + * descriptor. + * + * @param config the configuration + * @param desc the descriptor + */ + public V1ParameterModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public AdditionalUriParametersModel getAdditionalUriParameters() { + return (AdditionalUriParametersModel) getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return getModelAttribute("name"); + } + + /** + * {@inheritDoc} + */ + @Override + public ParameterModel setName(String name) { + setModelAttribute("name", name); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getValue() { + return getModelAttribute("value"); + } + + /** + * {@inheritDoc} + */ + @Override + public ParameterModel setValue(String value) { + setModelAttribute("value", value); + return this; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/selector/CamelOperationSelector.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/selector/CamelOperationSelector.java new file mode 100644 index 000000000..e96aac737 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/selector/CamelOperationSelector.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.selector; + +import org.apache.camel.Message; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.common.selector.BaseOperationSelector; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.w3c.dom.Document; + +/** + * Camel OperationSelector implementation. + */ +public class CamelOperationSelector extends BaseOperationSelector { + + /** + * Constructor. + * @param model OperationSelectorModel + */ + public CamelOperationSelector(OperationSelectorModel model) { + super(model); + } + + @Override + protected Document extractDomDocument(CamelBindingData content) throws Exception { + // expect Camel TypeConverter would convert it to a Document directly + Document document = content.getMessage().getBody(Document.class); + if (document == null) { + // falling back to let Camel TypeConverter convert it to String, + // and then convert that String to Document. + Message msg = content.getMessage(); + msg.setBody(msg.getBody(String.class)); + document = msg.getBody(Document.class); + } + return document; + } + + @Override + protected String extractString(CamelBindingData content) { + return content.getMessage().getBody(String.class); + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/selector/CamelOperationSelectorFactory.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/selector/CamelOperationSelectorFactory.java new file mode 100644 index 000000000..622ce197a --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/selector/CamelOperationSelectorFactory.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.selector; + +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.common.selector.OperationSelectorFactory; +import org.switchyard.selector.OperationSelector; + +/** + * A OperationSelectorFactory implementation for camel Message. + */ +public class CamelOperationSelectorFactory extends OperationSelectorFactory { + + @Override + public Class getTargetClass() { + return CamelBindingData.class; + } + + @Override + public Class> getDefaultOperationSelectorClass() { + return CamelOperationSelector.class; + } + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/transaction/TransactionHelper.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/transaction/TransactionHelper.java new file mode 100644 index 000000000..b26d993d7 --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/transaction/TransactionHelper.java @@ -0,0 +1,108 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.transaction; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; + +import org.apache.camel.spring.spi.SpringTransactionPolicy; +import org.apache.camel.util.URISupport; +import org.springframework.transaction.PlatformTransactionManager; +import org.switchyard.SwitchYardException; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.component.camel.common.CamelConstants; + +/** + * Utility class which encapsulates logic related to operations needed to register + * Spring {@link PlatformTransactionManager} and transaction policy beans necessary + * in camel routes. + */ +public final class TransactionHelper { + + private final SwitchYardCamelContext _context; + + /** + * Private constructor seen only from static method. + * + * @param context Camel context instance. + */ + private TransactionHelper(SwitchYardCamelContext context) { + this._context = context; + } + + private boolean isDefaultJtaTransactionName(final String tmName) { + return tmName.equals(TransactionManagerFactory.TM); + } + + private boolean isRegisteredInCamelRegistry(String beanName) { + return _context.getRegistry().lookup(beanName) != null; + } + + private void addToCamelRegistry() { + final PlatformTransactionManager transactionManager = TransactionManagerFactory.getInstance().create(); + // Add the transaction manager + _context.getWritebleRegistry().put(TransactionManagerFactory.TM, transactionManager); + // Add a policy ref bean pointing to the transaction manager + _context.getWritebleRegistry().put(CamelConstants.TRANSACTED_REF, new SpringTransactionPolicy(transactionManager)); + } + + private String getTransactionManagerName(URI uri) { + try { + final Map parseParameters = URISupport.parseParameters(uri); + String name = (String) parseParameters.get("transactionManager"); + if (name != null) { + name = name.replace("#", ""); + } + return name; + } catch (URISyntaxException e) { + throw new SwitchYardException(e); + } + } + + private boolean process(URI endpointUri) { + String transactionManagerName = getTransactionManagerName(endpointUri); + if (transactionManagerName == null) { + return false; + } + if (!isRegisteredInCamelRegistry(transactionManagerName) && isDefaultJtaTransactionName(transactionManagerName)) { + addToCamelRegistry(); + } + return true; + } + + /** + * Process component uri and register default transaction manager when necessary. + * + * @param endpointUri Camel endpoint uri. + * @param context Camel context instance. + * @return True if transaction manager is necessary for endpoint. + */ + public static boolean useTransactionManager(URI endpointUri, SwitchYardCamelContext context) { + return new TransactionHelper(context).process(endpointUri); + } + + /** + * Process component uri and register default transaction manager when necessary. + * + * @param endpointUri String with endpoint uri. + * @param context Camel context instance. + * @return True if transaction manager is necessary for endpoint. + */ + public static boolean useTransactionManager(String endpointUri, SwitchYardCamelContext context) { + return useTransactionManager(URI.create(endpointUri), context); + } + + +} diff --git a/components/common/camel/src/main/java/org/switchyard/component/camel/common/transaction/TransactionManagerFactory.java b/components/common/camel/src/main/java/org/switchyard/component/camel/common/transaction/TransactionManagerFactory.java new file mode 100644 index 000000000..21d0e39ab --- /dev/null +++ b/components/common/camel/src/main/java/org/switchyard/component/camel/common/transaction/TransactionManagerFactory.java @@ -0,0 +1,124 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.transaction; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.transaction.TransactionManager; + +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.jta.JtaTransactionManager; +import org.switchyard.component.camel.common.CommonCamelMessages; + +/** + * Simple factory which creates TransactedManager instances. + * + * @author Daniel Bevenius + */ +public final class TransactionManagerFactory { + + /** + * JBoss AS specific UserTransaction JNDI name. + */ + public static final String JBOSS_USER_TRANSACTION = "java:jboss/UserTransaction"; + + /** + * JBoss AS specific TransactionManager JNDI name. + */ + public static final String JBOSS_TRANSACTION_MANANGER = "java:jboss/TransactionManager"; + + /** + * JBoss AS specific TransactionSynchronizationRegistry JNDI name. + */ + public static final String JBOSS_TRANSACTION_SYNC_REG = "java:jboss/TransactionSynchronizationRegistry"; + + /** + * OSGi specific TransactionManager JNDI name. + */ + public static final String OSGI_TRANSACTION_MANAGER = "osgi:service/javax.transaction.TransactionManager"; + + /** + * Configuration name for the JtaTransactionManager. + */ + public static final String TM = "jtaTransactionManager"; + + private static final TransactionManagerFactory INSTANCE = new TransactionManagerFactory(); + + private TransactionManagerFactory() { + } + + /** + * Gets the singleton instance. + * + * @return TransactionManagerFactory the singleton instance. + */ + public static TransactionManagerFactory getInstance() { + return INSTANCE; + } + + /** + * Factory method that creates a {@link PlatformTransactionManager}. + * + * @return {@link PlatformTransactionManager} the created PlatformTransactionManager. + */ + public PlatformTransactionManager create() { + JtaTransactionManager transactionManager; + + if (isBound(JBOSS_USER_TRANSACTION)) { + transactionManager = new JtaTransactionManager(); + transactionManager.setUserTransactionName(JBOSS_USER_TRANSACTION); + transactionManager.setTransactionManagerName(JBOSS_TRANSACTION_MANANGER); + transactionManager.setTransactionSynchronizationRegistryName(JBOSS_TRANSACTION_SYNC_REG); + } else if (isBound(OSGI_TRANSACTION_MANAGER)) { + transactionManager = new JtaTransactionManager((TransactionManager)lookupInJndi(OSGI_TRANSACTION_MANAGER)); + } else if (isBound(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME)) { + transactionManager = new JtaTransactionManager(); + transactionManager.setUserTransactionName(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME); + } else { + throw CommonCamelMessages.MESSAGES.couldNotCreateAJtaTransactionManagerAsNoTransactionManagerWasFoundJBOSSUSERTRANSACTION( + JBOSS_USER_TRANSACTION, + OSGI_TRANSACTION_MANAGER, + JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME); + } + + // Initialize the transaction manager. + transactionManager.afterPropertiesSet(); + return transactionManager; + } + + private boolean isBound(final String jndiName) { + return lookupInJndi(jndiName) != null; + } + + private Object lookupInJndi(final String name) { + InitialContext context = null; + try { + context = new InitialContext(); + return context.lookup(name); + } catch (final NamingException e) { + return null; + } catch (final Exception e) { + throw CommonCamelMessages.MESSAGES.unexpectedExceptionRetrieving(name, e); + } finally { + if (context != null) { + try { + context.close(); + } catch (final Exception e) { + throw CommonCamelMessages.MESSAGES.unexpectedErrorClosingInitialContext(e); + } + } + } + } + +} diff --git a/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory b/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory new file mode 100644 index 000000000..37b5a2530 --- /dev/null +++ b/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.camel.common.composer.CamelContextMapperFactory diff --git a/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory b/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory new file mode 100644 index 000000000..7e8c7cf74 --- /dev/null +++ b/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.camel.common.composer.CamelMessageComposerFactory diff --git a/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory b/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory new file mode 100644 index 000000000..51e9c288b --- /dev/null +++ b/components/common/camel/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.camel.common.selector.CamelOperationSelectorFactory diff --git a/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v1/camel-common_1_0.xsd b/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v1/camel-common_1_0.xsd new file mode 100644 index 000000000..eedfc6c2c --- /dev/null +++ b/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v1/camel-common_1_0.xsd @@ -0,0 +1,154 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v1/camel-common_1_1.xsd b/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v1/camel-common_1_1.xsd new file mode 100644 index 000000000..95e74fc46 --- /dev/null +++ b/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v1/camel-common_1_1.xsd @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v2/camel-common_2_0.xsd b/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v2/camel-common_2_0.xsd new file mode 100644 index 000000000..0347ab120 --- /dev/null +++ b/components/common/camel/src/main/resources/org/switchyard/component/camel/common/model/v2/camel-common_2_0.xsd @@ -0,0 +1,167 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/common/camel/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/common/camel/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..409ded4e0 --- /dev/null +++ b/components/common/camel/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,26 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +camel_common_1_0.section=camel-common +camel_common_1_0.version=1.0 +camel_common_1_0.noNamespaceSchema=camel-common_1_0.xsd +camel_common_1_0.location=/org/switchyard/component/camel/common/model/v1/ + +camel_common_1_1.section=camel-common +camel_common_1_1.version=1.1 +camel_common_1_1.noNamespaceSchema=camel-common_1_1.xsd +camel_common_1_1.location=/org/switchyard/component/camel/common/model/v1/ + +camel_common_2_0.section=camel-common +camel_common_2_0.version=2.0 +camel_common_2_0.noNamespaceSchema=camel-common_2_0.xsd +camel_common_2_0.location=/org/switchyard/component/camel/common/model/v2/ diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/QueryStringTest.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/QueryStringTest.java new file mode 100644 index 000000000..2fcfdedc1 --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/QueryStringTest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class QueryStringTest { + + @Test + public void testEmptyQueryString() { + QueryString qs = new QueryString(); + assertEquals("", qs.toString()); + } + + @Test + public void testQueryStringSingleParam() { + final String queryString = "?foo=bar"; + QueryString qs = new QueryString().add("foo", "bar"); + assertEquals(queryString, qs.toString()); + } + + @Test + public void testNullParamIgnored() { + final String queryString = "?foo=bar"; + QueryString qs = new QueryString() + .add("foo", "bar") + .add(null, "abc") + .add("xyz", null); + assertEquals(queryString, qs.toString()); + } + + @Test + public void testQueryStringMultiParam() { + final String queryString = "?foo=bar&bar=foo"; + QueryString qs = new QueryString() + .add("foo", "bar") + .add("bar", "foo"); + assertEquals(queryString, qs.toString()); + } + +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/InboundHandlerTest.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/InboundHandlerTest.java new file mode 100644 index 000000000..4b72feac2 --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/InboundHandlerTest.java @@ -0,0 +1,118 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.junit.Test; + +/** + * Unit test for {@link InboundHandler}. + * + * @author Daniel Bevenius + */ +public class InboundHandlerTest extends InboundHandlerTestBase { + + @Test + public void reflexive() { + final InboundHandler x = createInboundHandler("direct://reflexive"); + assertThat(x.equals(x), is(true)); + } + + @Test + public void symmetric() { + final InboundHandler x = createInboundHandler("direct://symmetric"); + final InboundHandler y = createInboundHandler("direct://symmetric"); + + assertThat(x.equals(y), is(true)); + assertThat(y.equals(x), is(true)); + } + + @Test + public void nonSymmetric() { + final InboundHandler x = createInboundHandler("direct://symmetric"); + final InboundHandler y = createInboundHandler("direct://nonsymmetric"); + + assertThat(x.equals(y), is(false)); + assertThat(y.equals(x), is(false)); + } + + @Test + public void transitive() { + final InboundHandler x = createInboundHandler("direct://transitive"); + final InboundHandler y = createInboundHandler("direct://transitive"); + final InboundHandler z = createInboundHandler("direct://transitive"); + + assertThat(x.equals(y), is(true)); + assertThat(y.equals(z), is(true)); + assertThat(x.equals(z), is(true)); + } + + @Test + public void nonTransitive() { + final InboundHandler x = createInboundHandler("direct://transitive"); + final InboundHandler y = createInboundHandler("direct://nontransitive"); + final InboundHandler z = createInboundHandler("direct://transitive"); + + assertThat(x.equals(y), is(false)); + assertThat(y.equals(z), is(false)); + assertThat(x.equals(z), is(true)); + } + + @Test + public void verifyEqualHashCode() { + final InboundHandler x = createInboundHandler("direct://hashcode"); + final InboundHandler y = createInboundHandler("direct://hashcode"); + + assertThat(x.hashCode(), is(y.hashCode())); + } + + @Test + public void verifyUnEqualHashCode() { + final InboundHandler x = createInboundHandler("direct://hashcode"); + final InboundHandler y = createInboundHandler("direct://unEqualhashcode"); + + assertThat(x.hashCode() == y.hashCode(), is(false)); + } + + @Test + public void nullCheckForEqualsMethod() { + final InboundHandler x = createInboundHandler("direct://hashcode"); + assertThat(x.equals(null), is(false)); + } + + @Test + public void hasTransactionManagerConfigured() { + createInboundHandler("jms://queue?transactionManager=%23jtaTransactionMgr"); + assertThat(_camelContext.getRegistry().lookup("jtaTransactionMgr"), is(nullValue())); + createInboundHandler("jms://GreetingServiceQueue?connectionFactory=%23&JmsXA&transactionManager=%23jtaTransactionManager"); + assertThat(_camelContext.getRegistry().lookup("jtaTransactionManager"), is(notNullValue())); + } + + /** + * Test covering a case when transaction manager is specified - tests route definition. + * @throws Exception If route startup or shutdown fails. + */ + @Test + public void hasTransactionManager() throws Exception { + mockTransaction("jtaTransactionManager"); + createInboundHandler("transaction://foo?transactionManager=#jtaTransactionManager"); + _camelContext.start(); + _camelContext.stop(); + } + +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/InboundHandlerTestBase.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/InboundHandlerTestBase.java new file mode 100644 index 000000000..7efd6b01f --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/InboundHandlerTestBase.java @@ -0,0 +1,129 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import static org.mockito.Mockito.mock; + +import java.net.URI; + +import javax.transaction.TransactionManager; +import javax.transaction.TransactionSynchronizationRegistry; +import javax.transaction.UserTransaction; +import javax.xml.namespace.QName; + +import org.apache.camel.component.mock.MockComponent; +import org.apache.camel.spring.spi.SpringTransactionPolicy; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.mockito.Mockito; +import org.springframework.transaction.PlatformTransactionManager; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.component.camel.common.CamelConstants; +import org.switchyard.component.camel.common.model.v1.V1BaseCamelBindingModel; +import org.switchyard.component.camel.common.transaction.TransactionManagerFactory; +import org.switchyard.component.test.mixins.naming.NamingMixIn; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.selector.OperationSelectorModel; + +/** + * Base class for inbound handler tests. + * + * All component-common-camel tests can not use switchyard component directly. + * The camel mock component is used as replacement. + * It depends on this module, thus its circular dependency. All tests related to + * usage and execution of custom operation selector, message composer and context + * mapper are place in camel-switchyard module. + */ +public abstract class InboundHandlerTestBase { + + private static NamingMixIn mixIn = new NamingMixIn(); + + protected SwitchYardCamelContext _camelContext; + protected Configuration _configuration; + + @Before + public void startUp() { + _camelContext = new SwitchYardCamelContextImpl(false); + _camelContext.addComponent("switchyard", new MockComponent()); + _configuration = mock(Configuration.class); + } + + protected InboundHandler createInboundHandler(final String uri) { + return createInboundHandler(uri, null, null, null, null); + } + + protected InboundHandler createInboundHandler(final String uri, final String name, OperationSelectorModel selectorModel) { + return createInboundHandler(uri, name, selectorModel, null, null); + } + + protected InboundHandler createInboundHandler(final String uri, final String name, MessageComposerModel composerModel) { + return createInboundHandler(uri, name, null, composerModel, null); + } + + protected InboundHandler createInboundHandler(final String uri, final String name, ContextMapperModel mapperModel) { + return createInboundHandler(uri, name, null, null, mapperModel); + } + + protected InboundHandler createInboundHandler(final String uri, final String name, final OperationSelectorModel selectorModel, + final MessageComposerModel composerModel, final ContextMapperModel mapperModel) { + V1BaseCamelBindingModel camelBindingModel = new V1BaseCamelBindingModel(_configuration, new Descriptor()) { + @Override + public String getName() { + return name; + } + @Override + public URI getComponentURI() { + return URI.create(uri); + } + @Override + public OperationSelectorModel getOperationSelector() { + return selectorModel; + } + @Override + public MessageComposerModel getMessageComposer() { + return composerModel; + } + @Override + public ContextMapperModel getContextMapper() { + return mapperModel; + } + }; + return new InboundHandler(camelBindingModel, _camelContext, new QName("urn:foo", "dummyService"), null); + } + + protected void mockTransaction(String manager) { + PlatformTransactionManager transactionManager = Mockito.mock(PlatformTransactionManager.class); + _camelContext.getWritebleRegistry().put(manager, transactionManager); + _camelContext.getWritebleRegistry().put(CamelConstants.TRANSACTED_REF, new SpringTransactionPolicy(transactionManager)); + } + + @BeforeClass + public static void beforeClass() throws Exception { + mixIn.initialize(); + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_USER_TRANSACTION, mock(UserTransaction.class)); + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_TRANSACTION_MANANGER, mock(TransactionManager.class)); + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_TRANSACTION_SYNC_REG, mock(TransactionSynchronizationRegistry.class)); + } + + @AfterClass + public static void afterClass() { + mixIn.uninitialize(); + } + +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/OperationSelectorTest.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/OperationSelectorTest.java new file mode 100644 index 000000000..85eb49fe4 --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/OperationSelectorTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import java.util.List; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.TypeConversionException; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.support.TypeConverterSupport; +import org.jboss.netty.buffer.BigEndianHeapChannelBuffer; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.component.camel.common.CamelConstants; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.selector.CamelOperationSelector; +import org.switchyard.config.model.selector.XPathOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1StaticOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1XPathOperationSelectorModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.selector.OperationSelector; + +/** + * Test of operation selector stuff. + */ +public class OperationSelectorTest extends InboundHandlerTestBase { + + @Before + public void startUpTest() throws Exception { + _camelContext.start(); + } + + @After + public void tearDown() throws Exception { + _camelContext.stop(); + } + + @Test + public void operationSelectorProcessor() throws Exception { + ProducerTemplate producer = _camelContext.createProducerTemplate(); + InboundHandler handler1 = createInboundHandler("direct://foo", "foo", new V1StaticOperationSelectorModel(SwitchYardNamespace.DEFAULT.uri()).setOperationName("foo")); + InboundHandler handler2 = createInboundHandler("direct://bar", "bar", new V1StaticOperationSelectorModel(SwitchYardNamespace.DEFAULT.uri()).setOperationName("bar")); + + handler1.start(); + handler2.start(); + + MockEndpoint mockEndpoint = _camelContext.getEndpoint("switchyard://dummyService", MockEndpoint.class); + mockEndpoint.expectedBodiesReceived("FooOperationPayload", "BarOperationPayload"); + mockEndpoint.expectedMessageCount(2); + producer.sendBody("direct://foo", "FooOperationPayload"); + producer.sendBody("direct://bar", "BarOperationPayload"); + mockEndpoint.assertIsSatisfied(); + List exchanges = mockEndpoint.getReceivedExchanges(); + mockEndpoint.message(0).header(CamelConstants.OPERATION_SELECTOR_HEADER) + .isInstanceOf(OperationSelector.class).matches(exchanges.get(0)); + mockEndpoint.message(1).header(CamelConstants.OPERATION_SELECTOR_HEADER) + .isInstanceOf(OperationSelector.class).matches(exchanges.get(1)); + + handler1.stop(); + handler2.stop(); + } + + @Test + public void testOperationSelectorOnNettyChannelBuffer() throws Exception { + String payload = "greetTomas"; + ProducerTemplate producer = _camelContext.createProducerTemplate(); + XPathOperationSelectorModel operationSelectorModel = new V1XPathOperationSelectorModel(SwitchYardNamespace.DEFAULT.uri()); + operationSelectorModel.setExpression("//body/operation"); + InboundHandler handler = createInboundHandler("direct://xpath", "xpath", operationSelectorModel); + handler.start(); + + try { + // BigEndianHeapChannelBuffer->String converter is provided by camel-netty component + _camelContext.getTypeConverterRegistry() + .addTypeConverter(String.class, BigEndianHeapChannelBuffer.class, new MyConverter()); + MockEndpoint mockEndpoint = _camelContext.getEndpoint("switchyard://dummyService", MockEndpoint.class); + producer.sendBody("direct://xpath", new BigEndianHeapChannelBuffer(payload.getBytes())); + Exchange exchange = mockEndpoint.getExchanges().get(0); + CamelOperationSelector selector = new CamelOperationSelector(operationSelectorModel); + QName operation = selector.selectOperation(new CamelBindingData(exchange.getIn())); + Assert.assertNotNull(operation); + Assert.assertEquals("greet", operation.getLocalPart()); + } finally { + handler.stop(); + } + } + + private class MyConverter extends TypeConverterSupport { + @SuppressWarnings("unchecked") + @Override + public T convertTo(Class type, Exchange exchange, Object value) + throws TypeConversionException { + BigEndianHeapChannelBuffer buffer = BigEndianHeapChannelBuffer.class.cast(value); + return (T) new String(buffer.array()); + } + } +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/OutboundHandlerTest.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/OutboundHandlerTest.java new file mode 100644 index 000000000..5fbb949b1 --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/handler/OutboundHandlerTest.java @@ -0,0 +1,285 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.handler; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URI; + +import javax.transaction.TransactionManager; +import javax.transaction.TransactionSynchronizationRegistry; +import javax.transaction.UserTransaction; +import javax.xml.namespace.QName; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.component.camel.common.composer.CamelBindingData; +import org.switchyard.component.camel.common.composer.CamelComposition; +import org.switchyard.component.camel.common.composer.CamelContextMapper; +import org.switchyard.component.camel.common.composer.CamelMessageComposer; +import org.switchyard.component.camel.common.model.CamelBindingModel; +import org.switchyard.component.camel.common.transaction.TransactionManagerFactory; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.component.test.mixins.naming.NamingMixIn; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/** + * Functional test for {@link OutboundHandler}. + * + * @author Daniel Bevenius + * + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class OutboundHandlerTest extends CamelTestSupport { + + private NamingMixIn _mixIn; + + @EndpointInject(uri = "mock:result") + private static MockEndpoint camelEndpoint; + + private ServiceDomain _serviceDomain; + + @ServiceOperation("TargetService") + private Invoker _targetService; + + private CompositeReferenceModel referenceModel = mock(CompositeReferenceModel.class); + private MessageComposer _messageComposer; + private ServiceReference _service; + + /** + * Exception rule for verifying exceptions. + */ + @Rule + public ExpectedException exception = ExpectedException.none(); + + private CamelBindingModel bindingModel; + + @Before + public void setupSwitchyardService() { + bindingModel = mock(CamelBindingModel.class); + when(bindingModel.getComponentURI()).thenReturn(URI.create("direct:to")); + when(bindingModel.getName()).thenReturn("mockOutputHandler"); + when(bindingModel.getReference()).thenReturn(referenceModel); + _messageComposer = CamelComposition.getMessageComposer(); + _serviceDomain.registerService(_targetService.getServiceName(), + new InOnlyService(), + new OutboundHandler(bindingModel, + (SwitchYardCamelContext) context, _messageComposer, _serviceDomain + ) { + { + setState(State.STARTED); + } + } + ); + _service = _serviceDomain.registerServiceReference( + _targetService.getServiceName(), new InOnlyService()); + } + + @Test + public void routeInOnlyToCamel() throws Exception { + final String payload = "inOnly test string"; + _targetService.operation(ServiceInterface.DEFAULT_OPERATION).sendInOnly(payload); + + assertThat(camelEndpoint.getReceivedCounter(), is(1)); + final String received = (String) camelEndpoint.getReceivedExchanges().get(0).getIn().getBody(); + assertThat(received, is(equalTo(payload))); + } + + @Test + public void checkTransactionManagerRegistration() throws Exception { + _mixIn.initialize(); + _mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_USER_TRANSACTION, mock(UserTransaction.class)); + _mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_TRANSACTION_MANANGER, mock(TransactionManager.class)); + _mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_TRANSACTION_SYNC_REG, mock(TransactionSynchronizationRegistry.class)); + + bindingModel = mock(CamelBindingModel.class); + when(bindingModel.getComponentURI()).thenReturn(URI.create("transaction:foo?transactionManager=%23jtaTransactionManager")); + when(bindingModel.getReference()).thenReturn(referenceModel); + _messageComposer = CamelComposition.getMessageComposer(); + _serviceDomain.registerService(_targetService.getServiceName(), + new InOnlyService(), + new OutboundHandler(bindingModel, + (SwitchYardCamelContext) context, _messageComposer, null + ) { + { + setState(State.STARTED); + } + } + ); + _service = _serviceDomain.registerServiceReference( + _targetService.getServiceName(), new InOnlyService()); + Exchange exchange = _service.createExchange(); + + MockEndpoint endpoint = getMockEndpoint("mock:result"); + endpoint.expectedBodiesReceived("foo"); + exchange.send(exchange.createMessage().setContent("foo")); + + assertThat(context.getRegistry().lookup(TransactionManagerFactory.TM), is(notNullValue())); + _mixIn.uninitialize(); + } + + @Test + public void verifyThatEsbPropetiesArePassedToCamel() throws Exception { + final String propertyKey = "testProp"; + final String propertyValue = "dummyValue"; + final Exchange exchange = _service.createExchange(); + exchange.getContext().setProperty(propertyKey, propertyValue, Scope.EXCHANGE); + + Message message = exchange.createMessage(); + message.getContext().setProperty(propertyValue, propertyKey); + exchange.send(message); + + assertThat(camelEndpoint.getReceivedCounter(), is(1)); + org.apache.camel.Exchange ex = camelEndpoint.getReceivedExchanges().get(0); + final String actualPropertyValue = (String) ex.getProperty(propertyKey); + final String actualPropertyKey = (String) ex.getIn().getHeader(propertyValue); + assertThat(actualPropertyValue, is(propertyValue)); + assertThat(actualPropertyKey, is(propertyKey)); + } + + private Message createMessageWithBody(final Exchange exchange, final Object body) { + return exchange.createMessage().setContent(body); + } + + @Test + public void routeInOutToCamel() throws Exception { + final String body = "inOut test string"; + final Exchange exchange = _service.createExchange(); + final Message message = createMessageWithBody(exchange, body); + + exchange.send(message); + + final String payload = (String) exchange.getMessage().getContent(); + assertThat(payload, is(equalTo(body))); + } + + @Test + public void throwsIllegalArgumentExceptionIfBindingModelIsNull() { + exception.expect(IllegalArgumentException.class); + exception.expectMessage("binding argument must not be null"); + new OutboundHandler(null, mock(SwitchYardCamelContext.class), _messageComposer, null); + } + + @Test + public void throwsIllegalArgumentExceptionIfBindingModelURIIsNull() { + CamelBindingModel emptyURIModel = mock(CamelBindingModel.class); + when(bindingModel.getComponentURI()).thenReturn(null); + exception.expect(IllegalArgumentException.class); + exception.expectMessage("binding uri must not be null"); + new OutboundHandler(emptyURIModel, mock(SwitchYardCamelContext.class), _messageComposer, null); + } + + @Test + public void throwsIllegalArgumentExceptionIfCamelContextIsNull() { + exception.expect(IllegalArgumentException.class); + exception.expectMessage("camelContext argument must not be null"); + new OutboundHandler(bindingModel, null, _messageComposer, null); + } + + @Test + public void startStop() throws Exception { + final ProducerTemplate producerTemplate = mock(ProducerTemplate.class); + final OutboundHandler outboundHandler = new OutboundHandler(bindingModel, + (SwitchYardCamelContext) context, _messageComposer, producerTemplate, null); + outboundHandler.start(); + outboundHandler.stop(); + verify(producerTemplate).start(); + verify(producerTemplate).stop(); + } + + @Test + public void routeInOutToCamelUsingMessageComposer() throws Exception { + bindingModel = mock(CamelBindingModel.class); + when(bindingModel.getComponentURI()).thenReturn(URI.create("direct:MessageComposerService")); + when(bindingModel.getName()).thenReturn("mockOutputHandler"); + when(bindingModel.getReference()).thenReturn(referenceModel); + MessageComposer myMessageComposer = new CamelMessageComposer() { + @Override + public CamelBindingData decompose(Exchange exchange, CamelBindingData target) throws Exception { + exchange.getContext().setProperty("decomposeInvoked", true, Scope.EXCHANGE); + return super.decompose(exchange, target); + } + @Override + public Message compose(CamelBindingData source, Exchange exchange) throws Exception { + exchange.getContext().setProperty("composeInvoked", true, Scope.EXCHANGE); + return super.compose(source, exchange); + } + }; + myMessageComposer.setContextMapper(new CamelContextMapper()); + QName serviceName = new QName(_serviceDomain.getName().getNamespaceURI(), "MessageComposerService"); + _serviceDomain.registerService(serviceName, + new InOutService(), + new OutboundHandler(bindingModel, (SwitchYardCamelContext) context, myMessageComposer, _serviceDomain) { + { + setState(State.STARTED); + } + } + ); + _service = _serviceDomain.registerServiceReference(serviceName, new InOutService()); + Exchange exchange = _service.createExchange(); + exchange.send(exchange.createMessage().setContent("foo")); + assertThat((Boolean)exchange.getContext().getProperty("decomposeInvoked").getValue(), is(true)); + assertThat((Boolean)exchange.getContext().getProperty("composeInvoked").getValue(), is(true)); + } + + @Override + protected CamelContext createCamelContext() throws Exception { + return new SwitchYardCamelContextImpl(); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + public void configure() { + from("direct:to") + .convertBodyTo(String.class) + .log("Before Routing to mock:result body: ${body}") + .to("mock:result"); + from("transaction:foo").to("mock:result"); + from("direct:MessageComposerService").to("mock:result"); + } + }; + } + +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledBatchPollConsumerTest.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledBatchPollConsumerTest.java new file mode 100644 index 000000000..f66362050 --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/model/consumer/CamelScheduledBatchPollConsumerTest.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.consumer; + +import static junit.framework.Assert.assertEquals; + +import org.junit.Test; +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledBatchPollConsumer; + +/** + * Test of scheduled batch poll consumer binding. + * + * @author Lukasz Dywicki + */ +public class CamelScheduledBatchPollConsumerTest { + + private static final Integer MAX_MESSAGES_PER_POLL = 5; + + @Test + public void testConfigOverride() { + CamelScheduledBatchPollConsumer model = createModel(); + assertEquals(MAX_MESSAGES_PER_POLL, model.getMaxMessagesPerPoll()); + } + + private CamelScheduledBatchPollConsumer createModel() { + return new V1CamelScheduledBatchPollConsumer("test", "test") + .setMaxMessagesPerPoll(MAX_MESSAGES_PER_POLL); + } +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/model/consumer/V1CamelScheduledPollConsumerTest.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/model/consumer/V1CamelScheduledPollConsumerTest.java new file mode 100644 index 000000000..7f768ab4b --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/model/consumer/V1CamelScheduledPollConsumerTest.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.model.consumer; + +import static junit.framework.Assert.assertEquals; + +import java.util.concurrent.TimeUnit; + +import org.junit.Test; +import org.switchyard.component.camel.common.model.v1.V1CamelScheduledPollConsumer; + +/** + * Test of scheduled poll consumer binding. + * + * @author Lukasz Dywicki + */ +public class V1CamelScheduledPollConsumerTest { + + private static final Integer DELAY = 1000; + private static final TimeUnit TIME_UNIT = TimeUnit.MINUTES; + private static final Boolean SEND_EMPTY_MESSAGE_WHEN_IDLE = true; + private static final Integer INITIAL_DELAY = 999; + private static final Boolean USE_FIXED_DELAY = true; + + @Test + public void testConfigOverride() { + V1CamelScheduledPollConsumer model = createModel(); + assertEquals(DELAY, model.getDelay()); + assertEquals(INITIAL_DELAY, model.getInitialDelay()); + assertEquals(TIME_UNIT, model.getTimeUnit()); + assertEquals(SEND_EMPTY_MESSAGE_WHEN_IDLE, model.isSendEmptyMessageWhenIdle()); + assertEquals(USE_FIXED_DELAY, model.isUseFixedDelay()); + model.setDelay(750); + assertEquals(new Integer(750), model.getDelay()); + } + + private V1CamelScheduledPollConsumer createModel() { + return new V1CamelScheduledPollConsumer("test", "test") + .setDelay(DELAY) + .setInitialDelay(INITIAL_DELAY) + .setTimeUnit(TIME_UNIT.name()) + .setSendEmptyMessageWhenIdle(SEND_EMPTY_MESSAGE_WHEN_IDLE) + .setUseFixedDelay(USE_FIXED_DELAY); + } +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/transacted/TransactedDirectComponent.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/transacted/TransactedDirectComponent.java new file mode 100644 index 000000000..df990c6ed --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/transacted/TransactedDirectComponent.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.transacted; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.camel.Endpoint; +import org.apache.camel.component.direct.DirectComponent; +import org.apache.camel.component.direct.DirectConsumer; + +/** + * An extension of {@link DirectComponent} for testing Transaction Manager injection. + */ +public class TransactedDirectComponent extends DirectComponent { + + private final Map consumers = new HashMap(); + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + Endpoint endpoint = new TransactedDirectEndpoint(uri, this, consumers); + setProperties(endpoint, parameters); + return endpoint; + } + +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/transacted/TransactedDirectEndpoint.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/transacted/TransactedDirectEndpoint.java new file mode 100644 index 000000000..c1b39829a --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/transacted/TransactedDirectEndpoint.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.transacted; + +import java.util.Map; + +import org.apache.camel.component.direct.DirectConsumer; +import org.apache.camel.component.direct.DirectEndpoint; +import org.springframework.transaction.PlatformTransactionManager; + +public class TransactedDirectEndpoint extends DirectEndpoint { + + private PlatformTransactionManager manager; + + public TransactedDirectEndpoint(String uri, TransactedDirectComponent component, Map consumers) { + super(uri, component, consumers); + } + + public void setTransactionManager(PlatformTransactionManager manager) { + this.manager = manager; + } + + public PlatformTransactionManager getTransactionManager() { + return manager; + } + +} diff --git a/components/common/camel/src/test/java/org/switchyard/component/camel/common/transaction/TransactionManagerFactoryTest.java b/components/common/camel/src/test/java/org/switchyard/component/camel/common/transaction/TransactionManagerFactoryTest.java new file mode 100644 index 000000000..2106940b6 --- /dev/null +++ b/components/common/camel/src/test/java/org/switchyard/component/camel/common/transaction/TransactionManagerFactoryTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.camel.common.transaction; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; + +import javax.transaction.TransactionManager; +import javax.transaction.TransactionSynchronizationRegistry; +import javax.transaction.UserTransaction; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.jta.JtaTransactionManager; +import org.switchyard.SwitchYardException; +import org.switchyard.component.test.mixins.naming.NamingMixIn; + +/** + * Unit test for {@link TransactionManagerFactory}. + * + * @author Daniel Bevenius + */ +public class TransactionManagerFactoryTest { + + private NamingMixIn mixIn; + + @Before + public void setUp() { + mixIn = new NamingMixIn(); + mixIn.initialize(); + } + + @After + public void shutDown() { + mixIn.uninitialize(); + } + + @Test + public void getInstance() { + final TransactionManagerFactory factory = TransactionManagerFactory.getInstance(); + assertThat(factory, is(notNullValue())); + } + + @Test + public void createSpringTransactionManager() throws Exception { + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_USER_TRANSACTION, mock(UserTransaction.class)); + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_TRANSACTION_MANANGER, mock(TransactionManager.class)); + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_TRANSACTION_SYNC_REG, mock(TransactionSynchronizationRegistry.class)); + final TransactionManagerFactory factory = TransactionManagerFactory.getInstance(); + final PlatformTransactionManager tm = factory.create(); + assertThat(tm, is(notNullValue())); + } + + @Test (expected = SwitchYardException.class) + public void showThrowIfTMIsUnknown() { + final TransactionManagerFactory factory = TransactionManagerFactory.getInstance(); + factory.create(); + } + + @Test + public void createJBossTransactionManager() throws Exception { + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_USER_TRANSACTION, mock(UserTransaction.class)); + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_TRANSACTION_MANANGER, mock(TransactionManager.class)); + mixIn.getInitialContext().bind(TransactionManagerFactory.JBOSS_TRANSACTION_SYNC_REG, mock(TransactionSynchronizationRegistry.class)); + final TransactionManagerFactory factory = TransactionManagerFactory.getInstance(); + final PlatformTransactionManager tm = factory.create(); + assertThat(tm, is(instanceOf(JtaTransactionManager.class))); + } + +} diff --git a/components/common/camel/src/test/resources/META-INF/services/org/apache/camel/component/transaction b/components/common/camel/src/test/resources/META-INF/services/org/apache/camel/component/transaction new file mode 100644 index 000000000..48ccf64bf --- /dev/null +++ b/components/common/camel/src/test/resources/META-INF/services/org/apache/camel/component/transaction @@ -0,0 +1 @@ +class=org.switchyard.component.camel.common.transacted.TransactedDirectComponent \ No newline at end of file diff --git a/components/common/common/pom.xml b/components/common/common/pom.xml new file mode 100644 index 000000000..6b5d5ee42 --- /dev/null +++ b/components/common/common/pom.xml @@ -0,0 +1,40 @@ + + + + 4.0.0 + switchyard-component-common + bundle + SwitchYard: Common Component Library + The SwitchYard Common Component Library. + http://switchyard.org + + org.switchyard.components + switchyard-component-common-parent + 2.1.0-SNAPSHOT + ../pom.xml + + + + org.switchyard.component.common.* + + + + + org.switchyard + switchyard-security + + + + diff --git a/components/common/common/src/main/java/org/switchyard/component/common/CommonCommonLogger.java b/components/common/common/src/main/java/org/switchyard/component/common/CommonCommonLogger.java new file mode 100644 index 000000000..72672a6f0 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/CommonCommonLogger.java @@ -0,0 +1,65 @@ +package org.switchyard.component.common; + +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 34400-34499 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface CommonCommonLogger { + /** + * A root logger with the category of the package name. + */ + CommonCommonLogger ROOT_LOGGER = Logger.getMessageLogger(CommonCommonLogger.class, CommonCommonLogger.class.getPackage().getName()); + + /** + * couldNotInstantiateContextMapper method definition. + * @param customClassName customClassName + * @param eMessage eMessage + */ + @LogMessage(level = Level.ERROR) + @Message(id = 34400, value = "Could not instantiate ContextMapper: %s - %s") + void couldNotInstantiateContextMapper(String customClassName, String eMessage); + + /** + * couldNotInstantiateMessageComposer method definition. + * @param customClassName customClassName + * @param eMessage eMessage + */ + @LogMessage(level = Level.ERROR) + @Message(id = 34401, value = "Could not instantiate MessageComposer: %s - %s") + void couldNotInstantiateMessageComposer(String customClassName, String eMessage); + + /** + * couldNotInstantiateOperationSelector method definition. + * @param customClassName customClassName + * @param eMessage eMessage + */ + @LogMessage(level = Level.ERROR) + @Message(id = 34402, value = "Could not instantiate OperationSelector: %s - %s") + void couldNotInstantiateOperationSelector(String customClassName, String eMessage); + + /** + * replyArrivedAfterTimeout method definition. + * @param serviceName serviceName + */ + @LogMessage(level = Level.WARN) + @Message(id = 34403, value = "Reply message arrived after timeout has elapsed for service: %s") + void replyArrivedAfterTimeout(String serviceName); + + /** + * faultArrivedAfterTimeout method definition. + * @param serviceName serviceName + */ + @LogMessage(level = Level.WARN) + @Message(id = 34404, value = "Fault message arrived after timeout has elapsed for service: %s") + void faultArrivedAfterTimeout(String serviceName); + +} + diff --git a/components/common/common/src/main/java/org/switchyard/component/common/CommonCommonMessages.java b/components/common/common/src/main/java/org/switchyard/component/common/CommonCommonMessages.java new file mode 100644 index 000000000..79917b567 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/CommonCommonMessages.java @@ -0,0 +1,103 @@ +package org.switchyard.component.common; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 34500-34599 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface CommonCommonMessages { + /** + * The default messages. + */ + CommonCommonMessages MESSAGES = Messages.getBundle(CommonCommonMessages.class); + + /** + * isNotAValidRegexPattern method definition. + * @param regex the regex + * @param pseMessage pseMessage + * @return IllegalArgumentException + */ + @Message(id = 34500, value = "\"%s\" is not a valid regex pattern: %s") + IllegalArgumentException isNotAValidRegexPattern(String regex, String pseMessage); + + /** + * unsupportedOperationSelectorConfiguration method definition. + * @param model the model + * @return Exception + */ + @Message(id = 34501, value = "Unsupported OperationSelector configuration: %s") + Exception unsupportedOperationSelectorConfiguration(String model); + + /** + * couldnTEvaluateXPathExpression method definition. + * @param expression the expression + * @param e the e + * @return Exception + */ + @Message(id = 34502, value = "Couldn't evaluate XPath expression '%s'") + Exception couldnTEvaluateXPathExpression(String expression, @Cause Exception e); + + /** + * noNodeHasBeenMatchedWithTheXPathExpression method definition. + * @param expression the expression + * @return Exception + */ + @Message(id = 34503, value = "No node has been matched with the XPath expression '%s' in the payload. It couldn't determine the operation.") + Exception noNodeHasBeenMatchedWithTheXPathExpression(String expression); + + /** + * multipleNodesHaveBeenMatchedWithTheXPathExpression method definition. + * @param expression the expression + * @return Exception + */ + @Message(id = 34504, value = "Multiple nodes have been matched with the XPath expression '%s' in the payload. It couldn't determine the operation.") + Exception multipleNodesHaveBeenMatchedWithTheXPathExpression(String expression); + + /** + * noNodeHasBeenMatchedWithTheRegexExpression method definition. + * @param expression the expression + * @return Exception + */ + @Message(id = 34505, value = "No node has been matched with the Regex expression '%s' in the payload. It couldn't determine the operation.") + Exception noNodeHasBeenMatchedWithTheRegexExpression(String expression); + + /** + * multipleNodesHaveBeenMatchedWithTheRegexExpression method definition. + * @param expression the expression + * @return Exception + */ + @Message(id = 34506, value = "Multiple nodes have been matched with the Regex expression '%s' in the payload. It couldn't determine the operation.") + Exception multipleNodesHaveBeenMatchedWithTheRegexExpression(String expression); + + /** + * unexpectedInterruptWhileWaitingOnOUTExchangeMessage method definition. + * @param e the e + * @return DeliveryException + */ + @Message(id = 34507, value = "Unexpected interrupt while waiting on OUT Exchange message.") + DeliveryException unexpectedInterruptWhileWaitingOnOUTExchangeMessage(@Cause InterruptedException e); + + /** + * timedOutWaitingOnOUTExchangeMessage method definition. + * @return DeliveryException + */ + @Message(id = 34508, value = "Timed out waiting on OUT Exchange message.") + DeliveryException timedOutWaitingOnOUTExchangeMessage(); + + /** + * unexpectedInterruptException method definition. + * @param e the e + * @return IllegalStateException + */ + @Message(id = 34510, value = "Unexpected Interrupt exception.") + IllegalStateException unexpectedInterruptException(@Cause InterruptedException e); + +} + diff --git a/components/common/common/src/main/java/org/switchyard/component/common/DeliveryException.java b/components/common/common/src/main/java/org/switchyard/component/common/DeliveryException.java new file mode 100644 index 000000000..0b7dc99c9 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/DeliveryException.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.common; + +import org.switchyard.SwitchYardException; + +/** + * Exchange delivery exception. + * + * @author tom.fennelly@gmail.com + */ +public class DeliveryException extends SwitchYardException { + + /** + * Public constructor. + * @param message Exception message. + */ + public DeliveryException(String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Throwable cause. + */ + public DeliveryException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/Endpoint.java b/components/common/common/src/main/java/org/switchyard/component/common/Endpoint.java new file mode 100644 index 000000000..d83aa36e8 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/Endpoint.java @@ -0,0 +1,33 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.common; + +/** + * Interface for allowing to start and stop endpoints. + * + * @author Magesh Kumar B (C) 2014 Red Hat Inc. + */ +public interface Endpoint { + + /** + * Start/publish Endpoint. + */ + void start(); + + /** + * Stop the published Endpoint. + */ + void stop(); +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/SynchronousInOutHandler.java b/components/common/common/src/main/java/org/switchyard/component/common/SynchronousInOutHandler.java new file mode 100644 index 000000000..ee0b1c8ba --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/SynchronousInOutHandler.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; + +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.HandlerException; + +/** + * Synchronous IN_OUT exchange handler. + *

+ * Provides a blocking wait for the OUT exchange message. + * + * @author tom.fennelly@gmail.com + */ +public class SynchronousInOutHandler implements ExchangeHandler { + + /** + * Default timeout. + */ + public static final long DEFAULT_TIMEOUT = 1000 * 60 * 5; + + private static final Logger LOGGER = Logger.getLogger(SynchronousInOutHandler.class); + + private BlockingQueue _responseQueue = new ArrayBlockingQueue(1); + + /** + * Wait for an OUT Exchange message. + *

+ * Uses the {@link #DEFAULT_TIMEOUT}. + * + * @return The OUT Exchange instance. + * @throws DeliveryException Timeout or interrupt while waiting on OUT message. + */ + public Exchange waitForOut() throws DeliveryException { + return waitForOut(DEFAULT_TIMEOUT); + } + + /** + * Wait for an OUT Exchange message. + * + * @param timeout The timeout in milliseconds. + * @return The OUT Exchange instance. + * @throws DeliveryException Timeout or interrupt while waiting on OUT message. + */ + public Exchange waitForOut(long timeout) throws DeliveryException { + try { + Exchange outExchange; + + try { + outExchange = _responseQueue.poll(timeout, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + synchronized (this) { + _responseQueue = null; + throw CommonCommonMessages.MESSAGES.unexpectedInterruptWhileWaitingOnOUTExchangeMessage(e); + } + } + + if (outExchange == null) { + // we've timed out waiting on the OUT message... + synchronized (this) { + if (!_responseQueue.isEmpty()) { + // message arrived just after timeout... we're OK... + outExchange = _responseQueue.poll(); + } else { + _responseQueue = null; + throw CommonCommonMessages.MESSAGES.timedOutWaitingOnOUTExchangeMessage(); + } + } + } + + return outExchange; + } finally { + _responseQueue = null; + } + } + + @Override + public synchronized void handleMessage(Exchange exchange) throws HandlerException { + if (_responseQueue == null) { + CommonCommonLogger.ROOT_LOGGER.replyArrivedAfterTimeout(exchange.getConsumer().getName().toString()); + } else { + try { + _responseQueue.put(exchange); + } catch (InterruptedException e) { + throw new HandlerException(e); + } + } + } + + @Override + public synchronized void handleFault(Exchange exchange) { + if (_responseQueue == null) { + CommonCommonLogger.ROOT_LOGGER.faultArrivedAfterTimeout(exchange.getConsumer().getName().toString()); + } else { + try { + _responseQueue.put(exchange); + } catch (InterruptedException e) { + throw CommonCommonMessages.MESSAGES.unexpectedInterruptException(e); + } + } + } +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseContextMapper.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseContextMapper.java new file mode 100644 index 000000000..742401584 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseContextMapper.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import org.switchyard.Context; +import org.switchyard.config.model.composer.ContextMapperModel; + +/** + * Base class for ContextMapper, no-op'ing the required methods in case the extender only needs to override one of them. + * + * @param the type of binding data + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public class BaseContextMapper implements ContextMapper { + + private ContextMapperModel _model; + + /** + * {@inheritDoc} + */ + @Override + public ContextMapperModel getModel() { + return _model; + } + + /** + * {@inheritDoc} + */ + @Override + public void setModel(ContextMapperModel model) { + _model = model; + } + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(D source, Context context) throws Exception { + // No-op; override if desired. + } + + /** + * {@inheritDoc} + */ + @Override + public void mapTo(Context context, D target) throws Exception { + // No-op; override if desired. + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseMessageComposer.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseMessageComposer.java new file mode 100644 index 000000000..43ca54908 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseMessageComposer.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; + +/** + * Base class for MessageComposer. + * + * @param the type of binding data + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class BaseMessageComposer implements MessageComposer { + + private ContextMapper _contextMapper; + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper getContextMapper() { + return _contextMapper; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer setContextMapper(ContextMapper contextMapper) { + _contextMapper = contextMapper; + return this; + } + + /** + * Returns the current message type based on the state of the exchange. + * @param exchange exchange to query + * @return the current message type based on the exchange contract + */ + public static QName getMessageType(Exchange exchange) { + QName msgType; + if (exchange.getPhase() == null) { + msgType = exchange.getContract().getConsumerOperation().getInputType(); + } else { + msgType = exchange.getContract().getProviderOperation().getOutputType(); + } + + return msgType; + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseRegexContextMapper.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseRegexContextMapper.java new file mode 100644 index 000000000..138fc1ffc --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/BaseRegexContextMapper.java @@ -0,0 +1,139 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import javax.xml.namespace.QName; + +import org.switchyard.component.common.CommonCommonMessages; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.xml.XMLHelper; + +/** + * Base class for RegexContextMapper; adds the regex pattern matching ability. + * + * @param the type of binding data + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class BaseRegexContextMapper extends BaseContextMapper implements RegexContextMapper { + + private final List _includes = new ArrayList(); + private final List _excludes = new ArrayList(); + private final List _includeNamespaces = new ArrayList(); + private final List _excludeNamespaces = new ArrayList(); + + private void setPatternList(String regexs, List patternList) { + Set regexSet = Strings.uniqueSplitTrimToNull(regexs, ","); + List tmpList = new ArrayList(); + for (String regex : regexSet) { + try { + Pattern pattern = Pattern.compile(regex); + tmpList.add(pattern); + } catch (PatternSyntaxException pse) { + throw CommonCommonMessages.MESSAGES.isNotAValidRegexPattern(regex, pse.getMessage()); + } + } + synchronized (patternList) { + patternList.clear(); + patternList.addAll(tmpList); + } + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper setIncludes(String includes) { + setPatternList(includes, _includes); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper setExcludes(String excludes) { + setPatternList(excludes, _excludes); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper setIncludeNamespaces(String includeNamespaces) { + setPatternList(includeNamespaces, _includeNamespaces); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper setExcludeNamespaces(String excludeNamespaces) { + setPatternList(excludeNamespaces, _excludeNamespaces); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean matches(String name) { + return matches(XMLHelper.createQName(name)); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean matches(QName qname) { + return qname != null && matches(qname.getLocalPart(), _includes, _excludes) && matches(qname.getNamespaceURI(), _includeNamespaces, _excludeNamespaces); + } + + private boolean matches(String test, List includes, List excludes) { + boolean green = false; + boolean red = false; + for (Pattern include : includes) { + if (include.matcher(test).matches()) { + green = true; + break; + } else { + red = true; + } + } + boolean matches = green || !red; + if (matches) { + green = false; + red = false; + for (Pattern exclude : excludes) { + if (!exclude.matcher(test).matches()) { + green = true; + break; + } else { + red = true; + } + } + matches = green || !red; + } + return matches; + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/BindingData.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/BindingData.java new file mode 100644 index 000000000..91664a34b --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/BindingData.java @@ -0,0 +1,21 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +/** + * BindingData. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface BindingData {} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/Composition.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/Composition.java new file mode 100644 index 000000000..817dc1fc8 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/Composition.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.composer.v1.V1ContextMapperModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; + +/** + * Utility class for Component-specific Composition classes. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class Composition { + + /** + * Gets a ContextMapper instance based on the supported binding data type. + * @param the type of binding data + * @param bindingDataType the binding data type + * @return the ContextMapper instance + */ + public static final ContextMapper getContextMapper(Class bindingDataType) { + return ContextMapperFactory.getContextMapperFactory(bindingDataType).newContextMapperDefault(); + } + + /** + * Gets a ContextMapper instance based on the supported binding data type. + * @param the type of binding data + * @param bindingDataType the binding data type + * @param contextMapperModel specific context mapper details + * @return the ContextMapper instance + */ + public static final ContextMapper getContextMapper(Class bindingDataType, ContextMapperModel contextMapperModel) { + if (contextMapperModel == null) { + // If you don't specify a ContexMapperInfo, your ContextMapper will not match anything! + contextMapperModel = new V1ContextMapperModel(SwitchYardNamespace.DEFAULT.uri()).setExcludes(".*"); + } + return ContextMapperFactory.getContextMapperFactory(bindingDataType).newContextMapper(contextMapperModel); + } + + /** + * Gets a MessageComposer instance based on the supported binding data type. + * @param the type of binding data + * @param bindingDataType the binding data type + * @return the MessageComposer instance + */ + public static final MessageComposer getMessageComposer(Class bindingDataType) { + MessageComposer messageComposer = MessageComposerFactory.getMessageComposerFactory(bindingDataType).newMessageComposerDefault(); + messageComposer.setContextMapper(getContextMapper(bindingDataType)); + return messageComposer; + } + + /** + * Gets a MessageComposer instance based on the supported binding data type. + * @param the type of binding data + * @param bindingDataType the binding data type + * @param contextMapperModel specific context mapper details + * @param messageComposerModel message composer details + * @return the MessageComposer instance + */ + public static final MessageComposer getMessageComposer(Class bindingDataType, ContextMapperModel contextMapperModel, MessageComposerModel messageComposerModel) { + MessageComposer messageComposer = MessageComposerFactory.getMessageComposerFactory(bindingDataType).newMessageComposer(messageComposerModel); + messageComposer.setContextMapper(getContextMapper(bindingDataType, contextMapperModel)); + return messageComposer; + } + + private Composition() {} + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/ContextMapper.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/ContextMapper.java new file mode 100644 index 000000000..3c595ef00 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/ContextMapper.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import org.switchyard.Context; +import org.switchyard.config.model.composer.ContextMapperModel; + +/** + * Maps context properties from and to a source or target object. + * + * @param the type of binding data + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public interface ContextMapper { + + /** + * Gets the model. + * @return the model + */ + public ContextMapperModel getModel(); + + /** + * Sets the model. + * @param model the model + */ + public void setModel(ContextMapperModel model); + + /** + * Maps a source object's properties to the context. + * @param source the object to map from + * @param context the context to map to + * @throws Exception if there was a problem + */ + public void mapFrom(D source, Context context) throws Exception; + + /** + * Maps a context's properties into a target object. + * @param context the context to map from + * @param target the target to map to + * @throws Exception if there was a problem + */ + public void mapTo(Context context, D target) throws Exception; + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/ContextMapperFactory.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/ContextMapperFactory.java new file mode 100644 index 000000000..c912345ae --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/ContextMapperFactory.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.common.type.Classes; +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.component.common.CommonCommonLogger; +import org.switchyard.config.model.composer.ContextMapperModel; + +/** + * Utility AND base class making it easy for Component developers to specify their own ContextMapper implementations. + * + * @param the type of binding data + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class ContextMapperFactory { + + /** + * Component developer should implement this message to specify the type of source/target object. + * @return the type of source/target object + */ + public abstract Class getBindingDataClass(); + + /** + * Component developer should implement this message to provide their default/fallback implementation + * if the ContextMapperModel passed into {@link ContextMapperFactory#newContextMapper(ContextMapperModel)} + * doesn't specify (or specifies a bad) context mapper class to use. + * @return the default/fallback context mapper implementation + */ + public abstract ContextMapper newContextMapperDefault(); + + /** + * Will create a new ContextMapper based on the specifications of the passed in ContextMapperModel, or if + * a class it not specified, will apply the rest of the model properties on the default/fallback implementation. + * @param model contains the config details + * @return the new ContextMapper instance + */ + @SuppressWarnings("unchecked") + public final ContextMapper newContextMapper(ContextMapperModel model) { + ContextMapper contextMapper = null; + ContextMapperFactory contextMapperFactory = ContextMapperFactory.getContextMapperFactory(getBindingDataClass()); + if (model != null) { + contextMapper = contextMapperFactory.newContextMapper((Class>)Classes.forName(model.getClazz())); + contextMapper.setModel(model); + if (contextMapper instanceof RegexContextMapper) { + RegexContextMapper regexContextMapper = (RegexContextMapper)contextMapper; + regexContextMapper.setIncludes(model.getIncludes()); + regexContextMapper.setExcludes(model.getExcludes()); + regexContextMapper.setIncludeNamespaces(model.getIncludeNamespaces()); + regexContextMapper.setExcludeNamespaces(model.getExcludeNamespaces()); + } + } else { + contextMapper = contextMapperFactory.newContextMapperDefault(); + } + return contextMapper; + } + + /** + * Will create a new custom ContextMapper based on the specified class, or if it can't, will use the + * default/fallback implementation. + * @param custom the custom ContextMapper class + * @return the new ContextMapper instance + */ + public final ContextMapper newContextMapper(Class> custom) { + ContextMapper contextMapper = null; + if (custom != null) { + try { + contextMapper = custom.newInstance(); + } catch (Exception e) { + CommonCommonLogger.ROOT_LOGGER.couldNotInstantiateContextMapper(custom.getClass().getName(), e.getMessage()); + } + } + if (contextMapper == null) { + contextMapper = newContextMapperDefault(); + } + return contextMapper; + } + + /** + * Constructs a new ContextMapperFactory that is known to be able to construct ContextMappers + * of the specified type. + * @param the type of binding data + * @param targetClass the target ContextMapper class + * @return the new ContextMapperFactory instance + */ + @SuppressWarnings("unchecked") + public static final ContextMapperFactory getContextMapperFactory(Class targetClass) { + return (ContextMapperFactory)getContextMapperFactories().get(targetClass); + } + + /** + * Gets a map of all known ContextMapperFactories, keyed by their supported source/target object type. + * @return the ContextMapperFactories map + */ + @SuppressWarnings("rawtypes") + public static final Map getContextMapperFactories() { + Map factories = new HashMap(); + List services = ProviderRegistry.getProviders(ContextMapperFactory.class); + for (ContextMapperFactory factory : services) { + factories.put(factory.getBindingDataClass(), factory); + } + return factories; + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/MessageComposer.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/MessageComposer.java new file mode 100644 index 000000000..f46600dbb --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/MessageComposer.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import org.switchyard.Exchange; +import org.switchyard.Message; + +/** + * Composes or decomposes SwitchYard Messages (via their Exchange) to and from a source or target object. + * + * @param the type of binding data + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface MessageComposer { + + /** + * Gets this message composer's associated context mapper. + * @return the context mapper + */ + public ContextMapper getContextMapper(); + + /** + * Sets this message composer's associated context mapper. + * @param contextMapper the context mapper + * @return this message composer (useful for chaining) + */ + public MessageComposer setContextMapper(ContextMapper contextMapper); + + /** + * Takes the data from the passed in source object and composes a SwithYardMessage based on the specified Exchange. + * @param source the source object + * @param exchange the exchange to use + * @return the composed message + * @throws Exception if a problem happens + */ + public Message compose(D source, Exchange exchange) throws Exception; + + /** + * Takes the data from the SwitchYardMessage in the specified Exchange and decomposes it into the target object. + * @param exchange the exchange to use + * @param target the target object + * @return the new target object (could be the same or different than the original target) + * @throws Exception if a problem happens + */ + public D decompose(Exchange exchange, D target) throws Exception; + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/MessageComposerFactory.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/MessageComposerFactory.java new file mode 100644 index 000000000..2ccebcbfb --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/MessageComposerFactory.java @@ -0,0 +1,117 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.common.type.Classes; +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.component.common.CommonCommonLogger; +import org.switchyard.config.model.composer.MessageComposerModel; + +/** + * Utility AND base class making it easy for Component developers to specify their own MessageComposer implementations. + * + * @param the type of binding data + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class MessageComposerFactory { + + /** + * Component developer should implement this message to specify the type of source/target object. + * @return the type of source/target object + */ + public abstract Class getBindingDataClass(); + + /** + * Component developer should implement this message to provide their default/fallback implementation + * if the MessageComposerInfo passed into {@link MessageComposerFactory#newMessageComposer(MessageComposerInfo)} + * doesn't specify (or specifies a bad) message composer class to use. + * @return the default/fallback message composer implementation + */ + public abstract MessageComposer newMessageComposerDefault(); + + /** + * Will create a new MessageComposer based on the specifications of the passed in MessageComposerInfo, or if + * a class it not specified, will apply the rest of the info properties on the default/fallback implementation. + * @param model contains the config details + * @return the new MessageComposer instance + */ + @SuppressWarnings("unchecked") + public final MessageComposer newMessageComposer(MessageComposerModel model) { + MessageComposer messageComposer = null; + MessageComposerFactory messageComposerFactory = MessageComposerFactory.getMessageComposerFactory(getBindingDataClass()); + if (model != null) { + messageComposer = messageComposerFactory.newMessageComposer((Class>)Classes.forName(model.getClazz())); + } else { + messageComposer = messageComposerFactory.newMessageComposerDefault(); + } + return messageComposer; + } + + /** + * Will create a new custom MessageComposer based on the specified class, or if it can't, will use the + * default/fallback implementation. + * @param custom the custom MessageComposer class + * @return the new MessageComposer instance + */ + public final MessageComposer newMessageComposer(Class> custom) { + MessageComposer messageComposer = null; + if (custom != null) { + try { + messageComposer = custom.newInstance(); + } catch (Exception e) { + CommonCommonLogger.ROOT_LOGGER.couldNotInstantiateMessageComposer(custom.getClass().getName(), e.getMessage()); + } + } + if (messageComposer == null) { + messageComposer = newMessageComposerDefault(); + } + return messageComposer; + } + + /** + * Constructs a new MessageComposerFactory that is known to be able to construct MessageComposers + * of the specified type. + * @param the type of binding data + * @param targetClass the target MessageComposer class + * @return the new MessageComposerFactory instance + */ + @SuppressWarnings("unchecked") + public static final MessageComposerFactory getMessageComposerFactory(Class targetClass) { + MessageComposerFactory factory = (MessageComposerFactory)getMessageComposerFactories().get(targetClass); + if (factory == null) { + throw new IllegalStateException("Unable to find composer factory for " + targetClass.getName()); + } + return factory; + } + + /** + * Gets a map of all known MessageComposerFactories, keyed by their supported source/target object type. + * @return the MessageComposerFactories map + */ + @SuppressWarnings("rawtypes") + public static final Map getMessageComposerFactories() { + Map factories = new HashMap(); + List services = ProviderRegistry.getProviders(MessageComposerFactory.class); + for (MessageComposerFactory factory : services) { + factories.put(factory.getBindingDataClass(), factory); + } + return factories; + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/RegexContextMapper.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/RegexContextMapper.java new file mode 100644 index 000000000..39db45042 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/RegexContextMapper.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import javax.xml.namespace.QName; + +/** + * Maps context properties from and to a source or target object, with the ability to selectively choose which properties with regex expressions. + * + * @param the type of binding data + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface RegexContextMapper extends ContextMapper { + + /** + * Sets a comma-separated list of regex property includes. + * @param includes the includes + * @return this ContextMapper (useful for chaining) + */ + public ContextMapper setIncludes(String includes); + + /** + * Sets a comma-separated list of regex property excludes. + * @param excludes the excludes + * @return this ContextMapper (useful for chaining) + */ + public ContextMapper setExcludes(String excludes); + + /** + * Sets a comma-separated list of regex property namespace includes. + * @param includeNamespaces the namespace includes + * @return this ContextMapper (useful for chaining) + */ + public ContextMapper setIncludeNamespaces(String includeNamespaces); + + /** + * Sets a comma-separated list of regex property namespace excludes. + * @param excludeNamespaces the namespace excludes + * @return this ContextMapper (useful for chaining) + */ + public ContextMapper setExcludeNamespaces(String excludeNamespaces); + + /** + * Decides if the specified name passes the collective regex expressions. + * @param name the name to test + * @return whether the name passes the matching tests + */ + public boolean matches(String name); + + /** + * Decides if the specified qualified name passes the collective regex expressions. + * @param qname the qualified name to test + * @return whether the qualified name passes the matching tests + */ + public boolean matches(QName qname); + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/composer/SecurityBindingData.java b/components/common/common/src/main/java/org/switchyard/component/common/composer/SecurityBindingData.java new file mode 100644 index 000000000..1876a82de --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/composer/SecurityBindingData.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import java.util.Set; + +import org.switchyard.security.credential.Credential; + +/** + * SecurityBindingData. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface SecurityBindingData extends BindingData { + + /** + * Extracts the Credentials from the SecurityBindingData. + * @return the Credentials + */ + public Set extractCredentials(); + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/label/ComponentLabel.java b/components/common/common/src/main/java/org/switchyard/component/common/label/ComponentLabel.java new file mode 100644 index 000000000..4c6d4cdc8 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/label/ComponentLabel.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.label; + +import org.switchyard.label.Label; + +/** + * Represents component labels. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum ComponentLabel implements Label { + + /** Component labels. */ + CAMEL, HORNETQ, HTTP, JCA, RESTEASY, SOAP; + + private final String _label; + + private ComponentLabel() { + _label = Label.Util.toSwitchYardLabel("component", name()); + } + + /** + * {@inheritDoc} + */ + @Override + public String label() { + return _label; + } + + /** + * Gets the ComponentLabel enum via case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the ComponentLabel enum + */ + public static final ComponentLabel ofName(String name) { + return Label.Util.ofName(ComponentLabel.class, name); + } + + /** + * Gets the full-form component label from the case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the full-form component label + */ + public static final String toLabel(String name) { + ComponentLabel label = ofName(name); + return label != null ? label.label() : null; + } + + /** + * Prints all known component labels. + * @param args ignored + */ + public static void main(String... args) { + Label.Util.print(values()); + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/label/EndpointLabel.java b/components/common/common/src/main/java/org/switchyard/component/common/label/EndpointLabel.java new file mode 100644 index 000000000..70bf7bc3e --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/label/EndpointLabel.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.label; + +import org.switchyard.label.Label; + +/** + * Represents endpoint labels. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum EndpointLabel implements Label { + + /** Endpoint labels. */ + AMQP, ATOM, DIRECT, FILE, FTP, FTPS, HTTP, JCA, JMS, JPA, MAIL, MOCK, QUARTZ, REST, RSS, SEDA, SFTP, SOAP, SQL, TCP, TIMER, UDP, URI; + + private final String _label; + + private EndpointLabel() { + _label = Label.Util.toSwitchYardLabel("endpoint", name()); + } + + /** + * {@inheritDoc} + */ + @Override + public String label() { + return _label; + } + + /** + * Gets the EndpointLabel enum via case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the EndpointLabel enum + */ + public static final EndpointLabel ofName(String name) { + return Label.Util.ofName(EndpointLabel.class, name); + } + + /** + * Gets the full-form endpoint label from the case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the full-form endpoint label + */ + public static final String toLabel(String name) { + EndpointLabel label = ofName(name); + return label != null ? label.label() : null; + } + + /** + * Prints all known endpoint labels. + * @param args ignored + */ + public static void main(String... args) { + Label.Util.print(values()); + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/label/PropertyLabel.java b/components/common/common/src/main/java/org/switchyard/component/common/label/PropertyLabel.java new file mode 100644 index 000000000..ff0b0df5b --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/label/PropertyLabel.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.label; + +import org.switchyard.label.Label; + +/** + * Represents property labels. + */ +public enum PropertyLabel implements Label { + + /** Property labels. */ + HEADER, PROPERTY; + + private final String _label; + + private PropertyLabel() { + _label = Label.Util.toSwitchYardLabel("property", name()); + } + + /** + * {@inheritDoc} + */ + @Override + public String label() { + return _label; + } + + /** + * Gets the PropertyLabel enum via case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the PropertyLabel enum + */ + public static final PropertyLabel ofName(String name) { + return Label.Util.ofName(PropertyLabel.class, name); + } + + /** + * Gets the full-form property label from the case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the full-form property label + */ + public static final String toLabel(String name) { + PropertyLabel label = ofName(name); + return label != null ? label.label() : null; + } + + /** + * Prints all known property labels. + * @param args ignored + */ + public static void main(String... args) { + Label.Util.print(values()); + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/selector/BaseOperationSelector.java b/components/common/common/src/main/java/org/switchyard/component/common/selector/BaseOperationSelector.java new file mode 100644 index 000000000..d862a94c5 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/selector/BaseOperationSelector.java @@ -0,0 +1,142 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.common.selector; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathFactory; + +import org.switchyard.component.common.CommonCommonMessages; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.switchyard.config.model.selector.RegexOperationSelectorModel; +import org.switchyard.config.model.selector.StaticOperationSelectorModel; +import org.switchyard.config.model.selector.XPathOperationSelectorModel; +import org.switchyard.selector.OperationSelector; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; + +/** + * A base class of OperationSelector which determine the operation to be mapped to the binding. + * + * @param the type of source object + */ +public abstract class BaseOperationSelector implements OperationSelector { + + private String _defaultNamespace; + + private OperationSelectorModel _model; + + /** + * Constructor. + * @param model OperationSelectorModel + */ + public BaseOperationSelector(OperationSelectorModel model) { + _model = model; + } + + @Override + + public QName selectOperation(T content) throws Exception { + QName operationQName = null; + + if (_model instanceof StaticOperationSelectorModel) { + StaticOperationSelectorModel staticModel = StaticOperationSelectorModel.class.cast(_model); + operationQName = QName.valueOf(staticModel.getOperationName()); + + } else if (_model instanceof XPathOperationSelectorModel) { + XPathOperationSelectorModel xpathModel = XPathOperationSelectorModel.class.cast(_model); + operationQName = xpathMatch(xpathModel.getExpression(), extractDomDocument(content)); + } else if (_model instanceof RegexOperationSelectorModel) { + RegexOperationSelectorModel regexModel = RegexOperationSelectorModel.class.cast(_model); + operationQName = regexMatch(regexModel.getExpression(), extractString(content)); + } else { + throw CommonCommonMessages.MESSAGES.unsupportedOperationSelectorConfiguration(_model.toString()); + } + + if (_defaultNamespace != null && operationQName.getNamespaceURI().equals(XMLConstants.NULL_NS_URI)) { + operationQName = new QName(_defaultNamespace, operationQName.getLocalPart(), operationQName.getPrefix()); + } + return operationQName; + } + + @Override + public String getDefaultNamespace() { + return _defaultNamespace; + } + + @Override + public OperationSelector setDefaultNamespace(String namespace) { + _defaultNamespace = namespace; + return this; + } + + /** + * Extract a DOM Document from content. + * + * @param content content + * @return extracted DOM Document + */ + protected abstract Document extractDomDocument(T content) throws Exception; + + /** + * Extract a String from content. + * + * @param content content + * @return extracted String + */ + protected abstract String extractString(T content) throws Exception; + + private QName xpathMatch(String expression, Document content) throws Exception { + XPathFactory factory = XPathFactory.newInstance(); + XPath xpath = factory.newXPath(); + NodeList result = null; + try { + XPathExpression expr = xpath.compile(expression); + result = NodeList.class.cast(expr.evaluate(content, XPathConstants.NODESET)); + } catch (Exception e) { + throw CommonCommonMessages.MESSAGES.couldnTEvaluateXPathExpression(expression, e); + } + + if (result.getLength() == 1) { + return QName.valueOf(result.item(0).getTextContent()); + } else if (result.getLength() == 0) { + throw CommonCommonMessages.MESSAGES.noNodeHasBeenMatchedWithTheXPathExpression(expression); + } else { + throw CommonCommonMessages.MESSAGES.multipleNodesHaveBeenMatchedWithTheXPathExpression(expression); + } + } + + private QName regexMatch(String expression, String content) throws Exception { + Pattern pattern = Pattern.compile(expression); + Matcher matcher = pattern.matcher(content); + if (!matcher.find()) { + throw CommonCommonMessages.MESSAGES.noNodeHasBeenMatchedWithTheRegexExpression(expression); + } else { + String operation = matcher.group(); + + if (matcher.find()) { + throw CommonCommonMessages.MESSAGES.multipleNodesHaveBeenMatchedWithTheRegexExpression(expression); + } + return QName.valueOf(operation); + } + } + +} diff --git a/components/common/common/src/main/java/org/switchyard/component/common/selector/OperationSelectorFactory.java b/components/common/common/src/main/java/org/switchyard/component/common/selector/OperationSelectorFactory.java new file mode 100644 index 000000000..30648a547 --- /dev/null +++ b/components/common/common/src/main/java/org/switchyard/component/common/selector/OperationSelectorFactory.java @@ -0,0 +1,114 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.common.selector; + +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.common.type.Classes; +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.component.common.CommonCommonLogger; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.switchyard.config.model.selector.JavaOperationSelectorModel; +import org.switchyard.selector.OperationSelector; + +/** + * A base OperationSelectorFactory which creates OperationSelector instance. + * @param message type + */ +public abstract class OperationSelectorFactory { + + /** + * Component developer should implement this message to specify the type of source object. + * @return the type of source object + */ + public abstract Class getTargetClass(); + + /** + * Component developer should implement this message to provide their default/fallback implementation + * if the OperationSelectorModel passed into {@link OperationSelectorFactory#newOperationSelector(OperationSelectorModel)} + * doesn't specify (or specifies a bad) operation selector class to use. + * @return the default/fallback operation selector implementation + */ + public abstract Class> getDefaultOperationSelectorClass(); + + /** + * Create a new OperationSelector from configuration model. + * @param model OperationSelectorModel + * @return new OperationSelector instance + */ + @SuppressWarnings("unchecked") + public final OperationSelector newOperationSelector(OperationSelectorModel model) { + if (model == null) { + return null; + } + + OperationSelectorFactory operationSelectorFactory = OperationSelectorFactory.getOperationSelectorFactory(getTargetClass()); + if (model instanceof JavaOperationSelectorModel) { + JavaOperationSelectorModel javaModel = JavaOperationSelectorModel.class.cast(model); + return operationSelectorFactory.newOperationSelector((Class>)Classes.forName(javaModel.getClazz()), javaModel); + } else { + return operationSelectorFactory.newOperationSelector(operationSelectorFactory.getDefaultOperationSelectorClass(), model); + } + } + + /** + * Constructs a new OperationSelector. + * @param custom OperationSelector class + * @param model OperationSelector model + * @return the new OperationSelector instance + */ + public final OperationSelector newOperationSelector(Class> custom, OperationSelectorModel model) { + OperationSelector operationSelector = null; + if (custom != null) { + try { + Constructor> constructor = custom.getConstructor(OperationSelectorModel.class); + operationSelector = constructor.newInstance(model); + } catch (Exception e) { + CommonCommonLogger.ROOT_LOGGER.couldNotInstantiateOperationSelector(custom.getClass().getName(), e.getMessage()); + } + } + return operationSelector; + } + + /** + * Constructs a new OperationSelectorFactory that is known to be able to construct OperationSelectors + * of the specified type. + * @param the type of source object + * @param targetClass the target OperationSelector class + * @return the new OperationSelectorFactory instance + */ + @SuppressWarnings("unchecked") + public static final OperationSelectorFactory getOperationSelectorFactory(Class targetClass) { + return (OperationSelectorFactory)getOperationSelectorFactories().get(targetClass); + } + + /** + * Gets a map of all known OperationSelectorFactories, keyed by their supported source object type. + * @return the OperationSelectorFactories map + */ + @SuppressWarnings("rawtypes") + public static final Map getOperationSelectorFactories() { + Map factories = new HashMap(); + List services = ProviderRegistry.getProviders(OperationSelectorFactory.class); + for (OperationSelectorFactory factory : services) { + factories.put(factory.getTargetClass(), factory); + } + return factories; + } + +} diff --git a/components/common/common/src/test/java/org/switchyard/component/common/composer/RegexContextMapperTests.java b/components/common/common/src/test/java/org/switchyard/component/common/composer/RegexContextMapperTests.java new file mode 100644 index 000000000..c89c91ae3 --- /dev/null +++ b/components/common/common/src/test/java/org/switchyard/component/common/composer/RegexContextMapperTests.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.composer; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.xml.XMLHelper; + +/** + * RegexContextMapperTests. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RegexContextMapperTests { + + private static final class TestData implements BindingData {} + + private RegexContextMapper _regexContextMapper; + + @Before + public void before() throws Exception { + _regexContextMapper = new BaseRegexContextMapper(); + } + + @After + public void after() throws Exception { + _regexContextMapper = null; + } + + @Test + public void testName() throws Exception { + assertTrue(_regexContextMapper.matches("foo")); + } + + @Test + public void testNameIncludeEverything() throws Exception { + _regexContextMapper.setIncludes(".*"); + assertTrue(_regexContextMapper.matches("foo")); + } + + @Test + public void testNameExcludeEverything() throws Exception { + _regexContextMapper.setExcludes(".*"); + assertFalse(_regexContextMapper.matches("foo")); + } + + @Test + public void testNameIncludeEverythingExcludeEverything() throws Exception { + _regexContextMapper.setIncludes(".*"); + _regexContextMapper.setExcludes(".*"); + assertFalse(_regexContextMapper.matches("foo")); + } + + @Test + public void testNameIncludeFooExcludeBar() throws Exception { + _regexContextMapper.setIncludes(".*foo.*"); + _regexContextMapper.setExcludes(".*bar.*"); + assertTrue(_regexContextMapper.matches("abc_foo_def")); + assertFalse(_regexContextMapper.matches("abc_bar_def")); + } + + @Test + public void testQName() throws Exception { + _regexContextMapper.setIncludeNamespaces("urn:foo:1.0"); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "banana"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "banana"))); + } + + @Test + public void testQNameIncludeEverything() throws Exception { + _regexContextMapper.setIncludeNamespaces(".*"); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "banana"))); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "banana"))); + } + + @Test + public void testQNameIncludeEverythingExcludeEverything() throws Exception { + _regexContextMapper.setIncludeNamespaces(".*"); + _regexContextMapper.setExcludeNamespaces(".*"); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "banana"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "banana"))); + } + + @Test + public void testQNameIncludeFooIncludeBar() throws Exception { + _regexContextMapper.setIncludeNamespaces("urn:foo:1.0"); + _regexContextMapper.setIncludes("bar"); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "bar"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "banana"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "bar"))); + } + + @Test + public void testQNameFooExcludeTxt() throws Exception { + _regexContextMapper.setIncludeNamespaces("urn:foo:.*"); + _regexContextMapper.setExcludes(".*.txt"); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "bar.xml"))); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "bar.pdf"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "bar.txt"))); + } + + @Test + public void testQNameInclude2Exclude1() throws Exception { + _regexContextMapper.setIncludeNamespaces("urn:.*:2.0"); + _regexContextMapper.setExcludeNamespaces("urn:.*:1.0"); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "foo"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "foo"))); + } + + @Test + public void testMixedIncludesExcludes() throws Exception { + _regexContextMapper.setIncludes("david, tom.*"); + _regexContextMapper.setExcludes("keith"); + _regexContextMapper.setIncludeNamespaces("urn:.*:2.0,urn:.*:3.0"); + _regexContextMapper.setExcludeNamespaces("urn:.*:3.0"); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "tomc"))); + assertTrue(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "tomf"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:1.0", "tomc"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:3.0", "david"))); + assertFalse(_regexContextMapper.matches(XMLHelper.createQName("urn:foo:2.0", "keith"))); + } + +} diff --git a/components/common/common/src/test/java/org/switchyard/component/common/selector/OperationSelectorTest.java b/components/common/common/src/test/java/org/switchyard/component/common/selector/OperationSelectorTest.java new file mode 100644 index 000000000..db8fdf697 --- /dev/null +++ b/components/common/common/src/test/java/org/switchyard/component/common/selector/OperationSelectorTest.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.selector; + +import java.io.StringReader; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.switchyard.config.model.selector.RegexOperationSelectorModel; +import org.switchyard.config.model.selector.StaticOperationSelectorModel; +import org.switchyard.config.model.selector.XPathOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1RegexOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1StaticOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1XPathOperationSelectorModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.selector.OperationSelector; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +public class OperationSelectorTest { + + @Test + public void testStatic() throws Exception { + String namespace = "urn:operation-selector-test:1.0"; + String namespace2 = "urn:operation-selector-test:2.0"; + String operation = "invoke"; + String fullname = "{" + namespace2 + "}" + operation; + + StaticOperationSelectorModel model = new V1StaticOperationSelectorModel(SwitchYardNamespace.DEFAULT.uri()); + model.setOperationName(operation); + OperationSelector selector = new MyOperationSelector(model); + + QName operationQName = selector.selectOperation(null); + Assert.assertEquals(XMLConstants.NULL_NS_URI, operationQName.getNamespaceURI()); + Assert.assertEquals(operation, operationQName.getLocalPart()); + + selector.setDefaultNamespace(namespace); + operationQName = selector.selectOperation(null); + Assert.assertEquals(namespace, operationQName.getNamespaceURI()); + Assert.assertEquals(operation, operationQName.getLocalPart()); + + model.setOperationName(fullname); + selector = new MyOperationSelector(model); + selector.setDefaultNamespace(namespace); + operationQName = selector.selectOperation(null); + Assert.assertEquals(namespace2, operationQName.getNamespaceURI()); + Assert.assertEquals(operation, operationQName.getLocalPart()); + + } + + @Test + public void testXPath() throws Exception { + String expression = "/Message/Operation"; + String expressionAttribute = "/Message/Operation/@name"; + String content = "xpathOperation"; + + XPathOperationSelectorModel model = new V1XPathOperationSelectorModel(SwitchYardNamespace.DEFAULT.uri()); + model.setExpression(expression); + OperationSelector selector = new MyOperationSelector(model); + QName operationQName = selector.selectOperation(content); + Assert.assertEquals("xpathOperation", operationQName.getLocalPart()); + + model.setExpression(expressionAttribute); + selector = new MyOperationSelector(model); + operationQName = selector.selectOperation(content); + Assert.assertEquals("xpathOperationFromAttribute", operationQName.getLocalPart()); + } + + @Test + public void testRegex() throws Exception { + String expression = "[a-zA-Z]*Operation"; + String content = "xxx yyy zzz regexOperation aaa bbb ccc"; + + RegexOperationSelectorModel model = new V1RegexOperationSelectorModel(SwitchYardNamespace.DEFAULT.uri()); + model.setExpression(expression); + OperationSelector selector = new MyOperationSelector(model); + QName operationQName = selector.selectOperation(content); + Assert.assertEquals("regexOperation", operationQName.getLocalPart()); + } + + public class MyOperationSelector extends BaseOperationSelector { + public MyOperationSelector(OperationSelectorModel model) { + super(model); + } + + @Override + protected Document extractDomDocument(String content) + throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(extractString(content))); + return builder.parse(is); + } + + @Override + protected String extractString(String content) throws Exception { + return content; + } + } + +} diff --git a/components/common/knowledge/pom.xml b/components/common/knowledge/pom.xml new file mode 100644 index 000000000..437660030 --- /dev/null +++ b/components/common/knowledge/pom.xml @@ -0,0 +1,153 @@ + + + + 4.0.0 + switchyard-component-common-knowledge + bundle + SwitchYard: Knowledge Common Component Library + The SwitchYard Knowledge Common Component Library. + http://switchyard.org + + org.switchyard.components + switchyard-component-common-parent + 2.1.0-SNAPSHOT + ../pom.xml + + + + org.switchyard.component.common.knowledge.* + + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.common.io;${switchyard.osgi.import.switchyard.version}, + org.switchyard.common.io.resource;${switchyard.osgi.import.switchyard.version}, + org.hibernate.*;resolution:=optional, + * + + + org.jbpm.*, + org.drools.*, + org.kie.* + + + org.kie.api + + + + + + org.switchyard + switchyard-serial + + + org.switchyard.components + switchyard-component-common + + + + org.drools + drools-compiler + + + org.drools + drools-core + + + org.drools + drools-decisiontables + + + org.drools + drools-persistence-jpa + + + org.eclipse.aether + aether-api + + + org.hibernate + hibernate-core + + + org.jbpm + jbpm-audit + + + org.jbpm + jbpm-bpmn2 + + + org.jbpm + jbpm-flow + + + org.jbpm + jbpm-human-task-core + + + org.jbpm + jbpm-human-task-jpa + + + org.jbpm + jbpm-human-task-workitems + + + org.jbpm + jbpm-persistence-jpa + + + org.jbpm + jbpm-runtime-manager + + + org.jbpm + jbpm-workitems + + + org.kie + kie-api + + + org.kie + kie-ci + + provided + + + org.kie + kie-internal + + + org.kie.remote + kie-remote-client + + + org.mvel + mvel2 + + + + org.osgi + org.osgi.core + provided + + + org.osgi + org.osgi.compendium + provided + + + diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/CommonKnowledgeLogger.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/CommonKnowledgeLogger.java new file mode 100644 index 000000000..1f4264724 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/CommonKnowledgeLogger.java @@ -0,0 +1,97 @@ +package org.switchyard.component.common.knowledge; + +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 34600-34699 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface CommonKnowledgeLogger { + /** + * A root logger with the category of the package name. + */ + CommonKnowledgeLogger ROOT_LOGGER = Logger.getMessageLogger(CommonKnowledgeLogger.class, CommonKnowledgeLogger.class.getPackage().getName()); + + /** + * problemDisposing method definition. + * @param disposalClassSimpleName disposalClassSimpleName + * @param tMessage tMessage + */ + @LogMessage(level = Level.WARN) + @Message(id = 34600, value = "problem disposing [%s]: %s") + void problemDisposing(String disposalClassSimpleName, String tMessage); + + /** + * problemClosingEntityManagerFactory method definition. + * @param tMessage tMessage + */ + @LogMessage(level = Level.WARN) + @Message(id = 34601, value = "problem closing EntityManagerFactory: %s") + void problemClosingEntityManagerFactory(String tMessage); + + /** + * problemClosingKieRuntimeLogger method definition. + * @param tMessage tMessage + */ + @LogMessage(level = Level.WARN) + @Message(id = 34602, value = "problem closing KieRuntimeLogger: %s") + void problemClosingKieRuntimeLogger(String tMessage); + + /** + * problemStopppingKieScanner method definition. + * @param tMessage tMessage + */ + @LogMessage(level = Level.WARN) + @Message(id = 34603, value = "problem stoppping KieScanner: %s") + void problemStopppingKieScanner(String tMessage); + + /** + * problemDisposingKieSession method definition. + * @param tMessage tMessage + */ + @LogMessage(level = Level.WARN) + @Message(id = 34604, value = "problem disposing KieSession: %s") + void problemDisposingKieSession(String tMessage); + + /* SWITCHYARD-1755 + * problemDisposingKnowledgeAgent method definition. + * @param tMessage tMessage + * + @LogMessage(level = Level.WARN) + @Message(id = 34605, value = "problem disposing KnowledgeAgent: %s") + void problemDisposingKnowledgeAgent(String tMessage); + */ + + /** + * emsg method definition. + * @param emsg the emsg + */ + @LogMessage(level = Level.ERROR) + @Message(id = 34606, value = "%s") + void formattedFaultMessage(String emsg); + + /** + * unknownDefaultingTo method definition. + * @param faultAction the faultAction + * @param fa the fa + * @param message the message + * @param name the FaultAction.DEFAULT.name()) + */ + @LogMessage(level = Level.WARN) + @Message(id = 34607, value = "Unknown %s: %s (%s). Defaulting to %s.") + void unknownDefaultingTo(String faultAction, String fa, String message, String name); + + /** + * attemptToRegisterListenerReturnedNull method definition. + */ + @LogMessage(level = Level.DEBUG) + @Message(id = 34608, value = "Attempt to register listener returned null") + void attemptToRegisterListenerReturnedNull(); +} + diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/CommonKnowledgeMessages.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/CommonKnowledgeMessages.java new file mode 100644 index 000000000..e9c466d1e --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/CommonKnowledgeMessages.java @@ -0,0 +1,234 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge; + +import javax.transaction.HeuristicMixedException; +import javax.transaction.HeuristicRollbackException; +import javax.transaction.NotSupportedException; +import javax.transaction.RollbackException; +import javax.transaction.SystemException; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 34700-34799 for logger messages. + *

+ * + */ +/** + * @author tcunning + * + */ +@SuppressWarnings("deprecation") +@MessageBundle(projectCode = "SWITCHYARD") +public interface CommonKnowledgeMessages { + /** + * The default messages. + */ + CommonKnowledgeMessages MESSAGES = Messages.getBundle(CommonKnowledgeMessages.class); + + /** + * unknownExpressionType method definition. + * @param expressionType the expressionType + * @return IllegalArgumentException + */ + @Message(id = 34700, value = "Unknown expression type: %s") + IllegalArgumentException unknownExpressionType(String expressionType); + + /** + * serviceNameNull method definition. + * @return SwitchYardException + */ + @Message(id = 34701, value = "ServiceName == null") + SwitchYardException serviceNameNull(); + + /** + * serviceDomainNull method definition. + * @return SwitchYardException + */ + @Message(id = 34702, value = "ServiceDomain == null") + SwitchYardException serviceDomainNull(); + + /** + * serviceReferenceNull method definition. + * @param serviceName the serviceName + * @return SwitchYardException + */ + @Message(id = 34703, value = "ServiceReference [%s] == null") + SwitchYardException serviceReferenceNull(String serviceName); + + /** + * manifestContainerRequiredInConfigurationForPersistentSessions method definition. + * @return SwitchYardException + */ + @Message(id = 34706, value = "manifest container required in configuration for persistent sessions") + SwitchYardException manifestContainerRequiredInConfigurationForPersistentSessions(); + + /** + * containerScanIntervalMustBePositive method definition. + * @return IllegalArgumentException + */ + @Message(id = 34707, value = "container scanInterval must be positive") + IllegalArgumentException containerScanIntervalMustBePositive(); + + /** + * couldNotUseNullNameToRegisterChannel method definition. + * @param channelClassName channelClassName + * @return SwitchYardException + */ + @Message(id = 34708, value = "Could not use null name to register channel: %s") + SwitchYardException couldNotUseNullNameToRegisterChannel(String channelClassName); + + /** + * couldNotLoadListenerClass method definition. + * @param listenerModelClass listenerModelClass + * @return SwitchYardException + */ + @Message(id = 34709, value = "Could not load listener class: %s") + SwitchYardException couldNotLoadListenerClass(String listenerModelClass); + + /** + * couldNotInstantiateListenerClass method definition. + * @param listenerClassName listenerClassName + * @return SwitchYardException + */ + @Message(id = 34710, value = "Could not instantiate listener class: %s") + SwitchYardException couldNotInstantiateListenerClass(String listenerClassName); + + /** + * cannotRegisterOperation method definition. + * @param type type + * @param name name + * @return SwitchYardException + */ + @Message(id = 34711, value = "cannot register %s operation due to duplicate name: %s") + SwitchYardException cannotRegisterOperation(String type, String name); + + /** + * problemBuildingKnowledge method definition. + * @return String + */ + @Message(id = 34712, value = "Problem building knowledge") + String problemBuildingKnowledge(); + + /** + * faultEncountered method definition. + * @return String + */ + @Message(id = 34713, value = "Fault encountered") + String faultEncountered(); + + /** + * userTransactionBeginFailed method definition. + * @param se the se + * @return HandlerException + */ + @Message(id = 34714, value = "UserTransaction begin failed") + HandlerException userTransactionBeginFailedSystem(@Cause SystemException se); + + /** + * userTransactionBeginFailed method definition. + * @param nse the nse + * @return HandlerException + */ + @Message(id = 34715, value = "UserTransaction begin failed") + HandlerException userTransactionBeginFailedNSE(@Cause NotSupportedException nse); + + /** + * userTransactionCommitFailed method definition. + * @param se the se + * @return HandlerException + */ + @Message(id = 34716, value = "UserTransaction commit failed") + HandlerException userTransactionCommitFailedSystem(@Cause SystemException se); + + /** + * userTransactionCommitFailed method definition. + * @param hre the hre + * @return HandlerException + */ + @Message(id = 34717, value = "UserTransaction commit failed") + HandlerException userTransactionCommitFailedRollback(@Cause HeuristicRollbackException hre); + + /** + * userTransactionCommitFailed method definition. + * @param hme the hme + * @return HandlerException + */ + @Message(id = 34718, value = "UserTransaction commit failed") + HandlerException userTransactionCommitFailedMixed(@Cause HeuristicMixedException hme); + + /** + * userTransactionCommitFailed method definition. + * @param re the re + * @return HandlerException + */ + @Message(id = 34719, value = "UserTransaction commit failed") + HandlerException userTransactionCommitFailed(@Cause RollbackException re); + + /** + * userTransactionRollbackFailed method definition. + * @param se the se + * @return HandlerException + */ + @Message(id = 34720, value = "UserTransaction rollback failed") + HandlerException userTransactionRollbackFailed(@Cause SystemException se); + + /** + * userTransactionSetRollbackOnlyFailed method definition. + * @param se the se + * @return HandlerException + */ + @Message(id = 34721, value = "UserTransaction setRollbackOnly failed") + HandlerException userTransactionSetRollbackOnlyFailed(@Cause SystemException se); + + /** + * couldNotInstantiateUserGroupCallbackClass method definition. + * @param callbackClassName callbackClassName + * @return SwitchYardException + */ + @Message(id = 34722, value = "Could not instantiate userGroupCallback class: %s") + SwitchYardException couldNotInstantiateUserGroupCallbackClass(String callbackClassName); + + /** + * couldNotLoadWorkItemHandlerClass method definition. + * @param workItemHandlerModelClass workItemHandlerModelClass + * @return SwitchYardException + */ + @Message(id = 34723, value = "Could not load workItemHandler class: %s") + SwitchYardException couldNotLoadWorkItemHandlerClass(String workItemHandlerModelClass); + + /** + * couldNotUseNullNameToRegisterWorkItemHandler method definition. + * @param workItemHandlerClassName workItemHandlerClassName + * @return SwitchYardException + */ + @Message(id = 34724, value = "Could not use null name to register workItemHandler: %s") + SwitchYardException couldNotUseNullNameToRegisterWorkItemHandler(String workItemHandlerClassName); + + /** + * couldNotInstantiateWorkItemHandlerClass method definition. + * @param workItemHandlerClassName workItemHandlerClassName + * @return SwitchYardException + */ + @Message(id = 34725, value = "Could not instantiate workItemHandler class: %s") + SwitchYardException couldNotInstantiateWorkItemHandlerClass(String workItemHandlerClassName); +} + diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/KnowledgeConstants.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/KnowledgeConstants.java new file mode 100644 index 000000000..bdecbcfff --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/KnowledgeConstants.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge; + +/** + * Rules constants. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class KnowledgeConstants { + + /** default. */ + public static final String DEFAULT = "default"; + /** globals. */ + public static final String GLOBALS = "globals"; + /** context. */ + public static final String CONTEXT = "context"; + /** message. */ + public static final String MESSAGE = "message"; + + /** Parameter. */ + public static final String PARAMETER = "Parameter"; + /** Result. */ + public static final String RESULT = "Result"; + /** Fault. */ + public static final String FAULT = "Fault"; + + private KnowledgeConstants() {} + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/LoggerType.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/LoggerType.java new file mode 100644 index 000000000..588a1a408 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/LoggerType.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge; + +/** + * Represents logger types. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum LoggerType { + + /** The console logger type. */ + CONSOLE, + /** The file logger type. */ + FILE, + /** The threaded file logger type. */ + THREADED_FILE; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Channel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Channel.java new file mode 100644 index 000000000..547337e03 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Channel.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Channel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Channel { + + /** The channel class. */ + public Class value() default UndefinedChannel.class; + + /** The service reference interface. */ + public Class interfaze() default UndefinedInterface.class; + + /** The channel name. */ + public String name() default ""; + + /** The service reference operation. */ + public String operation() default ""; + + /** The service reference name. */ + public String reference() default ""; + + /** Undefined channel. */ + public static interface UndefinedChannel extends org.kie.api.runtime.Channel {}; + /** Undefined interface. */ + public static interface UndefinedInterface {}; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Container.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Container.java new file mode 100644 index 000000000..86020fc8f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Container.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Container. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Container { + + /** Base name. */ + public String baseName() default ""; + + /** ReleaseId. */ + public String releaseId() default ""; + + /** Scan. */ + public boolean scan() default false; + + /** ScanInterval. */ + public long scanInterval() default -1; + + /** Session name. */ + public String sessionName() default ""; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Fault.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Fault.java new file mode 100644 index 000000000..948f001ac --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Fault.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Fault. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Fault { + + /** From. */ + public String from(); + + /** To. */ + public String to() default ""; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Global.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Global.java new file mode 100644 index 000000000..425ca01bf --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Global.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Global. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Global { + + /** From. */ + public String from(); + + /** To. */ + public String to() default ""; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Input.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Input.java new file mode 100644 index 000000000..945824887 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Input.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Input. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Input { + + /** From. */ + public String from(); + + /** To. */ + public String to() default ""; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Listener.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Listener.java new file mode 100644 index 000000000..a576b028a --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Listener.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import java.util.EventListener; + +/** + * Listener. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Listener { + + /** Listener class. */ + public Class value(); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Logger.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Logger.java new file mode 100644 index 000000000..9bce8e1fa --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Logger.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.LoggerType; + +/** + * Logger. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Logger { + + /** Interval. */ + public int interval() default -1; + + /** Log. */ + public String log() default ""; + + /** Type. */ + public LoggerType type() default LoggerType.THREADED_FILE; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Manifest.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Manifest.java new file mode 100644 index 000000000..f43a1002d --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Manifest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Manifest. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Manifest { + + /** Container. */ + public Container[] container() default {}; + + /** Resources. */ + public Resource[] resources() default {}; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Output.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Output.java new file mode 100644 index 000000000..6de1c3d06 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Output.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Output. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Output { + + /** From. */ + public String from(); + + /** To. */ + public String to() default ""; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Property.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Property.java new file mode 100644 index 000000000..29f63b41b --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Property.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Property. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Property { + + /** Name. */ + public String name(); + + /** Value. */ + public String value(); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Resource.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Resource.java new file mode 100644 index 000000000..23db2e0ee --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/Resource.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Resource. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Resource { + + /** Location. */ + public String location(); + + /** Type. */ + public String type(); + + /** Detail. */ + public ResourceDetail[] detail() default {}; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/ResourceDetail.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/ResourceDetail.java new file mode 100644 index 000000000..b50fa52cd --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/annotation/ResourceDetail.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * ResourceDetail. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface ResourceDetail { + + /** InputType. */ + public String inputType(); + + /** WorksheetName. */ + public String worksheetName() default ""; + + /* SWITCHYARD-1662 + UsingExternalTypes. + public boolean usingExternalTypes() default false; + */ + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ChannelBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ChannelBuilder.java new file mode 100644 index 000000000..d769640ba --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ChannelBuilder.java @@ -0,0 +1,125 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.kie.api.runtime.Channel; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.ChannelModel; +import org.switchyard.component.common.knowledge.config.model.ChannelsModel; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.service.SwitchYardServiceChannel; +import org.switchyard.component.common.knowledge.service.SwitchYardServiceInvoker; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.deploy.ComponentNames; + +/** + * ChannelBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class ChannelBuilder extends KnowledgeBuilder { + + private Class _channelClass; + private String _channelName; + private QName _serviceName; + private String _operationName; + private String _targetNamespace; + + /** + * Creates a new ChannelBuilder. + * @param classLoader classLoader + * @param serviceDomain serviceDomain + * @param channelModel channelModel + */ + @SuppressWarnings("unchecked") + public ChannelBuilder(ClassLoader classLoader, ServiceDomain serviceDomain, ChannelModel channelModel) { + super(classLoader, serviceDomain); + if (channelModel != null) { + ChannelsModel channelsModel = (ChannelsModel)channelModel.getModelParent(); + KnowledgeComponentImplementationModel implementationModel = (KnowledgeComponentImplementationModel)channelsModel.getModelParent(); + ComponentModel componentModel = implementationModel.getComponent(); + QName componentName = componentModel.getQName(); + _targetNamespace = componentModel.getTargetNamespace(); + _channelClass = (Class)channelModel.getClazz(getClassLoader()); + if (_channelClass == null) { + _channelClass = SwitchYardServiceChannel.class; + } + _channelName = channelModel.getName(); + if (_channelName == null && SwitchYardServiceChannel.class.isAssignableFrom(_channelClass)) { + _channelName = SwitchYardServiceChannel.SERVICE; + } + _serviceName = XMLHelper.createQName(channelModel.getReference()); + if (_serviceName != null && componentName != null) { + _serviceName = ComponentNames.qualify(componentName, ComponentNames.unqualify(_serviceName)); + } + _operationName = channelModel.getOperation(); + } + } + + /** + * Gets the channel name. + * @return the channel name + */ + public String getChannelName() { + return _channelName; + } + + /** + * Builds a Channel. + * @return a Channel + */ + public Channel build() { + Channel channel = null; + if (_channelClass != null) { + channel = Construction.construct(_channelClass); + if (channel instanceof SwitchYardServiceChannel) { + SwitchYardServiceChannel sysc = (SwitchYardServiceChannel)channel; + sysc.setServiceName(_serviceName); + sysc.setOperationName(_operationName); + sysc.setInvoker(new SwitchYardServiceInvoker(getServiceDomain(), _targetNamespace)); + } + } + return channel; + } + + /** + * Creates ChannelBuilders. + * @param classLoader classLoader + * @param serviceDomain serviceDomain + * @param implementationModel implementationModel + * @return ChannelBuilders + */ + public static List builders(ClassLoader classLoader, ServiceDomain serviceDomain, KnowledgeComponentImplementationModel implementationModel) { + List builders = new ArrayList(); + if (implementationModel != null) { + ChannelsModel channelsModel = implementationModel.getChannels(); + if (channelsModel != null) { + for (ChannelModel channelModel : channelsModel.getChannels()) { + if (channelModel != null) { + builders.add(new ChannelBuilder(classLoader, serviceDomain, channelModel)); + } + } + } + } + return builders; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/EntityManagerFactoryBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/EntityManagerFactoryBuilder.java new file mode 100644 index 000000000..85de9542a --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/EntityManagerFactoryBuilder.java @@ -0,0 +1,67 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import javax.persistence.EntityManagerFactory; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.knowledge.persistence.EntityManagerFactoryLoader; +import org.switchyard.component.common.knowledge.persistence.NoopEntityManagerFactory; +import org.switchyard.component.common.knowledge.persistence.OSGiEntityManagerFactoryLoader; + +/** + * EntityManagerFactoryBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class EntityManagerFactoryBuilder extends KnowledgeBuilder { + + private static final EntityManagerFactoryLoader EMF_LOADER; + static { + // hacky way to integrate with OSGi. + EntityManagerFactoryLoader loader = new EntityManagerFactoryLoader(); + try { + loader = new OSGiEntityManagerFactoryLoader(); + } catch (Exception e) { + // above fails if OSGi types are not available. + e.fillInStackTrace(); + } + EMF_LOADER = loader; + } + + private final boolean _persistent; + + /** + * Creates a new EntityManagerFactoryBuilder. + * @param serviceDomain serviceDomain + * @param persistent persistent + */ + public EntityManagerFactoryBuilder(ServiceDomain serviceDomain, boolean persistent) { + super(null, serviceDomain); + _persistent = persistent; + } + + /** + * Builds an EntityManagerFactory. + * @return an EntityManagerFactory + */ + public EntityManagerFactory build() { + if (_persistent) { + return EMF_LOADER.getEntityManagerFactory(getServiceDomain()); + } else { + return new NoopEntityManagerFactory(); + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/KnowledgeBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/KnowledgeBuilder.java new file mode 100644 index 000000000..9bd8812ec --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/KnowledgeBuilder.java @@ -0,0 +1,69 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import org.switchyard.ServiceDomain; + +/** + * KnowledgeBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public abstract class KnowledgeBuilder { + + private final ClassLoader _classLoader; + private final ServiceDomain _serviceDomain; + + /** + * Creates a new KnowledgeBuilder. + */ + public KnowledgeBuilder() { + this(null, null); + } + + /** + * Creates a new KnowledgeBuilder. + * @param classLoader classLoader + */ + public KnowledgeBuilder(ClassLoader classLoader) { + this(classLoader, null); + } + + /** + * Creates a new KnowledgeBuilder. + * @param classLoader classLoader + * @param serviceDomain serviceDomain + */ + public KnowledgeBuilder(ClassLoader classLoader, ServiceDomain serviceDomain) { + _classLoader = classLoader != null ? classLoader : getClass().getClassLoader(); + _serviceDomain = serviceDomain; + } + + /** + * Gets the classLoader. + * @return the classLoader + */ + public final ClassLoader getClassLoader() { + return _classLoader; + } + + /** + * Gets the serviceDomain. + * @return the serviceDomain + */ + public final ServiceDomain getServiceDomain() { + return _serviceDomain; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ListenerBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ListenerBuilder.java new file mode 100644 index 000000000..169989d93 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ListenerBuilder.java @@ -0,0 +1,138 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.EventListener; +import java.util.List; + +import org.kie.api.event.KieRuntimeEventManager; +import org.kie.api.runtime.KieRuntime; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.component.common.knowledge.CommonKnowledgeLogger; +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.ListenerModel; +import org.switchyard.component.common.knowledge.config.model.ListenersModel; + +/** + * ListenerBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class ListenerBuilder extends KnowledgeBuilder { + + private static final Class[][] PARMAMETER_TYPES = new Class[][]{ + new Class[]{KieRuntimeEventManager.class}, + new Class[]{KieRuntime.class}, + new Class[0] + }; + + private Class _listenerClass; + private boolean _automaticRegistration; + + /** + * Creates a new ListenerBuilder. + * @param classLoader classLoader + * @param listenerModel listenerModel + */ + @SuppressWarnings("unchecked") + public ListenerBuilder(ClassLoader classLoader, ListenerModel listenerModel) { + super(classLoader); + if (listenerModel != null) { + _listenerClass = (Class)listenerModel.getClazz(getClassLoader()); + if (_listenerClass == null) { + throw CommonKnowledgeMessages.MESSAGES.couldNotLoadListenerClass(listenerModel.getModelConfiguration().getAttribute("class")); + } + } + } + + /** + * If automatic registration was performed. + *

+ * Note: This method only returns a reliable result after {@link #build()} has been called. + * @return if automatic registration has been performed + */ + public boolean wasAutomaticRegistration() { + return _automaticRegistration; + } + + /** + * Builds an EventListener. + * @param runtimeEventManager runtimeEventManager + * @return an EventListener + */ + public EventListener build(KieRuntimeEventManager runtimeEventManager) { + return construct(runtimeEventManager); + } + + private EventListener construct(KieRuntimeEventManager runtimeEventManager) { + EventListener listener = null; + if (_listenerClass != null) { + Constructor constructor = null; + for (Class[] parameterTypes : PARMAMETER_TYPES) { + try { + constructor = _listenerClass.getConstructor(parameterTypes); + if (constructor != null) { + break; + } + } catch (Throwable t) { + // keep checkstyle happy ("at least one statement") + t.getMessage(); + } + } + Class[] parameterTypes = constructor != null ? constructor.getParameterTypes() : new Class[0]; + try { + if (parameterTypes.length == 0) { + listener = Construction.construct(_listenerClass); + // manual registration + _automaticRegistration = false; + } else if (parameterTypes.length == 1) { + // automatic registration + listener = Construction.construct(_listenerClass, parameterTypes, new Object[]{runtimeEventManager}); + if (listener == null) { + CommonKnowledgeLogger.ROOT_LOGGER.attemptToRegisterListenerReturnedNull(); + } + _automaticRegistration = true; + } + } catch (Throwable t) { + throw CommonKnowledgeMessages.MESSAGES.couldNotInstantiateListenerClass(_listenerClass.getName()); + } + } + return listener; + } + + /** + * Creates ListenerBuilders. + * @param classLoader classLoader + * @param implementationModel implementationModel + * @return ListenerBuilders + */ + public static List builders(ClassLoader classLoader, KnowledgeComponentImplementationModel implementationModel) { + List builders = new ArrayList(); + if (implementationModel != null) { + ListenersModel listenersModel = implementationModel.getListeners(); + if (listenersModel != null) { + for (ListenerModel listenerModel : listenersModel.getListeners()) { + if (listenerModel != null) { + builders.add(new ListenerBuilder(classLoader, listenerModel)); + } + } + } + } + return builders; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/LoggerBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/LoggerBuilder.java new file mode 100644 index 000000000..d110ba153 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/LoggerBuilder.java @@ -0,0 +1,108 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.util.ArrayList; +import java.util.List; + +import org.kie.api.KieServices; +import org.kie.api.event.KieRuntimeEventManager; +import org.kie.api.logger.KieLoggers; +import org.kie.api.logger.KieRuntimeLogger; +import org.switchyard.common.lang.Strings; +import org.switchyard.component.common.knowledge.LoggerType; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.LoggerModel; +import org.switchyard.component.common.knowledge.config.model.LoggersModel; + +/** + * LoggerBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class LoggerBuilder extends KnowledgeBuilder { + + private LoggerType _loggerType; + private String _log; + private Integer _interval; + + /** + * Creates a new LoggerBuilder. + * @param classLoader classLoader + * @param loggerModel loggerModel + */ + public LoggerBuilder(ClassLoader classLoader, LoggerModel loggerModel) { + super(classLoader); + if (loggerModel != null) { + _loggerType = loggerModel.getType(); + _log = Strings.trimToNull(loggerModel.getLog()); + _interval = loggerModel.getInterval(); + } + if (_loggerType == null) { + _loggerType = LoggerType.THREADED_FILE; + } + if (_log == null) { + _log = "event"; + } + if (_interval == null) { + _interval = Integer.valueOf(1000); + } + } + + /** + * Builds a KieRuntimeLogger. + * @param runtimeEventManager runtimeEventManager + * @return a KieRuntimeLogger + */ + public KieRuntimeLogger build(KieRuntimeEventManager runtimeEventManager) { + KieRuntimeLogger logger = null; + if (_loggerType != null && runtimeEventManager != null) { + KieLoggers loggers = KieServices.Factory.get().getLoggers(); + switch (_loggerType) { + case CONSOLE: + logger = loggers.newConsoleLogger(runtimeEventManager); + break; + case FILE: + logger = loggers.newFileLogger(runtimeEventManager, _log); + break; + case THREADED_FILE: + logger = loggers.newThreadedFileLogger(runtimeEventManager, _log, _interval); + break; + } + } + return logger; + } + + /** + * Creates LoggerBuilders. + * @param classLoader classLoader + * @param implementationModel implementationModel + * @return LoggerBuilders + */ + public static List builders(ClassLoader classLoader, KnowledgeComponentImplementationModel implementationModel) { + List builders = new ArrayList(); + if (implementationModel != null) { + LoggersModel loggersModel = implementationModel.getLoggers(); + if (loggersModel != null) { + for (LoggerModel loggerModel : loggersModel.getLoggers()) { + if (loggerModel != null) { + builders.add(new LoggerBuilder(classLoader, loggerModel)); + } + } + } + } + return builders; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ManifestBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ManifestBuilder.java new file mode 100644 index 000000000..beeeb9849 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ManifestBuilder.java @@ -0,0 +1,89 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import org.switchyard.component.common.knowledge.config.manifest.ContainerManifest; +import org.switchyard.component.common.knowledge.config.manifest.Manifest; +import org.switchyard.component.common.knowledge.config.manifest.RemoteManifest; +import org.switchyard.component.common.knowledge.config.manifest.ResourcesManifest; +import org.switchyard.component.common.knowledge.config.model.ContainerModel; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.ManifestModel; +import org.switchyard.component.common.knowledge.config.model.RemoteModel; +import org.switchyard.config.model.resource.ResourcesModel; + +/** + * ManifestBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class ManifestBuilder extends KnowledgeBuilder { + + private final Manifest _manifest; + + /** + * Creates a new ManifestBuilder. + * @param classLoader classLoader + * @param manifestModel manifestModel + */ + public ManifestBuilder(ClassLoader classLoader, ManifestModel manifestModel) { + super(classLoader); + Manifest manifest = null; + if (manifestModel != null) { + ContainerModel containerModel = manifestModel.getContainer(); + if (containerModel != null) { + manifest = new ContainerManifest( + containerModel.getBaseName(), + containerModel.getReleaseId(), + containerModel.isScan(), + containerModel.getScanInterval(), + containerModel.getSessionName()); + } else { + ResourcesModel resourcesModel = manifestModel.getResources(); + if (resourcesModel != null) { + manifest = new ResourcesManifest(ResourceBuilder.builders(getClassLoader(), resourcesModel)); + } else { + RemoteModel remoteModel = manifestModel.getRemote(); + if (remoteModel != null) { + manifest = new RemoteManifest(new RemoteConfigurationBuilder(getClassLoader(), remoteModel)); + } + } + } + } + if (manifest == null) { + manifest = new ContainerManifest(); + } + _manifest = manifest; + } + + /** + * Builds a Manifest. + * @return a Manifest + */ + public Manifest build() { + return _manifest; + } + + /** + * Creates a ManifestBuilder. + * @param classLoader classLoader + * @param implementationModel implementationModel + * @return a ManifestBuilder + */ + public static ManifestBuilder builder(ClassLoader classLoader, KnowledgeComponentImplementationModel implementationModel) { + ManifestModel manifestModel = implementationModel != null ? implementationModel.getManifest() : null; + return new ManifestBuilder(classLoader, manifestModel); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/PropertiesBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/PropertiesBuilder.java new file mode 100644 index 000000000..7b8b727bf --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/PropertiesBuilder.java @@ -0,0 +1,112 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.util.Properties; + +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * PropertiesBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class PropertiesBuilder extends KnowledgeBuilder { + + private Properties _defaultProperties; + private Properties _modelProperties; + private Properties _overrideProperties; + + /** + * Creates a new PropertiesBuilder. + */ + public PropertiesBuilder() {} + + /** + * Creates a new PropertiesBuilder. + * @param propertiesModel sets the model properties + */ + public PropertiesBuilder(PropertiesModel propertiesModel) { + setModelProperties(propertiesModel); + } + + /** + * Sets the default properties. + * @param defaultProperties the default properties + * @return this PropertiesBuilder + */ + public PropertiesBuilder setDefaultProperties(Properties defaultProperties) { + _defaultProperties = defaultProperties; + return this; + } + + /** + * Sets the model properties. + * @param propertiesModel the properties model + * @return this PropertiesBuilder + */ + public PropertiesBuilder setModelProperties(PropertiesModel propertiesModel) { + _modelProperties = propertiesModel != null ? propertiesModel.toProperties() : null; + return this; + } + + /** + * Sets the override properties. + * @param overrideProperties the override properties + * @return this PropertisBuilder + */ + public PropertiesBuilder setOverrideProperties(Properties overrideProperties) { + _overrideProperties = overrideProperties; + return this; + } + + /** + * Builds a Properties. + * @return a Properties + */ + public Properties build() { + Properties buildProperties = new Properties(); + merge(_defaultProperties, buildProperties); + merge(_modelProperties, buildProperties); + merge(_overrideProperties, buildProperties); + return buildProperties; + } + + private void merge(Properties fromProperties, Properties toProperties) { + if (fromProperties != null && toProperties != null) { + for (Object key : fromProperties.keySet()) { + String name = (String)key; + String value = fromProperties.getProperty(name); + if (value != null) { + toProperties.put(name, value); + } + } + } + } + + /** + * Creates a PropertiesBuilder. + * @param implementationModel implementationModel + * @return a PropertiesBuilder + */ + public static PropertiesBuilder builder(KnowledgeComponentImplementationModel implementationModel) { + PropertiesModel propertiesModel = null; + if (implementationModel != null) { + propertiesModel = implementationModel.getProperties(); + } + return new PropertiesBuilder(propertiesModel); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RegisterableItemsFactoryBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RegisterableItemsFactoryBuilder.java new file mode 100644 index 000000000..7e9fcd544 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RegisterableItemsFactoryBuilder.java @@ -0,0 +1,152 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.EventListener; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.jbpm.runtime.manager.impl.RuntimeEngineImpl; +import org.kie.api.event.KieRuntimeEventManager; +import org.kie.api.event.kiebase.KieBaseEventListener; +import org.kie.api.event.process.ProcessEventListener; +import org.kie.api.event.rule.AgendaEventListener; +import org.kie.api.event.rule.RuleRuntimeEventListener; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.manager.RuntimeManager; +import org.kie.api.runtime.process.ProcessRuntime; +import org.kie.api.runtime.process.WorkItemHandler; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.knowledge.config.items.ExtendedRegisterableItemsFactory; +import org.switchyard.component.common.knowledge.config.items.NoopExtendedRegisterableItemsFactory; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.event.EventPublisherProcessEventListener; + +/** + * RegisterableItemsFactoryBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class RegisterableItemsFactoryBuilder extends KnowledgeBuilder { + + private final List _listenerBuilders; + private final boolean _bpm; + private final List _workItemHandlerBuilders; + + /** + * Creates a new RegisterableItemsFactoryBuilder. + * @param classLoader classLoader + * @param serviceDomain serviceDomain + * @param implementationModel implementationModel + */ + public RegisterableItemsFactoryBuilder(ClassLoader classLoader, ServiceDomain serviceDomain, KnowledgeComponentImplementationModel implementationModel) { + super(classLoader, serviceDomain); + _listenerBuilders = ListenerBuilder.builders(getClassLoader(), implementationModel); + _bpm = implementationModel != null && "bpm".equals(implementationModel.getType()); + if (_bpm) { + _workItemHandlerBuilders = WorkItemHandlerBuilder.builders(getClassLoader(), serviceDomain, implementationModel); + } else { + _workItemHandlerBuilders = Collections.emptyList(); + } + } + + /** + * Builds a ExtendedRegisterableItemsFactory. + * @return a ExtendedRegisterableItemsFactory + */ + public ExtendedRegisterableItemsFactory build() { + return new NoopExtendedRegisterableItemsFactory() { + private RuntimeEngine _runtime; + private List _listeners = new ArrayList(); + private synchronized List listeners(RuntimeEngine runtime) { + if (_runtime != runtime) { + _runtime = runtime; + _listeners.clear(); + KieRuntimeEventManager runtimeEventManager = _runtime.getKieSession(); + for (ListenerBuilder builder : _listenerBuilders) { + EventListener listener = builder.build(runtimeEventManager); + if (listener != null && !builder.wasAutomaticRegistration()) { + _listeners.add(listener); + } + } + } + return new ArrayList(_listeners); + } + @Override + public List getAgendaEventListeners(RuntimeEngine runtime) { + List list = new ArrayList(); + for (EventListener listener : listeners(runtime)) { + if (listener instanceof AgendaEventListener) { + list.add((AgendaEventListener)listener); + } + } + return list; + } + @Override + public List getProcessEventListeners(RuntimeEngine runtime) { + List list = new ArrayList(); + if (_bpm) { + // always add our EventPublisherProcessEventListener for bpm component + list.add(new EventPublisherProcessEventListener(getServiceDomain().getEventPublisher())); + } + for (EventListener listener : listeners(runtime)) { + if (listener instanceof ProcessEventListener) { + list.add((ProcessEventListener)listener); + } + } + return list; + } + @Override + public List getRuleRuntimeEventListeners(RuntimeEngine runtime) { + List list = new ArrayList(); + for (EventListener listener : listeners(runtime)) { + if (listener instanceof RuleRuntimeEventListener) { + list.add((RuleRuntimeEventListener)listener); + } + } + return list; + } + @Override + public Map getWorkItemHandlers(RuntimeEngine runtime) { + Map map = new LinkedHashMap(); + // wih builder list will always be empty for rules component + for (WorkItemHandlerBuilder builder : _workItemHandlerBuilders) { + ProcessRuntime processRuntime = runtime.getKieSession(); + RuntimeManager runtimeManager = null; + if (runtime instanceof RuntimeEngineImpl) { + runtimeManager = ((RuntimeEngineImpl)runtime).getManager(); + } + String name = builder.getWorkItemHandlerName(); + WorkItemHandler handler = builder.build(processRuntime, runtimeManager); + map.put(name, handler); + } + return map; + } + @Override + public List getKieBaseEventListeners(RuntimeEngine runtime) { + List list = new ArrayList(); + for (EventListener listener : listeners(runtime)) { + if (listener instanceof KieBaseEventListener) { + list.add((KieBaseEventListener)listener); + } + } + return list; + } + }; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RemoteConfigurationBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RemoteConfigurationBuilder.java new file mode 100644 index 000000000..ff3c348b0 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RemoteConfigurationBuilder.java @@ -0,0 +1,218 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Properties; +import java.util.Set; + +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.drools.core.command.runtime.BatchExecutionCommandImpl; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.remote.client.api.RemoteJmsRuntimeEngineBuilder; +import org.kie.remote.client.api.RemoteRestRuntimeEngineBuilder; +import org.kie.remote.client.api.RemoteRuntimeEngineBuilder; +import org.kie.remote.client.jaxb.AcceptedClientCommands; +import org.kie.services.client.api.RemoteRuntimeEngineFactory; +import org.kie.services.client.api.command.RemoteConfiguration; +import org.kie.services.client.api.command.RemoteRuntimeEngine; +import org.switchyard.common.type.reflect.Access; +import org.switchyard.common.type.reflect.FieldAccess; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel; +import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel; +import org.switchyard.component.common.knowledge.config.model.RemoteModel; +import org.switchyard.component.common.knowledge.config.model.RemoteRestModel; + +/** + * RemoteConfigurationBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class RemoteConfigurationBuilder extends KnowledgeBuilder { + + private static Set> acceptedCommands = new HashSet>(); + static { + Access>> access = new FieldAccess>>(AcceptedClientCommands.class, "acceptedCommands"); + acceptedCommands.addAll(access.read(null)); + acceptedCommands.add(BatchExecutionCommandImpl.class); + acceptedCommands = Collections.unmodifiableSet(acceptedCommands); + access.write(null, acceptedCommands); + } + + private final RemoteConfiguration _remoteConfiguration; + + /** + * Creates a new RemoteConfigurationBuilder. + * @param classLoader classLoader + * @param remoteModel remoteModel + */ + public RemoteConfigurationBuilder(ClassLoader classLoader, RemoteModel remoteModel) { + super(classLoader); + _remoteConfiguration = buildRemoteConfiguration(remoteModel); + } + + private RemoteConfiguration buildRemoteConfiguration(RemoteModel remoteModel) { + RuntimeEngine engine = null; + if (remoteModel instanceof RemoteJmsModel) { + RemoteJmsRuntimeEngineBuilder builder = RemoteRuntimeEngineFactory.newJmsBuilder(); + InitialContext ctx = configRemoteJms(builder, (RemoteJmsModel)remoteModel); + try { + engine = builder.build(); + } finally { + if (ctx != null) { + try { + ctx.close(); + } catch (Exception e) { + e.getMessage(); // ignore but keep checkstyle happy + } + } + } + } else if (remoteModel instanceof RemoteRestModel) { + RemoteRestRuntimeEngineBuilder builder = RemoteRuntimeEngineFactory.newRestBuilder(); + configRemoteRest(builder, (RemoteRestModel)remoteModel); + engine = builder.build(); + } + RemoteConfiguration config = null; + if (engine instanceof RemoteRuntimeEngine) { + Access configAccess = new FieldAccess(RemoteRuntimeEngine.class, "config"); + config = configAccess.isReadable() ? configAccess.read(engine) : null; + } + return config; + } + + private InitialContext configRemoteJms(RemoteJmsRuntimeEngineBuilder builder, RemoteJmsModel model) { + configRemote(builder, model); + InitialContext ctx = null; + String hostName = model.getHostName(); + if (hostName != null) { + builder.addHostName(hostName); + try { + Properties props = new Properties(); + props.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); + Integer remotingPort = model.getRemotingPort(); + if (remotingPort == null) { + // default EAP remoting port + remotingPort = Integer.valueOf(4447); + } + props.setProperty(InitialContext.PROVIDER_URL, "remote://"+ hostName + ":" + remotingPort); + String userName = model.getUserName(); + if (userName != null) { + props.setProperty(InitialContext.SECURITY_PRINCIPAL, userName); + } + String password = model.getPassword(); + if (password != null) { + props.setProperty(InitialContext.SECURITY_CREDENTIALS, password); + } + ctx = new InitialContext(props); + builder.addRemoteInitialContext(ctx); + } catch (NamingException ne) { + throw new RuntimeException(ne); + } + } else { + try { + ctx = new InitialContext(); + builder.addRemoteInitialContext(ctx); + } catch (NamingException ne) { + throw new RuntimeException(ne); + } + } + Integer messagingPort = model.getMessagingPort(); + if (messagingPort == null) { + // default EAP messaging port + messagingPort = Integer.valueOf(5455); + } + builder.addJmsConnectorPort(messagingPort); + builder.useSsl(model.isUseSsl()); + String keystorePassword = model.getKeystorePassword(); + if (keystorePassword != null) { + builder.addKeystorePassword(keystorePassword); + // same by default; can be overridden below + builder.addTruststorePassword(keystorePassword); + } + String keystoreLocation = model.getKeystoreLocation(); + if (keystoreLocation != null) { + builder.addKeystoreLocation(keystoreLocation); + // same by default; can be overridden below + builder.addTruststoreLocation(keystoreLocation); + } + String truststorePassword = model.getTruststorePassword(); + if (truststorePassword != null) { + builder.addTruststorePassword(truststorePassword); + } + String truststoreLocation = model.getTruststoreLocation(); + if (truststoreLocation != null) { + builder.addTruststoreLocation(truststoreLocation); + } + return ctx; + } + + @SuppressWarnings("deprecation") + private void configRemoteRest(RemoteRestRuntimeEngineBuilder builder, RemoteRestModel model) { + configRemote(builder, model); + try { + builder.addUrl(new URL(model.getUrl())); + } catch (MalformedURLException mue) { + throw new RuntimeException(mue); + } + builder.useFormBasedAuth(model.isUseFormBasedAuth()); + } + + private void configRemote(RemoteRuntimeEngineBuilder builder, RemoteModel model) { + builder.addDeploymentId(model.getDeploymentId()); + String userName = model.getUserName(); + if (userName != null) { + builder.addUserName(userName); + } + String password = model.getPassword(); + if (password != null) { + builder.addPassword(password); + } + Integer timeout = model.getTimeout(); + if (timeout != null) { + builder.addTimeout(timeout.intValue()); + } + ExtraJaxbClassesModel extraJaxbClasses = model.getExtraJaxbClasses(); + if (extraJaxbClasses != null) { + Set> clazzes = new LinkedHashSet>(); + ClassLoader loader = getClassLoader(); + for (ExtraJaxbClassModel extraJaxbClass : extraJaxbClasses.getExtraJaxbClasses()) { + Class clazz = extraJaxbClass.getClazz(loader); + if (clazz != null) { + clazzes.add(clazz); + } + } + int cs = clazzes.size(); + if (cs > 0) { + builder.addExtraJaxbClasses(clazzes.toArray(new Class[cs])); + } + } + builder.addExtraJaxbClasses(acceptedCommands.toArray(new Class[acceptedCommands.size()])); + } + + /** + * Builds a RemoteConfiguration. + * @return a RemoteConfiguration + */ + public RemoteConfiguration build() { + return _remoteConfiguration.clone(); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ResourceBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ResourceBuilder.java new file mode 100644 index 000000000..5729a706b --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/ResourceBuilder.java @@ -0,0 +1,173 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.kie.api.KieServices; +import org.kie.api.io.KieResources; +import org.kie.api.io.Resource; +import org.kie.api.io.ResourceConfiguration; +import org.kie.api.io.ResourceType; +// SWITCHYARD-1755: internal builder class usage still required (public APIs insufficient) +import org.kie.internal.builder.DecisionTableConfiguration; +import org.kie.internal.builder.DecisionTableInputType; +import org.kie.internal.builder.KnowledgeBuilderFactory; +import org.switchyard.common.io.resource.ResourceDetail; +import org.switchyard.common.lang.Strings; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.ManifestModel; +import org.switchyard.config.model.resource.ResourceModel; +import org.switchyard.config.model.resource.ResourcesModel; + +/** + * ResourceBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class ResourceBuilder extends KnowledgeBuilder { + + private final KieResources _kieResources; + private URL _url; + private ResourceType _resourceType; + private ResourceConfiguration _resourceConfiguration; + + /** + * Creates a new ResourceBuilder. + * @param classLoader classLoader + * @param resourceModel resourceModel + */ + public ResourceBuilder(ClassLoader classLoader, ResourceModel resourceModel) { + super(classLoader); + _kieResources = KieServices.Factory.get().getResources(); + if (resourceModel != null) { + _url = resourceModel.getLocationURL(getClassLoader()); + _resourceType = convertResourceType(resourceModel.getType()); + ResourceDetail syResourceDetail = resourceModel.getDetail(); + if (syResourceDetail != null) { + if (ResourceType.DTABLE.equals(_resourceType)) { + String inputType = getInputType(syResourceDetail, DecisionTableInputType.XLS.toString()); + DecisionTableConfiguration dtc = KnowledgeBuilderFactory.newDecisionTableConfiguration(); + dtc.setInputType(DecisionTableInputType.valueOf(inputType)); + dtc.setWorksheetName(getWorksheetName(syResourceDetail)); + //dtc.setUsingExternalTypes(syResourceDetail.isUsingExternalTypes()); + _resourceConfiguration = dtc; + } + /* SWITCHYARD-1662 + else if (ResourceType.SCARD.equals(_resourceType)) { + String inputType = getInputType(syResourceDetail, ScoreCardConfiguration.SCORECARD_INPUT_TYPE.EXCEL.name()); + if ("XLS".equals(inputType)) { + inputType = ScoreCardConfiguration.SCORECARD_INPUT_TYPE.EXCEL.name(); + } + ScoreCardConfiguration scc = KnowledgeBuilderFactory.newScoreCardConfiguration(); + scc.setInputType(ScoreCardConfiguration.SCORECARD_INPUT_TYPE.valueOf(inputType)); + scc.setWorksheetName(getWorksheetName(syResourceDetail)); + //scc.setUsingExternalTypes(syResourceDetail.isUsingExternalTypes()); + _resourceConfiguration = scc; + } + */ + } + } + } + + /** + * Builds a Resource. + * @return a Resource + */ + public Resource build() { + Resource resource = null; + if (_url != null) { + resource = _kieResources.newUrlResource(_url); + if (resource != null) { + if (_resourceType != null) { + resource.setResourceType(_resourceType); + } + if (_resourceConfiguration != null) { + resource.setConfiguration(_resourceConfiguration); + } + } + } + return resource; + } + + private String getInputType(ResourceDetail syResourceDetail, String defaultInputType) { + String inputType = Strings.trimToNull(syResourceDetail.getInputType()); + if (inputType != null) { + inputType = inputType.toUpperCase(); + } else { + inputType = defaultInputType; + } + return inputType; + } + + private String getWorksheetName(ResourceDetail syResourceDetail) { + String worksheetName = syResourceDetail.getWorksheetName(); + if (worksheetName == null) { + worksheetName = ""; + } + return worksheetName; + } + + private ResourceType convertResourceType(org.switchyard.common.io.resource.ResourceType syResourceType) { + if (syResourceType != null) { + String resourceTypeName = syResourceType.getName(); + if ("BPMN".equals(resourceTypeName)) { + // Drools ResourceType recognizes BPMN2, not BPMN + resourceTypeName = ResourceType.BPMN2.getName(); + } else if ("XLS".equals(resourceTypeName) || "CSV".equals(resourceTypeName)) { + // Drools ResourceType recognizes DTABLE, not XLS or CSV + resourceTypeName = ResourceType.DTABLE.getName(); + } + return ResourceType.getResourceType(resourceTypeName); + } + return null; + } + + /** + * Creates ResourceBuilders. + * @param classLoader classLoader + * @param implementationModel implementationModel + * @return ResourceBuilders + */ + public static List builders(ClassLoader classLoader, KnowledgeComponentImplementationModel implementationModel) { + List builders = new ArrayList(); + if (implementationModel != null) { + ManifestModel manifestModel = implementationModel.getManifest(); + if (manifestModel != null) { + ResourcesModel resourcesModel = manifestModel.getResources(); + builders.addAll(builders(classLoader, resourcesModel)); + } + } + return builders; + } + + /** + * Creates ResourceBuilders. + * @param classLoader classLoader + * @param resourcesModel resourcesModel + * @return ResourceBuilders + */ + public static List builders(ClassLoader classLoader, ResourcesModel resourcesModel) { + List builders = new ArrayList(); + if (resourcesModel != null) { + for (ResourceModel resourceModel : resourcesModel.getResources()) { + builders.add(new ResourceBuilder(classLoader, resourceModel)); + } + } + return builders; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RuntimeEnvironmentBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RuntimeEnvironmentBuilder.java new file mode 100644 index 000000000..2b8413a96 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RuntimeEnvironmentBuilder.java @@ -0,0 +1,238 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.transaction.TransactionManager; +import javax.transaction.UserTransaction; + +import org.drools.core.command.CommandService; +import org.drools.core.impl.EnvironmentFactory; +import org.jbpm.runtime.manager.impl.KModuleRegisterableItemsFactory; +import org.jbpm.runtime.manager.impl.SimpleRuntimeEnvironment; +import org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorImpl; +import org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorManager; +import org.jbpm.runtime.manager.impl.mapper.InMemoryMapper; +import org.jbpm.runtime.manager.impl.mapper.JPAMapper; +import org.jbpm.services.task.commands.TaskCommandExecutorImpl; +import org.jbpm.services.task.events.TaskEventSupport; +import org.jbpm.services.task.impl.command.CommandBasedTaskService; +import org.kie.api.builder.ReleaseId; +import org.kie.api.io.Resource; +import org.kie.api.marshalling.ObjectMarshallingStrategy; +import org.kie.api.runtime.Environment; +import org.kie.api.runtime.EnvironmentName; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.manager.RegisterableItemsFactory; +import org.kie.api.runtime.manager.RuntimeEnvironment; +import org.kie.api.runtime.manager.RuntimeEnvironmentBuilderFactory; +import org.kie.api.task.TaskService; +import org.kie.api.task.UserGroupCallback; +import org.kie.internal.runtime.conf.AuditMode; +import org.kie.internal.runtime.conf.DeploymentDescriptor; +import org.kie.internal.runtime.manager.InternalRegisterableItemsFactory; +import org.kie.internal.runtime.manager.Mapper; +import org.kie.internal.runtime.manager.TaskServiceFactory; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.reflect.Access; +import org.switchyard.common.type.reflect.FieldAccess; +import org.switchyard.component.common.knowledge.config.builder.patch.PatchedLocalTaskServiceFactory; +import org.switchyard.component.common.knowledge.config.builder.patch.PatchedRuntimeEnvironmentBuilder; +import org.switchyard.component.common.knowledge.config.items.CompoundRegisterableItemsFactory; +import org.switchyard.component.common.knowledge.config.items.ExtendedRegisterableItemsFactory; +import org.switchyard.component.common.knowledge.config.manifest.ContainerManifest; +import org.switchyard.component.common.knowledge.config.manifest.Manifest; +import org.switchyard.component.common.knowledge.config.manifest.RemoteManifest; +import org.switchyard.component.common.knowledge.config.manifest.ResourcesManifest; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.serial.SerializerObjectMarshallingStrategy; +import org.switchyard.component.common.knowledge.transaction.TransactionManagerLocator; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.SerializerFactory; + +/** + * RuntimeEnvironmentBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class RuntimeEnvironmentBuilder extends KnowledgeBuilder { + + private final RuntimeEnvironmentBuilderFactory _runtimeEnvironmentBuilderFactory; + private final boolean _persistent; + private final EntityManagerFactoryBuilder _entityManagerFactoryBuilder; + private final ManifestBuilder _manifestBuilder; + private final PropertiesBuilder _propertiesBuilder; + private final UserGroupCallbackBuilder _userGroupCallbackBuilder; + private final RegisterableItemsFactoryBuilder _registerableItemsFactoryBuilder; + + /** + * Creates a new RuntimeEnvironmentBuilder. + * @param classLoader classLoader + * @param serviceDomain serviceDomain + * @param implementationModel implementationModel + */ + public RuntimeEnvironmentBuilder(ClassLoader classLoader, ServiceDomain serviceDomain, KnowledgeComponentImplementationModel implementationModel) { + super(classLoader, serviceDomain); + //_runtimeEnvironmentBuilderFactory = org.kie.api.runtime.manager.RuntimeEnvironmentBuilder.Factory.get(); + _runtimeEnvironmentBuilderFactory = new PatchedRuntimeEnvironmentBuilder(); + _persistent = implementationModel != null ? implementationModel.isPersistent() : false; + _entityManagerFactoryBuilder = new EntityManagerFactoryBuilder(serviceDomain, _persistent); + _manifestBuilder = ManifestBuilder.builder(getClassLoader(), implementationModel); + _propertiesBuilder = PropertiesBuilder.builder(implementationModel); + _userGroupCallbackBuilder = UserGroupCallbackBuilder.builder(getClassLoader(), implementationModel); + _registerableItemsFactoryBuilder = new RegisterableItemsFactoryBuilder(getClassLoader(), serviceDomain, implementationModel); + } + + /** + * Builds a RuntimeEnvironment. + * @return a RuntimeEnvironment + */ + public RuntimeEnvironment build() { + final org.kie.api.runtime.manager.RuntimeEnvironmentBuilder jbpmRuntimeEnvironmentBuilder; + Manifest manifest = _manifestBuilder.build(); + if (manifest instanceof RemoteManifest) { + RemoteManifest remoteManifest = (RemoteManifest)manifest; + jbpmRuntimeEnvironmentBuilder = _runtimeEnvironmentBuilderFactory.newDefaultInMemoryBuilder(); + remoteManifest.addToEnvironment(jbpmRuntimeEnvironmentBuilder); + // we dont' do any other building for remote usage + return jbpmRuntimeEnvironmentBuilder.get(); + } else if (manifest instanceof ContainerManifest) { + ContainerManifest containerManifest = (ContainerManifest)manifest; + String baseName = containerManifest.getBaseName(); + ReleaseId releaseId = containerManifest.getReleaseId(); + String sessionName = containerManifest.getSessionName(); + if (releaseId != null) { + if (baseName != null || sessionName != null) { + jbpmRuntimeEnvironmentBuilder = _runtimeEnvironmentBuilderFactory.newDefaultBuilder(releaseId, baseName, sessionName); + } else { + jbpmRuntimeEnvironmentBuilder = _runtimeEnvironmentBuilderFactory.newDefaultBuilder(releaseId); + } + // we can't update classpath containers, so no point adding it to environment below here + containerManifest.addToEnvironment(jbpmRuntimeEnvironmentBuilder); + } else if (baseName != null || sessionName != null) { + jbpmRuntimeEnvironmentBuilder = _runtimeEnvironmentBuilderFactory.newClasspathKmoduleDefaultBuilder(baseName, sessionName); + } else { + jbpmRuntimeEnvironmentBuilder = _runtimeEnvironmentBuilderFactory.newClasspathKmoduleDefaultBuilder(); + } + } else { + if (_persistent) { + jbpmRuntimeEnvironmentBuilder = _runtimeEnvironmentBuilderFactory.newDefaultBuilder(); + } else { + jbpmRuntimeEnvironmentBuilder = _runtimeEnvironmentBuilderFactory.newDefaultInMemoryBuilder(); + } + if (manifest instanceof ResourcesManifest) { + ResourcesManifest resourcesManifest = (ResourcesManifest)manifest; + for (Resource resource : resourcesManifest.buildResources()) { + jbpmRuntimeEnvironmentBuilder.addAsset(resource, resource.getResourceType()); + } + } + } + jbpmRuntimeEnvironmentBuilder.classLoader(getClassLoader()); + jbpmRuntimeEnvironmentBuilder.persistence(_persistent); + // provides a noop EntityManagerFactory if no persistence + EntityManagerFactory entityManagerFactory = _entityManagerFactoryBuilder.build(); + jbpmRuntimeEnvironmentBuilder.entityManagerFactory(entityManagerFactory); + jbpmRuntimeEnvironmentBuilder.addEnvironmentEntry(EnvironmentName.ENTITY_MANAGER_FACTORY, entityManagerFactory); + // provides an ootb UserGroupCallback if fallen-back to + UserGroupCallback userGroupCallback = _userGroupCallbackBuilder.build(); + jbpmRuntimeEnvironmentBuilder.userGroupCallback(userGroupCallback); + if (_persistent) { + UserTransaction ut = TransactionManagerLocator.INSTANCE.getUserTransaction(); + TransactionManager tm = TransactionManagerLocator.INSTANCE.getTransactionManager(); + jbpmRuntimeEnvironmentBuilder.addEnvironmentEntry(EnvironmentName.TRANSACTION, ut); + jbpmRuntimeEnvironmentBuilder.addEnvironmentEntry(EnvironmentName.TRANSACTION_MANAGER, tm); + } else { + // TODO: why, when no persistence, do we have to do all this? + jbpmRuntimeEnvironmentBuilder.addEnvironmentEntry("IS_JTA_TRANSACTION", Boolean.FALSE); + TaskEventSupport taskEventSupport = new TaskEventSupport(); + CommandService executor = new TaskCommandExecutorImpl(EnvironmentFactory.newEnvironment(), taskEventSupport); + jbpmRuntimeEnvironmentBuilder.addEnvironmentEntry(TaskService.class.getName(), new CommandBasedTaskService(executor, taskEventSupport)); + } + Properties properties = _propertiesBuilder.build(); + for (Object key : properties.keySet()) { + String name = (String)key; + String value = properties.getProperty(name); + jbpmRuntimeEnvironmentBuilder.addConfiguration(name, value); // add to KieSessionConfiguration + jbpmRuntimeEnvironmentBuilder.addEnvironmentEntry(name, value); // add to Environment (SWITCHYARD-2393) + } + // things that need to be done to the original RuntimeEnvironment before the jBPM RuntimeEnvironmentBuilder is built (get->init) + /* + Access simpleREAccess = new FieldAccess( + org.jbpm.runtime.manager.impl.RuntimeEnvironmentBuilder.class, "runtimeEnvironment"); + if (simpleREAccess.isReadable()) { + SimpleRuntimeEnvironment originalRE = simpleREAccess.read(jbpmRuntimeEnvironmentBuilder); + */ + SimpleRuntimeEnvironment originalRE = ((PatchedRuntimeEnvironmentBuilder)jbpmRuntimeEnvironmentBuilder).getRuntimeEnvironment(); + if (originalRE != null) { + RegisterableItemsFactory originalRIF = originalRE.getRegisterableItemsFactory(); + if (originalRIF instanceof InternalRegisterableItemsFactory) { + ExtendedRegisterableItemsFactory extendedRIF = _registerableItemsFactoryBuilder.build(); + CompoundRegisterableItemsFactory compoundRIF = new CompoundRegisterableItemsFactory( + (InternalRegisterableItemsFactory)originalRIF, extendedRIF); + jbpmRuntimeEnvironmentBuilder.registerableItemsFactory(compoundRIF); + ExtendedRegisterableItemsFactory.Env.addToEnvironment(jbpmRuntimeEnvironmentBuilder, compoundRIF); + if (manifest instanceof ContainerManifest && originalRIF instanceof KModuleRegisterableItemsFactory) { + Access kieContainerAccess = new FieldAccess(KModuleRegisterableItemsFactory.class, "kieContainer"); + if (kieContainerAccess.isReadable()) { + KieContainer kieContainer = kieContainerAccess.read(originalRIF); + ((ContainerManifest)manifest).setKieContainer(kieContainer); + } + } + } + Mapper mapper; + AuditMode auditMode; + if (_persistent) { + mapper = new JPAMapper(entityManagerFactory); + auditMode = AuditMode.JPA; + } else { + mapper = new InMemoryMapper(); + auditMode = AuditMode.NONE; + } + originalRE.setMapper(mapper); + Environment environmentTemplate = originalRE.getEnvironmentTemplate(); + // set the patched LocalTaskServiceFactory + environmentTemplate.set(TaskServiceFactory.class.getName(), new PatchedLocalTaskServiceFactory(originalRE)); + // TODO: why, when no persistence, do we have to do all this? + DeploymentDescriptor deploymentDescriptor = (DeploymentDescriptor)environmentTemplate.get("KieDeploymentDescriptor"); + if (deploymentDescriptor == null) { + deploymentDescriptor = new DeploymentDescriptorManager().getDefaultDescriptor(); + environmentTemplate.set("KieDeploymentDescriptor", deploymentDescriptor); + } + ((DeploymentDescriptorImpl)deploymentDescriptor).setAuditMode(auditMode); + } + /* + } + */ + RuntimeEnvironment runtimeEnvironment = jbpmRuntimeEnvironmentBuilder.get(); + Environment environment = runtimeEnvironment.getEnvironment(); + // our ObjectMarshallingStrategy can be added to the Environment after the jBPM RuntimeEnvironmentBuilder is built (get->init) + List new_oms = new ArrayList(); + new_oms.add(new SerializerObjectMarshallingStrategy(SerializerFactory.create(FormatType.JSON, null, true))); + ObjectMarshallingStrategy[] old_oms = (ObjectMarshallingStrategy[])environment.get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES); + if (old_oms != null) { + for (int i=0; i < old_oms.length; i++) { + if (old_oms[i] != null) { + new_oms.add(old_oms[i]); + } + } + } + environment.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new_oms.toArray(new ObjectMarshallingStrategy[new_oms.size()])); + return runtimeEnvironment; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RuntimeManagerBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RuntimeManagerBuilder.java new file mode 100644 index 000000000..5bc34e172 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/RuntimeManagerBuilder.java @@ -0,0 +1,78 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import org.kie.api.runtime.manager.RuntimeEnvironment; +import org.kie.api.runtime.manager.RuntimeManager; +import org.kie.api.runtime.manager.RuntimeManagerFactory; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.knowledge.config.manifest.RemoteManifest; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerType; +import org.switchyard.component.common.knowledge.runtime.remote.RemoteRuntimeManager; + +/** + * RuntimeManagerBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class RuntimeManagerBuilder extends KnowledgeBuilder { + + private final RuntimeManagerFactory _runtimeManagerFactory; + private final RuntimeEnvironmentBuilder _runtimeEnvironmentBuilder; + + /** + * Creates a RuntimeManagerBuilder. + * @param classLoader classLoader + * @param serviceDomain serviceDomain + * @param implementationModel implementationModel + */ + public RuntimeManagerBuilder(ClassLoader classLoader, ServiceDomain serviceDomain, KnowledgeComponentImplementationModel implementationModel) { + super(classLoader, serviceDomain); + _runtimeManagerFactory = RuntimeManagerFactory.Factory.get(); + _runtimeEnvironmentBuilder = new RuntimeEnvironmentBuilder(getClassLoader(), serviceDomain, implementationModel); + } + + /** + * Builds a RuntimeManager. + * @param type type + * @param identifier identifier + * @return a RuntimeManager + */ + public RuntimeManager build(KnowledgeRuntimeManagerType type, String identifier) { + final RuntimeManager runtimeManager; + final RuntimeEnvironment runtimeEnvironment = _runtimeEnvironmentBuilder.build(); + final RemoteManifest remoteManifest = RemoteManifest.removeFromEnvironment(runtimeEnvironment.getEnvironment()); + if (remoteManifest != null) { + runtimeManager = new RemoteRuntimeManager(remoteManifest.buildConfiguration(), identifier); + } else { + switch (type) { + case SINGLETON: + runtimeManager = _runtimeManagerFactory.newSingletonRuntimeManager(runtimeEnvironment, identifier); + break; + case PER_REQUEST: + runtimeManager = _runtimeManagerFactory.newPerRequestRuntimeManager(runtimeEnvironment, identifier); + break; + case PER_PROCESS_INSTANCE: + runtimeManager = _runtimeManagerFactory.newPerProcessInstanceRuntimeManager(runtimeEnvironment, identifier); + break; + default: + runtimeManager = null; + break; + } + } + return runtimeManager; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/UserGroupCallbackBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/UserGroupCallbackBuilder.java new file mode 100644 index 000000000..c5cf7d83f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/UserGroupCallbackBuilder.java @@ -0,0 +1,143 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import java.lang.reflect.Constructor; +import java.util.Properties; + +import org.jbpm.runtime.manager.impl.identity.UserDataServiceProvider; +import org.jbpm.services.task.identity.JBossUserGroupCallbackImpl; +import org.kie.api.task.UserGroupCallback; +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.io.pull.PropertiesPuller.PropertiesType; +import org.switchyard.common.io.pull.Puller.PathType; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.UserGroupCallbackModel; +import org.switchyard.component.common.knowledge.task.PropertiesUserGroupCallback; + +/** + * UserGroupCallbackBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class UserGroupCallbackBuilder extends KnowledgeBuilder { + + private static final String USER_CALLBACK_IMPL = System.getProperty("org.jbpm.ht.callback"); + private static final String DEFAULT_PROPERTIES_LOCATION = System.getProperty("jbpm.user.group.mapping", System.getProperty("jboss.server.config.dir", "target/classes") + "/roles.properties"); + + private static final Class[][] PARAMETER_TYPES = new Class[][]{ + new Class[]{Properties.class}, + new Class[0] + }; + + private Class _userGroupCallbackClass; + private final PropertiesBuilder _propertiesBuilder; + + /** + * Creates a UserGroupCallbackBuilder. + * @param classLoader classLoader + * @param userGroupCallbackModel userGroupCallbackModel + */ + @SuppressWarnings("unchecked") + public UserGroupCallbackBuilder(ClassLoader classLoader, UserGroupCallbackModel userGroupCallbackModel) { + super(classLoader); + _propertiesBuilder = new PropertiesBuilder(); + String location = DEFAULT_PROPERTIES_LOCATION; + if (location.startsWith("classpath:")) { + location = location.replaceFirst("classpath:", ""); + } else if (location.startsWith("file:")) { + location = location.replaceFirst("file:", ""); + } + PropertiesType propertiesType = PropertiesType.PROPERTIES; + if (location != null && location.endsWith(".xml")) { + propertiesType = PropertiesType.XML; + } + Properties defaultProperties = new PropertiesPuller(propertiesType).pullPath(location, getClassLoader(), PathType.values()); + _propertiesBuilder.setDefaultProperties(defaultProperties); + if (userGroupCallbackModel != null) { + _userGroupCallbackClass = (Class)userGroupCallbackModel.getClazz(getClassLoader()); + _propertiesBuilder.setModelProperties(userGroupCallbackModel.getProperties()); + } + } + + /** + * Builds a UserGroupCallback. + * @return a UserGroupCallback + */ + public UserGroupCallback build() { + UserGroupCallback callback = null; + Properties properties = _propertiesBuilder.build(); + if (_userGroupCallbackClass != null) { + callback = construct(properties); + } + if (callback == null && USER_CALLBACK_IMPL != null) { + try { + if ("props".equalsIgnoreCase(USER_CALLBACK_IMPL)) { + callback = new JBossUserGroupCallbackImpl(properties); + } else { + callback = UserDataServiceProvider.getUserGroupCallback(); + } + } catch (Throwable t) { + // we might get here if on Karaf vs. JBoss + // keep checkstyle happy ("at least one statement") + t.getMessage(); + } + } + if (callback == null) { + callback = new PropertiesUserGroupCallback(properties); + } + return callback; + } + + private UserGroupCallback construct(Properties properties) { + UserGroupCallback userGroupCallback = null; + Constructor constructor = null; + for (Class[] parameterTypes : PARAMETER_TYPES) { + try { + constructor = _userGroupCallbackClass.getConstructor(parameterTypes); + if (constructor != null) { + break; + } + } catch (Throwable t) { + // keep checkstyle happy ("at least one statement") + t.getMessage(); + } + } + Class[] parameterTypes = constructor != null ? constructor.getParameterTypes() : new Class[0]; + try { + if (parameterTypes.length == 0) { + userGroupCallback = Construction.construct(_userGroupCallbackClass); + } else if (parameterTypes.length == 1) { + userGroupCallback = Construction.construct(_userGroupCallbackClass, parameterTypes, new Object[]{properties}); + } + } catch (Throwable t) { + throw CommonKnowledgeMessages.MESSAGES.couldNotInstantiateUserGroupCallbackClass(_userGroupCallbackClass.getName()); + } + return userGroupCallback; + } + + /** + * Creates a UserGroupCallbackBuilder. + * @param classLoader classLoader + * @param implementationModel implementationModel + * @return a UserGroupCallbackBuilder + */ + public static UserGroupCallbackBuilder builder(ClassLoader classLoader, KnowledgeComponentImplementationModel implementationModel) { + UserGroupCallbackModel userGroupCallbackModel = implementationModel != null ? implementationModel.getUserGroupCallback() : null; + return new UserGroupCallbackBuilder(classLoader, userGroupCallbackModel); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/WorkItemHandlerBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/WorkItemHandlerBuilder.java new file mode 100644 index 000000000..e9af8a3be --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/WorkItemHandlerBuilder.java @@ -0,0 +1,220 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder; + +import static org.switchyard.component.common.knowledge.service.StandardSwitchYardServiceTaskHandler.SERVICE_TASK; +import static org.switchyard.component.common.knowledge.service.SwitchYardServiceTaskHandler.SWITCHYARD_SERVICE_TASK; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.jbpm.services.task.wih.AbstractHTWorkItemHandler; +import org.kie.api.runtime.KieRuntime; +import org.kie.api.runtime.manager.RuntimeManager; +import org.kie.api.runtime.process.ProcessRuntime; +import org.kie.api.runtime.process.WorkItemHandler; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.reflect.Access; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.common.type.reflect.MethodAccess; +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlerModel; +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlersModel; +import org.switchyard.component.common.knowledge.service.StandardSwitchYardServiceTaskHandler; +import org.switchyard.component.common.knowledge.service.SwitchYardServiceInvoker; +import org.switchyard.component.common.knowledge.service.SwitchYardServiceTaskHandler; +import org.switchyard.config.model.composite.ComponentModel; + +/** + * WorkItemHandlerBuilder. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class WorkItemHandlerBuilder extends KnowledgeBuilder { + + private static final String HUMAN_TASK = "Human Task"; + + private static final Class[][] PARAMETER_TYPES = new Class[][]{ + new Class[]{ProcessRuntime.class}, + new Class[]{KieRuntime.class}, + new Class[0] + }; + + private static final Map> DEFAULT_HANDLERS = new HashMap>(); + static { + DEFAULT_HANDLERS.put(SWITCHYARD_SERVICE_TASK, SwitchYardServiceTaskHandler.class); + DEFAULT_HANDLERS.put(SERVICE_TASK, StandardSwitchYardServiceTaskHandler.class); + } + + private Class _workItemHandlerClass; + private String _workItemHandlerName; + private QName _componentName; + private String _targetNamespace; + + /** + * Creates a WorkItemHandlerBuilder. + * @param classLoader classLoader + * @param serviceDomain serviceDomain + * @param workItemHandlerModel workItemHandlerModel + */ + @SuppressWarnings("unchecked") + public WorkItemHandlerBuilder(ClassLoader classLoader, ServiceDomain serviceDomain, WorkItemHandlerModel workItemHandlerModel) { + super(classLoader, serviceDomain); + if (workItemHandlerModel != null) { + WorkItemHandlersModel workItemHandlersModel = (WorkItemHandlersModel)workItemHandlerModel.getModelParent(); + KnowledgeComponentImplementationModel implementationModel = (KnowledgeComponentImplementationModel)workItemHandlersModel.getModelParent(); + ComponentModel componentModel = implementationModel.getComponent(); + _componentName = componentModel.getQName(); + _targetNamespace = componentModel.getTargetNamespace(); + _workItemHandlerClass = (Class)workItemHandlerModel.getClazz(getClassLoader()); + if (_workItemHandlerClass == null) { + throw CommonKnowledgeMessages.MESSAGES.couldNotLoadWorkItemHandlerClass(workItemHandlerModel.getModelConfiguration().getAttribute("class")); + } + _workItemHandlerName = workItemHandlerModel.getName(); + if (_workItemHandlerName == null) { + if (StandardSwitchYardServiceTaskHandler.class.isAssignableFrom(_workItemHandlerClass)) { + _workItemHandlerName = SERVICE_TASK; + } else if (SwitchYardServiceTaskHandler.class.isAssignableFrom(_workItemHandlerClass)) { + _workItemHandlerName = SWITCHYARD_SERVICE_TASK; + } else if (AbstractHTWorkItemHandler.class.isAssignableFrom(_workItemHandlerClass)) { + _workItemHandlerName = HUMAN_TASK; + } else { + throw CommonKnowledgeMessages.MESSAGES.couldNotUseNullNameToRegisterWorkItemHandler(_workItemHandlerClass.getName()); + } + } + } + } + + private WorkItemHandlerBuilder( + ClassLoader classLoader, + ServiceDomain serviceDomain, + KnowledgeComponentImplementationModel implementationModel, + Class workItemHandlerClass, + String workItemHandlerName) { + super(classLoader, serviceDomain); + _workItemHandlerClass = workItemHandlerClass; + _workItemHandlerName = workItemHandlerName; + ComponentModel componentModel = implementationModel.getComponent(); + _componentName = componentModel.getQName(); + _targetNamespace = componentModel.getTargetNamespace(); + } + + /** + * Gets the workItemHandlerName. + * @return the workItemHandlerName + */ + public String getWorkItemHandlerName() { + return _workItemHandlerName; + } + + /** + * Builds a WorkItemHandler. + * @param processRuntime processRuntime + * @param runtimeManager runtimeManager + * @return a WorkItemHandler + */ + public WorkItemHandler build(ProcessRuntime processRuntime, RuntimeManager runtimeManager) { + WorkItemHandler workItemHandler = construct(processRuntime, runtimeManager); + if (workItemHandler instanceof SwitchYardServiceTaskHandler) { + SwitchYardServiceTaskHandler systh = (SwitchYardServiceTaskHandler)workItemHandler; + systh.setComponentName(_componentName); + systh.setInvoker(new SwitchYardServiceInvoker(getServiceDomain(), _targetNamespace)); + systh.setProcessRuntime(processRuntime); + } + return workItemHandler; + } + + private WorkItemHandler construct(ProcessRuntime processRuntime, RuntimeManager runtimeManager) { + WorkItemHandler handler = null; + if (_workItemHandlerClass != null) { + Constructor constructor = null; + for (Class[] parameterTypes : PARAMETER_TYPES) { + try { + constructor = _workItemHandlerClass.getConstructor(parameterTypes); + if (constructor != null) { + break; + } + } catch (Throwable t) { + // keep checkstyle happy ("at least one statement") + t.getMessage(); + } + } + Class[] parameterTypes = constructor != null ? constructor.getParameterTypes() : new Class[0]; + try { + if (parameterTypes.length == 0) { + handler = Construction.construct(_workItemHandlerClass); + } else if (parameterTypes.length == 1) { + handler = Construction.construct(_workItemHandlerClass, parameterTypes, new Object[]{processRuntime}); + } + } catch (Throwable t) { + throw CommonKnowledgeMessages.MESSAGES.couldNotInstantiateWorkItemHandlerClass(_workItemHandlerClass.getName()); + } + if (handler != null && runtimeManager != null) { + Access access = new MethodAccess(handler.getClass(), "getRuntimeManager", "setRuntimeManager"); + if (access.isWriteable()) { + access.write(handler, runtimeManager); + } + } + } + return handler; + } + + /** + * Creates WorkItemHandlerBuilders. + * @param classLoader classLoader + * @param serviceDomain serviceDomain + * @param implementationModel implementationModel + * @return WorkItemHandlerBuilders + */ + public static List builders(ClassLoader classLoader, ServiceDomain serviceDomain, KnowledgeComponentImplementationModel implementationModel) { + List builders = new ArrayList(); + Set registeredNames = new HashSet(); + if (implementationModel != null) { + WorkItemHandlersModel workItemHandlersModel = implementationModel.getWorkItemHandlers(); + if (workItemHandlersModel != null) { + for (WorkItemHandlerModel workItemHandlerModel : workItemHandlersModel.getWorkItemHandlers()) { + if (workItemHandlerModel != null) { + WorkItemHandlerBuilder builder = new WorkItemHandlerBuilder(classLoader, serviceDomain, workItemHandlerModel); + builders.add(builder); + String name = builder.getWorkItemHandlerName(); + if (name != null) { + registeredNames.add(name); + } + } + } + } + // add our default WorkItemHandlers if they haven't already been added + for (Entry> entry : DEFAULT_HANDLERS.entrySet()) { + String name = entry.getKey(); + if (!registeredNames.contains(name)) { + WorkItemHandlerBuilder builder = new WorkItemHandlerBuilder( + classLoader, serviceDomain, implementationModel, entry.getValue(), name); + builders.add(builder); + registeredNames.add(name); + } + } + } + return builders; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedLocalTaskServiceFactory.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedLocalTaskServiceFactory.java new file mode 100644 index 000000000..79eb9ff57 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedLocalTaskServiceFactory.java @@ -0,0 +1,53 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.builder.patch; + +import org.jbpm.runtime.manager.impl.factory.LocalTaskServiceFactory; +import org.kie.api.runtime.manager.RuntimeEnvironment; +import org.kie.api.task.TaskService; + +/** + * PatchedLocalTaskServiceFactory. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class PatchedLocalTaskServiceFactory extends LocalTaskServiceFactory { + + /** + * Creates a new PatchedLocalTaskServiceFactory. + * @param runtimeEnvironment the RuntimeEnvironment + */ + public PatchedLocalTaskServiceFactory(RuntimeEnvironment runtimeEnvironment) { + super(runtimeEnvironment); + } + + /** + * {@inheritDoc} + */ + @Override + public TaskService newTaskService() { + TaskService taskService; + try { + taskService = super.newTaskService(); + } catch (IllegalStateException ise) { + // There is a bug in TaskDeadlinesServiceImpl.initialize where there is no + // TaskPersistenceContext available on initialization, so it always fails the + // first time. We don't need theTaskDeadlinesServiceImpl to work the first time, + // so we try again, since by then the initialization is already done. + taskService = super.newTaskService(); + } + return taskService; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedRuntimeEnvironmentBuilder.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedRuntimeEnvironmentBuilder.java new file mode 100644 index 000000000..58a48e13a --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/builder/patch/PatchedRuntimeEnvironmentBuilder.java @@ -0,0 +1,572 @@ +/* + * Copyright 2013 JBoss Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +//package org.jbpm.runtime.manager.impl; +package org.switchyard.component.common.knowledge.config.builder.patch; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.persistence.EntityManagerFactory; + +import org.drools.compiler.kie.builder.impl.InternalKieModule; +import org.drools.compiler.kie.builder.impl.KieContainerImpl; +import org.drools.core.marshalling.impl.ClassObjectMarshallingStrategyAcceptor; +import org.drools.core.marshalling.impl.SerializablePlaceholderResolverStrategy; +import org.drools.core.util.StringUtils; +import org.jbpm.process.core.timer.GlobalSchedulerService; +import org.jbpm.process.instance.event.DefaultSignalManagerFactory; +import org.jbpm.process.instance.impl.DefaultProcessInstanceManagerFactory; +import org.jbpm.runtime.manager.impl.DefaultRegisterableItemsFactory; +import org.jbpm.runtime.manager.impl.KModuleRegisterableItemsFactory; +import org.jbpm.runtime.manager.impl.SimpleRuntimeEnvironment; +import org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorManager; +import org.jbpm.runtime.manager.impl.deploy.DeploymentDescriptorMerger; +import org.kie.api.KieBase; +import org.kie.api.KieServices; +import org.kie.api.builder.ReleaseId; +import org.kie.api.builder.model.KieBaseModel; +import org.kie.api.io.Resource; +import org.kie.api.io.ResourceType; +import org.kie.api.marshalling.ObjectMarshallingStrategy; +import org.kie.api.runtime.Environment; +import org.kie.api.runtime.EnvironmentName; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.manager.RegisterableItemsFactory; +import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder; +import org.kie.api.runtime.manager.RuntimeEnvironmentBuilderFactory; +import org.kie.api.task.UserGroupCallback; +import org.kie.internal.runtime.conf.DeploymentDescriptor; +import org.kie.internal.runtime.conf.MergeMode; +import org.kie.internal.runtime.conf.NamedObjectModel; +import org.kie.internal.runtime.conf.ObjectModel; +import org.kie.internal.runtime.conf.ObjectModelResolver; +import org.kie.internal.runtime.conf.ObjectModelResolverProvider; +import org.kie.internal.runtime.conf.PersistenceMode; +import org.kie.internal.runtime.manager.Mapper; +import org.kie.internal.runtime.manager.RuntimeEnvironment; +import org.kie.scanner.MavenRepository; + +/** + * Builder implementation that follows fluent approach to build RuntimeEnvironments. + * Comes with short cut methods to get predefined configurations of the RuntimeEnvironment: + *

    + *
  • getDefault() - returns preconfigured environment with enabled persistence
  • + *
  • getDefaultInMemory() - returns preconfigured environment with disabled persistence for runtime engine
  • + *
  • getDefault(ReleaseId) - returns preconfigured environment with enabled persistence that is tailored for kjar
  • + *
  • getDefault(ReleaseId, String, String) - returns preconfigured environment with enabled persistence that is tailored for kjar and allows to specify kbase and ksession name
  • + *
  • getDefault(String, String, String) - returns preconfigured environment with enabled persistence that is tailored for kjar
  • + *
  • getDefault(String, String, String, String, String) - returns preconfigured environment with enabled persistence that is tailored for kjar and allows to specify kbase and ksession name
  • + *
  • getEmpty() - completely empty environment for self configuration
  • + *
  • getClasspathKModuleDefault() - returns preconfigured environment with enabled persistence based on classpath kiecontainer
  • + *
  • getClasspathKModuleDefault(String, String) - returns preconfigured environment with enabled persistence based on classpath kiecontainer
  • + *
+ * + */ +//public class RuntimeEnvironmentBuilder implements RuntimeEnvironmentBuilderFactory, org.kie.api.runtime.manager.RuntimeEnvironmentBuilder{ +public class PatchedRuntimeEnvironmentBuilder implements RuntimeEnvironmentBuilderFactory, org.kie.api.runtime.manager.RuntimeEnvironmentBuilder { + + private static final class PatchedRuntimeEnvironment extends SimpleRuntimeEnvironment { + private final Set _names = Collections.synchronizedSet(new HashSet()); + private PatchedRuntimeEnvironment() { + super(new DefaultRegisterableItemsFactory()); + } + @Override + public void addToEnvironment(String name, Object value) { + if (name != null && name.startsWith("org.switchyard")) { + _names.add(name); + } + super.addToEnvironment(name, value); + } + @Override + protected Environment copyEnvironment() { + Environment copy = super.copyEnvironment(); + for (String name : _names) { + addIfPresent(name, copy); + } + return copy; + } + } + + private static final String DEFAULT_KBASE_NAME = "defaultKieBase"; + + /** + * Gets the SimpleRuntimeEnvironment. + * @return the SimpleRuntimeEnvironment + */ + public SimpleRuntimeEnvironment getRuntimeEnvironment() { + return _runtimeEnvironment; + } + + private SimpleRuntimeEnvironment _runtimeEnvironment; + + /** + * Creates a new PatchedRuntimeEnvironmentBuilder. + */ + public PatchedRuntimeEnvironmentBuilder() { + // PATCHED from: this.runtimeEnvironment = new SimpleRuntimeEnvironment(); + _runtimeEnvironment = new PatchedRuntimeEnvironment(); + } + + private PatchedRuntimeEnvironmentBuilder(SimpleRuntimeEnvironment runtimeEnvironment) { + _runtimeEnvironment = runtimeEnvironment; + } + /** + * Provides completely empty RuntimeEnvironmentBuilder instance that allows to manually + * set all required components instead of relying on any defaults. + * @return new instance of RuntimeEnvironmentBuilder + */ + public static RuntimeEnvironmentBuilder getEmpty() { + return new PatchedRuntimeEnvironmentBuilder(); + } + + /** + * Provides default configuration of RuntimeEnvironmentBuilder that is based on. + *
    + *
  • DefaultRuntimeEnvironment
  • + *
+ * @return new instance of RuntimeEnvironmentBuilder that is already preconfigured with defaults + * + */ + public static RuntimeEnvironmentBuilder getDefault() { + // PATCHED from: return new RuntimeEnvironmentBuilder(new DefaultRuntimeEnvironment()); + return new PatchedRuntimeEnvironmentBuilder(new PatchedRuntimeEnvironment()); + } + + /** + * Provides default configuration of RuntimeEnvironmentBuilder that is based on. + *
    + *
  • DefaultRuntimeEnvironment
  • + *
+ * but it does not have persistence for process engine configured so it will only store process instances in memory + * @return new instance of RuntimeEnvironmentBuilder that is already preconfigured with defaults + * + */ + public static RuntimeEnvironmentBuilder getDefaultInMemory() { + // PATCHED from: RuntimeEnvironmentBuilder builder = new RuntimeEnvironmentBuilder(new DefaultRuntimeEnvironment(null, false)); + RuntimeEnvironmentBuilder builder = new PatchedRuntimeEnvironmentBuilder(new PatchedRuntimeEnvironment()); + builder + .addConfiguration("drools.processSignalManagerFactory", DefaultSignalManagerFactory.class.getName()) + .addConfiguration("drools.processInstanceManagerFactory", DefaultProcessInstanceManagerFactory.class.getName()); + + return builder; + } + + /** + * Provides default configuration of RuntimeEnvironmentBuilder that is based on. + *
    + *
  • DefaultRuntimeEnvironment
  • + *
+ * This one is tailored to works smoothly with kjars as the notion of kbase and ksessions + * @param groupId group id of kjar + * @param artifactId artifact id of kjar + * @param version version number of kjar + * @return new instance of RuntimeEnvironmentBuilder that is already preconfigured with defaults + * + */ + public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version) { + return getDefault(groupId, artifactId, version, null, null); + } + + /** + * Provides default configuration of RuntimeEnvironmentBuilder that is based on. + *
    + *
  • DefaultRuntimeEnvironment
  • + *
+ * This one is tailored to works smoothly with kjars as the notion of kbase and ksessions + * @param groupId group id of kjar + * @param artifactId artifact id of kjar + * @param version version number of kjar + * @param kbaseName name of the kbase defined in kmodule.xml stored in kjar + * @param ksessionName name of the ksession define in kmodule.xml stored in kjar + * @return new instance of RuntimeEnvironmentBuilder that is already preconfigured with defaults + * + */ + public static RuntimeEnvironmentBuilder getDefault(String groupId, String artifactId, String version, String kbaseName, String ksessionName) { + KieServices ks = KieServices.Factory.get(); + return getDefault(ks.newReleaseId(groupId, artifactId, version), kbaseName, ksessionName); + } + + /** + * Provides default configuration of RuntimeEnvironmentBuilder that is based on. + *
    + *
  • DefaultRuntimeEnvironment
  • + *
+ * This one is tailored to works smoothly with kjars as the notion of kbase and ksessions + * @param releaseId ReleaseId that described the kjar + * @return new instance of RuntimeEnvironmentBuilder that is already preconfigured with defaults + * + */ + public static RuntimeEnvironmentBuilder getDefault(ReleaseId releaseId) { + return getDefault(releaseId, null, null); + } + + /** + * Provides default configuration of RuntimeEnvironmentBuilder that is based on. + *
    + *
  • DefaultRuntimeEnvironment
  • + *
+ * This one is tailored to works smoothly with kjars as the notion of kbase and ksessions + * @param releaseId ReleaseId that described the kjar + * @param kbaseName name of the kbase defined in kmodule.xml stored in kjar + * @param ksessionName name of the ksession define in kmodule.xml stored in kjar + * @return new instance of RuntimeEnvironmentBuilder that is already preconfigured with defaults + * + */ + public static RuntimeEnvironmentBuilder getDefault(ReleaseId releaseId, String kbaseName, String ksessionName) { + MavenRepository repository = MavenRepository.getMavenRepository(); + repository.resolveArtifact(releaseId.toExternalForm()); + KieServices ks = KieServices.Factory.get(); + KieContainer kieContainer = ks.newKieContainer(releaseId); + + DeploymentDescriptorManager descriptorManager = new DeploymentDescriptorManager(); + List descriptorHierarchy = descriptorManager.getDeploymentDescriptorHierarchy(kieContainer); + DeploymentDescriptorMerger merger = new DeploymentDescriptorMerger(); + DeploymentDescriptor descriptor = merger.merge(descriptorHierarchy, MergeMode.MERGE_COLLECTIONS); + + if (StringUtils.isEmpty(kbaseName)) { + KieBaseModel defaultKBaseModel = ((KieContainerImpl)kieContainer).getKieProject().getDefaultKieBaseModel(); + if (defaultKBaseModel != null) { + kbaseName = defaultKBaseModel.getName(); + } else { + kbaseName = DEFAULT_KBASE_NAME; + } + } + InternalKieModule module = (InternalKieModule) ((KieContainerImpl)kieContainer).getKieModuleForKBase(kbaseName); + if (module == null) { + throw new IllegalStateException("Cannot find kbase, either it does not exist or there are multiple default kbases in kmodule.xml"); + } + KieBase kbase = kieContainer.getKieBase(kbaseName); + + RuntimeEnvironmentBuilder builder = null; + if (descriptor.getPersistenceMode() == PersistenceMode.NONE) { + builder = getDefaultInMemory(); + } else { + builder = getDefault(); + } + Map contaxtParams = new HashMap(); + contaxtParams.put("classLoader", kieContainer.getClassLoader()); + // populate various properties of the builder + /* + if (descriptor.getPersistenceUnit() != null) { + EntityManagerFactory emf = EntityManagerFactoryManager.get().getOrCreate(descriptor.getPersistenceUnit()); + builder.entityManagerFactory(emf); + contaxtParams.put("entityManagerFactory", emf); + } + */ + + // process object models that are globally configured (environment entries, session configuration) + for (NamedObjectModel model : descriptor.getEnvironmentEntries()) { + Object entry = getInstanceFromModel(model, kieContainer, contaxtParams); + builder.addEnvironmentEntry(model.getName(), entry); + } + + for (NamedObjectModel model : descriptor.getConfiguration()) { + Object entry = getInstanceFromModel(model, kieContainer, contaxtParams); + builder.addConfiguration(model.getName(), (String) entry); + } + ObjectMarshallingStrategy[] mStrategies = new ObjectMarshallingStrategy[descriptor.getMarshallingStrategies().size() + 1]; + int index = 0; + for (ObjectModel model : descriptor.getMarshallingStrategies()) { + Object strategy = getInstanceFromModel(model, kieContainer, contaxtParams); + mStrategies[index] = (ObjectMarshallingStrategy)strategy; + index++; + } + // lastly add the main default strategy + mStrategies[index] = new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT); + builder.addEnvironmentEntry(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, mStrategies); + + builder.addEnvironmentEntry("KieDeploymentDescriptor", descriptor) + .knowledgeBase(kbase) + .classLoader(kieContainer.getClassLoader()) + .registerableItemsFactory(new KModuleRegisterableItemsFactory(kieContainer, ksessionName)); + + return builder; + } + + /** + * Provides default configuration of RuntimeEnvironmentBuilder that is based on. + *
    + *
  • DefaultRuntimeEnvironment
  • + *
+ * It relies on KieClasspathContainer that requires to have kmodule.xml present in META-INF folder which + * defines the kjar itself. + * Expects to use default kbase and ksession from kmodule. + * @return new instance of RuntimeEnvironmentBuilder that is already preconfigured with defaults + * + */ + public static RuntimeEnvironmentBuilder getClasspathKmoduleDefault() { + return getClasspathKmoduleDefault(null, null); + } + + /** + * Provides default configuration of RuntimeEnvironmentBuilder that is based on. + *
    + *
  • DefaultRuntimeEnvironment
  • + *
+ * It relies on KieClasspathContainer that requires to have kmodule.xml present in META-INF folder which + * defines the kjar itself. + * @param kbaseName name of the kbase defined in kmodule.xml + * @param ksessionName name of the ksession define in kmodule.xml + * @return new instance of RuntimeEnvironmentBuilder that is already preconfigured with defaults + * + */ + public static RuntimeEnvironmentBuilder getClasspathKmoduleDefault(String kbaseName, String ksessionName) { + return setupClasspathKmoduleBuilder(KieServices.Factory.get().getKieClasspathContainer(), kbaseName, ksessionName); + } + + private static RuntimeEnvironmentBuilder setupClasspathKmoduleBuilder(KieContainer kieContainer, + String kbaseName, + String ksessionName) { + if (StringUtils.isEmpty(kbaseName)) { + KieBaseModel defaultKBaseModel = ((KieContainerImpl)kieContainer).getKieProject().getDefaultKieBaseModel(); + if (defaultKBaseModel != null) { + kbaseName = defaultKBaseModel.getName(); + } else { + kbaseName = DEFAULT_KBASE_NAME; + } + } + InternalKieModule module = (InternalKieModule) ((KieContainerImpl)kieContainer).getKieModuleForKBase(kbaseName); + if (module == null) { + throw new IllegalStateException("Cannot find kbase with name " + kbaseName); + } + KieBase kbase = kieContainer.getKieBase(kbaseName); + + return getDefault() + .knowledgeBase(kbase) + .classLoader(kieContainer.getClassLoader()) + .registerableItemsFactory(new KModuleRegisterableItemsFactory(kieContainer, ksessionName)); + } + + /** + * Sets persistenceEnabled. + * @param persistenceEnabled persistenceEnabled + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder persistence(boolean persistenceEnabled) { + _runtimeEnvironment.setUsePersistence(persistenceEnabled); + + return this; + } + + /** + * Sets entityManagerFactory. + * @param emf entityManagerFactory + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder entityManagerFactory(Object emf) { + if (emf == null) { + return this; + } + if (!(emf instanceof EntityManagerFactory)) { + throw new IllegalArgumentException("Argument is not of type EntityManagerFactory"); + } + _runtimeEnvironment.setEmf((EntityManagerFactory) emf); + + return this; + } + + /** + * Adds and asset. + * @param asset asset + * @param type type + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder addAsset(Resource asset, ResourceType type) { + if (asset == null || type == null) { + return this; + } + _runtimeEnvironment.addAsset(asset, type); + return this; + } + + /** + * Adds an environmentEntry name/value pair. + * @param name name + * @param value value + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder addEnvironmentEntry(String name, Object value) { + if (name == null || value == null) { + return this; + } + _runtimeEnvironment.addToEnvironment(name, value); + + return this; + } + + /** + * Adds a configuration name/value pair. + * @param name name + * @param value value + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder addConfiguration(String name, String value) { + if (name == null || value == null) { + return this; + } + _runtimeEnvironment.addToConfiguration(name, value); + + return this; + } + + /** + * Sets the knowledgeBase. + * @param kbase knowledgeBase + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder knowledgeBase(KieBase kbase) { + if (kbase == null) { + return this; + } + _runtimeEnvironment.setKieBase(kbase); + + return this; + } + + /** + * Sets the userGroupCallback. + * @param callback userGroupCallback + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder userGroupCallback(UserGroupCallback callback) { + if (callback == null) { + return this; + } + _runtimeEnvironment.setUserGroupCallback(callback); + + return this; + } + + /** + * Sets the mapper. + * @param mapper mapper + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder mapper(Mapper mapper) { + if (mapper == null) { + return this; + } + _runtimeEnvironment.setMapper(mapper); + + return this; + } + + /** + * Sets the registerableItemsFactory. + * @param factory registerableItemsFactory + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder registerableItemsFactory(RegisterableItemsFactory factory) { + if (factory == null) { + return this; + } + _runtimeEnvironment.setRegisterableItemsFactory(factory); + + return this; + } + + /** + * Inits and returns the RuntimeEnvironment. + * @return the RuntimeEnvironment + */ + public RuntimeEnvironment get() { + _runtimeEnvironment.init(); + return _runtimeEnvironment; + } + + /** + * Sets the schedulerService. + * @param globalScheduler schedulerService + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder schedulerService(Object globalScheduler) { + if (globalScheduler == null) { + return this; + } + if (!(globalScheduler instanceof GlobalSchedulerService)) { + throw new IllegalArgumentException("Argument is not of type GlobalSchedulerService"); + } + _runtimeEnvironment.setSchedulerService((GlobalSchedulerService) globalScheduler); + return this; + } + + /** + * Sets the classLoader. + * @param cl classLoader + * @return this RuntimeEnvironmentBuilder + */ + public RuntimeEnvironmentBuilder classLoader(ClassLoader cl) { + if (cl == null) { + return this; + } + _runtimeEnvironment.setClassLoader(cl); + return this; + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newEmptyBuilder() { + return PatchedRuntimeEnvironmentBuilder.getEmpty(); + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder() { + return PatchedRuntimeEnvironmentBuilder.getDefault(); + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultInMemoryBuilder() { + return PatchedRuntimeEnvironmentBuilder.getDefaultInMemory(); + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder(String groupId, String artifactId, String version) { + return PatchedRuntimeEnvironmentBuilder.getDefault(groupId, artifactId, version); + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder(String groupId, String artifactId, String version, String kbaseName, String ksessionName) { + return PatchedRuntimeEnvironmentBuilder.getDefault(groupId, artifactId, version, kbaseName, ksessionName); + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder(ReleaseId releaseId) { + return PatchedRuntimeEnvironmentBuilder.getDefault(releaseId); + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newDefaultBuilder(ReleaseId releaseId, String kbaseName, String ksessionName) { + return PatchedRuntimeEnvironmentBuilder.getDefault(releaseId, kbaseName, ksessionName); + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newClasspathKmoduleDefaultBuilder() { + return newClasspathKmoduleDefaultBuilder(null, null); + } + + @Override + public org.kie.api.runtime.manager.RuntimeEnvironmentBuilder newClasspathKmoduleDefaultBuilder(String kbaseName, String ksessionName) { + return setupClasspathKmoduleBuilder(KieServices.Factory.get().newKieClasspathContainer(), kbaseName, ksessionName); + } + + protected static Object getInstanceFromModel(ObjectModel model, KieContainer kieContainer, Map contaxtParams) { + ObjectModelResolver resolver = ObjectModelResolverProvider.get(model.getResolver()); + return resolver.getInstance(model, kieContainer.getClassLoader(), contaxtParams); + } +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/CompoundRegisterableItemsFactory.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/CompoundRegisterableItemsFactory.java new file mode 100644 index 000000000..211879f9a --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/CompoundRegisterableItemsFactory.java @@ -0,0 +1,179 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.items; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.kie.api.event.kiebase.KieBaseEventListener; +import org.kie.api.event.process.ProcessEventListener; +import org.kie.api.event.rule.AgendaEventListener; +import org.kie.api.event.rule.RuleRuntimeEventListener; +import org.kie.api.runtime.manager.RegisterableItemsFactory; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.process.WorkItemHandler; +import org.kie.api.task.TaskLifeCycleEventListener; +import org.kie.internal.runtime.manager.InternalRegisterableItemsFactory; +import org.kie.internal.runtime.manager.InternalRuntimeManager; + +/** + * CompoundRegisterableItemsFactory. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class CompoundRegisterableItemsFactory implements ExtendedRegisterableItemsFactory { + + private final InternalRegisterableItemsFactory _rootFactory; + private final List _factories; + + /** + * Creates a new CompoundRegisterableItemsFactory. + * @param rootFactory the root InternalRegisterableItemsFactory + * @param factories any additional RegisterableItemsFactory instances + */ + public CompoundRegisterableItemsFactory(InternalRegisterableItemsFactory rootFactory, RegisterableItemsFactory... factories) { + this(rootFactory, (factories != null ? Arrays.asList(factories) : null)); + } + + /** + * Creates a new CompoundRegisterableItemsFactory. + * @param rootFactory the root InternalRegisterableItemsFactory + * @param factories any additional RegisterableItemsFactory instances + */ + public CompoundRegisterableItemsFactory(InternalRegisterableItemsFactory rootFactory, Collection factories) { + _rootFactory = rootFactory; + _factories = new ArrayList(); + if (factories != null) { + for (RegisterableItemsFactory f : factories) { + if (f != null && f != rootFactory && f != this && !_factories.contains(f)) { + _factories.add(f); + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public List getAgendaEventListeners(RuntimeEngine runtime) { + List list = new ArrayList(); + list.addAll(_rootFactory.getAgendaEventListeners(runtime)); + for (RegisterableItemsFactory f : _factories) { + list.addAll(f.getAgendaEventListeners(runtime)); + } + return list; + } + + /** + * {@inheritDoc} + */ + @Override + public Map getGlobals(RuntimeEngine runtime) { + Map map = new HashMap(); + map.putAll(_rootFactory.getGlobals(runtime)); + for (RegisterableItemsFactory f : _factories) { + map.putAll(f.getGlobals(runtime)); + } + return map; + } + + /** + * {@inheritDoc} + */ + @Override + public List getProcessEventListeners(RuntimeEngine runtime) { + List list = new ArrayList(); + list.addAll(_rootFactory.getProcessEventListeners(runtime)); + for (RegisterableItemsFactory f : _factories) { + list.addAll(f.getProcessEventListeners(runtime)); + } + return list; + } + + /** + * {@inheritDoc} + */ + @Override + public List getRuleRuntimeEventListeners(RuntimeEngine runtime) { + List list = new ArrayList(); + list.addAll(_rootFactory.getRuleRuntimeEventListeners(runtime)); + for (RegisterableItemsFactory f : _factories) { + list.addAll(f.getRuleRuntimeEventListeners(runtime)); + } + return list; + } + + /** + * {@inheritDoc} + */ + @Override + public List getTaskListeners() { + List list = new ArrayList(); + list.addAll(_rootFactory.getTaskListeners()); + for (RegisterableItemsFactory f : _factories) { + list.addAll(f.getTaskListeners()); + } + return list; + } + + /** + * {@inheritDoc} + */ + @Override + public Map getWorkItemHandlers(RuntimeEngine runtime) { + Map map = new HashMap(); + map.putAll(_rootFactory.getWorkItemHandlers(runtime)); + for (RegisterableItemsFactory f : _factories) { + map.putAll(f.getWorkItemHandlers(runtime)); + } + return map; + } + + /** + * {@inheritDoc} + */ + @Override + public List getKieBaseEventListeners(RuntimeEngine runtime) { + List list = new ArrayList(); + for (RegisterableItemsFactory f : _factories) { + if (f instanceof ExtendedRegisterableItemsFactory) { + ExtendedRegisterableItemsFactory e = (ExtendedRegisterableItemsFactory)f; + list.addAll(e.getKieBaseEventListeners(runtime)); + } + } + return list; + } + + /** + * {@inheritDoc} + */ + @Override + public InternalRuntimeManager getRuntimeManager() { + return _rootFactory.getRuntimeManager(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setRuntimeManager(InternalRuntimeManager manager) { + _rootFactory.setRuntimeManager(manager); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/ExtendedRegisterableItemsFactory.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/ExtendedRegisterableItemsFactory.java new file mode 100644 index 000000000..5b70c841c --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/ExtendedRegisterableItemsFactory.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.items; + +import java.util.List; + +import org.kie.api.event.kiebase.KieBaseEventListener; +import org.kie.api.runtime.Environment; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder; +import org.kie.internal.runtime.manager.InternalRegisterableItemsFactory; + +/** + * ExtendedRegisterableItemsFactory. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public interface ExtendedRegisterableItemsFactory extends InternalRegisterableItemsFactory { + + /** + * Gets the KieBaseEventListeners for the specified RuntimeEngine. + * @param runtime the RuntimeEngine + * @return the KieBaseEventListeners + */ + public List getKieBaseEventListeners(RuntimeEngine runtime); + + /** + * Environment helper class. + */ + public static final class Env { + private static final String ERIF = ExtendedRegisterableItemsFactory.class.getName(); + private Env() {} + /** + * Adds the ExtendedRegisterableItemsFactory to the RuntimeEnvironmentBuilder's Environment. + * @param reb the RuntimeEnvironmentBuilder + * @param erif the ExtendedRegisterableItemsFactory + */ + public static void addToEnvironment(RuntimeEnvironmentBuilder reb, ExtendedRegisterableItemsFactory erif) { + reb.addEnvironmentEntry(ERIF, erif); + } + /** + * Removes and returns the ExtendedRegisterableItemsFactory from the Environment. + * @param e the Environment + * @return the ExtendedRegisterableItemsFactory + */ + public static ExtendedRegisterableItemsFactory removeFromEnvironment(Environment e) { + Object erif = e.get(ERIF); + if (erif != null) { + e.set(ERIF, null); + } + return ExtendedRegisterableItemsFactory.class.cast(erif); + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/NoopExtendedRegisterableItemsFactory.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/NoopExtendedRegisterableItemsFactory.java new file mode 100644 index 000000000..8159dfcd6 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/items/NoopExtendedRegisterableItemsFactory.java @@ -0,0 +1,110 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.items; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.kie.api.event.kiebase.KieBaseEventListener; +import org.kie.api.event.process.ProcessEventListener; +import org.kie.api.event.rule.AgendaEventListener; +import org.kie.api.event.rule.RuleRuntimeEventListener; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.process.WorkItemHandler; +import org.kie.api.task.TaskLifeCycleEventListener; +import org.kie.internal.runtime.manager.InternalRuntimeManager; + +/** + * NoopExtendedRegisterableItemsFactory. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class NoopExtendedRegisterableItemsFactory implements ExtendedRegisterableItemsFactory { + + private InternalRuntimeManager _manager; + + /** + * {@inheritDoc} + */ + @Override + public List getAgendaEventListeners(RuntimeEngine runtime) { + return Collections.emptyList(); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getGlobals(RuntimeEngine runtime) { + return Collections.emptyMap(); + } + + /** + * {@inheritDoc} + */ + @Override + public List getProcessEventListeners(RuntimeEngine runtime) { + return Collections.emptyList(); + } + + /** + * {@inheritDoc} + */ + @Override + public List getRuleRuntimeEventListeners(RuntimeEngine runtime) { + return Collections.emptyList(); + } + + /** + * {@inheritDoc} + */ + @Override + public List getTaskListeners() { + return Collections.emptyList(); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getWorkItemHandlers(RuntimeEngine runtime) { + return Collections.emptyMap(); + } + + /** + * {@inheritDoc} + */ + @Override + public List getKieBaseEventListeners(RuntimeEngine runtime) { + return Collections.emptyList(); + } + + /** + * {@inheritDoc} + */ + @Override + public InternalRuntimeManager getRuntimeManager() { + return _manager; + } + + /** + * {@inheritDoc} + */ + @Override + public void setRuntimeManager(InternalRuntimeManager manager) { + _manager = manager; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/ContainerManifest.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/ContainerManifest.java new file mode 100644 index 000000000..1374fa49c --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/ContainerManifest.java @@ -0,0 +1,160 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.manifest; + +import org.kie.api.KieServices; +import org.kie.api.builder.ReleaseId; +import org.kie.api.runtime.Environment; +import org.kie.api.runtime.KieContainer; +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; + +/** + * ContainerManifest. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public final class ContainerManifest extends Manifest { + + private final String _baseName; + private final ReleaseId _releaseId; + private final boolean _scan; + private final Long _scanInterval; + private final String _sessionName; + + private KieContainer _kieContainer; + + /** + * Creates a new, empty ContainerManifest. + */ + public ContainerManifest() { + this(null, (ReleaseId)null, false, null, null); + } + + /** + * Creates a new ContainerManifest. + * @param baseName the base name + * @param releaseId the release id + * @param scan if scanning is enabled + * @param scanInterval the scan interval + * @param sessionName the session name + */ + public ContainerManifest(String baseName, String releaseId, boolean scan, Long scanInterval, String sessionName) { + this(baseName, toReleaseId(releaseId), scan, scanInterval, sessionName); + } + + /** + * Creates a new ContainerManifest. + * @param baseName the base name + * @param releaseId the release id + * @param scan if scanning is enabled + * @param scanInterval the scan interval + * @param sessionName the session name + */ + public ContainerManifest(String baseName, ReleaseId releaseId, boolean scan, Long scanInterval, String sessionName) { + _baseName = baseName; + _releaseId = releaseId; + _scan = scan; + if (scanInterval == null) { + scanInterval = Long.valueOf(60000); + } + long si = scanInterval.longValue(); + if (si < 1) { + throw CommonKnowledgeMessages.MESSAGES.containerScanIntervalMustBePositive(); + } + _scanInterval = scanInterval; + _sessionName = sessionName; + } + + /** + * Gets the base name. + * @return the base name + */ + public String getBaseName() { + return _baseName; + } + + /** + * Gets the release id. + * @return the release id + */ + public ReleaseId getReleaseId() { + return _releaseId; + } + + /** + * If scanning is enabled. + * @return if scanning is enabled + */ + public boolean isScan() { + return _scan; + } + + /** + * Gets the scan interval. + * @return the scan interval + */ + public Long getScanInterval() { + return _scanInterval; + } + + /** + * Gets the session name. + * @return the session name + */ + public String getSessionName() { + return _sessionName; + } + + /** + * Gets the kie container. + * @return the kie container + */ + public KieContainer getKieContainer() { + return _kieContainer; + } + + /** + * Sets the kie container. + * @param kieContainer the kie container + */ + public void setKieContainer(KieContainer kieContainer) { + _kieContainer = kieContainer; + } + + /** + * Removes a ContainerManifest from the Environment. + * @param environment the Environment + * @return the ContainerManifest + */ + public static ContainerManifest removeFromEnvironment(Environment environment) { + return Manifest.removeFromEnvironment(environment, ContainerManifest.class); + } + + /** + * Converts a colon (':') separated string into a ReleaseId. + * @param releaseId the string + * @return the ReleaseId + */ + public static ReleaseId toReleaseId(String releaseId) { + if (releaseId != null) { + String[] gav = releaseId.split(":", 3); + String groupId = gav.length > 0 ? gav[0] : null; + String artifactId = gav.length > 1 ? gav[1] : null; + String version = gav.length > 2 ? gav[2] : null; + return KieServices.Factory.get().newReleaseId(groupId, artifactId, version); + } + return null; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/Manifest.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/Manifest.java new file mode 100644 index 000000000..20c5d3977 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/Manifest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.manifest; + +import org.kie.api.runtime.Environment; +import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder; + +/** + * Manifest. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public abstract class Manifest { + + /** + * Adds the runtimeEnvironmentBuilder to the Environment. + * @param runtimeEnvironmentBuilder the runtimeEnvironmentBuilder + */ + public void addToEnvironment(RuntimeEnvironmentBuilder runtimeEnvironmentBuilder) { + runtimeEnvironmentBuilder.addEnvironmentEntry(getClass().getName(), this); + } + + /* + public void addToEnvironment(Environment environment) { + environment.set(getClass().getName(), this); + } + + protected static T getFromEnvironment(Environment environment, Class type) { + return type.cast(environment.get(type.getName())); + } + */ + + /** + * Removes and returns the Manifest from the Environment. + * @param environment the Environment + * @param type the type of Manifest + * @return the Manifest + */ + protected static T removeFromEnvironment(Environment environment, Class type) { + String identifier = type.getName(); + Object manifest = environment.get(identifier); + if (manifest != null) { + environment.set(identifier, null); + } + return type.cast(manifest); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/RemoteManifest.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/RemoteManifest.java new file mode 100644 index 000000000..d94f8a494 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/RemoteManifest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.manifest; + +import org.kie.api.runtime.Environment; +import org.kie.services.client.api.command.RemoteConfiguration; +import org.switchyard.component.common.knowledge.config.builder.RemoteConfigurationBuilder; + +/** + * RemoteManifest. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public final class RemoteManifest extends Manifest { + + private final RemoteConfigurationBuilder _remoteConfigurationBuilder; + + /** + * Creates a new RemoteManifest. + * @param remoteConfigurationBuilder the RemoteConfigurationBuilder + */ + public RemoteManifest(RemoteConfigurationBuilder remoteConfigurationBuilder) { + _remoteConfigurationBuilder = remoteConfigurationBuilder; + } + + /** + * Builds the RemoteConfiguration. + * @return the RemoteConfigurationBuilder + */ + public RemoteConfiguration buildConfiguration() { + return _remoteConfigurationBuilder.build(); + } + + /** + * Removes a RemoteManifest from the Environment. + * @param environment the Environment + * @return the RemoteManifest + */ + public static RemoteManifest removeFromEnvironment(Environment environment) { + return Manifest.removeFromEnvironment(environment, RemoteManifest.class); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/ResourcesManifest.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/ResourcesManifest.java new file mode 100644 index 000000000..2b03d2f8f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/manifest/ResourcesManifest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.manifest; + +import java.util.ArrayList; +import java.util.List; + +import org.kie.api.io.Resource; +import org.kie.api.runtime.Environment; +import org.switchyard.component.common.knowledge.config.builder.ResourceBuilder; + +/** + * ResourcesManifest. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public final class ResourcesManifest extends Manifest { + + private List _resourceBuilders = new ArrayList(); + + /** + * Creates a new ResourcesManifest. + * @param resourceBuilders the ResourceBuilders + */ + public ResourcesManifest(List resourceBuilders) { + if (resourceBuilders != null) { + _resourceBuilders.addAll(resourceBuilders); + } + } + + /** + * Builds the Resources. + * @return the Resources + */ + public List buildResources() { + List resources = new ArrayList(); + for (ResourceBuilder builder : _resourceBuilders) { + Resource resource = builder.build(); + if (resource != null) { + resources.add(resource); + } + } + return resources; + } + + /** + * Removes a ResourcesManifest from the Environment. + * @param environment the Environment + * @return the ResourcesManifest + */ + public static ResourcesManifest removeFromEnvironment(Environment environment) { + return Manifest.removeFromEnvironment(environment, ResourcesManifest.class); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ChannelModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ChannelModel.java new file mode 100644 index 000000000..e0ec7cbba --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ChannelModel.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.NamedModel; + +/** + * A Channel Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface ChannelModel extends NamedModel { + + /** + * The channel XML element. + */ + public static final String CHANNEL = "channel"; + + /** + * Gets the Channel class. + * @param loader the ClassLoader to use + * @return the Channel class + */ + public Class getClazz(ClassLoader loader); + + /** + * Sets the Channel class. + * @param clazz the Channel class + * @return this ChannelModel (useful for chaining) + */ + public ChannelModel setClazz(Class clazz); + + /** + * Gets the operation attribute. + * @return the operation attribute + */ + public String getOperation(); + + /** + * Sets the operation attribute. + * @param operation the operation attribute + * @return this ChannelModel (useful for chaining) + */ + public ChannelModel setOperation(String operation); + + /** + * Gets the reference attribute. + * @return the reference attribute + */ + public String getReference(); + + /** + * Sets the reference attribute. + * @param reference the reference attribute + * @return this ChannelModel (useful for chaining) + */ + public ChannelModel setReference(String reference); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ChannelsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ChannelsModel.java new file mode 100644 index 000000000..222f4c586 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ChannelsModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A Channels Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface ChannelsModel extends Model { + + /** The "channels" name. */ + public static final String CHANNELS = "channels"; + + /** + * Gets the child channel models. + * @return the child channel models + */ + public List getChannels(); + + /** + * Adds a child channel model. + * @param channel the child channel model + * @return this ChannelsModel (useful for chaining) + */ + public ChannelsModel addChannel(ChannelModel channel); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ContainerModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ContainerModel.java new file mode 100644 index 000000000..d6a87deca --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ContainerModel.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.Model; + +/** + * A Container Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface ContainerModel extends Model { + + /** The "container" name. */ + public static final String CONTAINER = "container"; + + /** + * Gets the baseName attribute. + * @return the baseName attribute + */ + public String getBaseName(); + + /** + * Sets the baseName attribute. + * @param baseName the baseName attribute + * @return this ContainerModel (useful for chaining) + */ + public ContainerModel setBaseName(String baseName); + + /** + * Gets the releaseId attribute. + * @return the releaseId attribute + */ + public String getReleaseId(); + + /** + * Sets the releaseId attribute. + * @param releaseId the releaseId attribute + * @return this ContainerModel (useful for chaining) + */ + public ContainerModel setReleaseId(String releaseId); + + /** + * Gets the scan attribute. + * @return the scan attribute + */ + public boolean isScan(); + + /** + * Sets the scan attribute. + * @param scan the scan attribute + * @return this ContainerModel (useful for chaining) + */ + public ContainerModel setScan(boolean scan); + + /** + * Gets the scanInterval attribute. + * @return the scanInterval attribute + */ + public Long getScanInterval(); + + /** + * Sets the scanInterval attribute. + * @param scanInterval the scanInterval attribute + * @return this ContainerModel (useful for chaining) + */ + public ContainerModel setScanInterval(Long scanInterval); + + /** + * Gets the sessionName attribute. + * @return the sessionName attribute + */ + public String getSessionName(); + + /** + * Sets the sessionName attribute. + * @param sessionName the baseName attribute + * @return this ContainerModel (useful for chaining) + */ + public ContainerModel setSessionName(String sessionName); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassModel.java new file mode 100644 index 000000000..93b3f9973 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassModel.java @@ -0,0 +1,44 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.Model; + +/** + * A ExtraJaxbClass Model. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public interface ExtraJaxbClassModel extends Model { + + /** + * The extraJaxbClass XML element. + */ + public static final String EXTRA_JAXB_CLASS = "extraJaxbClass"; + + /** + * Gets the extra JAXB class. + * @param loader the ClassLoader to use + * @return the extra JAXB class + */ + public Class getClazz(ClassLoader loader); + + /** + * Sets the extra JAXB class. + * @param clazz the extra JAXB class + * @return this ExtraJaxbClassModel (useful for chaining) + */ + public ExtraJaxbClassModel setClazz(Class clazz); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassesModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassesModel.java new file mode 100644 index 000000000..bcd88a423 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ExtraJaxbClassesModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A ExtraJaxbClasses Model. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public interface ExtraJaxbClassesModel extends Model { + + /** The "extraJaxbClasses" name. */ + public static final String EXTRA_JAXB_CLASSES = "extraJaxbClasses"; + + /** + * Gets the child extraJaxbClass models. + * @return the child extraJaxbClass models + */ + public List getExtraJaxbClasses(); + + /** + * Adds a child extraJaxbClass model. + * @param extraJaxbClass the child extraJaxbClass model + * @return this ExtraJaxbClassesModel (useful for chaining) + */ + public ExtraJaxbClassesModel addExtraJaxbClass(ExtraJaxbClassModel extraJaxbClass); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/FaultModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/FaultModel.java new file mode 100644 index 000000000..32bf17946 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/FaultModel.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +/** + * FaultModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface FaultModel extends MappingModel { + + /** The "fault" name. */ + public static final String FAULT = "fault"; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/FaultsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/FaultsModel.java new file mode 100644 index 000000000..938fc9250 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/FaultsModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A Faults Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface FaultsModel extends Model { + + /** The "faults" name. */ + public static final String FAULTS = "faults"; + + /** + * Gets the child fault models. + * @return the child fault models + */ + public List getFaults(); + + /** + * Adds a child fault model. + * @param fault the child fault model + * @return this FaultsModel (useful for chaining) + */ + public FaultsModel addFault(FaultModel fault); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/GlobalModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/GlobalModel.java new file mode 100644 index 000000000..7ec54a175 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/GlobalModel.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +/** + * GlobalModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface GlobalModel extends MappingModel { + + /** The "global" name. */ + public static final String GLOBAL = "global"; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/GlobalsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/GlobalsModel.java new file mode 100644 index 000000000..51daa95df --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/GlobalsModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A Globals Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface GlobalsModel extends Model { + + /** The "globals" name. */ + public static final String GLOBALS = "globals"; + + /** + * Gets the child global models. + * @return the child global models + */ + public List getGlobals(); + + /** + * Adds a child global model. + * @param global the child global model + * @return this GlobalsModel (useful for chaining) + */ + public GlobalsModel addGlobal(GlobalModel global); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/InputModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/InputModel.java new file mode 100644 index 000000000..80ee15c18 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/InputModel.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +/** + * InputModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface InputModel extends MappingModel { + + /** The "input" name. */ + public static final String INPUT = "input"; + + /** + * Gets the output. + * @return the output + */ + public String getOutput(); + + /** + * Sets the output. + * @param output the output + * @return this MappingModel (useful for chaining) + */ + public InputModel setOutput(String output); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/InputsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/InputsModel.java new file mode 100644 index 000000000..e6b6580ce --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/InputsModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A Inputs Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface InputsModel extends Model { + + /** The "inputs" name. */ + public static final String INPUTS = "inputs"; + + /** + * Gets the child input models. + * @return the child input models + */ + public List getInputs(); + + /** + * Adds a child input model. + * @param input the child input model + * @return this InputsModel (useful for chaining) + */ + public InputsModel addInput(InputModel input); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeComponentImplementationModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeComponentImplementationModel.java new file mode 100644 index 000000000..35b29aa13 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeComponentImplementationModel.java @@ -0,0 +1,156 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * KnowledgeComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface KnowledgeComponentImplementationModel extends ComponentImplementationModel { + + /** + * Gets the "persistent" attribute. + * @return the "persistent" attribute + */ + public boolean isPersistent(); + + /** + * Sets the "persistent" attribute. + * @param persistent the "persistent" attribute + * @return this instance (useful for chaining) + */ + public KnowledgeComponentImplementationModel setPersistent(boolean persistent); + + /** + * Gets the "processId" attribute. + * @return the "processId" attribute + */ + public String getProcessId(); + + /** + * Sets the "processId" attribute. + * @param processId the "processId" attribute + * @return this instance (useful for chaining) + */ + public KnowledgeComponentImplementationModel setProcessId(String processId); + + /** + * Gets the child channels model. + * @return the child channels model + */ + public ChannelsModel getChannels(); + + /** + * Sets the child channels model. + * @param channels the child channels model + * @return this KnowledgeComponentImplementationModel (useful for chaining) + */ + public KnowledgeComponentImplementationModel setChannels(ChannelsModel channels); + + /** + * Gets the child listeners model. + * @return the child listeners model + */ + public ListenersModel getListeners(); + + /** + * Sets the child listeners model. + * @param listeners the child listeners model + * @return this KnowledgeComponentImplementationModel (useful for chaining) + */ + public KnowledgeComponentImplementationModel setListeners(ListenersModel listeners); + + /** + * Gets the child loggers model. + * @return the child loggers model + */ + public LoggersModel getLoggers(); + + /** + * Sets the child loggers model. + * @param loggers the child loggers model + * @return this KnowledgeComponentImplementationModel (useful for chaining) + */ + public KnowledgeComponentImplementationModel setLoggers(LoggersModel loggers); + + /** + * Gets the child manifest model. + * @return the child manifest model + */ + public ManifestModel getManifest(); + + /** + * Sets the child manifest model. + * @param manifest the child manifest model + * @return this KnowledgeComponentImplementationModel (useful for chaining) + */ + public KnowledgeComponentImplementationModel setManifest(ManifestModel manifest); + + /** + * Gets the child operations model. + * @return the child operations model + */ + public OperationsModel getOperations(); + + /** + * Sets the child operations model. + * @param operations the child operations model + * @return this KnowledgeComponentImplementationModel (useful for chaining) + */ + public KnowledgeComponentImplementationModel setOperations(OperationsModel operations); + + /** + * Gets the child properties model. + * @return the child properties model + */ + public PropertiesModel getProperties(); + + /** + * Sets the child properties model. + * @param properties the child properties model + * @return this KnowledgeComponentImplementationModel (useful for chaining) + */ + public KnowledgeComponentImplementationModel setProperties(PropertiesModel properties); + + /** + * Gets the child userGroupCallback model. + * @return the child userGroupCallback model + */ + public UserGroupCallbackModel getUserGroupCallback(); + + /** + * Sets the child userGroupCallback model. + * @param userGroupCallback the child userGroupCallback model + * @return this instance (useful for chaining) + */ + public KnowledgeComponentImplementationModel setUserGroupCallback(UserGroupCallbackModel userGroupCallback); + + /** + * Gets the child workItemHandlers model. + * @return the child workItemHandlers model + */ + public WorkItemHandlersModel getWorkItemHandlers(); + + /** + * Sets the child workItemHandlers model. + * @param workItemHandlers the child workItemHandlers model + * @return this instance (useful for chaining) + */ + public KnowledgeComponentImplementationModel setWorkItemHandlers(WorkItemHandlersModel workItemHandlers); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeNamespace.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeNamespace.java new file mode 100644 index 000000000..1aa9fef70 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeNamespace.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.Namespace; + +/** + * Represents knowledge config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface KnowledgeNamespace extends Namespace {} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeSwitchYardScanner.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeSwitchYardScanner.java new file mode 100644 index 000000000..f461343c6 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/KnowledgeSwitchYardScanner.java @@ -0,0 +1,431 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.common.io.resource.ResourceType; +import org.switchyard.component.common.knowledge.LoggerType; +import org.switchyard.component.common.knowledge.annotation.Channel; +import org.switchyard.component.common.knowledge.annotation.Container; +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Listener; +import org.switchyard.component.common.knowledge.annotation.Logger; +import org.switchyard.component.common.knowledge.annotation.Manifest; +import org.switchyard.component.common.knowledge.annotation.Output; +import org.switchyard.component.common.knowledge.annotation.Property; +import org.switchyard.component.common.knowledge.annotation.Resource; +import org.switchyard.component.common.knowledge.annotation.ResourceDetail; +import org.switchyard.component.common.knowledge.config.model.v1.V1ChannelModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1ChannelsModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1ContainerModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1FaultModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1FaultsModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1GlobalModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1GlobalsModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1InputModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1InputsModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1ListenerModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1ListenersModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1LoggerModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1LoggersModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1ManifestModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1OutputModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1OutputsModel; +import org.switchyard.component.common.knowledge.service.SwitchYardServiceChannel; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.v1.V1ComponentReferenceModel; +import org.switchyard.config.model.composite.v1.V1InterfaceModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.property.v1.V1PropertiesModel; +import org.switchyard.config.model.property.v1.V1PropertyModel; +import org.switchyard.config.model.resource.ResourceDetailModel; +import org.switchyard.config.model.resource.ResourceModel; +import org.switchyard.config.model.resource.ResourcesModel; +import org.switchyard.config.model.resource.v1.V1ResourceDetailModel; +import org.switchyard.config.model.resource.v1.V1ResourceModel; +import org.switchyard.config.model.resource.v1.V1ResourcesModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; + +/** + * KnowledgeSwitchYardScanner. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class KnowledgeSwitchYardScanner implements Scanner { + + /** Undefined String value. */ + protected static final String UNDEFINED = ""; + + /** + * Converts channel annotations to a channels model. + * @param channelAnnotations channelAnnotations + * @param knowledgeNamespace knowledgeNamespace + * @param componentModel componentModel + * @param switchyardNamespace switchyardNamespace + * @return a channels model + */ + protected ChannelsModel toChannelsModel(Channel[] channelAnnotations, KnowledgeNamespace knowledgeNamespace, ComponentModel componentModel, SwitchYardNamespace switchyardNamespace) { + if (channelAnnotations == null || channelAnnotations.length == 0) { + return null; + } + ChannelsModel channelsModel = new V1ChannelsModel(knowledgeNamespace.uri()); + for (Channel channelAnnotation : channelAnnotations) { + ChannelModel channelModel = new V1ChannelModel(knowledgeNamespace.uri()); + Class clazz = channelAnnotation.value(); + if (Channel.UndefinedChannel.class.isAssignableFrom(clazz)) { + clazz = SwitchYardServiceChannel.class; + } + channelModel.setClazz(clazz); + String name = channelAnnotation.name(); + if (UNDEFINED.equals(name)) { + if (SwitchYardServiceChannel.class.isAssignableFrom(clazz)) { + name = SwitchYardServiceChannel.SERVICE; + } + } + if (UNDEFINED.equals(name)) { + name = clazz.getSimpleName(); + } + channelModel.setName(name); + String operation = channelAnnotation.operation(); + if (!UNDEFINED.equals(operation)) { + channelModel.setOperation(operation); + } + String reference = channelAnnotation.reference(); + if (!UNDEFINED.equals(reference)) { + channelModel.setReference(reference); + ComponentReferenceModel componentReferenceModel = new V1ComponentReferenceModel(switchyardNamespace.uri()); + componentReferenceModel.setName(reference); + Class interfaze = channelAnnotation.interfaze(); + if (!Channel.UndefinedInterface.class.isAssignableFrom(interfaze)) { + InterfaceModel interfaceModel = new V1InterfaceModel(InterfaceModel.JAVA); + interfaceModel.setInterface(interfaze.getName()); + componentReferenceModel.setInterface(interfaceModel); + componentModel.addReference(componentReferenceModel); + } + } + channelsModel.addChannel(channelModel); + } + return channelsModel; + } + + /** + * Converts container annotation to container model + * @param containerAnnotation annotation + * @param knowledgeNamespace knowledgeNamespace + * @return model + */ + protected ContainerModel toContainerModel(Container containerAnnotation, KnowledgeNamespace knowledgeNamespace) { + if (containerAnnotation == null) { + return null; + } + ContainerModel containerModel = new V1ContainerModel(knowledgeNamespace.uri()); + String baseName = containerAnnotation.baseName(); + if (!UNDEFINED.equals(baseName)) { + containerModel.setBaseName(baseName); + } + String releaseId = containerAnnotation.releaseId(); + if (!UNDEFINED.equals(releaseId)) { + containerModel.setReleaseId(releaseId); + } + boolean scan = containerAnnotation.scan(); + if (scan) { + containerModel.setScan(scan); + } + long scanInterval = containerAnnotation.scanInterval(); + if (scanInterval > 0) { + containerModel.setScanInterval(Long.valueOf(scanInterval)); + } + String sessionName = containerAnnotation.sessionName(); + if (!UNDEFINED.equals(sessionName)) { + containerModel.setSessionName(sessionName); + } + return containerModel; + } + + /** + * Converts listener annotations to listeners model. + * @param listenerAnnotations annotations + * @param knowledgeNamespace knowledgeNamespace + * @return model + */ + protected ListenersModel toListenersModel(Listener[] listenerAnnotations, KnowledgeNamespace knowledgeNamespace) { + if (listenerAnnotations == null || listenerAnnotations.length == 0) { + return null; + } + ListenersModel listenersModel = new V1ListenersModel(knowledgeNamespace.uri()); + for (Listener listenerAnnotation : listenerAnnotations) { + ListenerModel listenerModel = new V1ListenerModel(knowledgeNamespace.uri()); + listenerModel.setClazz(listenerAnnotation.value()); + listenersModel.addListener(listenerModel); + } + return listenersModel; + } + + /** + * Converts logger annotations to loggers model. + * @param loggerAnnotations annotations + * @param knowledgeNamespace knowledgeNamespace + * @return model + */ + protected LoggersModel toLoggersModel(Logger[] loggerAnnotations, KnowledgeNamespace knowledgeNamespace) { + if (loggerAnnotations == null || loggerAnnotations.length == 0) { + return null; + } + LoggersModel loggersModel = new V1LoggersModel(knowledgeNamespace.uri()); + for (Logger loggerAnnotation : loggerAnnotations) { + LoggerModel loggerModel = new V1LoggerModel(knowledgeNamespace.uri()); + int interval = loggerAnnotation.interval(); + if (interval > -1) { + loggerModel.setInterval(interval); + } + String log = loggerAnnotation.log(); + if (!UNDEFINED.equals(log)) { + loggerModel.setLog(log); + } + LoggerType loggerType = loggerAnnotation.type(); + if (!LoggerType.THREADED_FILE.equals(loggerType)) { + loggerModel.setType(loggerType); + } + loggersModel.addLogger(loggerModel); + } + return loggersModel; + } + + /** + * Converts manifest annotations to manifest model. + * @param manifestAnnotations annotations + * @param knowledgeNamespace knowledgeNamespace + * @return model + */ + protected ManifestModel toManifestModel(Manifest[] manifestAnnotations, KnowledgeNamespace knowledgeNamespace) { + if (manifestAnnotations == null || manifestAnnotations.length == 0) { + return null; + } + Manifest manifestAnnotation = manifestAnnotations[0]; + ManifestModel manifestModel = new V1ManifestModel(knowledgeNamespace.uri()); + Container[] container = manifestAnnotation.container(); + if (container != null && container.length > 0) { + manifestModel.setContainer(toContainerModel(container[0], knowledgeNamespace)); + } + manifestModel.setResources(toResourcesModel(manifestAnnotation.resources(), knowledgeNamespace)); + return manifestModel; + } + + /** + * Converts globals to mappings model. + * @param globals globals + * @param knowledgeNamespace knowledgeNamespace + * @return mappings model + */ + protected GlobalsModel toGlobalsModel(Global[] globals, KnowledgeNamespace knowledgeNamespace) { + GlobalsModel globalsModel = null; + if (globals != null) { + for (Global global : globals) { + if (global != null) { + GlobalModel globalModel = new V1GlobalModel(knowledgeNamespace.uri()); + String from = global.from(); + if (!UNDEFINED.equals(from)) { + globalModel.setFrom(from); + } + String to = global.to(); + if (!UNDEFINED.equals(to)) { + globalModel.setTo(to); + } + if (globalsModel == null) { + globalsModel = new V1GlobalsModel(knowledgeNamespace.uri()); + } + globalsModel.addGlobal(globalModel); + } + } + } + return globalsModel; + } + + /** + * Converts inputs to mappings model. + * @param inputs inputs + * @param knowledgeNamespace knowledgeNamespace + * @return mappings model + */ + protected InputsModel toInputsModel(Input[] inputs, KnowledgeNamespace knowledgeNamespace) { + InputsModel inputsModel = null; + if (inputs != null) { + for (Input input : inputs) { + if (input != null) { + InputModel inputModel = new V1InputModel(knowledgeNamespace.uri()); + String from = input.from(); + if (!UNDEFINED.equals(from)) { + inputModel.setFrom(from); + } + String to = input.to(); + if (!UNDEFINED.equals(to)) { + inputModel.setTo(to); + } + if (inputsModel == null) { + inputsModel = new V1InputsModel(knowledgeNamespace.uri()); + } + inputsModel.addInput(inputModel); + } + } + } + return inputsModel; + } + + /** + * Converts outputs to mappings model. + * @param outputs outputs + * @param knowledgeNamespace knowledgeNamespace + * @return mappings model + */ + protected OutputsModel toOutputsModel(Output[] outputs, KnowledgeNamespace knowledgeNamespace) { + OutputsModel outputsModel = null; + if (outputs != null) { + for (Output output : outputs) { + if (output != null) { + OutputModel outputModel = new V1OutputModel(knowledgeNamespace.uri()); + String from = output.from(); + if (!UNDEFINED.equals(from)) { + outputModel.setFrom(from); + } + String to = output.to(); + if (!UNDEFINED.equals(to)) { + outputModel.setTo(to); + } + if (outputsModel == null) { + outputsModel = new V1OutputsModel(knowledgeNamespace.uri()); + } + outputsModel.addOutput(outputModel); + } + } + } + return outputsModel; + } + + /** + * Converts faults to mappings model. + * @param faults faults + * @param knowledgeNamespace knowledgeNamespace + * @return mappings model + */ + protected FaultsModel toFaultsModel(Fault[] faults, KnowledgeNamespace knowledgeNamespace) { + FaultsModel faultsModel = null; + if (faults != null) { + for (Fault fault : faults) { + if (fault != null) { + FaultModel faultModel = new V1FaultModel(knowledgeNamespace.uri()); + String from = fault.from(); + if (!UNDEFINED.equals(from)) { + faultModel.setFrom(from); + } + String to = fault.to(); + if (!UNDEFINED.equals(to)) { + faultModel.setTo(to); + } + if (faultsModel == null) { + faultsModel = new V1FaultsModel(knowledgeNamespace.uri()); + } + faultsModel.addFault(faultModel); + } + } + } + return faultsModel; + } + + /** + * Converts property annotations to properties model. + * @param propertyAnnotations propertyAnnotations + * @param knowledgeNamespace knowledgeNamespace + * @return model + */ + protected PropertiesModel toPropertiesModel(Property[] propertyAnnotations, KnowledgeNamespace knowledgeNamespace) { + if (propertyAnnotations == null || propertyAnnotations.length == 0) { + return null; + } + PropertiesModel propertiesModel = new V1PropertiesModel(knowledgeNamespace.uri()); + for (Property propertyAnnotation : propertyAnnotations) { + PropertyModel propertyModel = new V1PropertyModel(knowledgeNamespace.uri()); + String name = propertyAnnotation.name(); + if (!UNDEFINED.equals(name)) { + propertyModel.setName(name); + } + String value = propertyAnnotation.value(); + if (!UNDEFINED.equals(value)) { + propertyModel.setValue(value); + } + propertiesModel.addProperty(propertyModel); + } + return propertiesModel; + } + + /** + * Converts resource annotations to resources model. + * @param resourceAnnotations resourceAnnotations + * @param knowledgeNamespace knowledgeNamespace + * @return model + */ + protected ResourcesModel toResourcesModel(Resource[] resourceAnnotations, KnowledgeNamespace knowledgeNamespace) { + if (resourceAnnotations == null || resourceAnnotations.length == 0) { + return null; + } + ResourcesModel resourcesModel = new V1ResourcesModel(knowledgeNamespace.uri()); + for (Resource resourceAnnotation : resourceAnnotations) { + ResourceModel resourceModel = new V1ResourceModel(knowledgeNamespace.uri()); + String location = resourceAnnotation.location(); + if (!UNDEFINED.equals(location)) { + resourceModel.setLocation(location); + } + String type = resourceAnnotation.type(); + if (!UNDEFINED.equals(type)) { + resourceModel.setType(ResourceType.valueOf(type)); + } + ResourceDetailModel resourceDetailModel = toResourceDetailModel(resourceAnnotation.detail(), knowledgeNamespace); + if (resourceDetailModel != null) { + resourceModel.setDetail(resourceDetailModel); + } + resourcesModel.addResource(resourceModel); + } + return resourcesModel; + } + + private ResourceDetailModel toResourceDetailModel(ResourceDetail[] resourceDetailAnnotations, KnowledgeNamespace knowledgeNamespace) { + if (resourceDetailAnnotations == null || resourceDetailAnnotations.length == 0) { + return null; + } + ResourceDetailModel resourceDetailModel = null; + for (ResourceDetail resourceDetailAnnotation : resourceDetailAnnotations) { + resourceDetailModel = new V1ResourceDetailModel(knowledgeNamespace.uri()); + String inputType = resourceDetailAnnotation.inputType(); + if (!UNDEFINED.equals(inputType)) { + resourceDetailModel.setInputType(inputType); + } + String worksheetName = resourceDetailAnnotation.worksheetName(); + if (!UNDEFINED.equals(worksheetName)) { + resourceDetailModel.setWorksheetName(worksheetName); + } + /* SWITCHYARD-1662 + boolean usingExternalTypes = resourceDetailAnnotation.usingExternalTypes(); + resourceDetailModel.setUsingExternalTypes(usingExternalTypes); + */ + break; + } + return resourceDetailModel; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ListenerModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ListenerModel.java new file mode 100644 index 000000000..9a980f93d --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ListenerModel.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.Model; + +/** + * EventListenerModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface ListenerModel extends Model { + + /** + * The listener XML element. + */ + public static final String LISTENER = "listener"; + + /** + * Gets the Listener class. + * @param loader the ClassLoader to use + * @return the Listener class + */ + public Class getClazz(ClassLoader loader); + + /** + * Sets the Listener class. + * @param clazz the Listener class + * @return this ListenerModel (useful for chaining) + */ + public ListenerModel setClazz(Class clazz); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ListenersModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ListenersModel.java new file mode 100644 index 000000000..3b7b6aa7a --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ListenersModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A Listeners Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface ListenersModel extends Model { + + /** The "listeners" name. */ + public static final String LISTENERS = "listeners"; + + /** + * Gets the child listener models. + * @return the child listener models + */ + public List getListeners(); + + /** + * Adds a child listener model. + * @param listener the child listener model + * @return this ListenersModel (useful for chaining) + */ + public ListenersModel addListener(ListenerModel listener); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/LoggerModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/LoggerModel.java new file mode 100644 index 000000000..da1c2fcf0 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/LoggerModel.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.component.common.knowledge.LoggerType; +import org.switchyard.config.model.Model; + +/** + * A Channel Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface LoggerModel extends Model { + + /** + * The logger XML element. + */ + public static final String LOGGER = "logger"; + + /** + * Gets the interval attribute. + * @return the interval attribute + */ + public Integer getInterval(); + + /** + * Sets the interval attribute. + * @param interval the interval attribute + * @return this LoggerModel (useful for chaining) + */ + public LoggerModel setInterval(Integer interval); + + /** + * Gets the log attribute. + * @return the log attribute + */ + public String getLog(); + + /** + * Sets the log attribute. + * @param log the log attribute + * @return this LoggerModel (useful for chaining) + */ + public LoggerModel setLog(String log); + + /** + * Gets the type attribute. + * @return the type attribute + */ + public LoggerType getType(); + + /** + * Sets the type attribute. + * @param type the type attribute + * @return this LoggerModel (useful for chaining) + */ + public LoggerModel setType(LoggerType type); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/LoggersModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/LoggersModel.java new file mode 100644 index 000000000..a3f670d43 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/LoggersModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A Loggers Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface LoggersModel extends Model { + + /** The "loggers" name. */ + public static final String LOGGERS = "loggers"; + + /** + * Gets the child logger models. + * @return the child logger models + */ + public List getLoggers(); + + /** + * Adds a child logger model. + * @param logger the child logger model + * @return this LoggersModel (useful for chaining) + */ + public LoggersModel addLogger(LoggerModel logger); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ManifestModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ManifestModel.java new file mode 100644 index 000000000..2d0d169cf --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/ManifestModel.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.Model; +import org.switchyard.config.model.resource.ResourcesModel; + +/** + * A Manifest Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface ManifestModel extends Model { + + /** The "manifest" name. */ + public static final String MANIFEST = "manifest"; + + /** + * Gets the child container model. + * @return the child container model + */ + public ContainerModel getContainer(); + + /** + * Sets the child container model. + * @param container the child container model + * @return this ManifestModel (useful for chaining) + */ + public ManifestModel setContainer(ContainerModel container); + + /** + * Gets the child resources model. + * @return the child resources model + */ + public ResourcesModel getResources(); + + /** + * Sets the child resources model. + * @param resources the child resources model + * @return this ManifestModel (useful for chaining) + */ + public ManifestModel setResources(ResourcesModel resources); + + /** + * Gets the child remote model. + * @return the child remote model + */ + public RemoteModel getRemote(); + + /** + * Sets the child remote model. + * @param remote the child remote model + * @return this ManifestModel (useful for chaining) + */ + public ManifestModel setRemote(RemoteModel remote); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/MappingModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/MappingModel.java new file mode 100644 index 000000000..01ec7a2a9 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/MappingModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.Model; + +/** + * MappingModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface MappingModel extends Model { + + /** + * Gets the from. + * @return the from + */ + public String getFrom(); + + /** + * Sets the from. + * @param from the from + * @return this MappingModel (useful for chaining) + */ + public MappingModel setFrom(String from); + + /** + * Gets the to. + * @return the to + */ + public String getTo(); + + /** + * Sets the to. + * @param to the to + * @return this MappingModel (useful for chaining) + */ + public MappingModel setTo(String to); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OperationModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OperationModel.java new file mode 100644 index 000000000..69adccb78 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OperationModel.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.component.common.knowledge.operation.KnowledgeOperationType; +import org.switchyard.config.model.NamedModel; + +/** + * An Operation Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface OperationModel extends NamedModel { + + /** The "operation" name. */ + public static final String OPERATION = "operation"; + + /** + * Gets the eventId attribute. + * @return the eventId attribute + */ + public String getEventId(); + + /** + * Sets the eventId attribute. + * @param eventId the eventId attribute + * @return this OperationModel (useful for chaining) + */ + public OperationModel setEventId(String eventId); + + /** + * Gets the type attribute. + * @return the type attribute + */ + public KnowledgeOperationType getType(); + + /** + * Sets the type attribute. + * @param type the type attribute + * @return this OperationModel (useful for chaining) + */ + public OperationModel setType(KnowledgeOperationType type); + + /** + * Gets the child globals mappings model. + * @return the child globals mappings model + */ + public GlobalsModel getGlobals(); + + /** + * Sets the child globals mappings model. + * @param globals the child globals mappings model + * @return this OperationModel (useful for chaining) + */ + public OperationModel setGlobals(GlobalsModel globals); + + /** + * Gets the child inputs mappings model. + * @return the child inputs mappings model + */ + public InputsModel getInputs(); + + /** + * Sets the child inputs mappings model. + * @param inputs the child inputs mappings model + * @return this OperationModel (useful for chaining) + */ + public OperationModel setInputs(InputsModel inputs); + + /** + * Gets the child outputs mappings model. + * @return the child outputs mappings model + */ + public OutputsModel getOutputs(); + + /** + * Sets the child outputs mappings model. + * @param outputs the child outputs mappings model + * @return this OperationModel (useful for chaining) + */ + public OperationModel setOutputs(OutputsModel outputs); + + /** + * Gets the child faults mappings model. + * @return the child faults mappings model + */ + public FaultsModel getFaults(); + + /** + * Sets the child faults mappings model. + * @param faults the child faults mappings model + * @return this OperationModel (useful for chaining) + */ + public OperationModel setFaults(FaultsModel faults); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OperationsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OperationsModel.java new file mode 100644 index 000000000..69217671f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OperationsModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * An Operations Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface OperationsModel extends Model { + + /** The "operations" name. */ + public static final String OPERATIONS = "operations"; + + /** + * Gets the child operation models. + * @return the child operation models + */ + public List getOperations(); + + /** + * Adds a child operation model. + * @param operation the child operation model + * @return this OperationsModel (useful for chaining) + */ + public OperationsModel addOperation(OperationModel operation); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OutputModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OutputModel.java new file mode 100644 index 000000000..b78918514 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OutputModel.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +/** + * OutputModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface OutputModel extends MappingModel { + + /** The "output" name. */ + public static final String OUTPUT = "output"; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OutputsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OutputsModel.java new file mode 100644 index 000000000..d3ab1648f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/OutputsModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A Outputs Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface OutputsModel extends Model { + + /** The "outputs" name. */ + public static final String OUTPUTS = "outputs"; + + /** + * Gets the child output models. + * @return the child output models + */ + public List getOutputs(); + + /** + * Adds a child output model. + * @param output the child output model + * @return this OutputsModel (useful for chaining) + */ + public OutputsModel addOutput(OutputModel output); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteJmsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteJmsModel.java new file mode 100644 index 000000000..ea31fb24b --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteJmsModel.java @@ -0,0 +1,130 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +/** + * A RemoteJmsModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public interface RemoteJmsModel extends RemoteModel { + + /** The "remoteJms" name. */ + public static final String REMOTE_JMS = "remoteJms"; + + /** + * Gets the hostName attribute. + * @return the hostName attribute + */ + public String getHostName(); + + /** + * Sets the hostName attribute. + * @param hostName the hostName attribute + * @return this RemoteJmsModel (useful for chaining) + */ + public RemoteJmsModel setHostName(String hostName); + + /** + * Gets the remotingPort attribute. + * @return the remotingPort attribute + */ + public Integer getRemotingPort(); + + /** + * Sets the remotingPort attribute. + * @param remotingPort the remotingPort attribute + * @return this RemoteJmsModel (useful for chaining) + */ + public RemoteModel setRemotingPort(Integer remotingPort); + + /** + * Gets the messagingPort attribute. + * @return the messagingPort attribute + */ + public Integer getMessagingPort(); + + /** + * Sets the messagingPort attribute. + * @param messagingPort the messagingPort attribute + * @return this RemoteJmsModel (useful for chaining) + */ + public RemoteModel setMessagingPort(Integer messagingPort); + + /** + * Gets the useSsl attribute. + * @return the useSsl attribute + */ + public boolean isUseSsl(); + + /** + * Sets the useSsl attribute. + * @param useSsl the useSsl attribute + * @return this RemoteJmsModel (useful for chaining) + */ + public RemoteJmsModel setUseSsl(boolean useSsl); + + /** + * Gets the keystorePassword attribute. + * @return the keystorePassword attribute + */ + public String getKeystorePassword(); + + /** + * Sets the keystorePassword attribute. + * @param keystorePassword the keystorePassword attribute + * @return this RemoteJmsModel (useful for chaining) + */ + public RemoteJmsModel setKeystorePassword(String keystorePassword); + + /** + * Gets the keystoreLocation attribute. + * @return the keystoreLocation attribute + */ + public String getKeystoreLocation(); + + /** + * Sets the keystoreLocation attribute. + * @param keystoreLocation the keystoreLocation attribute + * @return this RemoteJmsModel (useful for chaining) + */ + public RemoteJmsModel setKeystoreLocation(String keystoreLocation); + + /** + * Gets the truststorePassword attribute. + * @return the truststorePassword attribute + */ + public String getTruststorePassword(); + + /** + * Sets the truststorePassword attribute. + * @param truststorePassword the keystorePassword attribute + * @return this RemoteJmsModel (useful for chaining) + */ + public RemoteJmsModel setTruststorePassword(String truststorePassword); + + /** + * Gets the truststoreLocation attribute. + * @return the truststoreLocation attribute + */ + public String getTruststoreLocation(); + + /** + * Sets the truststoreLocation attribute. + * @param truststoreLocation the keystoreLocation attribute + * @return this RemoteJmsModel (useful for chaining) + */ + public RemoteJmsModel setTruststoreLocation(String truststoreLocation); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java new file mode 100644 index 000000000..e78b257f0 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteModel.java @@ -0,0 +1,90 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.Model; + +/** + * A RemoteModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public interface RemoteModel extends Model { + + /** + * Gets the deploymentId attribute. + * @return the deploymentId attribute + */ + public String getDeploymentId(); + + /** + * Sets the deploymentId attribute. + * @param deploymentId the deploymentId attribute + * @return this RemoteModel (useful for chaining) + */ + public RemoteModel setDeploymentId(String deploymentId); + + /** + * Gets the userName attribute. + * @return the userName attribute + */ + public String getUserName(); + + /** + * Sets the userName attribute. + * @param userName the userName attribute + * @return this RemoteModel (useful for chaining) + */ + public RemoteModel setUserName(String userName); + + /** + * Gets the password attribute. + * @return the password attribute + */ + public String getPassword(); + + /** + * Sets the password attribute. + * @param password the password attribute + * @return this RemoteModel (useful for chaining) + */ + public RemoteModel setPassword(String password); + + /** + * Gets the timeout attribute. + * @return the timeout attribute + */ + public Integer getTimeout(); + + /** + * Sets the timeout attribute. + * @param timeout the timeout attribute + * @return this RemoteModel (useful for chaining) + */ + public RemoteModel setTimeout(Integer timeout); + + /** + * Gets the child extraJaxbClasses model. + * @return the child extraJaxbClasses model + */ + public ExtraJaxbClassesModel getExtraJaxbClasses(); + + /** + * Sets the child extraJaxbClasses model. + * @param extraJaxbClasses the child extraJaxbClasses model + * @return this RemoteModel (useful for chaining) + */ + public RemoteModel setExtraJaxbClasses(ExtraJaxbClassesModel extraJaxbClasses); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteRestModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteRestModel.java new file mode 100644 index 000000000..0507e887f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/RemoteRestModel.java @@ -0,0 +1,56 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +/** + * A RemoteRestModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public interface RemoteRestModel extends RemoteModel { + + /** The "remoteRest" name. */ + public static final String REMOTE_REST = "remoteRest"; + + /** + * Gets the url attribute. + * @return the url attribute + */ + public String getUrl(); + + /** + * Sets the url attribute. + * @param url the url attribute + * @return this RemoteRestModel (useful for chaining) + */ + public RemoteRestModel setUrl(String url); + + /** + * Gets the useFormBasedAuth attribute. + * @return the useFormBasedAuth attribute + * @deprecated deprecated as of kie/drools/jbpm 6.2 + */ + @Deprecated + public boolean isUseFormBasedAuth(); + + /** + * Sets the useFormBasedAuth attribute. + * @param useFormBasedAuth the useFormBasedAuth attribute + * @return this RemoteRestModel (useful for chaining) + * @deprecated deprecated as of kie/drools/jbpm 6.2 + */ + @Deprecated + public RemoteRestModel setUseFormBasedAuth(boolean useFormBasedAuth); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/UserGroupCallbackModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/UserGroupCallbackModel.java new file mode 100644 index 000000000..5fab838ce --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/UserGroupCallbackModel.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.Model; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * A UserGroupCallback Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface UserGroupCallbackModel extends Model { + + /** + * The userGroupCallback XML element. + */ + public static final String USER_GROUP_CALLBACK = "userGroupCallback"; + + /** + * Gets the UserGroupCallback class. + * @param loader the ClassLoader to use + * @return the UserGroupCallback class + */ + public Class getClazz(ClassLoader loader); + + /** + * Sets the UserGroupCallback class. + * @param clazz the UserGroupCallback class + * @return this UserGroupCallbackModel (useful for chaining) + */ + public UserGroupCallbackModel setClazz(Class clazz); + + /** + * Gets the child properties model. + * @return the child properties model + */ + public PropertiesModel getProperties(); + + /** + * Sets the child properties model. + * @param properties the child properties model + * @return this UserGroupCallbackModel (useful for chaining) + */ + public UserGroupCallbackModel setProperties(PropertiesModel properties); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/WorkItemHandlerModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/WorkItemHandlerModel.java new file mode 100644 index 000000000..c1b36047c --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/WorkItemHandlerModel.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import org.switchyard.config.model.NamedModel; + +/** + * A WorkItemHandler Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface WorkItemHandlerModel extends NamedModel { + + /** + * The workItemHandler XML element. + */ + public static final String WORK_ITEM_HANDLER = "workItemHandler"; + + /** + * Gets the WorkItemHandler class. + * @param loader the ClassLoader to use + * @return the WorkItemHandler class + */ + public Class getClazz(ClassLoader loader); + + /** + * Sets the WorkItemHandler class. + * @param clazz the WorkItemHandler class + * @return this WorkItemHandlerModel (useful for chaining) + */ + public WorkItemHandlerModel setClazz(Class clazz); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/WorkItemHandlersModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/WorkItemHandlersModel.java new file mode 100644 index 000000000..37dffdc5b --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/WorkItemHandlersModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A WorkItemHandlers Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface WorkItemHandlersModel extends Model { + + /** The "workItemHandlers" name. */ + public static final String WORK_ITEM_HANDLERS = "workItemHandlers"; + + /** + * Gets the child workItemHandler models. + * @return the child workItemHandler models + */ + public List getWorkItemHandlers(); + + /** + * Adds a child workItemHandler model. + * @param workItemHandler the child workItemHandler model + * @return this ChannelsModel (useful for chaining) + */ + public WorkItemHandlersModel addWorkItemHandler(WorkItemHandlerModel workItemHandler); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ChannelModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ChannelModel.java new file mode 100644 index 000000000..db55c307c --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ChannelModel.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.config.model.ChannelModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version ChannelModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1ChannelModel extends BaseNamedModel implements ChannelModel { + + /** + * Creates a new ChannelModel in the specified namespace. + * @param namespace the namespace + */ + public V1ChannelModel(String namespace) { + super(namespace, CHANNEL); + } + + /** + * Creates a new ChannelModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ChannelModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getClazz(ClassLoader loader) { + String c = getModelAttribute("class"); + return c != null ? Classes.forName(c, loader) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public ChannelModel setClazz(Class clazz) { + String c = clazz != null ? clazz.getName() : null; + setModelAttribute("class", c); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getOperation() { + return getModelAttribute("operation"); + } + + /** + * {@inheritDoc} + */ + @Override + public ChannelModel setOperation(String operation) { + setModelAttribute("operation", operation); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getReference() { + return getModelAttribute("reference"); + } + + /** + * {@inheritDoc} + */ + @Override + public ChannelModel setReference(String reference) { + setModelAttribute("reference", reference); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ChannelsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ChannelsModel.java new file mode 100644 index 000000000..f8804a9d2 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ChannelsModel.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.ChannelModel.CHANNEL; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.component.common.knowledge.config.model.ChannelModel; +import org.switchyard.component.common.knowledge.config.model.ChannelsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 ChannelsModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1ChannelsModel extends BaseModel implements ChannelsModel { + + private List _channels = new ArrayList(); + + /** + * Creates a new ChannelsModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1ChannelsModel(String namespace) { + super(new QName(namespace, CHANNELS)); + setModelChildrenOrder(CHANNEL); + } + + /** + * Creates a new ChannelsModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ChannelsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration channel_config : config.getChildren(CHANNEL)) { + ChannelModel channel = (ChannelModel)readModel(channel_config); + if (channel != null) { + _channels.add(channel); + } + } + setModelChildrenOrder(CHANNEL); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getChannels() { + return Collections.unmodifiableList(_channels); + } + + /** + * {@inheritDoc} + */ + @Override + public ChannelsModel addChannel(ChannelModel channel) { + addChildModel(channel); + _channels.add(channel); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ContainerModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ContainerModel.java new file mode 100644 index 000000000..07d719233 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ContainerModel.java @@ -0,0 +1,134 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.ContainerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * AThe 1st version ContainerModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1ContainerModel extends BaseModel implements ContainerModel { + + /** + * Constructs a new V1ContainerModel of the specified namespace. + * @param namespace the namespace + */ + public V1ContainerModel(String namespace) { + super(XMLHelper.createQName(namespace, CONTAINER)); + } + + /** + * Constructs a new V1ContainerModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ContainerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getBaseName() { + return getModelAttribute("baseName"); + } + + /** + * {@inheritDoc} + */ + @Override + public ContainerModel setBaseName(String baseName) { + setModelAttribute("baseName", baseName); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getReleaseId() { + return getModelAttribute("releaseId"); + } + + /** + * {@inheritDoc} + */ + @Override + public ContainerModel setReleaseId(String releaseId) { + setModelAttribute("releaseId", releaseId); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isScan() { + String scan = getModelAttribute("scan"); + return scan != null ? Boolean.parseBoolean(scan) : false; + } + + /** + * {@inheritDoc} + */ + @Override + public ContainerModel setScan(boolean scan) { + setModelAttribute("scan", String.valueOf(scan)); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Long getScanInterval() { + String scanInterval = getModelAttribute("scanInterval"); + return scanInterval != null ? Long.valueOf(scanInterval) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public ContainerModel setScanInterval(Long scanInterval) { + String si = scanInterval != null ? scanInterval.toString() : null; + setModelAttribute("scanInterval", si); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSessionName() { + return getModelAttribute("sessionName"); + } + + /** + * {@inheritDoc} + */ + @Override + public ContainerModel setSessionName(String sessionName) { + setModelAttribute("sessionName", sessionName); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1FaultModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1FaultModel.java new file mode 100644 index 000000000..4f748378f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1FaultModel.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.component.common.knowledge.config.model.FaultModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version FaultModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1FaultModel extends V1MappingModel implements FaultModel { + + /** + * Creates a new FaultModel in the specified namespace and localName. + * @param namespace the specified namespace + */ + public V1FaultModel(String namespace) { + super(namespace, FAULT); + } + + /** + * Creates a new FaultModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1FaultModel(Configuration config, Descriptor desc) { + super(config, desc); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1FaultsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1FaultsModel.java new file mode 100644 index 000000000..6242ec7ef --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1FaultsModel.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.FaultModel.FAULT; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.FaultModel; +import org.switchyard.component.common.knowledge.config.model.FaultsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 FaultsModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1FaultsModel extends BaseModel implements FaultsModel { + + private List _faults = new ArrayList(); + + /** + * Creates a new V1FaultsModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1FaultsModel(String namespace) { + super(XMLHelper.createQName(namespace, FAULTS)); + setModelChildrenOrder(FAULT); + } + + /** + * Creates a new V1FaultsModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1FaultsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration fault_config : config.getChildren(FAULT)) { + FaultModel fault = (FaultModel)readModel(fault_config); + if (fault != null) { + _faults.add(fault); + } + } + setModelChildrenOrder(FAULT); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getFaults() { + return Collections.unmodifiableList(_faults); + } + + /** + * {@inheritDoc} + */ + @Override + public FaultsModel addFault(FaultModel fault) { + addChildModel(fault); + _faults.add(fault); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1GlobalModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1GlobalModel.java new file mode 100644 index 000000000..524b5f7f1 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1GlobalModel.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.component.common.knowledge.config.model.GlobalModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version GlobalModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1GlobalModel extends V1MappingModel implements GlobalModel { + + /** + * Creates a new GlobalModel in the specified namespace and localName. + * @param namespace the specified namespace + */ + public V1GlobalModel(String namespace) { + super(namespace, GLOBAL); + } + + /** + * Creates a new GlobalModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1GlobalModel(Configuration config, Descriptor desc) { + super(config, desc); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1GlobalsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1GlobalsModel.java new file mode 100644 index 000000000..619912c2d --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1GlobalsModel.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.GlobalModel.GLOBAL; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.GlobalModel; +import org.switchyard.component.common.knowledge.config.model.GlobalsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 GlobalsModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1GlobalsModel extends BaseModel implements GlobalsModel { + + private List _globals = new ArrayList(); + + /** + * Creates a new V1GlobalsModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1GlobalsModel(String namespace) { + super(XMLHelper.createQName(namespace, GLOBALS)); + setModelChildrenOrder(GLOBAL); + } + + /** + * Creates a new V1GlobalsModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1GlobalsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration global_config : config.getChildren(GLOBAL)) { + GlobalModel global = (GlobalModel)readModel(global_config); + if (global != null) { + _globals.add(global); + } + } + setModelChildrenOrder(GLOBAL); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getGlobals() { + return Collections.unmodifiableList(_globals); + } + + /** + * {@inheritDoc} + */ + @Override + public GlobalsModel addGlobal(GlobalModel global) { + addChildModel(global); + _globals.add(global); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1InputModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1InputModel.java new file mode 100644 index 000000000..80ff5044f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1InputModel.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.component.common.knowledge.config.model.InputModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version InputModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1InputModel extends V1MappingModel implements InputModel { + + /** + * Creates a new InputModel in the specified namespace and localName. + * @param namespace the specified namespace + */ + public V1InputModel(String namespace) { + super(namespace, INPUT); + } + + /** + * Creates a new InputModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1InputModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getOutput() { + // unsupported until v2 + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public InputModel setOutput(String output) { + // unsupported until v2 + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1InputsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1InputsModel.java new file mode 100644 index 000000000..3125ad6a5 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1InputsModel.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.InputModel.INPUT; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.InputModel; +import org.switchyard.component.common.knowledge.config.model.InputsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 InputsModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1InputsModel extends BaseModel implements InputsModel { + + private List _inputs = new ArrayList(); + + /** + * Creates a new V1InputsModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1InputsModel(String namespace) { + super(XMLHelper.createQName(namespace, INPUTS)); + setModelChildrenOrder(INPUT); + } + + /** + * Creates a new V1InputsModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1InputsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration input_config : config.getChildren(INPUT)) { + InputModel input = (InputModel)readModel(input_config); + if (input != null) { + _inputs.add(input); + } + } + setModelChildrenOrder(INPUT); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getInputs() { + return Collections.unmodifiableList(_inputs); + } + + /** + * {@inheritDoc} + */ + @Override + public InputsModel addInput(InputModel input) { + addChildModel(input); + _inputs.add(input); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1KnowledgeComponentImplementationModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1KnowledgeComponentImplementationModel.java new file mode 100644 index 000000000..60090f563 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1KnowledgeComponentImplementationModel.java @@ -0,0 +1,243 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.ChannelsModel.CHANNELS; +import static org.switchyard.component.common.knowledge.config.model.ListenersModel.LISTENERS; +import static org.switchyard.component.common.knowledge.config.model.LoggersModel.LOGGERS; +import static org.switchyard.component.common.knowledge.config.model.ManifestModel.MANIFEST; +import static org.switchyard.component.common.knowledge.config.model.OperationsModel.OPERATIONS; +import static org.switchyard.component.common.knowledge.config.model.UserGroupCallbackModel.USER_GROUP_CALLBACK; +import static org.switchyard.component.common.knowledge.config.model.WorkItemHandlersModel.WORK_ITEM_HANDLERS; +import static org.switchyard.config.model.property.PropertiesModel.PROPERTIES; + +import org.switchyard.component.common.knowledge.config.model.ChannelsModel; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.ListenersModel; +import org.switchyard.component.common.knowledge.config.model.LoggersModel; +import org.switchyard.component.common.knowledge.config.model.ManifestModel; +import org.switchyard.component.common.knowledge.config.model.OperationsModel; +import org.switchyard.component.common.knowledge.config.model.UserGroupCallbackModel; +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlersModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1ComponentImplementationModel; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * An abstract "knowledge" implementation of a ComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class V1KnowledgeComponentImplementationModel extends V1ComponentImplementationModel implements KnowledgeComponentImplementationModel { + + private ChannelsModel _channels; + private ListenersModel _listeners; + private LoggersModel _loggers; + private ManifestModel _manifest; + private OperationsModel _operations; + private PropertiesModel _properties; + private UserGroupCallbackModel _userGroupCallback; + private WorkItemHandlersModel _workItemHandlers; + + + /** + * Constructs a new V1KnowledgeComponentImplementationModel of the specified "type", and in the specified namespace. + * @param type the "type" of KnowledgeComponentImplementationModel + * @param namespace the namespace + */ + public V1KnowledgeComponentImplementationModel(String type, String namespace) { + super(type, namespace); + setModelChildrenOrder(CHANNELS, LISTENERS, LOGGERS, MANIFEST, OPERATIONS, PROPERTIES, USER_GROUP_CALLBACK, WORK_ITEM_HANDLERS); + } + + /** + * Constructs a new V1KnowledgeComponentImplementationModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1KnowledgeComponentImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(CHANNELS, LISTENERS, LOGGERS, MANIFEST, OPERATIONS, PROPERTIES, USER_GROUP_CALLBACK, WORK_ITEM_HANDLERS); + } + + /** + * {@inheritDoc} + */ + @Override + public ChannelsModel getChannels() { + if (_channels == null) { + _channels = (ChannelsModel)getFirstChildModel(CHANNELS); + } + return _channels; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setChannels(ChannelsModel channels) { + setChildModel(channels); + _channels = channels; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ListenersModel getListeners() { + if (_listeners == null) { + _listeners = (ListenersModel)getFirstChildModel(LISTENERS); + } + return _listeners; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setListeners(ListenersModel listeners) { + setChildModel(listeners); + _listeners = listeners; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public LoggersModel getLoggers() { + if (_loggers == null) { + _loggers = (LoggersModel)getFirstChildModel(LOGGERS); + } + return _loggers; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setLoggers(LoggersModel loggers) { + setChildModel(loggers); + _loggers = loggers; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ManifestModel getManifest() { + if (_manifest == null) { + _manifest = (ManifestModel)getFirstChildModel(MANIFEST); + } + return _manifest; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setManifest(ManifestModel manifest) { + setChildModel(manifest); + _manifest = manifest; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public OperationsModel getOperations() { + if (_operations == null) { + _operations = (OperationsModel)getFirstChildModel(OPERATIONS); + } + return _operations; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setOperations(OperationsModel operations) { + setChildModel(operations); + _operations = operations; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public PropertiesModel getProperties() { + if (_properties == null) { + _properties = (PropertiesModel)getFirstChildModel(PROPERTIES); + } + return _properties; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setProperties(PropertiesModel properties) { + setChildModel(properties); + _properties = properties; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public UserGroupCallbackModel getUserGroupCallback() { + if (_userGroupCallback == null) { + _userGroupCallback = (UserGroupCallbackModel)getFirstChildModel(USER_GROUP_CALLBACK); + } + return _userGroupCallback; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setUserGroupCallback(UserGroupCallbackModel userGroupCallback) { + setChildModel(userGroupCallback); + _userGroupCallback = userGroupCallback; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public WorkItemHandlersModel getWorkItemHandlers() { + if (_workItemHandlers == null) { + _workItemHandlers = (WorkItemHandlersModel)getFirstChildModel(WORK_ITEM_HANDLERS); + } + return _workItemHandlers; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setWorkItemHandlers(WorkItemHandlersModel workItemHandlers) { + setChildModel(workItemHandlers); + _workItemHandlers = workItemHandlers; + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1KnowledgeMarshaller.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1KnowledgeMarshaller.java new file mode 100644 index 000000000..bb6ca8bac --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1KnowledgeMarshaller.java @@ -0,0 +1,133 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.ChannelModel.CHANNEL; +import static org.switchyard.component.common.knowledge.config.model.ChannelsModel.CHANNELS; +import static org.switchyard.component.common.knowledge.config.model.ContainerModel.CONTAINER; +import static org.switchyard.component.common.knowledge.config.model.FaultModel.FAULT; +import static org.switchyard.component.common.knowledge.config.model.FaultsModel.FAULTS; +import static org.switchyard.component.common.knowledge.config.model.GlobalModel.GLOBAL; +import static org.switchyard.component.common.knowledge.config.model.GlobalsModel.GLOBALS; +import static org.switchyard.component.common.knowledge.config.model.InputModel.INPUT; +import static org.switchyard.component.common.knowledge.config.model.InputsModel.INPUTS; +import static org.switchyard.component.common.knowledge.config.model.ListenerModel.LISTENER; +import static org.switchyard.component.common.knowledge.config.model.ListenersModel.LISTENERS; +import static org.switchyard.component.common.knowledge.config.model.LoggerModel.LOGGER; +import static org.switchyard.component.common.knowledge.config.model.LoggersModel.LOGGERS; +import static org.switchyard.component.common.knowledge.config.model.ManifestModel.MANIFEST; +import static org.switchyard.component.common.knowledge.config.model.OperationsModel.OPERATIONS; +import static org.switchyard.component.common.knowledge.config.model.OutputModel.OUTPUT; +import static org.switchyard.component.common.knowledge.config.model.OutputsModel.OUTPUTS; +import static org.switchyard.component.common.knowledge.config.model.UserGroupCallbackModel.USER_GROUP_CALLBACK; +import static org.switchyard.component.common.knowledge.config.model.WorkItemHandlerModel.WORK_ITEM_HANDLER; +import static org.switchyard.component.common.knowledge.config.model.WorkItemHandlersModel.WORK_ITEM_HANDLERS; +import static org.switchyard.config.model.property.PropertiesModel.PROPERTIES; +import static org.switchyard.config.model.property.PropertyModel.PROPERTY; +import static org.switchyard.config.model.resource.ResourceDetailModel.RESOURCE_DETAIL; +import static org.switchyard.config.model.resource.ResourceModel.RESOURCE; +import static org.switchyard.config.model.resource.ResourcesModel.RESOURCES; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.v1.V1CompositeMarshaller; +import org.switchyard.config.model.property.v1.V1PropertiesModel; +import org.switchyard.config.model.property.v1.V1PropertyModel; +import org.switchyard.config.model.resource.v1.V1ResourceDetailModel; +import org.switchyard.config.model.resource.v1.V1ResourceModel; +import org.switchyard.config.model.resource.v1.V1ResourcesModel; + +/** + * A CompositeMarshaller which can also create knowledge models. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1KnowledgeMarshaller extends V1CompositeMarshaller { + + /** + * Required constructor called via reflection. + * + * @param desc the Descriptor + */ + public V1KnowledgeMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1CompositeMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (CHANNELS.equals(name)) { + return new V1ChannelsModel(config, desc); + } else if (CHANNEL.equals(name)) { + return new V1ChannelModel(config, desc); + } else if (LISTENERS.equals(name)) { + return new V1ListenersModel(config, desc); + } else if (LISTENER.equals(name)) { + return new V1ListenerModel(config, desc); + } else if (LOGGERS.equals(name)) { + return new V1LoggersModel(config, desc); + } else if (LOGGER.equals(name)) { + return new V1LoggerModel(config, desc); + } else if (MANIFEST.equals(name)) { + return new V1ManifestModel(config, desc); + } else if (CONTAINER.equals(name)) { + return new V1ContainerModel(config, desc); + } else if (RESOURCES.equals(name)) { + return new V1ResourcesModel(config, desc); + } else if (RESOURCE.equals(name)) { + return new V1ResourceModel(config, desc); + } else if (RESOURCE_DETAIL.equals(name)) { + return new V1ResourceDetailModel(config, desc); + } else if (OPERATIONS.equals(name)) { + return new V1OperationsModel(config, desc); + } else if (GLOBALS.equals(name)) { + return new V1GlobalsModel(config, desc); + } else if (GLOBAL.equals(name)) { + return new V1GlobalModel(config, desc); + } else if (INPUTS.equals(name)) { + return new V1InputsModel(config, desc); + } else if (INPUT.equals(name)) { + return new V1InputModel(config, desc); + } else if (OUTPUTS.equals(name)) { + return new V1OutputsModel(config, desc); + } else if (OUTPUT.equals(name)) { + return new V1OutputModel(config, desc); + } else if (FAULTS.equals(name)) { + return new V1FaultsModel(config, desc); + } else if (FAULT.equals(name)) { + return new V1FaultModel(config, desc); + } else if (PROPERTIES.equals(name)) { + return new V1PropertiesModel(config, desc); + } else if (PROPERTY.equals(name)) { + return new V1PropertyModel(config, desc); + } else if (USER_GROUP_CALLBACK.equals(name)) { + return new V1UserGroupCallbackModel(config, desc); + } else if (WORK_ITEM_HANDLERS.equals(name)) { + return new V1WorkItemHandlersModel(config, desc); + } else if (WORK_ITEM_HANDLER.equals(name)) { + return new V1WorkItemHandlerModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ListenerModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ListenerModel.java new file mode 100644 index 000000000..692147bd1 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ListenerModel.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.common.type.Classes; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.ListenerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version ListenerModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1ListenerModel extends BaseModel implements ListenerModel { + + /** + * Creates a new ListenerModel in the specified namespace. + * @param namespace the namespace + */ + public V1ListenerModel(String namespace) { + super(XMLHelper.createQName(namespace, LISTENER)); + } + + /** + * Creates a new ListenerModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ListenerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getClazz(ClassLoader loader) { + String c = getModelAttribute("class"); + return c != null ? Classes.forName(c, loader) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public ListenerModel setClazz(Class clazz) { + String c = clazz != null ? clazz.getName() : null; + setModelAttribute("class", c); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ListenersModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ListenersModel.java new file mode 100644 index 000000000..67f633a99 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ListenersModel.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.ListenerModel.LISTENER; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.component.common.knowledge.config.model.ListenerModel; +import org.switchyard.component.common.knowledge.config.model.ListenersModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 ListenersModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1ListenersModel extends BaseModel implements ListenersModel { + + private List _listeners = new ArrayList(); + + /** + * Creates a new ListenersModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1ListenersModel(String namespace) { + super(new QName(namespace, LISTENERS)); + setModelChildrenOrder(LISTENER); + } + + /** + * Creates a new ListenersModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ListenersModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration listener_config : config.getChildren(LISTENER)) { + ListenerModel listener = (ListenerModel)readModel(listener_config); + if (listener != null) { + _listeners.add(listener); + } + } + setModelChildrenOrder(LISTENER); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getListeners() { + return Collections.unmodifiableList(_listeners); + } + + /** + * {@inheritDoc} + */ + @Override + public ListenersModel addListener(ListenerModel listener) { + addChildModel(listener); + _listeners.add(listener); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1LoggerModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1LoggerModel.java new file mode 100644 index 000000000..3627253a5 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1LoggerModel.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.component.common.knowledge.LoggerType; +import org.switchyard.component.common.knowledge.config.model.LoggerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version ChannelModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1LoggerModel extends BaseNamedModel implements LoggerModel { + + /** + * Creates a new MappingModel in the specified namespace. + * @param namespace the namespace + */ + public V1LoggerModel(String namespace) { + super(namespace, LOGGER); + } + + /** + * Creates a new MappingModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1LoggerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Integer getInterval() { + String i = getModelAttribute("interval"); + return i != null ? Integer.valueOf(i) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public LoggerModel setInterval(Integer interval) { + String i = interval != null ? interval.toString() : null; + setModelAttribute("interval", i); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getLog() { + return getModelAttribute("log"); + } + + /** + * {@inheritDoc} + */ + @Override + public LoggerModel setLog(String log) { + setModelAttribute("log", log); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public LoggerType getType() { + String t = getModelAttribute("type"); + return t != null ? LoggerType.valueOf(t) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public LoggerModel setType(LoggerType type) { + String t = type != null ? type.name() : null; + setModelAttribute("type", t); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1LoggersModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1LoggersModel.java new file mode 100644 index 000000000..1f73b22ca --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1LoggersModel.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.LoggerModel.LOGGER; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.component.common.knowledge.config.model.LoggerModel; +import org.switchyard.component.common.knowledge.config.model.LoggersModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 LoggersModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1LoggersModel extends BaseModel implements LoggersModel { + + private List _loggers = new ArrayList(); + + /** + * Creates a new LoggersModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1LoggersModel(String namespace) { + super(new QName(namespace, LOGGERS)); + setModelChildrenOrder(LOGGER); + } + + /** + * Creates a new LoggersModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1LoggersModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration logger_config : config.getChildren(LOGGER)) { + LoggerModel logger = (LoggerModel)readModel(logger_config); + if (logger != null) { + _loggers.add(logger); + } + } + setModelChildrenOrder(LOGGER); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getLoggers() { + return Collections.unmodifiableList(_loggers); + } + + /** + * {@inheritDoc} + */ + @Override + public LoggersModel addLogger(LoggerModel logger) { + addChildModel(logger); + _loggers.add(logger); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ManifestModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ManifestModel.java new file mode 100644 index 000000000..fa6f7bc07 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1ManifestModel.java @@ -0,0 +1,115 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.ContainerModel.CONTAINER; +import static org.switchyard.config.model.resource.ResourcesModel.RESOURCES; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.ContainerModel; +import org.switchyard.component.common.knowledge.config.model.ManifestModel; +import org.switchyard.component.common.knowledge.config.model.RemoteModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.resource.ResourcesModel; + +/** + * The 1st version ManifestModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1ManifestModel extends BaseModel implements ManifestModel { + + private ContainerModel _container; + private ResourcesModel _resources; + + /** + * Constructs a new V1ManifestModel of the specified namespace. + * @param namespace the namespace + */ + public V1ManifestModel(String namespace) { + super(XMLHelper.createQName(namespace, MANIFEST)); + setModelChildrenOrder(CONTAINER, RESOURCES); + } + + /** + * Constructs a new V1ManifestModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ManifestModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(CONTAINER, RESOURCES); + } + + /** + * {@inheritDoc} + */ + @Override + public ContainerModel getContainer() { + if (_container == null) { + _container = (ContainerModel)getFirstChildModel(CONTAINER); + } + return _container; + } + + /** + * {@inheritDoc} + */ + @Override + public ManifestModel setContainer(ContainerModel container) { + setChildModel(container); + _container = container; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ResourcesModel getResources() { + if (_resources == null) { + _resources = (ResourcesModel)getFirstChildModel(RESOURCES); + } + return _resources; + } + + /** + * {@inheritDoc} + */ + @Override + public ManifestModel setResources(ResourcesModel resources) { + setChildModel(resources); + _resources = resources; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel getRemote() { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public ManifestModel setRemote(RemoteModel remote) { + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1MappingModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1MappingModel.java new file mode 100644 index 000000000..76f631f7c --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1MappingModel.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.MappingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version MappingModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class V1MappingModel extends BaseModel implements MappingModel { + + /** + * Creates a new V1MappingModel in the specified namespace and localName. + * @param namespace the specified namespace + * @param localName the specified localName + */ + public V1MappingModel(String namespace, String localName) { + super(XMLHelper.createQName(namespace, localName)); + } + + /** + * Creates a new V1MappingModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1MappingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getFrom() { + return getModelAttribute("from"); + } + + /** + * {@inheritDoc} + */ + @Override + public MappingModel setFrom(String from) { + setModelAttribute("from", from); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTo() { + return getModelAttribute("to"); + } + + /** + * {@inheritDoc} + */ + @Override + public MappingModel setTo(String to) { + setModelAttribute("to", to); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OperationModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OperationModel.java new file mode 100644 index 000000000..0e29f6083 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OperationModel.java @@ -0,0 +1,172 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.FaultsModel.FAULTS; +import static org.switchyard.component.common.knowledge.config.model.GlobalsModel.GLOBALS; +import static org.switchyard.component.common.knowledge.config.model.InputsModel.INPUTS; +import static org.switchyard.component.common.knowledge.config.model.OutputsModel.OUTPUTS; + +import org.switchyard.component.common.knowledge.config.model.FaultsModel; +import org.switchyard.component.common.knowledge.config.model.GlobalsModel; +import org.switchyard.component.common.knowledge.config.model.InputsModel; +import org.switchyard.component.common.knowledge.config.model.OperationModel; +import org.switchyard.component.common.knowledge.config.model.OutputsModel; +import org.switchyard.component.common.knowledge.operation.KnowledgeOperationType; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version OperationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class V1OperationModel extends BaseNamedModel implements OperationModel { + + private GlobalsModel _globals; + private InputsModel _inputs; + private OutputsModel _outputs; + private FaultsModel _faults; + + /** + * Creates a new V1OperationModel in the specified namespace. + * @param namespace the namespace + */ + public V1OperationModel(String namespace) { + super(namespace, OPERATION); + setModelChildrenOrder(GLOBALS, INPUTS, OUTPUTS, FAULTS); + } + + /** + * Creates a new V1OperationModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1OperationModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(GLOBALS, INPUTS, OUTPUTS, FAULTS); + } + + /** + * {@inheritDoc} + */ + @Override + public String getEventId() { + return getModelAttribute("eventId"); + } + + /** + * {@inheritDoc} + */ + @Override + public OperationModel setEventId(String eventId) { + setModelAttribute("eventId", eventId); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public OperationModel setType(KnowledgeOperationType type) { + setModelAttribute("type", type != null ? type.name() : null); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public GlobalsModel getGlobals() { + if (_globals == null) { + _globals = (GlobalsModel)getFirstChildModel(GLOBALS); + } + return _globals; + } + + /** + * {@inheritDoc} + */ + @Override + public OperationModel setGlobals(GlobalsModel globals) { + setChildModel(globals); + _globals = globals; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public InputsModel getInputs() { + if (_inputs == null) { + _inputs = (InputsModel)getFirstChildModel(INPUTS); + } + return _inputs; + } + + /** + * {@inheritDoc} + */ + @Override + public OperationModel setInputs(InputsModel inputs) { + setChildModel(inputs); + _inputs = inputs; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public OutputsModel getOutputs() { + if (_outputs == null) { + _outputs = (OutputsModel)getFirstChildModel(OUTPUTS); + } + return _outputs; + } + + /** + * {@inheritDoc} + */ + @Override + public OperationModel setOutputs(OutputsModel outputs) { + setChildModel(outputs); + _outputs = outputs; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public FaultsModel getFaults() { + if (_faults == null) { + _faults = (FaultsModel)getFirstChildModel(FAULTS); + } + return _faults; + } + + /** + * {@inheritDoc} + */ + @Override + public OperationModel setFaults(FaultsModel faults) { + setChildModel(faults); + _faults = faults; + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OperationsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OperationsModel.java new file mode 100644 index 000000000..470571f92 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OperationsModel.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.OperationModel.OPERATION; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.component.common.knowledge.config.model.OperationModel; +import org.switchyard.component.common.knowledge.config.model.OperationsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 OperationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1OperationsModel extends BaseModel implements OperationsModel { + + private List _operations = new ArrayList(); + + /** + * Creates a new V1OperationsModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1OperationsModel(String namespace) { + super(new QName(namespace, OPERATIONS)); + setModelChildrenOrder(OPERATION); + } + + /** + * Creates a new V1OperationsModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1OperationsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration operation_config : config.getChildren(OPERATION)) { + OperationModel operation = (OperationModel)readModel(operation_config); + if (operation != null) { + _operations.add(operation); + } + } + setModelChildrenOrder(OPERATION); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getOperations() { + return Collections.unmodifiableList(_operations); + } + + /** + * {@inheritDoc} + */ + @Override + public OperationsModel addOperation(OperationModel operation) { + addChildModel(operation); + _operations.add(operation); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OutputModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OutputModel.java new file mode 100644 index 000000000..cd0f8643f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OutputModel.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.component.common.knowledge.config.model.OutputModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version OutputModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1OutputModel extends V1MappingModel implements OutputModel { + + /** + * Creates a new OutputModel in the specified namespace and localName. + * @param namespace the specified namespace + */ + public V1OutputModel(String namespace) { + super(namespace, OUTPUT); + } + + /** + * Creates a new OutputModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1OutputModel(Configuration config, Descriptor desc) { + super(config, desc); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OutputsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OutputsModel.java new file mode 100644 index 000000000..ef13f9031 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1OutputsModel.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.OutputModel.OUTPUT; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.OutputModel; +import org.switchyard.component.common.knowledge.config.model.OutputsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 OutputsModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1OutputsModel extends BaseModel implements OutputsModel { + + private List _outputs = new ArrayList(); + + /** + * Creates a new V1OutputsModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1OutputsModel(String namespace) { + super(XMLHelper.createQName(namespace, OUTPUTS)); + setModelChildrenOrder(OUTPUT); + } + + /** + * Creates a new V1OutputsModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1OutputsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration output_config : config.getChildren(OUTPUT)) { + OutputModel output = (OutputModel)readModel(output_config); + if (output != null) { + _outputs.add(output); + } + } + setModelChildrenOrder(OUTPUT); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getOutputs() { + return Collections.unmodifiableList(_outputs); + } + + /** + * {@inheritDoc} + */ + @Override + public OutputsModel addOutput(OutputModel output) { + addChildModel(output); + _outputs.add(output); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1UserGroupCallbackModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1UserGroupCallbackModel.java new file mode 100644 index 000000000..c930278c8 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1UserGroupCallbackModel.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.config.model.property.PropertiesModel.PROPERTIES; + +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.config.model.UserGroupCallbackModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * The 1st version UserGroupCallbackModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1UserGroupCallbackModel extends BaseModel implements UserGroupCallbackModel { + + private PropertiesModel _properties; + + /** + * Creates a new UserGroupCallbackModel. + * @param namespace namespace + */ + public V1UserGroupCallbackModel(String namespace) { + super(namespace, USER_GROUP_CALLBACK); + setModelChildrenOrder(PROPERTIES); + } + + /** + * Creates a new UserGroupCallbackModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1UserGroupCallbackModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(PROPERTIES); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getClazz(ClassLoader loader) { + String c = getModelAttribute("class"); + return c != null ? Classes.forName(c, loader) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public UserGroupCallbackModel setClazz(Class clazz) { + String c = clazz != null ? clazz.getName() : null; + setModelAttribute("class", c); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public PropertiesModel getProperties() { + if (_properties == null) { + _properties = (PropertiesModel)getFirstChildModel(PROPERTIES); + } + return _properties; + } + + /** + * {@inheritDoc} + */ + @Override + public UserGroupCallbackModel setProperties(PropertiesModel properties) { + setChildModel(properties); + _properties = properties; + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1WorkItemHandlerModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1WorkItemHandlerModel.java new file mode 100644 index 000000000..e6f881eb1 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1WorkItemHandlerModel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version WorkItemHandlerModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1WorkItemHandlerModel extends BaseNamedModel implements WorkItemHandlerModel { + + /** + * Creates a new WorkItemHandlerModel. + * @param namespace namespace + */ + public V1WorkItemHandlerModel(String namespace) { + super(namespace, WORK_ITEM_HANDLER); + } + + /** + * Creates a new WorkItemHandlerModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1WorkItemHandlerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getClazz(ClassLoader loader) { + String c = getModelAttribute("class"); + return c != null ? Classes.forName(c, loader) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public WorkItemHandlerModel setClazz(Class clazz) { + String c = clazz != null ? clazz.getName() : null; + setModelAttribute("class", c); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1WorkItemHandlersModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1WorkItemHandlersModel.java new file mode 100644 index 000000000..60dbd3b93 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v1/V1WorkItemHandlersModel.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.WorkItemHandlerModel.WORK_ITEM_HANDLER; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlerModel; +import org.switchyard.component.common.knowledge.config.model.WorkItemHandlersModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 WorkItemHandlersModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1WorkItemHandlersModel extends BaseModel implements WorkItemHandlersModel { + + private List _workItemHandlers = new ArrayList(); + + /** + * Creates a new WorkItemHandlersModel. + * @param namespace namespace + */ + public V1WorkItemHandlersModel(String namespace) { + super(namespace, WORK_ITEM_HANDLERS); + setModelChildrenOrder(WORK_ITEM_HANDLER); + } + + /** + * Creates a new WorkItemHandlersModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1WorkItemHandlersModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration workItemHandler_config : config.getChildren(WORK_ITEM_HANDLER)) { + WorkItemHandlerModel workItemHandler = (WorkItemHandlerModel)readModel(workItemHandler_config); + if (workItemHandler != null) { + _workItemHandlers.add(workItemHandler); + } + } + setModelChildrenOrder(WORK_ITEM_HANDLER); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getWorkItemHandlers() { + return Collections.unmodifiableList(_workItemHandlers); + } + + /** + * {@inheritDoc} + */ + @Override + public WorkItemHandlersModel addWorkItemHandler(WorkItemHandlerModel workItemHandler) { + addChildModel(workItemHandler); + _workItemHandlers.add(workItemHandler); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ExtraJaxbClassModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ExtraJaxbClassModel.java new file mode 100644 index 000000000..fc64efe60 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ExtraJaxbClassModel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v2; + +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 2nd version ExtraJaxbClassModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2ExtraJaxbClassModel extends BaseModel implements ExtraJaxbClassModel { + + /** + * Creates a new ExtraJaxbClassModel in the specified namespace. + * @param namespace the namespace + */ + public V2ExtraJaxbClassModel(String namespace) { + super(namespace, EXTRA_JAXB_CLASS); + } + + /** + * Creates a new ExtraJaxbClassModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V2ExtraJaxbClassModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getClazz(ClassLoader loader) { + String c = getModelValue(); + return c != null ? Classes.forName(c, loader) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public ExtraJaxbClassModel setClazz(Class clazz) { + String c = clazz != null ? clazz.getName() : null; + setModelValue(c); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ExtraJaxbClassesModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ExtraJaxbClassesModel.java new file mode 100644 index 000000000..75087c180 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ExtraJaxbClassesModel.java @@ -0,0 +1,82 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v2; + +import static org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel.EXTRA_JAXB_CLASS; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 2 ExtraJaxbClassesModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2ExtraJaxbClassesModel extends BaseModel implements ExtraJaxbClassesModel { + + private List _extraJaxbClasses = new ArrayList(); + + /** + * Creates a new ExtraJaxbClassesModel in the specified namespace. + * @param namespace the specified namespace + */ + public V2ExtraJaxbClassesModel(String namespace) { + super(new QName(namespace, EXTRA_JAXB_CLASSES)); + setModelChildrenOrder(EXTRA_JAXB_CLASS); + } + + /** + * Creates a new ExtraJaxbClassesModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V2ExtraJaxbClassesModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration extraJaxbClass_config : config.getChildren(EXTRA_JAXB_CLASS)) { + ExtraJaxbClassModel extraJaxbClass = (ExtraJaxbClassModel)readModel(extraJaxbClass_config); + if (extraJaxbClass != null) { + _extraJaxbClasses.add(extraJaxbClass); + } + } + setModelChildrenOrder(EXTRA_JAXB_CLASS); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getExtraJaxbClasses() { + return Collections.unmodifiableList(_extraJaxbClasses); + } + + /** + * {@inheritDoc} + */ + @Override + public ExtraJaxbClassesModel addExtraJaxbClass(ExtraJaxbClassModel extraJaxbClass) { + addChildModel(extraJaxbClass); + _extraJaxbClasses.add(extraJaxbClass); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2InputModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2InputModel.java new file mode 100644 index 000000000..f0e9e51c3 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2InputModel.java @@ -0,0 +1,62 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v2; + +import org.switchyard.component.common.knowledge.config.model.InputModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1InputModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 2nd version InputModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2InputModel extends V1InputModel { + + /** + * Creates a new InputModel in the specified namespace and localName. + * @param namespace the specified namespace + */ + public V2InputModel(String namespace) { + super(namespace); + } + + /** + * Creates a new InputModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V2InputModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getOutput() { + return getModelAttribute("output"); + } + + /** + * {@inheritDoc} + */ + @Override + public InputModel setOutput(String output) { + setModelAttribute("output", output); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2KnowledgeMarshaller.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2KnowledgeMarshaller.java new file mode 100644 index 000000000..b7712ad59 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2KnowledgeMarshaller.java @@ -0,0 +1,75 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v2; + +import static org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel.EXTRA_JAXB_CLASS; +import static org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel.EXTRA_JAXB_CLASSES; +import static org.switchyard.component.common.knowledge.config.model.InputModel.INPUT; +import static org.switchyard.component.common.knowledge.config.model.ManifestModel.MANIFEST; +import static org.switchyard.component.common.knowledge.config.model.RemoteJmsModel.REMOTE_JMS; +import static org.switchyard.component.common.knowledge.config.model.RemoteRestModel.REMOTE_REST; +import static org.switchyard.config.model.property.PropertiesModel.PROPERTIES; + +import org.switchyard.component.common.knowledge.config.model.v1.V1KnowledgeMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.property.v2.V2PropertiesModel; + +/** + * A CompositeMarshaller which can also create knowledge models. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2KnowledgeMarshaller extends V1KnowledgeMarshaller { + + /** + * Required constructor called via reflection. + * + * @param desc the Descriptor + */ + public V2KnowledgeMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1KnowledgeMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (MANIFEST.equals(name)) { + return new V2ManifestModel(config, desc); + } else if (REMOTE_JMS.equals(name)) { + return new V2RemoteJmsModel(config, desc); + } else if (REMOTE_REST.equals(name)) { + return new V2RemoteRestModel(config, desc); + } else if (EXTRA_JAXB_CLASSES.equals(name)) { + return new V2ExtraJaxbClassesModel(config, desc); + } else if (EXTRA_JAXB_CLASS.equals(name)) { + return new V2ExtraJaxbClassModel(config, desc); + } else if (INPUT.equals(name)) { + return new V2InputModel(config, desc); + } else if (PROPERTIES.equals(name)) { + return new V2PropertiesModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ManifestModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ManifestModel.java new file mode 100644 index 000000000..f27abfca8 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2ManifestModel.java @@ -0,0 +1,92 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v2; + +import static org.switchyard.component.common.knowledge.config.model.RemoteJmsModel.REMOTE_JMS; +import static org.switchyard.component.common.knowledge.config.model.RemoteRestModel.REMOTE_REST; + +import javax.xml.namespace.QName; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.ManifestModel; +import org.switchyard.component.common.knowledge.config.model.RemoteModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1ManifestModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 2nd version ManifestModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2ManifestModel extends V1ManifestModel { + + private QName _jmsRemoteQName; + private QName _restRemoteQName; + private RemoteModel _remote; + + /** + * Constructs a new V2ManifestModel of the specified namespace. + * @param namespace the namespace + */ + public V2ManifestModel(String namespace) { + super(namespace); + init(); + } + + /** + * Constructs a new V2ManifestModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V2ManifestModel(Configuration config, Descriptor desc) { + super(config, desc); + init(); + } + + private void init() { + setModelChildrenOrder(REMOTE_JMS, REMOTE_REST); // this appends to CONTAINER, RESOURCES + QName qname = getModelConfiguration().getQName(); + _jmsRemoteQName = XMLHelper.createQName(qname.getNamespaceURI(), REMOTE_JMS, qname.getPrefix()); + _restRemoteQName = XMLHelper.createQName(qname.getNamespaceURI(), REMOTE_REST, qname.getPrefix()); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel getRemote() { + if (_remote == null) { + _remote = (RemoteModel)getFirstChildModel(REMOTE_JMS); + if (_remote == null) { + _remote = (RemoteModel)getFirstChildModel(REMOTE_REST); + } + } + return _remote; + } + + /** + * {@inheritDoc} + */ + @Override + public ManifestModel setRemote(RemoteModel remote) { + Configuration config = getModelConfiguration(); + config.removeChildren(_jmsRemoteQName); + config.removeChildren(_restRemoteQName); + setChildModel(remote); + _remote = remote; + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteJmsModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteJmsModel.java new file mode 100644 index 000000000..2864c8f1e --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteJmsModel.java @@ -0,0 +1,187 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v2; + +import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel; +import org.switchyard.component.common.knowledge.config.model.RemoteModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 2nd version RemoteJmsModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2RemoteJmsModel extends V2RemoteModel implements RemoteJmsModel { + + /** + * Constructs a new V2JmsRemoteModel of the specified namespace. + * @param namespace the namespace + */ + public V2RemoteJmsModel(String namespace) { + super(namespace, REMOTE_JMS); + } + + /** + * Constructs a new V2RemoteJmsModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V2RemoteJmsModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getHostName() { + return getModelAttribute("hostName"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteJmsModel setHostName(String hostName) { + setModelAttribute("hostName", hostName); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Integer getRemotingPort() { + String rp = getModelAttribute("remotingPort"); + return rp != null ? Integer.valueOf(rp) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel setRemotingPort(Integer remotingPort) { + String rp = remotingPort != null ? remotingPort.toString() : null; + setModelAttribute("remotingPort", rp); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Integer getMessagingPort() { + String mp = getModelAttribute("messagingPort"); + return mp != null ? Integer.valueOf(mp) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel setMessagingPort(Integer messagingPort) { + String mp = messagingPort != null ? messagingPort.toString() : null; + setModelAttribute("messagingPort", mp); + return this; + } + + + /** + * {@inheritDoc} + */ + @Override + public boolean isUseSsl() { + String useSsl = getModelAttribute("useSsl"); + return useSsl != null ? Boolean.parseBoolean(useSsl) : false; + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteJmsModel setUseSsl(boolean useSsl) { + setModelAttribute("useSsl", String.valueOf(useSsl)); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getKeystorePassword() { + return getModelAttribute("keystorePassword"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteJmsModel setKeystorePassword(String keystorePassword) { + setModelAttribute("keystorePassword", keystorePassword); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getKeystoreLocation() { + return getModelAttribute("keystoreLocation"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteJmsModel setKeystoreLocation(String keystoreLocation) { + setModelAttribute("keystoreLocation", keystoreLocation); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTruststorePassword() { + return getModelAttribute("truststorePassword"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteJmsModel setTruststorePassword(String truststorePassword) { + setModelAttribute("truststorePassword", truststorePassword); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTruststoreLocation() { + return getModelAttribute("truststoreLocation"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteJmsModel setTruststoreLocation(String truststoreLocation) { + setModelAttribute("truststoreLocation", truststoreLocation); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteModel.java new file mode 100644 index 000000000..c1e07ac3a --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteModel.java @@ -0,0 +1,143 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v2; + +import static org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel.EXTRA_JAXB_CLASSES; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel; +import org.switchyard.component.common.knowledge.config.model.RemoteModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 2nd version RemoteModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public abstract class V2RemoteModel extends BaseModel implements RemoteModel { + + private ExtraJaxbClassesModel _extraJaxbClasses = null; + + /** + * Constructs a new V2RemoteModel of the specified namespace and name. + * @param namespace the namespace + * @param name the name + */ + public V2RemoteModel(String namespace, String name) { + super(XMLHelper.createQName(namespace, name)); + } + + /** + * Constructs a new V2RemoteJmsModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V2RemoteModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getDeploymentId() { + return getModelAttribute("deploymentId"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel setDeploymentId(String deploymentId) { + setModelAttribute("deploymentId", deploymentId); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getUserName() { + return getModelAttribute("userName"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel setUserName(String userName) { + setModelAttribute("userName", userName); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPassword() { + return getModelAttribute("password"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel setPassword(String password) { + setModelAttribute("password", password); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Integer getTimeout() { + String timeout = getModelAttribute("timeout"); + return timeout != null ? Integer.valueOf(timeout) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel setTimeout(Integer timeout) { + String t = timeout != null ? timeout.toString() : null; + setModelAttribute("timeout", t); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ExtraJaxbClassesModel getExtraJaxbClasses() { + if (_extraJaxbClasses == null) { + _extraJaxbClasses = (ExtraJaxbClassesModel)getFirstChildModel(EXTRA_JAXB_CLASSES); + } + return _extraJaxbClasses; + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteModel setExtraJaxbClasses(ExtraJaxbClassesModel extraJaxbClasses) { + setChildModel(extraJaxbClasses); + _extraJaxbClasses = extraJaxbClasses; + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteRestModel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteRestModel.java new file mode 100644 index 000000000..fa3c195b1 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/config/model/v2/V2RemoteRestModel.java @@ -0,0 +1,79 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.config.model.v2; + +import org.switchyard.component.common.knowledge.config.model.RemoteRestModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 2nd version RemoteRestModel. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2RemoteRestModel extends V2RemoteModel implements RemoteRestModel { + + /** + * Constructs a new V2RemoteRestModel of the specified namespace. + * @param namespace the namespace + */ + public V2RemoteRestModel(String namespace) { + super(namespace, REMOTE_REST); + } + + /** + * Constructs a new V2RemoteRestModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V2RemoteRestModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getUrl() { + return getModelAttribute("url"); + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteRestModel setUrl(String url) { + setModelAttribute("url", url); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isUseFormBasedAuth() { + String useFormBasedAuth = getModelAttribute("useFormBasedAuth"); + return useFormBasedAuth != null ? Boolean.parseBoolean(useFormBasedAuth) : false; + } + + /** + * {@inheritDoc} + */ + @Override + public RemoteRestModel setUseFormBasedAuth(boolean useFormBasedAuth) { + setModelAttribute("useFormBasedAuth", String.valueOf(useFormBasedAuth)); + return this; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/deploy/OSGiKnowledgeBundleActivator.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/deploy/OSGiKnowledgeBundleActivator.java new file mode 100644 index 000000000..b38ba3417 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/deploy/OSGiKnowledgeBundleActivator.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.deploy; + +import java.util.Hashtable; +import java.util.concurrent.Callable; + +import org.jbpm.persistence.correlation.JPACorrelationKeyFactory; +import org.kie.internal.process.CorrelationKeyFactory; +import org.kie.internal.utils.ServiceRegistryImpl; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +/** + * Bundle activator for Knowledge component. We need to register some KIE services in OSGi environments. + */ +public class OSGiKnowledgeBundleActivator implements BundleActivator { + + private ServiceRegistration _correlationKeyFactoryService; + + @Override + public void start(final BundleContext context) throws Exception { + _correlationKeyFactoryService = context.registerService(CorrelationKeyFactory.class, + new JPACorrelationKeyFactory(), new Hashtable()); + ServiceRegistryImpl.getInstance().registerLocator(CorrelationKeyFactory.class, new Callable() { + @Override + public CorrelationKeyFactory call() throws Exception { + return context.getService(_correlationKeyFactoryService.getReference()); + } + }); + } + + @Override + public void stop(BundleContext context) throws Exception { + ServiceRegistryImpl.getInstance().unregisterLocator(CorrelationKeyFactory.class); + _correlationKeyFactoryService.unregister(); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/event/EventPublisherProcessEventListener.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/event/EventPublisherProcessEventListener.java new file mode 100644 index 000000000..e051c0d54 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/event/EventPublisherProcessEventListener.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.event; + +import java.util.EventObject; + +import org.kie.api.event.process.ProcessCompletedEvent; +import org.kie.api.event.process.ProcessEvent; +import org.kie.api.event.process.ProcessEventListener; +import org.kie.api.event.process.ProcessNodeLeftEvent; +import org.kie.api.event.process.ProcessNodeTriggeredEvent; +import org.kie.api.event.process.ProcessStartedEvent; +import org.kie.api.event.process.ProcessVariableChangedEvent; +import org.switchyard.event.EventPublisher; + +/** + * This process event listener routes select events to the switchyard service domain's event publisher. + */ +public class EventPublisherProcessEventListener implements ProcessEventListener { + + private final EventPublisher _eventPublisher; + + /** + * Constructs a BPMProcessEventListener with an EventPublisher. + * @param eventPublisher the EventPublisher + */ + public EventPublisherProcessEventListener(EventPublisher eventPublisher) { + _eventPublisher = eventPublisher; + } + + /** + * {@inheritDoc} + */ + @Override + public void beforeProcessStarted(ProcessStartedEvent event) { + publish(event); + } + + /** + * {@inheritDoc} + */ + @Override + public void afterProcessStarted(ProcessStartedEvent event) { + } + + /** + * {@inheritDoc} + */ + @Override + public void beforeProcessCompleted(ProcessCompletedEvent event) { + } + + /** + * {@inheritDoc} + */ + @Override + public void afterProcessCompleted(ProcessCompletedEvent event) { + publish(event); + } + + /** + * {@inheritDoc} + */ + @Override + public void beforeNodeTriggered(ProcessNodeTriggeredEvent event) { + } + + /** + * {@inheritDoc} + */ + @Override + public void afterNodeTriggered(ProcessNodeTriggeredEvent event) { + } + + /** + * {@inheritDoc} + */ + @Override + public void beforeNodeLeft(ProcessNodeLeftEvent event) { + } + + /** + * {@inheritDoc} + */ + @Override + public void afterNodeLeft(ProcessNodeLeftEvent event) { + } + + /** + * {@inheritDoc} + */ + @Override + public void beforeVariableChanged(ProcessVariableChangedEvent event) { + } + + /** + * {@inheritDoc} + */ + @Override + public void afterVariableChanged(ProcessVariableChangedEvent event) { + publish(event); + } + + private void publish(ProcessEvent event) { + if (event instanceof EventObject) { + _eventPublisher.publish((EventObject)event); + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/exchange/KnowledgeExchangeHandler.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/exchange/KnowledgeExchangeHandler.java new file mode 100644 index 000000000..12d5d68e6 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/exchange/KnowledgeExchangeHandler.java @@ -0,0 +1,299 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.exchange; + +import static org.switchyard.component.common.knowledge.KnowledgeConstants.DEFAULT; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.kie.api.runtime.Globals; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.common.io.resource.ResourceType; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.operation.KnowledgeOperation; +import org.switchyard.component.common.knowledge.operation.KnowledgeOperations; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeEngine; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManager; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerFactory; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerType; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.deploy.ServiceHandler; +import org.switchyard.metadata.ExchangeContract; +import org.switchyard.metadata.ServiceOperation; + +/** + * An abstract "knowledge" implementation of an ExchangeHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class KnowledgeExchangeHandler extends BaseServiceHandler implements ServiceHandler { + + private final KnowledgeComponentImplementationModel _model; + private final ServiceDomain _serviceDomain; + private final QName _serviceName; + private final Map _operations = new HashMap(); + private ClassLoader _loader; + private KnowledgeRuntimeManagerFactory _runtimeManagerFactory; + + /** + * Constructs a new KnowledgeExchangeHandler with the specified model, service domain, and service name. + * @param model the specified model + * @param serviceDomain the specified service domain + * @param serviceName the specified service name + */ + public KnowledgeExchangeHandler(KnowledgeComponentImplementationModel model, ServiceDomain serviceDomain, QName serviceName) { + super(serviceDomain); + _model = model; + _serviceDomain = serviceDomain; + _serviceName = serviceName; + } + + /** + * Gets the service domain. + * @return the service domain + */ + public ServiceDomain getServiceDomain() { + return _serviceDomain; + } + + /** + * Gets the service name. + * @return the service name + */ + public QName getServiceName() { + return _serviceName; + } + + /** + * Gets the class loader. + * @return the class loader + */ + protected ClassLoader getLoader() { + return _loader; + } + + /** + * {@inheritDoc} + */ + @Override + protected void doStart() { + _loader = Classes.getClassLoader(getDeploymentClassLoader(), getClass().getClassLoader()); + ResourceType.install(_loader); + KnowledgeOperations.registerOperations(_model, _operations, getDefaultOperation()); + _runtimeManagerFactory = new KnowledgeRuntimeManagerFactory(_loader, _serviceDomain, _serviceName, _model); + } + + /** + * Creates a new Singleton KnowledgeRuntimeManager. + * @return the Singleton KnowledgeRuntimeManager + */ + protected KnowledgeRuntimeManager newSingletonRuntimeManager() { + return _runtimeManagerFactory.newRuntimeManager(KnowledgeRuntimeManagerType.SINGLETON); + } + + /** + * Creates a new PerRequest KnowledgeRuntimeManager. + * @return the PerRequest KnowledgeRuntimeManager + */ + protected KnowledgeRuntimeManager newPerRequestRuntimeManager() { + return _runtimeManagerFactory.newRuntimeManager(KnowledgeRuntimeManagerType.PER_REQUEST); + } + + /** + * Creates a new PerProcessInstance KnowledgeRuntimeManager. + * @return the PerProcessInstance KnowledgeRuntimeManager + */ + protected KnowledgeRuntimeManager newPerProcessInstanceRuntimeManager() { + return _runtimeManagerFactory.newRuntimeManager(KnowledgeRuntimeManagerType.PER_PROCESS_INSTANCE); + } + + /** + * {@inheritDoc} + */ + @Override + protected void doStop() { + _loader = null; + _operations.clear(); + } + + /** + * Gets the default knowledge operation. + * @return the default knowledge operation + */ + public abstract KnowledgeOperation getDefaultOperation(); + + private KnowledgeOperation getOperation(ServiceOperation serviceOperation) { + if (serviceOperation != null) { + String operationName = Strings.trimToNull(serviceOperation.getName()); + if (operationName != null) { + return _operations.get(operationName); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public final void handleMessage(Exchange exchange) throws HandlerException { + if (ExchangePhase.IN.equals(exchange.getPhase())) { + ExchangeContract contract = exchange.getContract(); + KnowledgeOperation operation = getOperation(contract.getProviderOperation()); + if (operation == null) { + operation = getOperation(contract.getConsumerOperation()); + } + if (operation == null) { + // we use "default" here instead of getDefaultOperation() so that a + // user can define a name="default" in their switchyard.xml + operation = _operations.get(DEFAULT); + } + handleOperation(exchange, operation); + } + } + + /** + * Handles a knowledge operation. + * @param exchange the exchange + * @param operation the operation + * @throws HandlerException oops + */ + public abstract void handleOperation(Exchange exchange, KnowledgeOperation operation) throws HandlerException; + + /** + * Gets a primitive boolean context property. + * @param exchange the exchange + * @param message the message + * @param name the name + * @return the property + */ + protected boolean isBoolean(Exchange exchange, Message message, String name) { + Boolean b = getBoolean(exchange, message, name); + return b != null && b.booleanValue(); + } + + /** + * Gets a Boolean context property. + * @param exchange the exchange + * @param message the message + * @param name the name + * @return the property + */ + protected Boolean getBoolean(Exchange exchange, Message message, String name) { + Object value = getObject(exchange, message, name); + if (value instanceof Boolean) { + return (Boolean)value; + } else if (value instanceof String) { + return Boolean.valueOf(((String)value).trim()); + } + return false; + } + + /** + * Gets an Integer context property. + * @param exchange the exchange + * @param message the message + * @param name the name + * @return the property + */ + protected Integer getInteger(Exchange exchange, Message message, String name) { + Object value = getObject(exchange, message, name); + if (value instanceof Integer) { + return (Integer)value; + } else if (value instanceof Number) { + return Integer.valueOf(((Number)value).intValue()); + } else if (value instanceof String) { + return Integer.valueOf(((String)value).trim()); + } + return null; + } + + /** + * Gets a Long context property. + * @param exchange the exchange + * @param message the message + * @param name the name + * @return the property + */ + protected Long getLong(Exchange exchange, Message message, String name) { + Object value = getObject(exchange, message, name); + if (value instanceof Long) { + return (Long)value; + } else if (value instanceof Number) { + return Long.valueOf(((Number)value).longValue()); + } else if (value instanceof String) { + return Long.valueOf(((String)value).trim()); + } + return null; + } + + /** + * Gets a String context property. + * @param exchange the exchange + * @param message the message + * @param name the name + * @return the property + */ + protected String getString(Exchange exchange, Message message, String name) { + Object value = getObject(exchange, message, name); + if (value instanceof String) { + return (String)value; + } else if (value != null) { + return String.valueOf(value); + } + return null; + } + + /** + * Gets an Object context property. + * @param exchange the exchange + * @param message the message + * @param name the name + * @return the property + */ + protected Object getObject(Exchange exchange, Message message, String name) { + Context context = message != null ? exchange.getContext(message) : exchange.getContext(); + return context.getPropertyValue(name); + } + + /** + * Gets the global variables from the knowledge runtime engine. + * @param runtimeEngine the knowledge runtime engine + * @return the global variables + */ + protected Map getGlobalVariables(KnowledgeRuntimeEngine runtimeEngine) { + Map globalVariables = new HashMap(); + if (runtimeEngine != null) { + Globals globals = runtimeEngine.getSessionGlobals(); + if (globals != null) { + for (String key : globals.getGlobalKeys()) { + Object value = globals.get(key); + globalVariables.put(key, value); + } + } + } + return globalVariables; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ContextMap.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ContextMap.java new file mode 100644 index 000000000..31d1f2775 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ContextMap.java @@ -0,0 +1,281 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.expression; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; + +/** + * A Context that is also a Map. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class ContextMap implements Context, Map { + + private final Context _context; + private final Scope _scope; + + /** + * Wraps a context and scope for map operations. + * @param context the context + * @param scope the scope for map operations + */ + public ContextMap(Context context, Scope scope) { + _context = context; + _scope = scope; + } + + /** + * {@inheritDoc} + */ + @Override + public Property getProperty(String name) { + return _context.getProperty(name); + } + + /** + * {@inheritDoc} + */ + @Override + public Property getProperty(String name, Scope scope) { + return _context.getProperty(name, scope); + } + + /** + * {@inheritDoc} + */ + @Override + public T getPropertyValue(String name) { + return _context.getPropertyValue(name); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getProperties() { + return _context.getProperties(); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getProperties(Scope scope) { + return _context.getProperties(scope); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperty(Property property) { + _context.removeProperty(property); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperties() { + _context.removeProperties(); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperties(Scope scope) { + _context.removeProperties(scope); + } + + /** + * {@inheritDoc} + */ + @Override + public Property setProperty(String name, Object val) { + return _context.setProperty(name, val); + } + + /** + * {@inheritDoc} + */ + @Override + public Property setProperty(String name, Object val, Scope scope) { + return _context.setProperty(name, val, scope); + } + + /** + * {@inheritDoc} + */ + @Override + public Context setProperties(Set properties) { + _context.setProperties(properties); + return this; + } + + @Override + public void mergeInto(Context context) { + _context.mergeInto(context); + } + + @Override + public Set getProperties(String label) { + return _context.getProperties(label); + } + + @Override + public void removeProperties(String label) { + _context.removeProperties(label); + } + + /** + * {@inheritDoc} + */ + @Override + public int size() { + return getProperties(_scope).size(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isEmpty() { + return getProperties(_scope).isEmpty(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsKey(Object key) { + return key != null ? getProperty(key.toString(), _scope) != null : false; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsValue(Object value) { + if (value != null) { + for (Property property : getProperties(_scope)) { + if (value.equals(property.getValue())) { + return true; + } + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public Object get(Object key) { + if (key != null) { + Property property = getProperty(key.toString(), _scope); + if (property != null) { + return property.getValue(); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Object put(String key, Object value) { + return setProperty(key, value, _scope); + } + + /** + * {@inheritDoc} + */ + @Override + public Object remove(Object key) { + if (key != null) { + Property property = getProperty(key.toString(), _scope); + if (property != null) { + removeProperty(property); + return property.getValue(); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public void putAll(Map m) { + for (Entry entry : m.entrySet()) { + setProperty(entry.getKey(), entry.getValue(), _scope); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void clear() { + removeProperties(_scope); + } + + /** + * {@inheritDoc} + */ + @Override + public Set keySet() { + Set keySet = new HashSet(); + for (Property property : getProperties(_scope)) { + keySet.add(property.getName()); + } + return keySet; + } + + /** + * {@inheritDoc} + */ + @Override + public Collection values() { + Collection values = new ArrayList(); + for (Property property : getProperties(_scope)) { + values.add(property.getValue()); + } + return values; + } + + /** + * {@inheritDoc} + */ + @Override + public Set> entrySet() { + Map entries = new HashMap(); + for (Property property : getProperties(_scope)) { + entries.put(property.getName(), property.getValue()); + } + return entries.entrySet(); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/Expression.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/Expression.java new file mode 100644 index 000000000..e389096b9 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/Expression.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.expression; + +import java.util.Map; + +/** + * Expression. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface Expression { + + /** + * Gets the expression value. + * @return the expression value + */ + public String getExpression(); + + /** + * Gets the expression type. + * @return the expression type + */ + public ExpressionType getType(); + + /** + * If this expression is compiled. + * @return if this expression is compiled + */ + public boolean isCompiled(); + + /** + * Runs the expression. + * @return the result of running the expression + */ + public Object run(); + + /** + * Runs the expression. + * @param variables the variables to run with + * @return the result of running the expression + */ + public Object run(Map variables); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionFactory.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionFactory.java new file mode 100644 index 000000000..07f39ac31 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionFactory.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.expression; + +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.common.property.SystemAndTestPropertyResolver; + +/** + * ExpressionFactory. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class ExpressionFactory { + + /** The singleton instance. */ + public static final ExpressionFactory INSTANCE = new ExpressionFactory(); + + private ExpressionFactory() {} + + /** + * Creates a new Expression. + * @param expression the expression string + * @return the Expression + */ + public Expression create(String expression) { + return create(expression, null); + } + + /** + * Creates a new Expression. + * @param expression the expression string + * @param expressionType the expression type + * @return the Expression + */ + public Expression create(String expression, ExpressionType expressionType) { + return create(expression, expressionType, null); + } + + /** + * Creates a new Expression. + * @param expression the expression string + * @param expressionType the expression type + * @param propertyResolver the property resolver + * @return the Expression + */ + public Expression create(String expression, ExpressionType expressionType, PropertyResolver propertyResolver) { + if (expressionType == null) { + expressionType = ExpressionType.MVEL; + } + if (propertyResolver == null) { + propertyResolver = SystemAndTestPropertyResolver.INSTANCE; + } + switch (expressionType) { + case MVEL: + return new MVELExpression(expression, propertyResolver); + default: + throw CommonKnowledgeMessages.MESSAGES.unknownExpressionType(expressionType.toString()); + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionMapping.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionMapping.java new file mode 100644 index 000000000..fa63c2e13 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionMapping.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.expression; + +import org.switchyard.common.lang.Strings; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.common.property.SystemAndTestPropertyResolver; +import org.switchyard.component.common.knowledge.config.model.InputModel; +import org.switchyard.component.common.knowledge.config.model.MappingModel; + +/** + * An expression mapping. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class ExpressionMapping { + + private final PropertyResolver _propertyResolver; + private final String _from; + private final String _to; + private final String _output; + private Expression _fromExpression = null; + private Expression _toExpression = null; + + /** + * Constructs an expression mapping from a mapping model. + * @param mappingModel the mapping model + */ + public ExpressionMapping(MappingModel mappingModel) { + PropertyResolver propertyResolver = mappingModel.getModelConfiguration().getPropertyResolver(); + _propertyResolver = propertyResolver != null ? propertyResolver : SystemAndTestPropertyResolver.INSTANCE; + _from = Strings.trimToNull(mappingModel.getFrom()); + _to = Strings.trimToNull(mappingModel.getTo()); + _output = mappingModel instanceof InputModel ? Strings.trimToNull(((InputModel)mappingModel).getOutput()) : null; + } + + /** + * Gets the property resolver. + * @return the property resolver + */ + public PropertyResolver getPropertyResolver() { + return _propertyResolver; + } + + /** + * Gets the from. + * @return the from + */ + public String getFrom() { + return _from; + } + + /** + * Gets the from expression. + * @return the from expression + */ + public Expression getFromExpression() { + if (_fromExpression == null && _from != null) { + _fromExpression = ExpressionFactory.INSTANCE.create(_from, null, _propertyResolver); + } + return _fromExpression; + } + + /** + * Gets the to. + * @return the to + */ + public String getTo() { + return _to; + } + + /** + * Gets the to expression. + * @return the to expression + */ + public Expression getToExpression() { + if (_toExpression == null && _to != null) { + _toExpression = ExpressionFactory.INSTANCE.create(_to, null, _propertyResolver); + } + return _toExpression; + } + + /** + * Gets the output. + * @return the output + */ + public String getOutput() { + return _output; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionType.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionType.java new file mode 100644 index 000000000..1825b7e28 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/ExpressionType.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.expression; + +/** + * Represents known expression types. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum ExpressionType { + + /** The mvel expression type. */ + MVEL; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/MVELExpression.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/MVELExpression.java new file mode 100644 index 000000000..e3ba34c23 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/expression/MVELExpression.java @@ -0,0 +1,130 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.expression; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +import org.mvel2.MVEL; +import org.mvel2.ParserContext; +import org.mvel2.integration.VariableResolver; +import org.mvel2.integration.VariableResolverFactory; +import org.mvel2.integration.impl.ImmutableDefaultFactory; +import org.mvel2.integration.impl.MapVariableResolverFactory; +import org.mvel2.integration.impl.SimpleValueResolver; +import org.switchyard.common.property.PropertyResolver; + +/** + * MVELExpression. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class MVELExpression implements Expression { + + private final String _expression; + private final PropertyResolverFactory _propertyResolverFactory; + private Serializable _compiled; + + /** + * Creates a new MVELExpression with the specified expression and {@link PropertyResolver}. + * @param expression the specified expression + * @param propertyResolver the specified {@link PropertyResolver} + */ + public MVELExpression(String expression, PropertyResolver propertyResolver) { + _expression = expression; + _propertyResolverFactory = new PropertyResolverFactory(propertyResolver); + compile(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getExpression() { + return _expression; + } + + /** + * {@inheritDoc} + */ + @Override + public ExpressionType getType() { + return ExpressionType.MVEL; + } + + private void compile() { + ParserContext pc = new ParserContext(); + pc.addPackageImport("java.util"); + pc.addPackageImport("org.switchyard"); + _compiled = MVEL.compileExpression(_expression, pc); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isCompiled() { + return _compiled != null; + } + + /** + * {@inheritDoc} + */ + @Override + public Object run() { + return run(null); + } + + /** + * {@inheritDoc} + */ + @Override + public Object run(Map variables) { + if (variables == null) { + variables = new HashMap(); + } + VariableResolverFactory factory = new MapVariableResolverFactory(variables, _propertyResolverFactory); + return isCompiled() ? MVEL.executeExpression(_compiled, factory) : MVEL.eval(_expression, factory); + } + + @SuppressWarnings("serial") + private static final class PropertyResolverFactory extends ImmutableDefaultFactory { + + private final PropertyResolver _propertyResolver; + + private PropertyResolverFactory(PropertyResolver propertyResolver) { + _propertyResolver = propertyResolver; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isResolveable(String name) { + return name != null && _propertyResolver.resolveProperty(name) != null; + } + + /** + * {@inheritDoc} + */ + @Override + public VariableResolver getVariableResolver(String name) { + Object value = name != null ? _propertyResolver.resolveProperty(name) : null; + return new SimpleValueResolver(value); + } + + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperation.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperation.java new file mode 100644 index 000000000..65d68be12 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperation.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.operation; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.switchyard.component.common.knowledge.expression.ExpressionMapping; + +/** + * A Knowledge operation. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class KnowledgeOperation { + + private final KnowledgeOperationType _type; + private final String _eventId; + + private final List _globalExpressionMappings = new ArrayList(); + private final List _inputExpressionMappings = new ArrayList(); + private final List _outputExpressionMappings = new ArrayList(); + private final List _faultExpressionMappings = new ArrayList(); + + /** + * Constructs a new knowledge operation. + * @param type the operation type + */ + public KnowledgeOperation(KnowledgeOperationType type) { + this(type, null); + } + + /** + * Constructs a new knowledge operation. + * @param type the operation type + * @param eventId the event id + */ + public KnowledgeOperation(KnowledgeOperationType type, String eventId) { + _type = type; + _eventId = eventId; + } + + /** + * Gets the operation type. + * @return the operation type + */ + public KnowledgeOperationType getType() { + return _type; + } + + /** + * Gets the event id. + * @return the event id + */ + public String getEventId() { + return _eventId; + } + + /** + * Gets the global expression mappings. + * @return the global expression mappings + */ + public List getGlobalExpressionMappings() { + return _globalExpressionMappings; + } + + /** + * Gets the input expression mappings. + * @return the input expression mappings + */ + public List getInputExpressionMappings() { + return _inputExpressionMappings; + } + + /** + * Gets the input-only expression mappings. + * @return the input-only expression mappings + */ + public List getInputOnlyExpressionMappings() { + List list = new LinkedList(); + for (ExpressionMapping em : _inputExpressionMappings) { + if (em.getOutput() == null) { + list.add(em); + } + } + return list; + } + + /** + * Gets the input-output expression mappings. + * @return the input-output expression mappings + */ + public Map getInputOutputExpressionMappings() { + Map map = new LinkedHashMap(); + for (ExpressionMapping em : _inputExpressionMappings) { + String output = em.getOutput(); + if (output != null) { + if (map.containsKey(output)) { + throw new IllegalArgumentException("duplicate input/output variable [" + output + "] not allowed"); + } else { + map.put(output, em); + } + } + } + return map; + } + + /** + * Gets the output expression mappings. + * @return the output expression mappings. + */ + public List getOutputExpressionMappings() { + return _outputExpressionMappings; + } + + /** + * Gets the fault expression mappings. + * @return the fault expression mappings. + */ + public List getFaultExpressionMappings() { + return _faultExpressionMappings; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperationType.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperationType.java new file mode 100644 index 000000000..1b63be7eb --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperationType.java @@ -0,0 +1,29 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.operation; + +/** + * Represents operation types. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface KnowledgeOperationType { + + /** + * Gets the name. + * @return the name + */ + public String name(); + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperations.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperations.java new file mode 100644 index 000000000..bd01ee789 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperations.java @@ -0,0 +1,473 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.operation; + +import static org.switchyard.component.common.knowledge.KnowledgeConstants.CONTEXT; +import static org.switchyard.component.common.knowledge.KnowledgeConstants.DEFAULT; +import static org.switchyard.component.common.knowledge.KnowledgeConstants.FAULT; +import static org.switchyard.component.common.knowledge.KnowledgeConstants.GLOBALS; +import static org.switchyard.component.common.knowledge.KnowledgeConstants.MESSAGE; +import static org.switchyard.component.common.knowledge.KnowledgeConstants.PARAMETER; +import static org.switchyard.component.common.knowledge.KnowledgeConstants.RESULT; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.bind.annotation.XmlType; + +import org.kie.api.runtime.Globals; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.common.lang.Strings; +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; +import org.switchyard.component.common.knowledge.config.model.FaultModel; +import org.switchyard.component.common.knowledge.config.model.FaultsModel; +import org.switchyard.component.common.knowledge.config.model.GlobalModel; +import org.switchyard.component.common.knowledge.config.model.GlobalsModel; +import org.switchyard.component.common.knowledge.config.model.InputModel; +import org.switchyard.component.common.knowledge.config.model.InputsModel; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.OperationModel; +import org.switchyard.component.common.knowledge.config.model.OperationsModel; +import org.switchyard.component.common.knowledge.config.model.OutputModel; +import org.switchyard.component.common.knowledge.config.model.OutputsModel; +import org.switchyard.component.common.knowledge.expression.ContextMap; +import org.switchyard.component.common.knowledge.expression.Expression; +import org.switchyard.component.common.knowledge.expression.ExpressionFactory; +import org.switchyard.component.common.knowledge.expression.ExpressionMapping; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeEngine; + +/** + * KnowledgeOperation functions. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class KnowledgeOperations { + + /** + * Registers operations. + * @param model the model + * @param operations the operations + * @param defaultOperation the default operation + */ + public static void registerOperations(KnowledgeComponentImplementationModel model, Map operations, KnowledgeOperation defaultOperation) { + OperationsModel operationsModel = model.getOperations(); + if (operationsModel != null) { + for (OperationModel operationModel : operationsModel.getOperations()) { + String name = Strings.trimToNull(operationModel.getName()); + if (name == null) { + name = DEFAULT; + } + KnowledgeOperationType type = operationModel.getType(); + if (type == null) { + type = defaultOperation.getType(); + } + String eventId = operationModel.getEventId(); + if (eventId == null) { + eventId = defaultOperation.getEventId(); + } + KnowledgeOperation operation = new KnowledgeOperation(type, eventId); + mapExpressions(operationModel, operation); + if (operations.containsKey(name)) { + throw CommonKnowledgeMessages.MESSAGES.cannotRegisterOperation(type.toString(), name); + } + operations.put(name, operation); + } + } + if (!operations.containsKey(DEFAULT)) { + operations.put(DEFAULT, defaultOperation); + } + } + + private static void mapExpressions(OperationModel operationModel, KnowledgeOperation operation) { + GlobalsModel globalsModel = operationModel.getGlobals(); + if (globalsModel != null) { + for (GlobalModel globalModel : globalsModel.getGlobals()) { + operation.getGlobalExpressionMappings().add(new ExpressionMapping(globalModel)); + } + } + InputsModel inputsModel = operationModel.getInputs(); + if (inputsModel != null) { + for (InputModel inputModel : inputsModel.getInputs()) { + operation.getInputExpressionMappings().add(new ExpressionMapping(inputModel)); + } + } + OutputsModel outputsModel = operationModel.getOutputs(); + if (outputsModel != null) { + for (OutputModel outputModel : outputsModel.getOutputs()) { + operation.getOutputExpressionMappings().add(new ExpressionMapping(outputModel)); + } + } + FaultsModel faultsModel = operationModel.getFaults(); + if (faultsModel != null) { + for (FaultModel faultModel : faultsModel.getFaults()) { + operation.getFaultExpressionMappings().add(new ExpressionMapping(faultModel)); + } + } + } + + /** + * Sets the globals. + * @param message the message + * @param operation the operation + * @param runtime the runtime engine + * @param singleton singleton + */ + public static void setGlobals(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime, boolean singleton) { + Globals globals = runtime.getSessionGlobals(); + if (globals != null) { + Map globalsMap = new HashMap(); + globalsMap.put(GLOBALS, new ConcurrentHashMap()); + Map expressionMap = getMap(message, operation.getGlobalExpressionMappings(), null); + if (expressionMap != null) { + globalsMap.putAll(expressionMap); + } + for (Entry globalsEntry : globalsMap.entrySet()) { + if (!singleton) { + globals.set(globalsEntry.getKey(), globalsEntry.getValue()); + } else { + if (globals.get(globalsEntry.getKey()) == null + || (globalsEntry.getValue() != null && (globalsEntry + .getValue() instanceof Map && !((Map) globalsEntry + .getValue()).isEmpty()))) { + globals.set(globalsEntry.getKey(), globalsEntry.getValue()); + } + } + } + } + } + + /** + * Contains the globals. + * + * @param message + * the message + * @param operation + * the operation + * @param runtime + * the runtime engine + * @return containsGlobal + */ + public static boolean containsGlobals(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime) { + Map expressionMap = getMap(message, operation.getGlobalExpressionMappings(), null); + return expressionMap != null && expressionMap.size() > 0; + + } + + /** + * Gets the input. + * @param message the message + * @param operation the operation + * @param runtime the runtime engine + * @return the input + */ + public static Object getInput(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime) { + List list = getList(message, operation.getInputExpressionMappings()); + switch (list.size()) { + case 0: + return filterRemoteDefaultInputContent(message.getContent(), runtime); + case 1: + return list.get(0); + default: + return list; + } + } + + /** + * Gets an input (all) list. + * @param message the message + * @param operation the operation + * @param runtime the runtime engine + * @return the input (all) list + */ + public static List getInputList(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime) { + return getInputList(message, operation.getInputExpressionMappings(), runtime); + } + + /** + * Gets an input-only list. + * @param message the message + * @param operation the operation + * @param runtime the runtime engine + * @return the input-only list + */ + public static List getInputOnlyList(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime) { + return getInputList(message, operation.getInputOnlyExpressionMappings(), runtime); + } + + private static List getInputList(Message message, List inputs, KnowledgeRuntimeEngine runtime) { + List list = new ArrayList(); + if (inputs.size() > 0) { + list.addAll(getList(message, inputs)); + } else { + expand(filterRemoteDefaultInputContent(message.getContent(), runtime), list); + } + return list; + } + + /** + * Gets an input-output map. + * @param message the message + * @param operation the operation + * @param runtime the runtime engine + * @return the input-output map + */ + public static Map getInputOutputMap(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime) { + Map map = new LinkedHashMap(); + Map inputs = operation.getInputOutputExpressionMappings(); + for (Entry entry : inputs.entrySet()) { + List list = getList(message, Collections.singletonList(entry.getValue())); + final Object output; + switch (list.size()) { + case 0: + output = null; + break; + case 1: + output = list.get(0); + break; + default: + output = list; + } + map.put(entry.getKey(), output); + } + return map; + } + + /** + * Gets an input map. + * @param message the message + * @param operation the operation + * @param runtime the runtime engine + * @return the input map + */ + public static Map getInputMap(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime) { + Map map = new HashMap(); + List inputs = operation.getInputExpressionMappings(); + if (inputs.size() > 0) { + map.putAll(getMap(message, inputs, null)); + } else { + Object content = filterRemoteDefaultInputContent(message.getContent(), runtime); + if (content != null) { + map.put(PARAMETER, content); + } + } + return map; + } + + private static Object filterRemoteDefaultInputContent(Object content, KnowledgeRuntimeEngine runtime) { + if (runtime.isRemote() && content != null && content.getClass().getAnnotation(XmlType.class) == null) { + content = null; + } + return content; + } + + /** + * Sets the outputs. + * @param message the message + * @param operation the operation + * @param contextOverrides the context overrides + */ + public static void setOutputs(Message message, KnowledgeOperation operation, Map contextOverrides) { + setOutputsOrFaults(message, operation.getOutputExpressionMappings(), contextOverrides, RESULT); + } + + /** + * Sets the faults. + * @param message the message + * @param operation the operation + * @param contextOverrides the context overrides + */ + public static void setFaults(Message message, KnowledgeOperation operation, Map contextOverrides) { + setOutputsOrFaults(message, operation.getFaultExpressionMappings(), contextOverrides, FAULT); + } + + private static void setOutputsOrFaults(Message message, List expressionMappings, Map expressionVariables, String defaultReturnVariable) { + Map> toListMap = new HashMap>(); + for (ExpressionMapping expressionMapping : expressionMappings) { + String to = expressionMapping.getTo(); + if (to != null) { + List toList = toListMap.get(to); + if (toList == null) { + toList = new ArrayList(); + toListMap.put(to, toList); + } + toList.add(expressionMapping); + } + } + if (toListMap.size() == 0) { + Object output = getValue(expressionVariables, defaultReturnVariable); + if (output != null) { + message.setContent(output); + } + } else { + if (!expressionVariables.containsKey(defaultReturnVariable)) { + expressionVariables.put(defaultReturnVariable, null); + } + for (Entry> toListEntry : toListMap.entrySet()) { + List from_list = new ArrayList(); + ExpressionMapping to_em = null; + for (ExpressionMapping from_em : toListEntry.getValue()) { + if (to_em == null) { + to_em = from_em; + } + Object from_value = run(message, from_em.getFromExpression(), expressionVariables); + if (from_value != null) { + from_list.add(from_value); + } else { + from_value = getValue(expressionVariables, from_em.getFrom()); + if (from_value != null) { + from_list.add(from_value); + } + } + } + final Object output; + switch (from_list.size()) { + case 0: + output = null; + break; + case 1: + output = from_list.get(0); + break; + default: + output = from_list; + break; + } + String output_var = toVariable(output); + expressionVariables.put(output_var, output); + String output_to = to_em.getTo() + " = " + output_var; + Expression output_to_expr = ExpressionFactory.INSTANCE.create(output_to, null, to_em.getPropertyResolver()); + run(message, output_to_expr, expressionVariables); + } + } + } + + @SuppressWarnings("unchecked") + private static Object getValue(Map expressionVariables, String name) { + Object output = null; + if (expressionVariables != null) { + output = expressionVariables.get(name); + if (output == null) { + Object globals = expressionVariables.get(GLOBALS); + if (globals instanceof Map) { + output = ((Map)globals).get(name); + } + } + } + return output; + } + + private static List getList(Message message, List expressionMappings) { + List list = new ArrayList(); + if (expressionMappings == null || expressionMappings.size() == 0) { + expand(message.getContent(), list); + } else { + Map> listMap = getListMap(message, expressionMappings, true, toVariable(message)); + for (List value : listMap.values()) { + expand(value, list); + } + } + return list; + } + + private static Map getMap(Message message, List expressionMappings, Map contextOverrides) { + Map map = new HashMap(); + Map> listMap = getListMap(message, expressionMappings, false, toVariable(message), contextOverrides); + for (Entry> entry : listMap.entrySet()) { + List list = entry.getValue(); + map.put(entry.getKey(), list != null && list.size() > 0 ? list.get(0) : null); + } + return map; + } + + /** + * Gets a list map. + * @param message the message + * @param expressionMappings the expression mappings + * @param expand whether to expand + * @param undefinedVariable the undefined variable name + * @return the list map + */ + public static Map> getListMap(Message message, List expressionMappings, boolean expand, String undefinedVariable) { + return getListMap(message, expressionMappings, expand, undefinedVariable, null); + } + + private static Map> getListMap(Message message, List expressionMappings, boolean expand, String undefinedVariable, Map expressionVariables) { + Map> map = new HashMap>(); + if (expressionMappings != null) { + for (ExpressionMapping em : expressionMappings) { + String variable = em.getTo(); + if (variable == null && undefinedVariable != null) { + variable = undefinedVariable; + } + if (variable != null) { + List list = map.get(variable); + if (list == null) { + list = new ArrayList(); + map.put(variable, list); + } + Object value = run(message, em.getFromExpression(), expressionVariables); + if (expand) { + expand(value, list); + } else if (value != null) { + list.add(value); + } + } + } + } + return map; + } + + private static Object run(Message message, Expression expression, Map expressionVariables) { + Map variables = new HashMap(); + if (expressionVariables != null) { + variables.putAll(expressionVariables); + } + // these always take precedence! + variables.put(CONTEXT, new ContextMap(message.getContext(), Scope.MESSAGE)); + variables.put(MESSAGE, message); + return expression.run(variables); + } + + private static void expand(Object value, List list) { + if (value != null) { + if (value instanceof Iterable) { + for (Object o : (Iterable)value) { + if (o != null) { + list.add(o); + } + } + } else { + list.add(value); + } + } + } + + /** + * Converts an object to a variable name. + * @param object the object + * @return the variable name + */ + public static String toVariable(Object object) { + return ("_var" + System.identityHashCode(object)).replaceFirst("-", "_"); + } + + private KnowledgeOperations() {} + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/EntityManagerFactoryLoader.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/EntityManagerFactoryLoader.java new file mode 100644 index 000000000..6892776c9 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/EntityManagerFactoryLoader.java @@ -0,0 +1,35 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.persistence; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.switchyard.ServiceDomain; + +/** + * Loads the EntityManagerFactory used for BPM. + */ +public class EntityManagerFactoryLoader { + + protected static final String UNIT_NAME = "org.jbpm.persistence.jpa"; + + /** + * @param domain the service domain + * @return the BPM EMF associated with the specified domain. + */ + public EntityManagerFactory getEntityManagerFactory(ServiceDomain domain) { + return Persistence.createEntityManagerFactory(UNIT_NAME); + } +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/NoopEntityManagerFactory.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/NoopEntityManagerFactory.java new file mode 100644 index 000000000..3a4394f01 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/NoopEntityManagerFactory.java @@ -0,0 +1,81 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.persistence; + +import java.util.Collections; +import java.util.Map; + +import javax.persistence.Cache; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnitUtil; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.metamodel.Metamodel; + +/** + * NoopEntityManagerFactory. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class NoopEntityManagerFactory implements EntityManagerFactory { + + private boolean _open = true; + + @Override + public EntityManager createEntityManager() { + return null; + } + + @Override + @SuppressWarnings("rawtypes") + public EntityManager createEntityManager(Map map) { + return null; + } + + @Override + public CriteriaBuilder getCriteriaBuilder() { + return null; + } + + @Override + public Metamodel getMetamodel() { + return null; + } + + @Override + public boolean isOpen() { + return _open; + } + + @Override + public void close() { + _open = false; + } + + @Override + public Map getProperties() { + return Collections.emptyMap(); + } + + @Override + public Cache getCache() { + return null; + } + + @Override + public PersistenceUnitUtil getPersistenceUnitUtil() { + return null; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/OSGiEntityManagerFactoryLoader.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/OSGiEntityManagerFactoryLoader.java new file mode 100644 index 000000000..3f58ed961 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/persistence/OSGiEntityManagerFactoryLoader.java @@ -0,0 +1,57 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.persistence; + +import java.util.Collection; + +import javax.persistence.EntityManagerFactory; + +import org.osgi.framework.Bundle; +import org.osgi.framework.ServiceReference; +import org.switchyard.ServiceDomain; + +/** + * Retrieves the EMF from the bundle context. + */ +public class OSGiEntityManagerFactoryLoader extends EntityManagerFactoryLoader { + + /** + * {@inheritDoc} + */ + @Override + public EntityManagerFactory getEntityManagerFactory(ServiceDomain domain) { + try { + final Bundle bundle = getApplicationBundle(domain); + if (bundle != null) { + Collection> refs = bundle.getBundleContext() + .getServiceReferences(EntityManagerFactory.class, "(osgi.unit.name=org.jbpm.persistence.jpa)"); + if (refs != null && refs.size() > 0) { + EntityManagerFactory emf = bundle.getBundleContext().getService(refs.iterator().next()); + if (emf != null) { + return emf; + } + } + } + } catch (Exception e) { + e.fillInStackTrace(); + } + // try the default + return super.getEntityManagerFactory(domain); + } + + private Bundle getApplicationBundle(ServiceDomain domain) { + return (Bundle)domain.getProperty("switchyard.deployment.bundle"); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeEngine.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeEngine.java new file mode 100644 index 000000000..88eecada1 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeEngine.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.runtime; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; + +import org.jbpm.process.audit.AuditLogService; +import org.kie.api.runtime.Globals; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.manager.audit.AuditService; +import org.kie.api.task.TaskService; +import org.kie.internal.task.api.EventService; +import org.kie.internal.task.api.InternalTaskService; +import org.kie.services.client.api.command.RemoteRuntimeEngine; +import org.switchyard.component.common.knowledge.transaction.TransactionInvocationHandler; + +/** + * KnowledgeRuntimeEngine. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class KnowledgeRuntimeEngine implements RuntimeEngine { + + private final RuntimeEngine _wrapped; + private final boolean _persistent; + + /** + * Constructs a new knowledge runtime. + * @param wrapped the wrapped RuntimeEngine + * @param persistent if persistence is enabled + */ + public KnowledgeRuntimeEngine(RuntimeEngine wrapped, boolean persistent) { + _wrapped = wrapped; + _persistent = persistent; + } + + /** + * Gets the RuntimeEngine. + * @return the RuntimeEngine + */ + public RuntimeEngine getWrapped() { + return _wrapped; + } + + /** + * If the wrapped KieSession is remote. + * @return if so + */ + public boolean isRemote() { + return _wrapped instanceof RemoteRuntimeEngine; + } + + /** + * If persistence is enabled. + * @return true if persistence is enabled + */ + public boolean isPersistent() { + return _persistent; + } + + /** + * {@inheritDoc} + */ + @Override + public KieSession getKieSession() { + return _wrapped.getKieSession(); + } + + /** + * {@inheritDoc} + */ + @Override + public TaskService getTaskService() { + InvocationHandler ih = new TransactionInvocationHandler(_wrapped.getTaskService(), _persistent); + return (TaskService)Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{InternalTaskService.class, EventService.class}, ih); + } + + /** + * {@inheritDoc} + */ + @Override + public AuditService getAuditService() { + InvocationHandler ih = new TransactionInvocationHandler(_wrapped.getAuditService(), _persistent); + return (AuditService)Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{AuditLogService.class}, ih); + } + + /** + * Gets the wrapped KieSession identifier. + * @return the id + */ + public Long getSessionIdentifier() { + return Long.valueOf(getKieSession().getIdentifier()); + } + + /** + * Gets the wrapped globals. + * @return the globals + */ + public Globals getSessionGlobals() { + return isRemote() ? null : getKieSession().getGlobals(); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManager.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManager.java new file mode 100644 index 000000000..7a6b13665 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManager.java @@ -0,0 +1,329 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.runtime; + +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.kie.api.KieServices; +import org.kie.api.builder.KieScanner; +import org.kie.api.builder.ReleaseId; +import org.kie.api.event.kiebase.KieBaseEventListener; +import org.kie.api.logger.KieRuntimeLogger; +import org.kie.api.runtime.Channel; +import org.kie.api.runtime.Environment; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.manager.Context; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.manager.RuntimeManager; +import org.kie.internal.process.CorrelationKey; +import org.kie.internal.runtime.manager.Disposable; +import org.kie.internal.runtime.manager.DisposeListener; +import org.kie.internal.runtime.manager.context.CorrelationKeyContext; +import org.kie.internal.runtime.manager.context.EmptyContext; +import org.kie.internal.runtime.manager.context.ProcessInstanceIdContext; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.CommonKnowledgeLogger; +import org.switchyard.component.common.knowledge.config.builder.ChannelBuilder; +import org.switchyard.component.common.knowledge.config.builder.LoggerBuilder; +import org.switchyard.component.common.knowledge.config.items.ExtendedRegisterableItemsFactory; +import org.switchyard.component.common.knowledge.config.manifest.ContainerManifest; + +/** + * KnowledgeRuntimeManager. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class KnowledgeRuntimeManager implements RuntimeManager { + + private final KieServices _kieServices; + private final ClassLoader _classLoader; + private final KnowledgeRuntimeManagerType _type; + private final QName _serviceDomainName; + private final QName _serviceName; + private final RuntimeManager _runtimeManager; + private final List _channelBuilders; + private final List _loggerBuilders; + private final boolean _persistent; + private final Set _sessionIds = Collections.synchronizedSet(new LinkedHashSet()); + + /** + * Creates a new KnowledgeRuntimeManager. + * @param classLoader the classLoader + * @param type the type + * @param serviceDomainName the serviceDomainName + * @param serviceName the serviceName + * @param runtimeManager the runtimeManager + * @param persistent if persistent + * @param channelBuilders the channelBuilders + * @param loggerBuilders the loggerBuilders + */ + KnowledgeRuntimeManager( + ClassLoader classLoader, + KnowledgeRuntimeManagerType type, + QName serviceDomainName, + QName serviceName, + RuntimeManager runtimeManager, + boolean persistent, + List channelBuilders, + List loggerBuilders) { + _kieServices = KieServices.Factory.get(); + _classLoader = classLoader; + _type = type; + _serviceDomainName = serviceDomainName; + _serviceName = serviceName; + _runtimeManager = runtimeManager; + _persistent = persistent; + _channelBuilders = channelBuilders; + _loggerBuilders = loggerBuilders; + } + + /** + * Gets the type. + * @return the type + */ + public KnowledgeRuntimeManagerType getType() { + return _type; + } + + /** + * Gets the serviceDomainName. + * @return serviceDomainName + */ + public QName getServiceDomainName() { + return _serviceDomainName; + } + + /** + * Gets the serviceName. + * @return the serviceName + */ + public QName getServiceName() { + return _serviceName; + } + + /** + * {@inheritDoc} + */ + @Override + public String getIdentifier() { + return _runtimeManager.getIdentifier(); + } + + /** + * If persistent. + * @return if persistent + */ + public boolean isPersistent() { + return _persistent; + } + + /** + * Gets a RuntimeEngine for an undefined {@link Context}. + * @return the RuntimeEngine + */ + public RuntimeEngine getRuntimeEngine() { + return getRuntimeEngine((Context)null); + } + + /** + * Gets a RuntimeEngine for a {@link Context} associated with the processInstanceId. + * @param processInstanceId the processInstanceId + * @return the RuntimeEngine + */ + public RuntimeEngine getRuntimeEngine(Long processInstanceId) { + return getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId)); + } + + /** + * Gets a RuntimeEngine for a {@link Context} associated with the correlationKey. + * @param correlationKey the correlationKey + * @return the RuntimeEngine + */ + public RuntimeEngine getRuntimeEngine(CorrelationKey correlationKey) { + return getRuntimeEngine(CorrelationKeyContext.get(correlationKey)); + } + + /** + * {@inheritDoc} + */ + @Override + public RuntimeEngine getRuntimeEngine(Context context) { + KnowledgeRuntimeEngine runtimeEngine; + if (context == null || _type != KnowledgeRuntimeManagerType.PER_PROCESS_INSTANCE) { + context = EmptyContext.get(); + } + final ClassLoader origTCCL = Classes.setTCCL(_classLoader); + try { + RuntimeEngine wrapped = _runtimeManager.getRuntimeEngine(context); + initRuntimeEngine(wrapped); + runtimeEngine = new KnowledgeRuntimeEngine(wrapped, _persistent); + } finally { + Classes.setTCCL(origTCCL); + } + return runtimeEngine; + } + + private void initRuntimeEngine(final RuntimeEngine runtimeEngine) { + // NOTE: RemoteRuntimeEngines are not Disposable, which is fine considering + // none of these Listeners are allowed to be added in remote cases anyways. + if (runtimeEngine instanceof Disposable) { + final Disposable disposable = (Disposable)runtimeEngine; + final KieSession session = runtimeEngine.getKieSession(); + if (session != null) { + final Long sessionId = Long.valueOf(session.getIdentifier()); + synchronized (_sessionIds) { + if (!_sessionIds.contains(sessionId)) { + _sessionIds.add(sessionId); + disposable.addDisposeListener(new DisposeListener() { + @Override + public void onDispose(RuntimeEngine runtime) { + synchronized (_sessionIds) { + _sessionIds.remove(sessionId); + } + } + }); + final Environment environment = session.getEnvironment(); + ExtendedRegisterableItemsFactory extendedRIF = ExtendedRegisterableItemsFactory.Env.removeFromEnvironment(environment); + if (extendedRIF != null) { + List baseListeners = extendedRIF.getKieBaseEventListeners(runtimeEngine); + for (KieBaseEventListener baseListener : baseListeners) { + session.getKieBase().addEventListener(baseListener); + } + } + for (ChannelBuilder builder : _channelBuilders) { + final String name = builder.getChannelName(); + Channel channel = builder.build(); + if (name != null && channel != null) { + session.registerChannel(name, channel); + disposable.addDisposeListener(new DisposeListener() { + @Override + public void onDispose(RuntimeEngine runtime) { + session.unregisterChannel(name); + } + }); + } + } + for (LoggerBuilder builder : _loggerBuilders) { + final KieRuntimeLogger logger = builder.build(session); + disposable.addDisposeListener(new DisposeListener() { + @Override + public void onDispose(RuntimeEngine runtime) { + try { + logger.close(); + } catch (Throwable t) { + CommonKnowledgeLogger.ROOT_LOGGER.problemClosingKieRuntimeLogger(t.getMessage()); + } + } + }); + } + ContainerManifest containerManifest = ContainerManifest.removeFromEnvironment(environment); + if (containerManifest != null && containerManifest.isScan()) { + KieContainer kieContainer = containerManifest.getKieContainer(); + final ReleaseId releaseId = containerManifest.getReleaseId(); + final KieScanner scanner = _kieServices.newKieScanner(kieContainer); + //final KieScanner scanner = new KnowledgeScanner(kieContainer); + disposable.addDisposeListener(new DisposeListener() { + @Override + public void onDispose(RuntimeEngine runtime) { + try { + scanner.stop(); + scanner.shutdown(); + } catch (Throwable t) { + CommonKnowledgeLogger.ROOT_LOGGER.problemStopppingKieScanner(t.getMessage()); + } finally { + if (releaseId != null) { + // fix for SWITCHYARD-2241 + _kieServices.getRepository().removeKieModule(releaseId); + } + } + } + }); + scanner.start(containerManifest.getScanInterval().longValue()); + } + } + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void disposeRuntimeEngine(RuntimeEngine runtime) { + if (runtime instanceof KnowledgeRuntimeEngine) { + runtime = ((KnowledgeRuntimeEngine)runtime).getWrapped(); + } + _runtimeManager.disposeRuntimeEngine(runtime); + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + _runtimeManager.close(); + } + + /* attempt at fixing SWITCHYARD-2240 + private static final class KnowledgeScanner extends KieRepositoryScannerImpl { + private ReleaseId _originalReleaseId = null; + private KnowledgeScanner(KieContainer kieContainer) { + setKieContainer(kieContainer); + } + @Override + public synchronized void setKieContainer(KieContainer kieContainer) { + _originalReleaseId = kieContainer != null ? kieContainer.getReleaseId() : null; + super.setKieContainer(kieContainer); + } + @Override + @SuppressWarnings("unchecked") + public synchronized void scanNow() { + Set releaseIds = new HashSet(); + try { + Method scanForUpdates = KieRepositoryScannerImpl.class.getDeclaredMethod("scanForUpdates", new Class[0]); + scanForUpdates.setAccessible(true); + Map updatedArtifacts = (Map)scanForUpdates.invoke(this, (Object[])null); + if (!updatedArtifacts.isEmpty()) { + if (_originalReleaseId != null) { + releaseIds.add(_originalReleaseId); + } + for (DependencyDescriptor dd : updatedArtifacts.keySet()) { + releaseIds.add(dd.getReleaseId()); + releaseIds.add(dd.getArtifactReleaseId()); + } + //KieRepository kieRepository = KieServices.Factory.get().getRepository(); + //for (ReleaseId releaseId : releaseIds) { + // kieRepository.removeKieModule(releaseId); + //} + } + } catch (Throwable t) { + t.printStackTrace(); + } + super.scanNow(); + //KieRepository kieRepository = KieServices.Factory.get().getRepository(); + //for (ReleaseId releaseId : releaseIds) { + // kieRepository.removeKieModule(releaseId); + //} + } + } + */ + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerFactory.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerFactory.java new file mode 100644 index 000000000..ea8c43faf --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerFactory.java @@ -0,0 +1,89 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.runtime; + +import static org.switchyard.deploy.ServiceDomainManager.ROOT_DOMAIN; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.namespace.QName; + +import org.kie.api.runtime.manager.RuntimeManager; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.config.builder.ChannelBuilder; +import org.switchyard.component.common.knowledge.config.builder.LoggerBuilder; +import org.switchyard.component.common.knowledge.config.builder.RuntimeManagerBuilder; +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; + +/** + * KnowledgeRuntimeManagerFactory. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class KnowledgeRuntimeManagerFactory { + + private static final AtomicInteger IDENTIFIER_COUNT = new AtomicInteger(); + + private final ClassLoader _classLoader; + private final RuntimeManagerBuilder _runtimeManagerBuilder; + private final List _channelBuilders; + private final List _loggerBuilders; + private final boolean _persistent; + private final QName _serviceDomainName; + private final QName _serviceName; + private final String _identifierRoot; + + /** + * Creates a new KnowledgeRuntimeManagerFactory. + * @param classLoader the classLoader + * @param serviceDomain the serviceDomain + * @param serviceName the serviceName + * @param implementationModel the implementationModel + */ + public KnowledgeRuntimeManagerFactory( + ClassLoader classLoader, + ServiceDomain serviceDomain, + QName serviceName, + KnowledgeComponentImplementationModel implementationModel) { + _classLoader = classLoader; + _runtimeManagerBuilder = new RuntimeManagerBuilder(classLoader, serviceDomain, implementationModel); + _persistent = implementationModel.isPersistent(); + _channelBuilders = ChannelBuilder.builders(classLoader, serviceDomain, implementationModel); + _loggerBuilders = LoggerBuilder.builders(classLoader, implementationModel); + _serviceDomainName = serviceDomain.getName() != null ? serviceDomain.getName() : ROOT_DOMAIN; + _serviceName = serviceName; + _identifierRoot = _serviceDomainName.toString() + "/" + _serviceName.toString() + "/"; + } + + /** + * Creates a new KnowledgeRuntimeManager. + * @param type the KnowledgeRuntimeManagerType + * @return the new KnowledgeRuntimeManager + */ + public KnowledgeRuntimeManager newRuntimeManager(KnowledgeRuntimeManagerType type) { + RuntimeManager runtimeManager; + final String identifier = _identifierRoot + IDENTIFIER_COUNT.incrementAndGet(); + final ClassLoader origTCCL = Classes.setTCCL(_classLoader); + try { + runtimeManager = _runtimeManagerBuilder.build(type, identifier); + } finally { + Classes.setTCCL(origTCCL); + } + return new KnowledgeRuntimeManager( + _classLoader, type, _serviceDomainName, _serviceName, runtimeManager, _persistent, _channelBuilders, _loggerBuilders); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerRegistry.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerRegistry.java new file mode 100644 index 000000000..6bd4ff2dc --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerRegistry.java @@ -0,0 +1,80 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.runtime; + +import static org.switchyard.deploy.ServiceDomainManager.ROOT_DOMAIN; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +/** + * KnowledgeRuntimeManagerRegistry. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public final class KnowledgeRuntimeManagerRegistry { + + private static final Map> REGISTRY = Collections.synchronizedMap(new HashMap>()); + + /** + * Gets a runtime manager. + * @param serviceDomainName the service domain name + * @param serviceName the service name + * @return the runtime manager + */ + public static final synchronized KnowledgeRuntimeManager getRuntimeManager(QName serviceDomainName, QName serviceName) { + if (serviceDomainName == null) { + serviceDomainName = ROOT_DOMAIN; + } + Map reg = REGISTRY.get(serviceDomainName); + return reg != null ? reg.get(serviceName) : null; + } + + /** + * Puts a runtime manager. + * @param serviceDomainName the service domain name + * @param serviceName the service name + * @param runtimeManager the runtime manager + */ + public static final synchronized void putRuntimeManager(QName serviceDomainName, QName serviceName, KnowledgeRuntimeManager runtimeManager) { + if (serviceDomainName == null) { + serviceDomainName = ROOT_DOMAIN; + } + Map reg = REGISTRY.get(serviceDomainName); + if (reg == null) { + reg = Collections.synchronizedMap(new HashMap()); + REGISTRY.put(serviceDomainName, reg); + } + if (runtimeManager == null) { + reg.remove(serviceName); + } else { + reg.put(serviceName, runtimeManager); + } + } + + /** + * Removes a runtime manager. + * @param serviceDomainName the service domain name + * @param serviceName the service name + */ + public static final synchronized void removeRuntimeManager(QName serviceDomainName, QName serviceName) { + putRuntimeManager(serviceDomainName, serviceName, null); + } + + private KnowledgeRuntimeManagerRegistry() {} + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerType.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerType.java new file mode 100644 index 000000000..dbe41b6ae --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/KnowledgeRuntimeManagerType.java @@ -0,0 +1,30 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.runtime; + +/** + * KnowledgeRuntimeManagerType. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public enum KnowledgeRuntimeManagerType { + + /** The Singleton type. */ + SINGLETON, + /** The PerRequest type. */ + PER_REQUEST, + /** The PerProcessInstance type. */ + PER_PROCESS_INSTANCE; + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/ExtendedKieSessionClientCommandObject.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/ExtendedKieSessionClientCommandObject.java new file mode 100644 index 000000000..1f83c0fbc --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/ExtendedKieSessionClientCommandObject.java @@ -0,0 +1,65 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.runtime.remote; + +import org.kie.api.runtime.manager.Context; +import org.kie.api.runtime.rule.FactHandle; +import org.kie.remote.jaxb.gen.InsertObjectCommand; +import org.kie.services.client.api.command.KieSessionClientCommandObject; +import org.kie.services.client.api.command.RemoteConfiguration; + +/** + * ExtendedKieSessionClientCommandObject. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class ExtendedKieSessionClientCommandObject extends KieSessionClientCommandObject { + + //private final Context _context; + private final Long _sessionIdentifier; + + ExtendedKieSessionClientCommandObject(RemoteConfiguration config, Context context, Long sessionIdentifier) { + super(config); + //_context = context; + _sessionIdentifier = sessionIdentifier; + } + + /** + * {@inheritDoc} + */ + @Override + public FactHandle insert(Object object) { + InsertObjectCommand cmd = new InsertObjectCommand(); + cmd.setObject(object); + executeCommand(cmd); + return null; // TODO + } + + /** + * {@inheritDoc} + */ + @Override + public int getId() { + return _sessionIdentifier.intValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getIdentifier() { + return _sessionIdentifier.longValue(); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/ExtendedRemoteRuntimeEngine.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/ExtendedRemoteRuntimeEngine.java new file mode 100644 index 000000000..7097dbdb3 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/ExtendedRemoteRuntimeEngine.java @@ -0,0 +1,48 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.runtime.remote; + +import java.util.concurrent.atomic.AtomicLong; + +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.manager.Context; +import org.kie.services.client.api.command.RemoteConfiguration; +import org.kie.services.client.api.command.RemoteRuntimeEngine; + +/** + * ExtendedRemoteRuntimeEngine. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class ExtendedRemoteRuntimeEngine extends RemoteRuntimeEngine { + + private static final AtomicLong SESSION_IDENTIFIER = new AtomicLong(); + + private final KieSession _kieSession; + + ExtendedRemoteRuntimeEngine(RemoteConfiguration configuration, Context context) { + super(configuration); + // we use negative numbers so as not to clash with ones generated by kie/drools/jbpm + _kieSession = new ExtendedKieSessionClientCommandObject(configuration, context, Long.valueOf(SESSION_IDENTIFIER.decrementAndGet())); + } + + /** + * {@inheritDoc} + */ + @Override + public KieSession getKieSession() { + return _kieSession; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/RemoteRuntimeManager.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/RemoteRuntimeManager.java new file mode 100644 index 000000000..97667c564 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/RemoteRuntimeManager.java @@ -0,0 +1,88 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.runtime.remote; + +import java.util.Map; +import java.util.WeakHashMap; + +import org.kie.api.runtime.manager.Context; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.manager.RuntimeManager; +import org.kie.services.client.api.command.RemoteConfiguration; + +/** + * RemoteRuntimeManager. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class RemoteRuntimeManager implements RuntimeManager { + + private static final String NULL_CONTEXT_ID = "NullContext"; + + private final RemoteConfiguration _configuration; + private final String _identifier; + private Map _engines = new WeakHashMap(); + + /** + * Creates a new RemoteRuntimeManager. + * @param configuration the RemoteConfiguration + * @param identifier the identifier + */ + public RemoteRuntimeManager(RemoteConfiguration configuration, String identifier) { + _configuration = configuration; + _identifier = identifier; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized RuntimeEngine getRuntimeEngine(Context context) { + Object contextId = context != null ? context.getContextId() : null; + if (contextId == null) { + contextId = NULL_CONTEXT_ID; + } + RuntimeEngine engine = _engines.get(contextId); + if (engine == null) { + engine = new ExtendedRemoteRuntimeEngine(_configuration, context); + _engines.put(contextId, engine); + } + return engine; + } + + /** + * {@inheritDoc} + */ + @Override + public String getIdentifier() { + return _identifier; + } + + /** + * {@inheritDoc} + */ + @Override + public void disposeRuntimeEngine(RuntimeEngine runtime) { + // no-op + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + // no-op + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/serial/SerializerObjectMarshallingStrategy.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/serial/SerializerObjectMarshallingStrategy.java new file mode 100644 index 000000000..b69692340 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/serial/SerializerObjectMarshallingStrategy.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.serial; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.kie.api.marshalling.ObjectMarshallingStrategy; +import org.switchyard.serial.Serializer; + +/** + * SerializerObjectMarshallingStrategy. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class SerializerObjectMarshallingStrategy implements ObjectMarshallingStrategy { + + private static final String[] IGNORE_PKGS = new String[] { + "java.", "javax.", "org.w3c.dom.", "org.jbpm.", "org.drools.", "org.kie." + }; + + private final Serializer _serializer; + + /** + * Constructs a new SerializerObjectMarshallingStrategy with the specified Serializer. + * @param serializer the specified Serializer + */ + public SerializerObjectMarshallingStrategy(Serializer serializer) { + _serializer = serializer; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean accept(Object object) { + if (object != null) { + String cn = object.getClass().getName(); + for (String ip : IGNORE_PKGS) { + // TODO: Replace with something more elegant? Perhaps check the classloader? + if (cn.startsWith(ip)) { + return false; + } + } + return true; + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public void write(ObjectOutputStream os, Object object) throws IOException { + os.writeObject(_serializer.serialize(object, Object.class)); + } + + /** + * {@inheritDoc} + */ + @Override + public Object read(ObjectInputStream os) throws IOException, ClassNotFoundException { + return _serializer.deserialize((byte[])os.readObject(), Object.class); + } + + /** + * {@inheritDoc} + */ + @Override + public byte[] marshal(Context context, ObjectOutputStream os, Object object) throws IOException { + return _serializer.serialize(object, Object.class); + } + + /** + * {@inheritDoc} + */ + @Override + public Object unmarshal(Context context, ObjectInputStream is, byte[] object, ClassLoader classloader) throws IOException, ClassNotFoundException { + return _serializer.deserialize(object, Object.class); + } + + /** + * {@inheritDoc} + */ + @Override + public Context createContext() { + return null; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/StandardSwitchYardServiceTaskHandler.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/StandardSwitchYardServiceTaskHandler.java new file mode 100644 index 000000000..23653514f --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/StandardSwitchYardServiceTaskHandler.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.service; + +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.jbpm.process.workitem.bpmn2.ServiceTaskHandler; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.process.ProcessRuntime; +import org.kie.api.runtime.process.WorkItem; +import org.kie.api.runtime.process.WorkItemManager; + +/** + * StandardSwitchYardServiceTaskHandler. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class StandardSwitchYardServiceTaskHandler extends SwitchYardServiceTaskHandler { + + /** Service Task. */ + public static final String SERVICE_TASK = "Service Task"; + + /** implementation. */ + public static final String IMPLEMENTATION = "implementation"; + /** ##SwitchYard. */ + public static final String IMPLEMENTATION_SWITCHYARD = "##SwitchYard"; + + /** Interface. */ + public static final String INTERFACE = "Interface"; + /** interfaceImplementationRef. */ + public static final String INTERFACE_IMPLEMENTATION_REF = "interfaceImplementationRef"; + /** operationImplementationRef. */ + public static final String OPERATION_IMPLEMENTATION_REF = "operationImplementationRef"; + + /** + * Constructs a new StandardSwitchYardServiceTaskHandler. + */ + public StandardSwitchYardServiceTaskHandler() {} + + /** + * {@inheritDoc} + */ + @Override + public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { + String implementation = getImplementation(workItem.getParameters()); + if (IMPLEMENTATION_SWITCHYARD.equalsIgnoreCase(implementation)) { + super.executeWorkItem(workItem, manager); + } else { + ServiceTaskHandler sth; + ProcessRuntime runtime = getProcessRuntime(); + if (runtime instanceof KieSession) { + sth = new ServiceTaskHandler((KieSession)runtime); + } else { + sth = new ServiceTaskHandler(); + } + sth.setClassLoader(getClass().getClassLoader()); + sth.executeWorkItem(workItem, manager); + } + } + + private String getImplementation(Map parameters) { + return getString(IMPLEMENTATION, parameters, null); + } + + /** + * {@inheritDoc} + */ + @Override + protected QName getServiceName(Map parameters) { + return getQName(INTERFACE, parameters, getQName(INTERFACE_IMPLEMENTATION_REF, parameters, null)); + } + + /** + * {@inheritDoc} + */ + @Override + protected String getOperationName(Map parameters) { + return getString(OPERATION, parameters, getString(OPERATION_IMPLEMENTATION_REF, parameters, null)); + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceChannel.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceChannel.java new file mode 100644 index 000000000..0c682c1c5 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceChannel.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.service; + +import javax.xml.namespace.QName; + +import org.kie.api.runtime.Channel; + +/** + * SwitchYardServiceChannel. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SwitchYardServiceChannel implements Channel { + + /** service. */ + public static final String SERVICE = "service"; + + private QName _serviceName; + private String _operationName; + private SwitchYardServiceInvoker _invoker; + + /** + * Constructs a new SwitchYardServiceChannel. + */ + public SwitchYardServiceChannel() {} + + /** + * Gets the service name. + * @return the service name + */ + public QName getServiceName() { + return _serviceName; + } + + /** + * Sets the service name. + * @param serviceName the service name + */ + public void setServiceName(QName serviceName) { + _serviceName = serviceName; + } + + /** + * Gets the operation name. + * @return the operation name + */ + public String getOperationName() { + return _operationName; + } + + /** + * Sets the operation name. + * @param operationName the operation name + */ + public void setOperationName(String operationName) { + _operationName = operationName; + } + + /** + * Gets the invoker. + * @return the invoker + */ + public SwitchYardServiceInvoker getInvoker() { + return _invoker; + } + + /** + * Sets the invoker. + * @param invoker the invoker + */ + public void setInvoker(SwitchYardServiceInvoker invoker) { + _invoker = invoker; + } + + /** + * {@inheritDoc} + */ + @Override + public void send(Object object) { + SwitchYardServiceRequest request = new SwitchYardServiceRequest(getServiceName(), getOperationName(), object); + SwitchYardServiceResponse response = getInvoker().invoke(request); + if (response.hasFault()) { + response.logFaultMessage(); + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceInvoker.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceInvoker.java new file mode 100644 index 000000000..3d08a4454 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceInvoker.java @@ -0,0 +1,149 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.service; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; + +/** + * SwitchYardServiceInvoker. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SwitchYardServiceInvoker { + + private final ServiceDomain _serviceDomain; + private final String _targetNamespace; + + /** + * Constructs a new SwitchYardServiceInvoker with the specified service domain. + * @param serviceDomain the service domain + */ + public SwitchYardServiceInvoker(ServiceDomain serviceDomain) { + this(serviceDomain, null); + } + + /** + * Constructs a new SwitchYardServiceInvoker with the specified service domain and target namespace. + * @param serviceDomain the service domain + * @param targetNamespace the target namespace + */ + public SwitchYardServiceInvoker(ServiceDomain serviceDomain, String targetNamespace) { + _serviceDomain = serviceDomain; + _targetNamespace = targetNamespace; + } + + /** + * Gets the service domain. + * @return the service domain + */ + public ServiceDomain getServiceDomain() { + return _serviceDomain; + } + + /** + * Gets the target namespace. + * @return the target namespace + */ + public String getTargetNamespace() { + return _targetNamespace; + } + + /** + * Invokes the request and returns the response. + * @param request the request + * @return the response + */ + public SwitchYardServiceResponse invoke(SwitchYardServiceRequest request) { + Map contextOut = new HashMap(); + Object contentOut = null; + Object fault = null; + try { + QName serviceName = request.getServiceName(); + if (serviceName == null) { + throw CommonKnowledgeMessages.MESSAGES.serviceNameNull(); + } else if (Strings.trimToNull(serviceName.getNamespaceURI()) == null) { + String tns = getTargetNamespace(); + if (tns != null) { + serviceName = XMLHelper.createQName(tns, serviceName.getLocalPart()); + } + } + ServiceDomain serviceDomain = getServiceDomain(); + if (serviceDomain == null) { + throw CommonKnowledgeMessages.MESSAGES.serviceDomainNull(); + } + ServiceReference serviceReference = serviceDomain.getServiceReference(serviceName); + if (serviceReference == null) { + throw CommonKnowledgeMessages.MESSAGES.serviceReferenceNull(serviceName.toString()); + } + final Exchange exchangeIn; + FaultHandler handler = new FaultHandler(); + String operationName = request.getOperationName(); + if (operationName != null) { + exchangeIn = serviceReference.createExchange(operationName, handler); + } else { + exchangeIn = serviceReference.createExchange(handler); + } + Message messageIn = exchangeIn.createMessage(); + Context contextIn = exchangeIn.getContext(messageIn); + for (Map.Entry entry : request.getContext().entrySet()) { + contextIn.setProperty(entry.getKey(), entry.getValue()); + } + Object contentIn = request.getContent(); + if (contentIn != null) { + messageIn.setContent(contentIn); + } + exchangeIn.send(messageIn); + if (ExchangePattern.IN_OUT.equals(exchangeIn.getContract().getConsumerOperation().getExchangePattern())) { + Exchange exchangeOut = handler.waitForOut(); + Message messageOut = exchangeOut.getMessage(); + contentOut = messageOut.getContent(); + for (Property property : exchangeOut.getContext(messageOut).getProperties()) { + contextOut.put(property.getName(), property.getValue()); + } + } + fault = handler.getFault(); + } catch (Throwable t) { + fault = t; + } + return new SwitchYardServiceResponse(contentOut, contextOut, fault); + } + + private static final class FaultHandler extends SynchronousInOutHandler { + private Object _fault; + private Object getFault() { + return _fault; + } + @Override + public void handleFault(Exchange exchange) { + _fault = exchange.getMessage().getContent(); + super.handleFault(exchange); + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceRequest.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceRequest.java new file mode 100644 index 000000000..bf6330e3b --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceRequest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.service; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +/** + * SwitchYardServiceRequest. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SwitchYardServiceRequest { + + private final QName _serviceName; + private final String _operationName; + private final Object _content; + private final Map _context = new HashMap(); + + /** + * Constructs a SwitchYardServiceRequest with the specified service name, operation name, and content. + * @param serviceName the service name + * @param operationName the operation name + * @param content the content + */ + public SwitchYardServiceRequest(QName serviceName, String operationName, Object content) { + this(serviceName, operationName, content, null); + } + + /** + * Constructs a SwitchYardServiceRequest with the specified service name, operation name, content, and context. + * @param serviceName the service name + * @param operationName the operation name + * @param content the content + * @param context the context + */ + public SwitchYardServiceRequest(QName serviceName, String operationName, Object content, Map context) { + _serviceName = serviceName; + _operationName = operationName; + _content = content; + if (context != null) { + _context.putAll(context); + } + } + + /** + * Gets the service name. + * @return the service name + */ + public QName getServiceName() { + return _serviceName; + } + + /** + * Gets the operation name. + * @return the operation name + */ + public String getOperationName() { + return _operationName; + } + + /** + * Gets the content. + * @return the content + */ + public Object getContent() { + return _content; + } + + /** + * Gets the context. + * @return the context + */ + public Map getContext() { + return _context; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceResponse.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceResponse.java new file mode 100644 index 000000000..9376c4d9a --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceResponse.java @@ -0,0 +1,142 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.service; + +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +import org.switchyard.HandlerException; +import org.switchyard.component.common.knowledge.CommonKnowledgeLogger; +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; + +/** + * SwitchYardServiceResponse. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SwitchYardServiceResponse { + + private final Object _content; + private final Map _context = new HashMap(); + private final Object _fault; + + /** + * Constructs a SwitchYardServiceResponse with the specified context, context, and fault. + * @param content the content + * @param context the context + * @param fault the fault + */ + SwitchYardServiceResponse(Object content, Map context, Object fault) { + _content = content; + if (context != null) { + _context.putAll(context); + } + _fault = fault; + } + + /** + * Gets the content. + * @return the content + */ + public Object getContent() { + return _content; + } + + /** + * Gets the context. + * @return the context + */ + public Map getContext() { + return _context; + } + + /** + * If a fault exists. + * @return if a fault exists + */ + public boolean hasFault() { + return getFault(false) != null; + } + + /** + * Gets the unwrapped fault, if it exists. + * @return the unwrapped fault, or null if it doesn't exist + */ + public Object getFault() { + return getFault(true); + } + + /** + * Gets the fault, optionally unwrapping it, or null if it doesn't exist. + * @param unwrap whether to unwrap the fault + * @return the fault, or null if it doesn't exist + */ + public Object getFault(boolean unwrap) { + return unwrap ? unwrapFault(_fault) : _fault; + } + + private Object unwrapFault(Object fault) { + if (fault instanceof HandlerException) { + Throwable cause = ((HandlerException)fault).getCause(); + if (cause != null) { + return unwrapFault(cause); + } + } + if (fault instanceof InvocationTargetException) { + Throwable cause = ((InvocationTargetException)fault).getCause(); + if (cause != null) { + return unwrapFault(cause); + } + } + return fault; + } + + /** + * Gets a fault message, if a fault exists. + * @return the fault message + */ + public String getFaultMessage() { + String fmsg = null; + Object fault = getFault(); + if (fault != null) { + if (fault instanceof Throwable) { + fmsg = String.format(CommonKnowledgeMessages.MESSAGES.faultEncountered() + + " [%s(message=%s)]: %s", fault.getClass().getName(), ((Throwable)fault).getMessage(), fault); + } else { + fmsg = String.format(CommonKnowledgeMessages.MESSAGES.faultEncountered() + + " [%s]: %s", fault.getClass().getName(), fault); + } + } + return fmsg; + } + + /** + * Logs a fault message, if a fault exists. + */ + public void logFaultMessage() { + logFaultMessage(getFaultMessage()); + } + + /** + * Logs a fault message, if specified. + * @param fmsg the fault message + */ + public void logFaultMessage(String fmsg) { + if (fmsg != null) { + CommonKnowledgeLogger.ROOT_LOGGER.formattedFaultMessage(fmsg); + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceTaskHandler.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceTaskHandler.java new file mode 100644 index 000000000..5bfa6cf83 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/service/SwitchYardServiceTaskHandler.java @@ -0,0 +1,279 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.service; + +import static org.switchyard.component.common.knowledge.KnowledgeConstants.FAULT; +import static org.switchyard.component.common.knowledge.KnowledgeConstants.PARAMETER; +import static org.switchyard.component.common.knowledge.KnowledgeConstants.RESULT; + +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.jbpm.bpmn2.handler.WorkItemHandlerRuntimeException; +import org.kie.api.runtime.process.ProcessRuntime; +import org.kie.api.runtime.process.WorkItem; +import org.kie.api.runtime.process.WorkItemHandler; +import org.kie.api.runtime.process.WorkItemManager; +import org.switchyard.SwitchYardException; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.knowledge.CommonKnowledgeLogger; +import org.switchyard.deploy.ComponentNames; + +/** + * SwitchYardServiceTaskHandler. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SwitchYardServiceTaskHandler implements WorkItemHandler { + + /** SwitchYard Service Task. */ + public static final String SWITCHYARD_SERVICE_TASK = "SwitchYard Service Task"; + + /** ServiceName. */ + public static final String SERVICE_NAME = "ServiceName"; + /** Operation. */ + public static final String OPERATION = "Operation"; + /** OperationName. */ + public static final String OPERATION_NAME = OPERATION + "Name"; + /** ParameterName. */ + public static final String PARAMETER_NAME = PARAMETER + "Name"; + /** ResultName. */ + public static final String RESULT_NAME = RESULT + "Name"; + /** FaultName. */ + public static final String FAULT_NAME = FAULT + "Name"; + /** FaultEventId. */ + public static final String FAULT_EVENT_ID = FAULT + "EventId"; + /** FaultAction. */ + public static final String FAULT_ACTION = FAULT + "Action"; + + private QName _componentName; + private SwitchYardServiceInvoker _invoker; + private ProcessRuntime _processRuntime; + + /** + * Constructs a new SwitchYardServiceTaskHandler. + */ + public SwitchYardServiceTaskHandler() {} + + /** + * Gets the component name. + * @return the component name + */ + public QName getComponentName() { + return _componentName; + } + + /** + * Set the component name. + * @param componentName the component name + */ + public void setComponentName(QName componentName) { + _componentName = componentName; + } + + /** + * Gets the invoker. + * @return the invoker + */ + public SwitchYardServiceInvoker getInvoker() { + return _invoker; + } + + /** + * Sets the invoker. + * @param invoker the invoker + */ + public void setInvoker(SwitchYardServiceInvoker invoker) { + _invoker = invoker; + } + + /** + * Gets the ProcessRuntime. + * @return the ProcessRuntime + */ + public ProcessRuntime getProcessRuntime() { + return _processRuntime; + } + + /** + * Sets the ProcessRuntime. + * @param processRuntime the ProcessRuntime + */ + public void setProcessRuntime(ProcessRuntime processRuntime) { + _processRuntime = processRuntime; + } + + /** + * {@inheritDoc} + */ + @Override + public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { + // parameters (input) + Map parameters = workItem.getParameters(); + Object content = null; + String parameterName = getParameterName(parameters); + if (parameterName != null) { + content = parameters.get(parameterName); + } + // service invocation + QName serviceName = getServiceName(parameters); + if (serviceName != null && _componentName != null) { + serviceName = ComponentNames.qualify(_componentName, ComponentNames.unqualify(serviceName)); + } + String operationName = getOperationName(parameters); + SwitchYardServiceRequest request = new SwitchYardServiceRequest(serviceName, operationName, content); + SwitchYardServiceResponse response = getInvoker().invoke(request); + // results (output) + Map results = workItem.getResults(); + String resultName = getResultName(parameters); + if (!response.hasFault()) { + // result (success) + if (resultName != null) { + Object result = response.getContent(); + results.put(resultName, result); + } + manager.completeWorkItem(workItem.getId(), results); + } else { + // fault (failure) + String fmsg = response.getFaultMessage(); + response.logFaultMessage(fmsg); + Object fault = response.getFault(); + String faultName = getFaultName(parameters); + if (faultName != null) { + results.put(faultName, fault); + } + String faultEventId = getFaultEventId(parameters); + if (faultEventId != null) { + getProcessRuntime().signalEvent(faultEventId, fault, workItem.getProcessInstanceId()); + } + FaultAction faultAction = getFaultAction(parameters); + switch (faultAction) { + case ABORT: { + manager.abortWorkItem(workItem.getId()); + break; + } + case COMPLETE: { + manager.completeWorkItem(workItem.getId(), results); + break; + } + case SKIP: { + break; + } + case THROW: { + final RuntimeException runtimeException; + if (fault instanceof RuntimeException) { + runtimeException = (RuntimeException)fault; + } else { + final Throwable cause; + if (fault instanceof Throwable) { + cause = (Throwable)fault; + } else { + cause = new SwitchYardException(fmsg); + cause.fillInStackTrace(); + } + WorkItemHandlerRuntimeException wihre = new WorkItemHandlerRuntimeException(cause, fmsg); + wihre.setStackTrace(cause.getStackTrace()); + wihre.setInformation(SERVICE_NAME, serviceName != null ? serviceName.toString() : null); + wihre.setInformation(OPERATION_NAME, operationName); + wihre.setInformation(PARAMETER_NAME, parameterName); + wihre.setInformation(RESULT_NAME, resultName); + wihre.setInformation(FAULT_NAME, faultName); + wihre.setInformation(FAULT_EVENT_ID, faultEventId); + wihre.setInformation(FAULT_ACTION, faultAction.name()); + wihre.setInformation(WorkItemHandlerRuntimeException.WORKITEMHANDLERTYPE, getClass().getSimpleName()); + runtimeException = wihre; + } + throw runtimeException; + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { + // noop + } + + protected QName getServiceName(Map parameters) { + return getQName(SERVICE_NAME, parameters, null); + } + + protected String getOperationName(Map parameters) { + return getString(OPERATION_NAME, parameters, null); + } + + private String getParameterName(Map parameters) { + return getString(PARAMETER_NAME, parameters, PARAMETER); + } + + private String getResultName(Map parameters) { + return getString(RESULT_NAME, parameters, RESULT); + } + + private String getFaultName(Map parameters) { + return getString(FAULT_NAME, parameters, FAULT); + } + + private String getFaultEventId(Map parameters) { + return getString(FAULT_EVENT_ID, parameters, null); + } + + private FaultAction getFaultAction(Map parameters) { + FaultAction faultAction; + String fa = getString(FAULT_ACTION, parameters, FaultAction.DEFAULT.name()); + try { + faultAction = FaultAction.valueOf(fa.toUpperCase()); + } catch (Throwable t) { + CommonKnowledgeLogger.ROOT_LOGGER.unknownDefaultingTo(FAULT_ACTION, fa, t.getMessage(), FaultAction.DEFAULT.name()); + faultAction = FaultAction.DEFAULT; + } + return faultAction; + } + + protected QName getQName(String parameterName, Map parameters, QName defaultValue) { + Object serviceName = parameters.get(parameterName); + if (serviceName instanceof QName) { + return (QName)serviceName; + } else if (serviceName instanceof String) { + return XMLHelper.createQName((String)serviceName); + } + return defaultValue; + } + + protected String getString(String parameterName, Map parameters, String defaultValue) { + String value = null; + Object p = parameters.get(parameterName); + if (p != null) { + value = Strings.trimToNull(String.valueOf(p)); + } + if (value == null) { + value = defaultValue; + } + return value; + } + + private static enum FaultAction { + ABORT, + COMPLETE, + SKIP, + THROW; + private static final FaultAction DEFAULT = THROW; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/task/PropertiesUserGroupCallback.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/task/PropertiesUserGroupCallback.java new file mode 100644 index 000000000..e2b19c443 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/task/PropertiesUserGroupCallback.java @@ -0,0 +1,127 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.task; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +// SWITCHYARD-1755: internal api usage still required (public APIs insufficient) +import org.kie.internal.task.api.UserGroupCallback; +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.io.pull.PropertiesPuller.PropertiesType; +import org.switchyard.common.io.pull.Puller.PathType; + +/** + * An implementation of a UserGroupCallback based on org.jbpm.services.task.identity.JBossUserGroupCallbackImpl. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class PropertiesUserGroupCallback implements UserGroupCallback { + + private Map> _groupStore = new HashMap>(); + private Set _allGroups = new HashSet(); + + /** + * Constructs a new PropertiesUserGroupCallback. + */ + public PropertiesUserGroupCallback() { + init(System.getProperty("jbpm.user.group.mapping", System.getProperty("jboss.server.config.dir", "target/classes") + "/roles.properties")); + } + + /** + * Constructs a new PropertiesUserGroupCallback. + * @param location the location + */ + public PropertiesUserGroupCallback(String location) { + init(location); + } + + /** + * Constructs a new PropertiesUserGroupCallback. + * @param userGroups the userGroups + */ + public PropertiesUserGroupCallback(Properties userGroups) { + init(userGroups); + } + + private void init(String location) { + if (location.startsWith("classpath:")) { + location = location.replaceFirst("classpath:", ""); + } else if (location.startsWith("file:")) { + location = location.replaceFirst("file:", ""); + } + PropertiesType propertiesType = PropertiesType.PROPERTIES; + if (location != null && location.endsWith(".xml")) { + propertiesType = PropertiesType.XML; + } + Properties userGroups = new PropertiesPuller(propertiesType).pullPath(location, PathType.values()); + init(userGroups); + } + + private void init(Properties userGroups) { + if (userGroups == null) { + userGroups = new Properties(); + } + List groups = null; + Iterator it = userGroups.keySet().iterator(); + while (it.hasNext()) { + String userId = (String) it.next(); + groups = Arrays.asList(userGroups.getProperty(userId, "").split(",")); + _groupStore.put(userId, groups); + _allGroups.addAll(groups); + } + // always add Administrator if not already present + if (!_groupStore.containsKey("Administrator")) { + _groupStore.put("Administrator", Collections.singletonList("Administrators")); + _allGroups.add("Administrators"); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean existsUser(String userId) { + return _groupStore.containsKey(userId); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean existsGroup(String groupId) { + return _allGroups.contains(groupId); + } + + /** + * {@inheritDoc} + */ + @Override + public List getGroupsForUser(String userId, List groupIds, List allExistingGroupIds) { + List groups = _groupStore.get(userId); + if (groups == null) { + groups = new ArrayList(0); + } + return groups; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/KnowledgeJtaPlatform.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/KnowledgeJtaPlatform.java new file mode 100644 index 000000000..4bbc7a9ca --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/KnowledgeJtaPlatform.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.transaction; + +import javax.transaction.TransactionManager; +import javax.transaction.UserTransaction; + +import org.hibernate.HibernateException; +import org.hibernate.service.jta.platform.internal.AbstractJtaPlatform; + +/** + * KnowledgeJtaPlatform. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public class KnowledgeJtaPlatform extends AbstractJtaPlatform { + + /** + * {@inheritDoc} + */ + @Override + protected TransactionManager locateTransactionManager() { + try { + return TransactionManagerLocator.INSTANCE.getTransactionManager(); + } catch (Exception e) { + throw new HibernateException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + protected UserTransaction locateUserTransaction() { + try { + return TransactionManagerLocator.INSTANCE.getUserTransaction(); + } catch (Exception e) { + throw new HibernateException(e); + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/KnowledgeTransactionManagerLookup.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/KnowledgeTransactionManagerLookup.java new file mode 100644 index 000000000..da88f0d7a --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/KnowledgeTransactionManagerLookup.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.transaction; + +import java.util.Properties; + +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; + +import org.hibernate.HibernateException; +import org.hibernate.transaction.TransactionManagerLookup; + +/** + * KnowledgeTransactionManagerLookup. + *

+ * See: jBPM5 on AS7: Lightning ! + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + * @deprecated use {@link KnowledgeJtaPlatform} instead + */ +@Deprecated +public class KnowledgeTransactionManagerLookup implements TransactionManagerLookup { + + /** + * {@inheritDoc} + * @Override + */ + public TransactionManager getTransactionManager(Properties properties) throws HibernateException { + return (TransactionManager)TransactionHelper.getTransactionManager(properties); + } + + /** + * {@inheritDoc} + * @Override + */ + public String getUserTransactionName() { + return TransactionHelper.JNDI_USER_TRANSACTION; + } + + /** + * {@inheritDoc} + * @Override + */ + public Object getTransactionIdentifier(Transaction transaction) { + return transaction; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/OSGiTransactionManagerLocator.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/OSGiTransactionManagerLocator.java new file mode 100644 index 000000000..d99639ff2 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/OSGiTransactionManagerLocator.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.transaction; + +import javax.transaction.TransactionManager; +import javax.transaction.UserTransaction; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; + +/** + * TransactionManagerLocator for OSGi environments. + */ +public class OSGiTransactionManagerLocator extends TransactionManagerLocator { + + private TransactionManager _transactionManager; + private UserTransaction _userTransaction; + + /** + * Create a new OsgiTransactionManagerLocator. + */ + public OSGiTransactionManagerLocator() { + final Bundle bundle = FrameworkUtil.getBundle(getClass()); + final BundleContext context = bundle.getBundleContext(); + _transactionManager = context.getService(context.getServiceReference(TransactionManager.class)); + _userTransaction = context.getService(context.getServiceReference(UserTransaction.class)); + } + + @Override + public TransactionManager getTransactionManager() { + return _transactionManager; + } + + @Override + public UserTransaction getUserTransaction() { + return _userTransaction; + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionHelper.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionHelper.java new file mode 100644 index 000000000..0d4d4921c --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionHelper.java @@ -0,0 +1,164 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.transaction; + +import java.util.Properties; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.transaction.HeuristicMixedException; +import javax.transaction.HeuristicRollbackException; +import javax.transaction.NotSupportedException; +import javax.transaction.RollbackException; +import javax.transaction.Status; +import javax.transaction.SystemException; +import javax.transaction.TransactionManager; +import javax.transaction.UserTransaction; + +import org.jboss.logging.Logger; +import org.switchyard.HandlerException; +import org.switchyard.component.common.knowledge.CommonKnowledgeMessages; + +/** + * TransactionHelper. + * + * @author Tomohisa Igarashi <tigarash@redhat.com> © 2012 Red Hat Inc. + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class TransactionHelper { + private static final Logger LOGGER = Logger.getLogger(TransactionHelper.class); + + /** java:jboss/TransactionManager . */ + public static final String JNDI_TRANSACTION_MANAGER = "java:jboss/TransactionManager"; + /** java:jboss/UserTransaction . */ + public static final String JNDI_USER_TRANSACTION = "java:jboss/UserTransaction"; + + private final boolean _enabled; + private UserTransaction _userTx = null; + private boolean _isInitiator = false; + + /** + * Constructs a new utx helper. + * @param enabled if enabled + */ + public TransactionHelper(boolean enabled) { + _enabled = enabled; + } + + /** + * Begin. + * @throws HandlerException oops + */ + public void begin() throws HandlerException { + if (_enabled) { + try { + _userTx = TransactionManagerLocator.INSTANCE.getUserTransaction(); + if (_userTx.getStatus() == Status.STATUS_NO_TRANSACTION) { + _userTx.begin(); + _isInitiator = true; + } + } catch (SystemException se) { + throw CommonKnowledgeMessages.MESSAGES.userTransactionBeginFailedSystem(se); + } catch (NotSupportedException nse) { + throw CommonKnowledgeMessages.MESSAGES.userTransactionBeginFailedNSE(nse); + } + } + } + + /** + * Commit. + * @throws HandlerException oops + */ + public void commit() throws HandlerException { + if (_isInitiator) { + try { + _userTx.commit(); + } catch (SystemException se) { + throw CommonKnowledgeMessages.MESSAGES.userTransactionCommitFailedSystem(se); + } catch (HeuristicRollbackException hre) { + throw CommonKnowledgeMessages.MESSAGES.userTransactionCommitFailedRollback(hre); + } catch (HeuristicMixedException hme) { + throw CommonKnowledgeMessages.MESSAGES.userTransactionCommitFailedMixed(hme); + } catch (RollbackException re) { + throw CommonKnowledgeMessages.MESSAGES.userTransactionCommitFailed(re); + } + } + } + + /** + * Rollback. + * @throws HandlerException oops + */ + public void rollback() throws HandlerException { + if (_isInitiator) { + try { + _userTx.rollback(); + } catch (SystemException se) { + throw CommonKnowledgeMessages.MESSAGES.userTransactionRollbackFailed(se); + } + } else if (_userTx != null) { + try { + _userTx.setRollbackOnly(); + } catch (SystemException se) { + throw CommonKnowledgeMessages.MESSAGES.userTransactionSetRollbackOnlyFailed(se); + } + } + } + + /** + * Helper method to get the TransactionManager, if possible. + * @return the TransactionManager + */ + public static TransactionManager getTransactionManager() { + return getTransactionManager(null); + } + + /** + * Helper method to get the TransactionManager, if possible. + * @param properties optional jndi initial context properties, or null + * @return the TransactionManager + */ + public static TransactionManager getTransactionManager(Properties properties) { + return (TransactionManager)jndiLookup(JNDI_TRANSACTION_MANAGER, properties); + } + + /** + * Helper method to get the UserTransaction, if possible. + * @return the UserTransaction + */ + public static UserTransaction getUserTransaction() { + return (UserTransaction)jndiLookup(JNDI_USER_TRANSACTION, null); + } + + private static Object jndiLookup(String name, Properties properties) { + Context ctx = null; + try { + ctx = properties != null ? new InitialContext(properties) : new InitialContext(); + return ctx.lookup(name); + } catch (NamingException ne) { + LOGGER.error(ne.getMessage()); + throw new RuntimeException(ne); + } finally { + if (ctx != null) { + try { + ctx.close(); + } catch (Throwable t) { + LOGGER.error(t.getMessage()); + } + } + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionInvocationHandler.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionInvocationHandler.java new file mode 100644 index 000000000..9fe39f2ec --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionInvocationHandler.java @@ -0,0 +1,71 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.transaction; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + +/** + * TransactionInvocationHandler. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class TransactionInvocationHandler implements InvocationHandler { + + private final Object _target; + private final boolean _enabled; + + /** + * Creates a new, enabled TransactionInvocationHandler. + * @param target the target object + */ + public TransactionInvocationHandler(Object target) { + this(target, true); + } + + /** + * Creates a new TransactionInvocationHandler. + * @param target the target object + * @param enabled whether transactions are enabled or not + */ + public TransactionInvocationHandler(Object target, boolean enabled) { + _target = target; + _enabled = enabled; + } + + /** + * {@inheritDoc} + */ + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (_target == null) { + return null; + } else if (!_enabled || Object.class.equals(method.getDeclaringClass())) { + return method.invoke(_target, args); + } else { + Object ret; + TransactionHelper utx = new TransactionHelper(_enabled); + try { + utx.begin(); + ret = method.invoke(_target, args); + utx.commit(); + } catch (Throwable t) { + utx.rollback(); + throw t; + } + return ret; + } + } + +} diff --git a/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionManagerLocator.java b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionManagerLocator.java new file mode 100644 index 000000000..f2c826c82 --- /dev/null +++ b/components/common/knowledge/src/main/java/org/switchyard/component/common/knowledge/transaction/TransactionManagerLocator.java @@ -0,0 +1,60 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.common.knowledge.transaction; + +import javax.transaction.TransactionManager; +import javax.transaction.UserTransaction; + +/** + * Interface providing location services for transaction managers. + */ +public abstract class TransactionManagerLocator { + + /** The locator instance. */ + public static final TransactionManagerLocator INSTANCE; + + /** + * Get the TransactionManager, if possible. + * + * @return the TransactionManager + */ + public abstract TransactionManager getTransactionManager(); + + /** + * Get the UserTransaction, if possible. + * + * @return the UserTransaction + */ + public abstract UserTransaction getUserTransaction(); + + static { + TransactionManagerLocator instance = new TransactionManagerLocator() { + @Override + public UserTransaction getUserTransaction() { + return TransactionHelper.getUserTransaction(); + } + @Override + public TransactionManager getTransactionManager() { + return TransactionHelper.getTransactionManager(); + } + }; + try { + TransactionManagerLocator.class.getClassLoader().loadClass("org.osgi.framework.Bundle"); + instance = new OSGiTransactionManagerLocator(); + } catch (Exception e) { + e.fillInStackTrace(); + } + INSTANCE = instance; + } +} diff --git a/components/common/knowledge/src/main/resources/org/switchyard/common/io/resource/resourceType.properties b/components/common/knowledge/src/main/resources/org/switchyard/common/io/resource/resourceType.properties new file mode 100644 index 000000000..bddd90bc3 --- /dev/null +++ b/components/common/knowledge/src/main/resources/org/switchyard/common/io/resource/resourceType.properties @@ -0,0 +1,28 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +BPMN = Business Process Modeling Notation | .bpmn +BPMN2 = Business Process Modeling Notation 2 | .bpmn2, {BPMN} +BRL = Drools Business Rule Language | .brl +CHANGE_SET = Change Set | .xcs +DESCR = Knowledge Descriptor | .descr +DRF = Drools Rule Flow | .rf +DRL = Drools Rule Language | .drl, .gdrl, .rdrl +DSL = Domain Specific Language | .dsl +DSLR = Drools DSL Rules | .dslr, .rdslr +DTABLE = Decision Table | {XLS}, {CSV} +PMML = Predictive Model Markup Language | .pmml +PKG = Binary Package | .pkg +#SWITCHYARD-1662 +#SCARD = Score Card | .sxls, {XLS} +WID = Work Item Definition | .wid +XDRL = Xml Drools Rule Language | .xdrl diff --git a/components/common/pom.xml b/components/common/pom.xml new file mode 100644 index 000000000..82c711157 --- /dev/null +++ b/components/common/pom.xml @@ -0,0 +1,68 @@ + + + + 4.0.0 + switchyard-component-common-parent + pom + SwitchYard: Common Component Libraries Parent + The parent for SwitchYard Common Component Libraries. + http://switchyard.org + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + + camel + common + knowledge + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-test + test + + + diff --git a/components/http/pom.xml b/components/http/pom.xml new file mode 100644 index 000000000..f7b7983f1 --- /dev/null +++ b/components/http/pom.xml @@ -0,0 +1,129 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-http + bundle + SwitchYard: HTTP Component + + + org.switchyard.component.http.* + + + org.jboss.com.sun.net.httpserver.*;resolution:=optional, + org.switchyard.security.jboss.credential.extractor;resolution:=optional;${switchyard.osgi.import.switchyard.version}, + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-security + + + org.switchyard + switchyard-security-jboss + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.jboss.spec.javax.servlet + jboss-servlet-api_3.0_spec + + + junit + junit + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents + httpcore + + + org.littleshoot + littleproxy + test + + + org.javassist + javassist + + + org.jboss.com.sun.httpserver + httpserver + + + junit + junit + + + + + org.osgi + org.osgi.core + provided + + + org.osgi + org.osgi.compendium + provided + + + diff --git a/components/http/src/main/java/org/switchyard/component/http/ContentType.java b/components/http/src/main/java/org/switchyard/component/http/ContentType.java new file mode 100644 index 000000000..b06faad98 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/ContentType.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http; + +import java.nio.charset.Charset; + +/** + * Content Type place holder. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class ContentType { + + private static final String DEFAULT_MIME_TYPE = "text/plain"; + private static final String CHARSET = "charset"; + + private String _mimeType; + private String _charset; + + /** + * Construct a default content type. + */ + public ContentType() { + _mimeType = DEFAULT_MIME_TYPE; + _charset = Charset.defaultCharset().name(); + } + + /** + * Construct a content type with a Content-Type string. + * @param contentType the Content-Type string + */ + public ContentType(String contentType) { + if (contentType == null) { + _mimeType = DEFAULT_MIME_TYPE; + _charset = Charset.defaultCharset().name(); + } else { + String[] types = contentType.split(";"); + _mimeType = types[0]; + for (int i = 1; i < types.length; i++) { + if (types[i].contains(CHARSET)) { + _charset = types[i].split("=")[1]; + } + } + } + } + + /** + * Get the mime type. + * @return the MimeType + */ + public String getMimeType() { + return _mimeType; + } + + /** + * Set the mime type. + * @param mimeType the mime type to set + */ + public void setMimeType(String mimeType) { + _mimeType = mimeType; + } + + /** + * Get the character encoding. + * @return the charset + */ + public String getCharset() { + return _charset; + } + + /** + * Set the character encoding. + * @param charset the character encoding to set + */ + public void setCharset(String charset) { + _charset = charset; + } + + @Override + public String toString() { + return _mimeType + ";" + CHARSET + "=" + _charset; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/HttpConsumeException.java b/components/http/src/main/java/org/switchyard/component/http/HttpConsumeException.java new file mode 100644 index 000000000..2140f14ea --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/HttpConsumeException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http; + +import org.switchyard.SwitchYardException; + +/** + * Wrapper for HTTP consumer exceptions. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpConsumeException extends SwitchYardException { + private static final long serialVersionUID = 1L; + + /** + * Public constructor. + * @param message Exception message. + */ + public HttpConsumeException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Exception cause. + */ + public HttpConsumeException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Public constructor. + * @param cause Exception cause. + */ + public HttpConsumeException(final Throwable cause) { + super(cause); + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/HttpGatewayServlet.java b/components/http/src/main/java/org/switchyard/component/http/HttpGatewayServlet.java new file mode 100644 index 000000000..693128114 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/HttpGatewayServlet.java @@ -0,0 +1,255 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.jboss.logging.Logger; +import org.switchyard.common.type.Classes; +import org.switchyard.component.http.composer.HttpRequestBindingData; +import org.switchyard.component.http.composer.HttpRequestInfo; +import org.switchyard.component.http.composer.HttpResponseBindingData; +import org.switchyard.security.SecurityServices; + +/** + * Hanldes HTTP requests to invoke a SwitchYard service. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpGatewayServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + private static final Logger LOGGER = Logger.getLogger(HttpGatewayServlet.class); + private static final Map LOCALNAMEMAP = new ConcurrentHashMap(); + + private transient InboundHandler _handler; + private transient ClassLoader _classLoader; + + // request.getLocalName() has proven expensive, so cache it + private static final String getLocalName(HttpServletRequest request) { + String localAddr = request.getLocalAddr(); + String localName = LOCALNAMEMAP.get(localAddr); + if (localName == null) { + localName = request.getLocalName(); + LOCALNAMEMAP.put(localAddr, localName); + } + return localName; + } + + /** + * Set the SwitchYard component handler for this instance. + * @param handler the SwicthYard component handler + */ + public void setHandler(InboundHandler handler) { + _handler = handler; + } + + /** + * Set the ClassLoader to use as a TCCL on execution. + * @param loader ClassLoader + */ + public void setClassLoader(ClassLoader loader) { + _classLoader = loader; + } + + /** + * {@inheritDoc} + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + handle(request, response); + } + + /** + * {@inheritDoc} + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + handle(request, response); + } + + /** + * {@inheritDoc} + */ + public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + handle(request, response); + } + + /** + * {@inheritDoc} + */ + public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + handle(request, response); + } + + /** + * {@inheritDoc} + */ + public void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + handle(request, response); + } + + /** + * {@inheritDoc} + */ + public void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + handle(request, response); + } + + /** + * {@inheritDoc} + */ + public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + handle(request, response); + } + + /** + * Handles a HTTP Servlet request and responds. + * @param request the HttpServletRequest object + * @param response the HttpServletResponse object + * @throws ServletException if any Servlet exception + * @throws IOException if the streams could not be written or read + */ + public void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + HttpRequestBindingData httpRequest = new HttpRequestBindingData(); + try { + httpRequest.setContentType(new ContentType(request.getContentType())); + httpRequest.setBodyFromStream(request.getInputStream()); + for (Enumeration headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) { + String name = headerNames.nextElement(); + for (Enumeration values = request.getHeaders(name); values.hasMoreElements();) { + String value = values.nextElement(); + httpRequest.addHeader(name, value); + } + } + httpRequest.setRequestInfo(getRequestInfo(request)); + } catch (IOException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + HttpLogger.ROOT_LOGGER.unexpectedExceptionWhileReadingRequest(e); + } + ClassLoader origCl = null; + try { + if (_classLoader != null) { + origCl = Classes.setTCCL(_classLoader); + + } + + HttpResponseBindingData httpResponse = _handler.invoke(httpRequest); + if (httpResponse != null) { + Iterator>> entries = httpResponse.getHeaders().entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry> entry = entries.next(); + String name = entry.getKey(); + List values = entry.getValue(); + for (String value : values) { + response.addHeader(name, value); + } + } + if (httpResponse.getBodyBytes() != null) { + response.setStatus(httpResponse.getStatus()); + httpResponse.writeBodyToStream(response.getOutputStream()); + } else { + if (httpResponse.getStatus() != null) { + response.setStatus(httpResponse.getStatus()); + } else { + // Consider it as a One-Way MEP + response.setStatus(HttpServletResponse.SC_ACCEPTED); + response.setContentLength(0); + } + } + } else { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + HttpLogger.ROOT_LOGGER.unexpectedExceptionWhileWritingResponse(e); + } finally { + if (origCl != null) { + Classes.setTCCL(origCl); + } + } + } + + /** + * Method for get request information from a servlet request. + * + * @param request ServletRequest + * @return Request information parsed by servlet container from a servlet request + */ + @SuppressWarnings("unchecked") + public HttpRequestInfo getRequestInfo(HttpServletRequest request) { + HttpRequestInfo requestInfo = new HttpRequestInfo(); + + requestInfo.setAuthType(request.getAuthType()); + requestInfo.setCharacterEncoding(request.getCharacterEncoding()); + requestInfo.setContentType(request.getContentType()); + requestInfo.setContextPath(request.getContextPath()); + requestInfo.setLocalAddr(request.getLocalAddr()); + requestInfo.setLocalName(getLocalName(request)); + requestInfo.setMethod(request.getMethod()); + requestInfo.setProtocol(request.getProtocol()); + requestInfo.setQueryString(request.getQueryString()); + requestInfo.setRemoteAddr(request.getRemoteAddr()); + requestInfo.setRemoteHost(request.getRemoteHost()); + requestInfo.setRemoteUser(request.getRemoteUser()); + requestInfo.setContentLength(request.getContentLength()); + requestInfo.setRequestSessionId(request.getRequestedSessionId()); + requestInfo.setRequestURI(request.getRequestURI()); + requestInfo.setScheme(request.getScheme()); + requestInfo.setServerName(request.getServerName()); + requestInfo.setRequestPath(request.getServletPath()); + + String pathInfo = request.getPathInfo(); + requestInfo.setPathInfo(pathInfo); + + if (pathInfo != null) { + List pathInfoTokens = requestInfo.getPathInfoTokens(); + + pathInfoTokens.addAll(Arrays.asList(request.getPathInfo().split("/"))); + + // remove empty tokens... + Iterator tokensIterator = pathInfoTokens.iterator(); + while (tokensIterator.hasNext()) { + if (tokensIterator.next().trim().length() == 0) { + tokensIterator.remove(); + } + } + } + + // Http Query params... + Map paramMap = request.getParameterMap(); + if (paramMap != null) { + requestInfo.getQueryParams().putAll(paramMap); + } + + // Credentials... + requestInfo.getCredentials().addAll(SecurityServices.getServletRequestCredentialExtractor().extract(request)); + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace(requestInfo); + } + return requestInfo; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/HttpLogger.java b/components/http/src/main/java/org/switchyard/component/http/HttpLogger.java new file mode 100644 index 000000000..311c87116 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/HttpLogger.java @@ -0,0 +1,65 @@ +package org.switchyard.component.http; + +import java.io.IOException; + +import org.jboss.logging.Cause; +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 36000-36399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface HttpLogger { + /** + * A root logger with the category of the package name. + */ + HttpLogger ROOT_LOGGER = Logger.getMessageLogger(HttpLogger.class, HttpLogger.class.getPackage().getName()); + + /** + * unableToLaunchStandaloneHttpServer method definition. + * @param ioe the ioe + */ + @LogMessage(level = Level.ERROR) + @Message(id = 36000, value = "Unable to launch standalone http server") + void unableToLaunchStandaloneHttpServer(@Cause IOException ioe); + + /** + * unexpectedExceptionWhileReadingRequest method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 36001, value = "Unexpected Exception while reading request") + void unexpectedExceptionWhileReadingRequest(@Cause IOException e); + + /** + * unexpectedExceptionWhileWritingResponse method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 36002, value = "Unexpected Exception while writing response") + void unexpectedExceptionWhileWritingResponse(@Cause Exception e); + + /** + * unexpectedExceptionWhileHandlingHttpRequest method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 36003, value = "Unexpected Exception while handling http request") + void unexpectedExceptionWhileHandlingHttpRequest(@Cause Exception e); + + /** + * unexpectedExceptionInvokingSwitchyardServcie method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 36004, value = "Unexpected Exception invoking SwitchYard service") + void unexpectedExceptionInvokingSwitchyardServcie(@Cause Exception e); + +} + diff --git a/components/http/src/main/java/org/switchyard/component/http/HttpMessages.java b/components/http/src/main/java/org/switchyard/component/http/HttpMessages.java new file mode 100644 index 000000000..4f3734384 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/HttpMessages.java @@ -0,0 +1,90 @@ +package org.switchyard.component.http; + +import java.net.MalformedURLException; +import java.util.Set; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; +import org.switchyard.metadata.ServiceOperation; +/** + *

+ * This file is using the subset 36400-36799 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface HttpMessages { + /** + * The default messages. + */ + HttpMessages MESSAGES = Messages.getBundle(HttpMessages.class); + + /** + * unableToFindPublisher method definition. + * @param e the e + * @return HttpPublishException + */ + @Message(id = 36400, value = "Unable to find any Http Endpoint Publisher") + HttpPublishException unableToFindPublisher(@Cause Exception e); + + /** + * unableToPublish method definition. + * @param e the e + * @return HttpPublishException + */ + @Message(id = 36401, value = "Unable to publish HttpEndpoint") + HttpPublishException unableToPublish(@Cause Exception e); + + /** + * unexpectedFault method definition. + * @return IllegalStateException + */ + @Message(id = 36402, value = "Unexpected fault occurred, please see log file for more information") + IllegalStateException unexpectedFault(); + + /** + * unexpectedMessage method definition. + * @return IllegalStateException + */ + @Message(id = 36403, value = "Unexpected message, please see log for more information") + IllegalStateException unexpectedMessage(); + + /** + * moreThanOneOperationSelector method definition. + * @param operations the operations + * @return SwitchYardException + */ + @Message(id = 36404, value = "No operationSelector was configured for the Http Component and the Service Interface contains more than one operation: %s. Please add an operationSelector element.") + SwitchYardException moreThanOneOperationSelector(Set operations); + + /** + * invalidHttpURL method definition. + * @param mue the mue + * @return HttpConsumeException + */ + @Message(id = 36405, value = "The address URL seem to be invalid") + HttpConsumeException invalidHttpURL(@Cause MalformedURLException mue); + + /** + * bindingNotStarted method definition. + * @param _referenceName the _referenceName + * @param _bindingName the _bindingName + * @return HandlerException + */ + @Message(id = 36406, value = "Reference binding '%s/%s' is not started.") + HandlerException bindingNotStarted(String _referenceName, String _bindingName); + + /** + * unexpectedExceptionHandlingHTTPMessage method definition. + * @param e the e + * @return HandlerException + */ + @Message(id = 36407, value = "Unexpected exception handling HTTP Message") + HandlerException unexpectedExceptionHandlingHTTPMessage(@Cause Exception e); + +} + diff --git a/components/http/src/main/java/org/switchyard/component/http/HttpPublishException.java b/components/http/src/main/java/org/switchyard/component/http/HttpPublishException.java new file mode 100644 index 000000000..a08a60ffa --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/HttpPublishException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http; + +import org.switchyard.SwitchYardException; + +/** + * Wrapper for HTTP creation exceptions. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpPublishException extends SwitchYardException { + private static final long serialVersionUID = 1L; + + /** + * Public constructor. + * @param message Exception message. + */ + public HttpPublishException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Exception cause. + */ + public HttpPublishException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Public constructor. + * @param cause Exception cause. + */ + public HttpPublishException(final Throwable cause) { + super(cause); + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/InboundHandler.java b/components/http/src/main/java/org/switchyard/component/http/InboundHandler.java new file mode 100644 index 000000000..7ccfc3e5b --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/InboundHandler.java @@ -0,0 +1,170 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http; + +import java.util.Set; + +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.selector.OperationSelectorFactory; +import org.switchyard.component.http.composer.HttpBindingData; +import org.switchyard.component.http.composer.HttpComposition; +import org.switchyard.component.http.composer.HttpRequestBindingData; +import org.switchyard.component.http.composer.HttpResponseBindingData; +import org.switchyard.component.http.config.model.HttpBindingModel; +import org.switchyard.component.http.endpoint.EndpointPublisherFactory; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.security.context.SecurityContextManager; +import org.switchyard.selector.OperationSelector; + +/** + * Hanldes HTTP requests to invoke a SwitchYard service. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class InboundHandler extends BaseServiceHandler { + + private final HttpBindingModel _config; + private final String _gatewayName; + private SecurityContextManager _securityContextManager; + private ServiceDomain _domain; + private ServiceReference _serviceRef; + private MessageComposer _messageComposer; + private final OperationSelector _operationSelector; + private Endpoint _endpoint; + + /** + * Constructor. + * @param config the configuration settings + * @param domain the service domain + */ + public InboundHandler(final HttpBindingModel config, ServiceDomain domain) { + super(domain); + _config = config; + _gatewayName = config.getName(); + _domain = domain; + _securityContextManager = new SecurityContextManager(_domain); + _operationSelector = OperationSelectorFactory + .getOperationSelectorFactory(HttpBindingData.class) + .newOperationSelector(config.getOperationSelector()); + } + + /** + * Start lifecycle. + * + * @throws HttpPublishException If unable to publish the service + */ + @Override + protected void doStart() throws HttpPublishException { + try { + _serviceRef = _domain.getServiceReference(_config.getServiceName()); + String contextPath = _config.getContextPath(); + if (contextPath == null) { + contextPath = "/"; + } + _endpoint = EndpointPublisherFactory.getPublisher().publish(_domain, contextPath, this); + // Create and configure the HTTP message composer + _messageComposer = HttpComposition.getMessageComposer(_config); + } catch (Exception e) { + throw HttpMessages.MESSAGES.unableToPublish(e); + } + _endpoint.start(); + } + + /** + * Invokes the SwitchYard service. + * + * @param input the HTTP request message + * @return the HTTP response message from invocation + */ + public HttpResponseBindingData invoke(final HttpRequestBindingData input) { + HttpResponseBindingData response = null; + try { + SynchronousInOutHandler inOutHandler = new SynchronousInOutHandler(); + Exchange exchange = _serviceRef.createExchange(getOperationName(input), inOutHandler); + + // identify ourselves + exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _gatewayName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + + Message message = _messageComposer.compose(input, exchange); + _securityContextManager.addCredentials(exchange, input.extractCredentials()); + if (exchange.getContract().getConsumerOperation().getExchangePattern() == ExchangePattern.IN_ONLY) { + exchange.send(message); + if (exchange.getState().equals(ExchangeState.FAULT)) { + response = (HttpResponseBindingData) _messageComposer.decompose(exchange, new HttpResponseBindingData()); + } else { + response = new HttpResponseBindingData(); + } + } else { + exchange.send(message); + exchange = inOutHandler.waitForOut(); + response = (HttpResponseBindingData) _messageComposer.decompose(exchange, new HttpResponseBindingData()); + } + } catch (Exception e) { + HttpLogger.ROOT_LOGGER.unexpectedExceptionInvokingSwitchyardServcie(e); + } + return response; + } + + /** + * Stop lifecycle. + */ + @Override + protected void doStop() { + _endpoint.stop(); + } + + @Override + public void handleFault(Exchange exchange) { + throw HttpMessages.MESSAGES.unexpectedFault(); + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + throw HttpMessages.MESSAGES.unexpectedMessage(); + } + + private String getOperationName(HttpRequestBindingData message) throws Exception { + String operationName = null; + if (_operationSelector != null) { + operationName = _operationSelector.selectOperation(message).getLocalPart(); + } + + if (operationName == null) { + final Set operations = _serviceRef.getInterface().getOperations(); + if (operations.size() != 1) { + throw HttpMessages.MESSAGES.moreThanOneOperationSelector(operations); + } + final ServiceOperation serviceOperation = operations.iterator().next(); + operationName = serviceOperation.getName(); + } + + return operationName; + + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/OutboundHandler.java b/components/http/src/main/java/org/switchyard/component/http/OutboundHandler.java new file mode 100644 index 000000000..e3f94ca47 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/OutboundHandler.java @@ -0,0 +1,294 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.jboss.logging.Logger; +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.ChallengeState; +import org.apache.http.auth.Credentials; +import org.apache.http.auth.NTCredentials; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.auth.params.AuthPNames; +import org.apache.http.client.AuthCache; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpHead; +import org.apache.http.client.methods.HttpOptions; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.params.AuthPolicy; +import org.apache.http.client.protocol.ClientContext; +import org.apache.http.client.utils.HttpClientUtils; +import org.apache.http.conn.params.ConnRoutePNames; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.BasicHttpContext; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.http.composer.HttpComposition; +import org.switchyard.component.http.composer.HttpBindingData; +import org.switchyard.component.http.composer.HttpRequestBindingData; +import org.switchyard.component.http.composer.HttpResponseBindingData; +import org.switchyard.component.http.config.model.HttpBindingModel; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * Handles invoking external HTTP services. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class OutboundHandler extends BaseServiceHandler { + + private static final Logger LOGGER = Logger.getLogger(OutboundHandler.class); + + private static final String HTTP_GET = "GET"; + private static final String HTTP_POST = "POST"; + private static final String HTTP_DELETE = "DELETE"; + private static final String HTTP_HEAD = "HEAD"; + private static final String HTTP_PUT = "PUT"; + private static final String HTTP_OPTIONS = "OPTIONS"; + + private final HttpBindingModel _config; + private final String _bindingName; + private final String _referenceName; + private MessageComposer _messageComposer; + private String _baseAddress = "http://localhost:8080"; + private String _httpMethod = HTTP_GET; + private String _contentType; + private AuthScope _authScope; + private AuthCache _authCache; + private Credentials _credentials; + private HttpHost _proxyHost; + private Integer _timeout; + + /** + * Constructor. + * @param config the configuration settings + * @param domain the service domain + */ + public OutboundHandler(final HttpBindingModel config, final ServiceDomain domain) { + super(domain); + _config = config; + _bindingName = config.getName(); + _referenceName = config.getReference().getName(); + } + + /** + * Start lifecycle. + * + * @throws HttpConsumeException If unable to load or access a HTTP uri + */ + @Override + protected void doStart() throws HttpConsumeException { + String address = _config.getAddress(); + if (address != null) { + _baseAddress = address; + } + String method = _config.getMethod(); + if (method != null) { + _httpMethod = method; + } + String contentType = _config.getContentType(); + if (contentType != null) { + _contentType = contentType; + } + // Create and configure the HTTP message composer + _messageComposer = HttpComposition.getMessageComposer(_config); + + if (_config.hasAuthentication()) { + // Set authentication + if (_config.isBasicAuth()) { + _authScope = createAuthScope(_config.getBasicAuthConfig().getHost(), _config.getBasicAuthConfig().getPort(), _config.getBasicAuthConfig().getRealm()); + _credentials = new UsernamePasswordCredentials(_config.getBasicAuthConfig().getUser(), _config.getBasicAuthConfig().getPassword()); + // Create AuthCache instance + _authCache = new BasicAuthCache(); + _authCache.put(new HttpHost(_authScope.getHost(), _authScope.getPort()), new BasicScheme(ChallengeState.TARGET)); + } else { + _authScope = createAuthScope(_config.getNtlmAuthConfig().getHost(), _config.getNtlmAuthConfig().getPort(), _config.getNtlmAuthConfig().getRealm()); + _credentials = new NTCredentials(_config.getNtlmAuthConfig().getUser(), + _config.getNtlmAuthConfig().getPassword(), + "", + _config.getNtlmAuthConfig().getDomain()); + } + } + if (_config.getProxyConfig() != null) { + if (_config.getProxyConfig().getPort() != null) { + _proxyHost = new HttpHost(_config.getProxyConfig().getHost(), Integer.valueOf(_config.getProxyConfig().getPort()).intValue()); + } else { + _proxyHost = new HttpHost(_config.getProxyConfig().getHost(), -1); + } + if (_config.getProxyConfig().getUser() != null) { + _authScope = createAuthScope(_config.getProxyConfig().getHost(), _config.getProxyConfig().getPort(), null); + _credentials = new UsernamePasswordCredentials(_config.getProxyConfig().getUser(), _config.getProxyConfig().getPassword()); + if (_authCache == null) { + _authCache = new BasicAuthCache(); + } + _authCache.put(_proxyHost, new BasicScheme(ChallengeState.PROXY)); + } + } + _timeout = _config.getTimeout(); + } + + private AuthScope createAuthScope(String host, String portStr, String realm) throws HttpConsumeException { + URL url = null; + try { + url = new URL(_baseAddress); + } catch (MalformedURLException mue) { + throw HttpMessages.MESSAGES.invalidHttpURL(mue); + } + if (realm == null) { + realm = AuthScope.ANY_REALM; + } + int port = url.getPort(); + if (host == null) { + host = url.getHost(); + } + if (portStr != null) { + port = Integer.valueOf(portStr).intValue(); + } + return new AuthScope(host, port, realm); + } + + /** + * The handler method that invokes the actual HTTP service when the + * component is used as a HTTP consumer. + * @param exchange the Exchange + * @throws HandlerException handler exception + */ + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + // identify ourselves + exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + if (getState() != State.STARTED) { + throw HttpMessages.MESSAGES.bindingNotStarted(_referenceName, _bindingName); + } + + HttpClient httpclient = new DefaultHttpClient(); + if (_timeout != null) { + HttpParams httpParams = httpclient.getParams(); + HttpConnectionParams.setConnectionTimeout(httpParams, _timeout); + HttpConnectionParams.setSoTimeout(httpParams, _timeout); + } + try { + if (_credentials != null) { + ((DefaultHttpClient)httpclient).getCredentialsProvider().setCredentials(_authScope, _credentials); + List authpref = new ArrayList(); + authpref.add(AuthPolicy.NTLM); + authpref.add(AuthPolicy.BASIC); + httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); + } + if (_proxyHost != null) { + httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxyHost); + } + HttpBindingData httpRequest = _messageComposer.decompose(exchange, new HttpRequestBindingData()); + HttpRequestBase request = null; + if (_httpMethod.equals(HTTP_GET)) { + request = new HttpGet(_baseAddress); + } else if (_httpMethod.equals(HTTP_POST)) { + request = new HttpPost(_baseAddress); + ((HttpPost) request).setEntity(new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())); + } else if (_httpMethod.equals(HTTP_DELETE)) { + request = new HttpDelete(_baseAddress); + } else if (_httpMethod.equals(HTTP_HEAD)) { + request = new HttpHead(_baseAddress); + } else if (_httpMethod.equals(HTTP_PUT)) { + request = new HttpPut(_baseAddress); + ((HttpPut) request).setEntity(new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())); + } else if (_httpMethod.equals(HTTP_OPTIONS)) { + request = new HttpOptions(_baseAddress); + } + Iterator>> entries = httpRequest.getHeaders().entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry> entry = entries.next(); + String name = entry.getKey(); + List values = entry.getValue(); + for (String value : values) { + request.addHeader(name, value); + } + } + if (_contentType != null) { + request.addHeader("Content-Type", _contentType); + } + + HttpResponse response = null; + if ((_credentials != null) && (_credentials instanceof NTCredentials)) { + // Send a request for the Negotiation + response = httpclient.execute(new HttpGet(_baseAddress)); + HttpClientUtils.closeQuietly(response); + } + if (_authCache != null) { + BasicHttpContext context = new BasicHttpContext(); + context.setAttribute(ClientContext.AUTH_CACHE, _authCache); + response = httpclient.execute(request, context); + } else { + response = httpclient.execute(request); + } + int status = response.getStatusLine().getStatusCode(); + + HttpEntity entity = response.getEntity(); + HttpResponseBindingData httpResponse = new HttpResponseBindingData(); + Header[] headers = response.getAllHeaders(); + for (Header header : headers) { + httpResponse.addHeader(header.getName(), header.getValue()); + } + if (entity != null) { + if (entity.getContentType() != null) { + httpResponse.setContentType(new ContentType(entity.getContentType().getValue())); + } else { + httpResponse.setContentType(new ContentType()); + } + httpResponse.setBodyFromStream(entity.getContent()); + } + httpResponse.setStatus(status); + Message out = _messageComposer.compose(httpResponse, exchange); + if (httpResponse.getStatus() < 400) { + exchange.send(out); + } else { + exchange.sendFault(out); + } + } catch (Exception e) { + throw HttpMessages.MESSAGES.unexpectedExceptionHandlingHTTPMessage(e); + } finally { + // When HttpClient instance is no longer needed, + // shut down the connection manager to ensure + // immediate deallocation of all system resources + httpclient.getConnectionManager().shutdown(); + } + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpBindingData.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpBindingData.java new file mode 100644 index 000000000..31713f81e --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpBindingData.java @@ -0,0 +1,227 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.composer; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.component.common.composer.BindingData; +import org.switchyard.component.http.ContentType; + +/** + * HTTP binding data that wraps the headers and body. + * + * @author Magesh Kumar B © 2012 Red Hat Inc. + */ +public abstract class HttpBindingData implements BindingData { + + private Map> _headers; + private byte[] _body; + private ContentType _contentType; + + /** + * Get the HTTP headers map. + * @return a Map of headers + */ + public Map> getHeaders() { + if (_headers == null) { + _headers = new HashMap>(); + } + return _headers; + } + + /** + * Set the HTTP headers map. + * @param headers a Map of headers + */ + public void setHeaders(Map> headers) { + _headers = headers; + } + + /** + * Add a HTTP header. + * @param name the name of the header + * @param values a List of header values + */ + public void addHeader(String name, List values) { + if (_headers == null) { + _headers = new HashMap>(); + } + _headers.put(name, values); + } + + /** + * Add a HTTP header. + * @param name the name of the header + * @param value a header value + */ + public void addHeader(String name, String value) { + if (_headers == null) { + _headers = new HashMap>(); + } + List values = _headers.get(name); + if (values == null) { + values = new ArrayList(); + _headers.put(name, values); + } + values.add(value); + } + + /** + * Get the HTTP body. + * @return the body as a StringReader + * @throws UnsupportedEncodingException if content encoding is not supported + */ + public StringReader getBody() throws UnsupportedEncodingException { + String body = null; + if ((_contentType != null) && (_contentType.getCharset() != null)) { + body = new String(_body, _contentType.getCharset()); + } else { + body = new String(_body); + } + return new StringReader(body); + } + + /** + * Get the HTTP body. + * @return the body as a String + * @throws UnsupportedEncodingException if content encoding is not supported + */ + public String getBodyAsString() throws UnsupportedEncodingException { + String body = null; + if ((_contentType != null) && (_contentType.getCharset() != null)) { + body = new String(_body, _contentType.getCharset()); + } else { + body = new String(_body); + } + return body; + } + + /** + * Get the HTTP body as byte array. + * @return the body + */ + public ByteArrayInputStream getBodyBytes() { + if (_body != null) { + return new ByteArrayInputStream(_body); + } else { + return null; + } + } + + /** + * Set the HTTP body using a stream. + * @param is the body as InputStream + * @throws IOException if content could not be read + */ + public void setBodyFromStream(InputStream is) throws IOException { + if (is != null) { + ByteArrayOutputStream tmp = new ByteArrayOutputStream(); + byte[] buff = new byte[512]; + int buffSize = 0; + while ((buffSize = is.read(buff)) >= 0) { + tmp.write(buff, 0, buffSize); + } + _body = tmp.toByteArray(); + is.close(); + } else { + _body = null; + } + } + + /** + * Set the HTTP body using a reader. + * @param reader the body as Reader + * @throws IOException if content could not be read + */ + public void setBodyFromReader(Reader reader) throws IOException { + if (reader != null) { + StringWriter tmp = new StringWriter(); + char[] buff = new char[512]; + int buffSize = 0; + while ((buffSize = reader.read(buff)) >= 0) { + tmp.write(buff, 0, buffSize); + } + _body = tmp.toString().getBytes(); + reader.close(); + } else { + _body = null; + } + } + + /** + * Writes the HTTP body to a stream. + * @param os an OutputStream to write to + * @throws IOException if content could not be written + */ + public void writeBodyToStream(OutputStream os) throws IOException { + if (os != null) { + os.write(_body); + os.close(); + } + } + + /** + * Set the HTTP body. + * @param body the body as String + */ + public void setBody(String body) { + if (_contentType != null) { + _body = body.getBytes(Charset.forName(_contentType.getCharset())); + } else { + _body = body.getBytes(); + } + } + + /** + * Set the HTTP body. + * @param body the body as byte array + */ + public void setBodyBytes(byte[] body) { + if (body != null) { + _body = body.clone(); + } else { + _body = null; + } + } + + /** + * Get the HTTP body's content type. + * @return the content type + */ + public ContentType getContentType() { + return _contentType; + } + + /** + * Set the HTTP body's content type. + * @param contentType the content type + */ + public void setContentType(ContentType contentType) { + _contentType = contentType; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpComposition.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpComposition.java new file mode 100644 index 000000000..617ac6e22 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpComposition.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.composer; + +import org.switchyard.component.common.composer.Composition; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.http.config.model.HttpBindingModel; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; + +/** + * Utility class for HTTP-specific Composition. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class HttpComposition { + + /** The http_request_info property name. */ + public static final String HTTP_REQUEST_INFO = "http_request_info"; + + /** + * Uses the {@link Composition} class to create a HTTP-specific MessageComposer. + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer() { + return Composition.getMessageComposer(HttpBindingData.class); + } + + /** + * Uses the {@link Composition} class to create a HTTP-specific MessageComposer. + * @param hbm a HttpBindingModel to get configuration details from + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer(HttpBindingModel hbm) { + ContextMapperModel cmm = hbm != null ? hbm.getContextMapper() : null; + MessageComposerModel mcm = hbm != null ? hbm.getMessageComposer() : null; + MessageComposer mc = Composition.getMessageComposer(HttpBindingData.class, cmm, mcm); + if (mc instanceof HttpMessageComposer && mcm != null) { + HttpMessageComposer smc = (HttpMessageComposer)mc; + smc.setComposerConfig(mcm); + } + return mc; + } + + private HttpComposition() {} + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpContextMapper.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpContextMapper.java new file mode 100644 index 000000000..dc6273045 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpContextMapper.java @@ -0,0 +1,114 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.composer; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.component.common.composer.BaseRegexContextMapper; +import org.switchyard.component.common.label.ComponentLabel; +import org.switchyard.component.common.label.EndpointLabel; + +/** + * HttpContextMapper. + * + * @author Magesh Kumar B © 2012 Red Hat Inc. + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class HttpContextMapper extends BaseRegexContextMapper { + + /** + * The HTTP responce code. + */ + public static final String HTTP_RESPONSE_STATUS = "http_response_status"; + + private static final String[] HTTP_LABELS = new String[]{ComponentLabel.HTTP.label(), EndpointLabel.HTTP.label()}; + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(HttpBindingData source, Context context) throws Exception { + if (source instanceof HttpResponseBindingData) { + HttpResponseBindingData response = (HttpResponseBindingData) source; + context.setProperty(HTTP_RESPONSE_STATUS, response.getStatus()).addLabels(HTTP_LABELS); + } else { + HttpRequestBindingData request = (HttpRequestBindingData) source; + if (request.getRequestInfo() != null) { + context.setProperty(HttpComposition.HTTP_REQUEST_INFO, request.getRequestInfo()).addLabels(HTTP_LABELS); + } + } + Iterator>> entries = source.getHeaders().entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry> entry = entries.next(); + String name = entry.getKey(); + if (matches(name)) { + List values = entry.getValue(); + if ((values != null) && (values.size() == 1)) { + context.setProperty(name, values.get(0)).addLabels(HTTP_LABELS); + } else if ((values != null) && (values.size() > 1)) { + context.setProperty(name, values).addLabels(HTTP_LABELS); + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public void mapTo(Context context, HttpBindingData target) throws Exception { + Map> httpHeaders = target.getHeaders(); + for (Property property : context.getProperties()) { + String name = property.getName(); + Object value = property.getValue(); + if ((value != null) && (matches(name) || property.hasLabel(EndpointLabel.HTTP.label()))) { + if (HTTP_RESPONSE_STATUS.equalsIgnoreCase(name) && (target instanceof HttpResponseBindingData)) { + HttpResponseBindingData response = (HttpResponseBindingData)target; + if (value instanceof String) { + response.setStatus(Integer.parseInt((String) value)); + } else if (value instanceof Integer) { + response.setStatus((Integer) value); + } + } else { + if (value instanceof List) { + // We need to check through the list for non-string values and map .toString() + // values to those entries + List vals = new ArrayList(); + List valueList = (List)value; + for (Object obj : valueList) { + if (obj instanceof String) { + vals.add((String) obj); + } else { + vals.add(obj.toString()); + } + } + + httpHeaders.put(name, vals); + } else if (value instanceof String) { + List list = new ArrayList(); + list.add(String.valueOf(value)); + httpHeaders.put(name, list); + } + } + } + } + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpContextMapperFactory.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpContextMapperFactory.java new file mode 100644 index 000000000..63d1ae398 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpContextMapperFactory.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.composer; + +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.ContextMapperFactory; + +/** + * HttpContextMapperFactory. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpContextMapperFactory extends ContextMapperFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return HttpBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper newContextMapperDefault() { + return new HttpContextMapper(); + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpMessageComposer.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpMessageComposer.java new file mode 100644 index 000000000..5e14d0087 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpMessageComposer.java @@ -0,0 +1,131 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.composer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; + +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeState; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.component.common.composer.BaseMessageComposer; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.config.model.composer.MessageComposerModel; + +/** + * The HTTP implementation of MessageComposer simply copies the HTTP body into + * the Message and HTTP headers into the Message's context, and vice-versa. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpMessageComposer extends BaseMessageComposer { + + private MessageComposerModel _config; + + /** + * {@inheritDoc} + */ + @Override + public Message compose(HttpBindingData source, Exchange exchange) throws Exception { + final Message message = exchange.createMessage(); + + getContextMapper().mapFrom(source, exchange.getContext(message)); + + QName msgType = getMessageType(exchange); + message.setContent(source.getBody()); + Object content; + if ((msgType != null) && (QNameUtil.isJavaMessageType(msgType))) { + // Hack - the getContent() call triggers a conversion from native content type and the result is set as the new body + message.setContent(message.getContent(QNameUtil.toJavaMessageType(msgType))); + } + + return message; + } + + /** + * {@inheritDoc} + */ + @Override + public HttpBindingData decompose(Exchange exchange, HttpBindingData target) throws Exception { + final Message message = exchange.getMessage(); + if (message != null) { + Object content = message.getContent(); + if (target instanceof HttpResponseBindingData) { + Property responseCode = exchange.getContext().getProperty(HttpContextMapper.HTTP_RESPONSE_STATUS); + if (!((responseCode != null) && responseCode.hasLabel(EndpointLabel.HTTP.label()))) { + int status = HttpServletResponse.SC_ACCEPTED; + if (exchange.getState() == ExchangeState.FAULT) { + status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; + } else if (content == null) { + status = HttpServletResponse.SC_NO_CONTENT; + } else if (content instanceof HttpResponseBindingData) { + status = ((HttpResponseBindingData) content).getStatus(); + } else if ((content instanceof String) || (content instanceof byte[]) + || (content instanceof InputStream) || (content instanceof Reader)) { + status = HttpServletResponse.SC_OK; + } else { + status = HttpServletResponse.SC_BAD_GATEWAY; + } + HttpResponseBindingData response = (HttpResponseBindingData) target; + response.setStatus(status); + } + } + setContent(content, target); + } + + getContextMapper().mapTo(exchange.getContext(), target); + + return target; + } + + private void setContent(final Object content, HttpBindingData message) throws IOException { + if (content == null) { + message.setBodyBytes(null); + } else if (content instanceof String) { + message.setBody((String) content); + } else if (content instanceof byte[]) { + message.setBodyBytes((byte[]) content); + } else if (content instanceof InputStream) { + message.setBodyFromStream((InputStream) content); + } else if (content instanceof Reader) { + message.setBodyFromReader((Reader) content); + } else { + message.setBody("" + content); + } + } + + /** + * Gets the MessageComposerModel config. + * @return the MessageComposerModel + */ + public MessageComposerModel getComposerConfig() { + return _config; + } + + /** + * Sets the MessageComposerModel config. + * @param composerConfig configuration + */ + public void setComposerConfig(MessageComposerModel composerConfig) { + _config = composerConfig; + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpMessageComposerFactory.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpMessageComposerFactory.java new file mode 100644 index 000000000..16d4340e4 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpMessageComposerFactory.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.composer; + +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.MessageComposerFactory; + +/** + * HttpMessageComposerFactory. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpMessageComposerFactory extends MessageComposerFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return HttpBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer newMessageComposerDefault() { + return new HttpMessageComposer(); + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpRequestBindingData.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpRequestBindingData.java new file mode 100644 index 000000000..186b4b417 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpRequestBindingData.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.composer; + +import java.util.Collections; +import java.util.Set; + +import org.switchyard.component.common.composer.SecurityBindingData; +import org.switchyard.security.credential.Credential; + +/** + * HTTP request binding data. + * + * @author Magesh Kumar B © 2012 Red Hat Inc. + */ +public class HttpRequestBindingData extends HttpBindingData implements SecurityBindingData { + private HttpRequestInfo _requestInfo; + + /** + * @return the requestInfo + */ + public HttpRequestInfo getRequestInfo() { + return _requestInfo; + } + + /** + * @param requestInfo the requestInfo to set + */ + public void setRequestInfo(HttpRequestInfo requestInfo) { + _requestInfo = requestInfo; + } + + /** + * {@inheritDoc} + */ + @Override + public Set extractCredentials() { + return _requestInfo != null ? _requestInfo.getCredentials() : Collections.emptySet(); + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpRequestInfo.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpRequestInfo.java new file mode 100644 index 000000000..f51d6be43 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpRequestInfo.java @@ -0,0 +1,393 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.composer; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.switchyard.security.credential.Credential; + +/** + * Wrapper for HTTP request details. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpRequestInfo implements Serializable { + + private static final long serialVersionUID = -859903642423693992L; + + private String _authType; + private String _characterEncoding; + private String _contentType; + private String _contextPath; + private String _localAddr; + private String _localName; + private String _method; + private String _pathInfo; + private String _protocol; + private String _queryString; + private String _remoteAddr; + private String _remoteHost; + private String _remoteUser; + private int _contentLength; + private String _requestSessionId; + private String _requestURI; + private String _scheme; + private String _serverName; + private String _requestPath; + private List _pathInfoTokens = new ArrayList(); + private Map _queryParams = new HashMap(); + private Set _credentials = new HashSet(); + + /** + * @return _the authType + */ + public String getAuthType() { + return _authType; + } + + /** + * @param authType the authType to set + */ + public void setAuthType(String authType) { + _authType = authType; + } + + /** + * @return _the characterEncoding + */ + public String getCharacterEncoding() { + return _characterEncoding; + } + + /** + * @param characterEncoding the characterEncoding to set + */ + public void setCharacterEncoding(String characterEncoding) { + _characterEncoding = characterEncoding; + } + + /** + * @return _the contextPath + */ + public String getContextPath() { + return _contextPath; + } + + /** + * @param contextPath the contextPath to set + */ + public void setContextPath(String contextPath) { + _contextPath = contextPath; + } + + /** + * @return _the contentType + */ + public String getContentType() { + return _contentType; + } + + /** + * @param contentType the contentType to set + */ + public void setContentType(String contentType) { + _contentType = contentType; + } + + /** + * @return _the localAddr + */ + public String getLocalAddr() { + return _localAddr; + } + + /** + * @param localAddr the localAddr to set + */ + public void setLocalAddr(String localAddr) { + _localAddr = localAddr; + } + + /** + * @return _the localName + */ + public String getLocalName() { + return _localName; + } + + /** + * @param localName the localName to set + */ + public void setLocalName(String localName) { + _localName = localName; + } + + /** + * @return _the method + */ + public String getMethod() { + return _method; + } + + /** + * @param method the method to set + */ + public void setMethod(String method) { + _method = method; + } + + /** + * @return _the pathInfo + */ + public String getPathInfo() { + return _pathInfo; + } + + /** + * @param pathInfo the pathInfo to set + */ + public void setPathInfo(String pathInfo) { + _pathInfo = pathInfo; + } + + /** + * @return _the protocol + */ + public String getProtocol() { + return _protocol; + } + + /** + * @param protocol the protocol to set + */ + public void setProtocol(String protocol) { + _protocol = protocol; + } + + /** + * @return _the queryString + */ + public String getQueryString() { + return _queryString; + } + + /** + * @param queryString the queryString to set + */ + public void setQueryString(String queryString) { + _queryString = queryString; + } + + /** + * @return _the remoteAddr + */ + public String getRemoteAddr() { + return _remoteAddr; + } + + /** + * @param remoteAddr the remoteAddr to set + */ + public void setRemoteAddr(String remoteAddr) { + _remoteAddr = remoteAddr; + } + + /** + * @return _the remoteHost + */ + public String getRemoteHost() { + return _remoteHost; + } + + /** + * @param remoteHost the remoteHost to set + */ + public void setRemoteHost(String remoteHost) { + _remoteHost = remoteHost; + } + + /** + * @return _the remoteUser + */ + public String getRemoteUser() { + return _remoteUser; + } + + /** + * @param remoteUser the remoteUser to set + */ + public void setRemoteUser(String remoteUser) { + _remoteUser = remoteUser; + } + + /** + * @return _the contentLength + */ + public int getContentLength() { + return _contentLength; + } + + /** + * @param contentLength the contentLength to set + */ + public void setContentLength(int contentLength) { + _contentLength = contentLength; + } + + /** + * @return _the requestSessionId + */ + public String getRequestSessionId() { + return _requestSessionId; + } + + /** + * @param requestSessionId the requestSessionId to set + */ + public void setRequestSessionId(String requestSessionId) { + _requestSessionId = requestSessionId; + } + + /** + * @return _the requestURI + */ + public String getRequestURI() { + return _requestURI; + } + + /** + * @param requestURI the requestURI to set + */ + public void setRequestURI(String requestURI) { + _requestURI = requestURI; + } + + /** + * @return _the scheme + */ + public String getScheme() { + return _scheme; + } + + /** + * @param scheme the scheme to set + */ + public void setScheme(String scheme) { + _scheme = scheme; + } + + /** + * @return _the serverName + */ + public String getServerName() { + return _serverName; + } + + /** + * @param serverName the serverName to set + */ + public void setServerName(String serverName) { + _serverName = serverName; + } + + /** + * @return _the requestPath + */ + public String getRequestPath() { + return _requestPath; + } + + /** + * @param requestPath the requestPath to set + */ + public void setRequestPath(String requestPath) { + _requestPath = requestPath; + } + + /** + * @return _the pathInfoTokens + */ + public List getPathInfoTokens() { + return _pathInfoTokens; + } + + /** + * @param pathInfoTokens the pathInfoTokens to set + */ + public void setPathInfoTokens(List pathInfoTokens) { + _pathInfoTokens = pathInfoTokens; + } + + /** + * @return _the queryParams + */ + public Map getQueryParams() { + return _queryParams; + } + + /** + * @param queryParams the queryParams to set + */ + public void setQueryParams(Map queryParams) { + _queryParams = queryParams; + } + + /** + * @param name the name of the parameter + * @param value the value of the parameter + */ + public void addQueryParam(String name, String value) { + String[] values = _queryParams.get(name); + if (values == null) { + _queryParams.put(name, new String[]{value}); + } else { + String[] newValues= new String[values.length + 1]; + System.arraycopy(values, 0, newValues, 0, values.length); + System.arraycopy(new String[]{value}, 0, newValues, values.length, 1); + } + } + + /** + * Gets the credentials. + * @return the credentials + */ + public Set getCredentials() { + return _credentials; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "HttpRequestInfo [authType=" + _authType + ", characterEncoding=" + + _characterEncoding + ", contentType=" + _contentType + + ", contextPath=" + _contextPath + ", localAddr=" + _localAddr + + ", localName=" + _localName + ", method=" + _method + + ", pathInfo=" + _pathInfo + ", protocol=" + _protocol + + ", queryString=" + _queryString + ", remoteAddr=" + _remoteAddr + + ", remoteHost=" + _remoteHost + ", remoteUser=" + _remoteUser + + ", contentLength=" + _contentLength + ", requestSessionId=" + + _requestSessionId + ", requestURI=" + _requestURI + ", scheme=" + + _scheme + ", serverName=" + _serverName + ", requestPath=" + + _requestPath + ", pathInfoTokens=" + _pathInfoTokens + + ", queryParams=" + _queryParams + ", credentials=" + _credentials + "]"; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/composer/HttpResponseBindingData.java b/components/http/src/main/java/org/switchyard/component/http/composer/HttpResponseBindingData.java new file mode 100644 index 000000000..265bb50d8 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/composer/HttpResponseBindingData.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.composer; + +/** + * HTTP response binding data. + * + * @author Magesh Kumar B © 2012 Red Hat Inc. + */ +public class HttpResponseBindingData extends HttpBindingData { + + private Integer _status; + + /** + * Get the HTTP response status. + * @return HTTP response status + */ + public Integer getStatus() { + return _status; + } + + /** + * Set the HTTP response status. + * @param status the response status + */ + public void setStatus(Integer status) { + _status = status; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/BasicAuthModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/BasicAuthModel.java new file mode 100644 index 000000000..2b7342a97 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/BasicAuthModel.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.config.model; + +import org.switchyard.config.model.Model; + +/** + * A Basic Authentication Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface BasicAuthModel extends Model { + + /** + * Get user name. + * @return authentication username + */ + public String getUser(); + + /** + * Set user name. + * @param user the user name + * @return this BasicAuthModel + */ + public BasicAuthModel setUser(String user); + + /** + * Get user password. + * @return authentication password + */ + public String getPassword(); + + /** + * Set user password. + * @param password the user password + * @return this BasicAuthModel + */ + public BasicAuthModel setPassword(String password); + + /** + * Get authentication realm. + * @return authentication realm + */ + public String getRealm(); + + /** + * Set authentication realm. + * @param realm the authentication realm + * @return this BasicAuthModel + */ + public BasicAuthModel setRealm(String realm); + + /** + * Get host. + * @return authentication host + */ + public String getHost(); + + /** + * Set host. + * @param host the authentication host + * @return this BasicAuthModel + */ + public BasicAuthModel setHost(String host); + + /** + * Get authentication port. + * @return authentication port + */ + public String getPort(); + + /** + * Set authentication port. + * @param port the authentication port + * @return this BasicAuthModel + */ + public BasicAuthModel setPort(String port); + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/HttpBindingModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/HttpBindingModel.java new file mode 100644 index 000000000..dd3f09c8e --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/HttpBindingModel.java @@ -0,0 +1,181 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.config.model; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.composite.BindingModel; + +/** + * A HTTP binding model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface HttpBindingModel extends BindingModel { + + /** + * Prefix for HTTP Gateway Configuration. + */ + public static final String HTTP = "http"; + + /** + * Returns the HTTP Service name. + * + * @return the serviceName + */ + public QName getServiceName(); + + /** + * Sets the HTTP Service name. + * + * @param serviceName the serviceName to set + * @return this HttpBindingModel + */ + public HttpBindingModel setServiceName(QName serviceName); + + /** + * Gets the Endpoint's context path. + * + * @return the endpoint contextPath + */ + public String getContextPath(); + + /** + * Sets the HTTP URL. + * + * @param contextPath the endpoint contextPath + * @return this HttpBindingModel + */ + public HttpBindingModel setContextPath(String contextPath); + + /** + * Gets the HTTP URL. + * + * @return the endpoint address + */ + public String getAddress(); + + /** + * Sets the HTTP URL. + * + * @param address the endpoint address + * @return this HttpBindingModel + */ + public HttpBindingModel setAddress(String address); + + /** + * Gets the HTTP method. + * + * @return the HTTP method + */ + public String getMethod(); + + /** + * Sets the HTTP method. + * + * @param method the HTTP method + * @return this HttpBindingModel + */ + public HttpBindingModel setMethod(String method); + + /** + * Gets the HTTP request's Content-Type. + * + * @return the content type + */ + public String getContentType(); + + /** + * Sets the HTTP request's Content-Type. + * + * @param contentType the content type + * @return this HttpBindingModel + */ + public HttpBindingModel setContentType(String contentType); + + /** + * Gets the request's time-out value. + * + * @return the time-out value + */ + public Integer getTimeout(); + + /** + * Sets the request's time-out value. + * + * @param timeout the time-out value + * @return this HttpBindingModel + */ + public HttpBindingModel setTimeout(Integer timeout); + + /** + * Sets the global configuration. + * + * @param config the environment/global config + */ + public void setEnvironment(Configuration config); + + /** + * Gets the basic config. + * @return the basic config + */ + public BasicAuthModel getBasicAuthConfig(); + + /** + * Sets the basic config. + * @param config the basic config + * @return this HttpBindingModel + */ + public HttpBindingModel setBasicAuthConfig(BasicAuthModel config); + + /** + * Gets the ntlm config. + * @return the ntlm config + */ + public NtlmAuthModel getNtlmAuthConfig(); + + /** + * Sets the ntlm config. + * @param config the ntlm config + * @return this HttpBindingModel + */ + public HttpBindingModel setNtlmAuthConfig(NtlmAuthModel config); + + /** + * Gets the proxy config. + * @return the proxy config + */ + public ProxyModel getProxyConfig(); + + /** + * Sets the proxy config. + * @param proxyConfig the proxy config + * @return this HttpBindingModel (useful for chaining) + */ + public HttpBindingModel setProxyConfig(ProxyModel proxyConfig); + + /** + * Check if Basic authentication is set. + * @return true if Basic, false otherwise + */ + public Boolean isBasicAuth(); + + /** + * Check if authentication is set. + * @return true if set, false otherwise + */ + public Boolean hasAuthentication(); +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/HttpNameValueModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/HttpNameValueModel.java new file mode 100644 index 000000000..cd8c166e8 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/HttpNameValueModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.config.model; + +import org.switchyard.config.model.Model; + +/** + * A HTTP value model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface HttpNameValueModel extends Model { + + /** Known XML element names. */ + public enum HttpName { + /** Known XML element names. */ + address, contextPath, method, contentType, basic, ntlm, user, password, realm, domain, host, port, proxy, timeout; + } + + /** + * Gets the name. + * @return the name + */ + public HttpName getName(); + + /** + * Gets the value. + * @return the value + */ + public String getValue(); + + /** + * Sets the value. + * @param value the value + * @return this HttpValueModel (useful for chaining) + */ + public HttpNameValueModel setValue(String value); + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/HttpNamespace.java b/components/http/src/main/java/org/switchyard/component/http/config/model/HttpNamespace.java new file mode 100644 index 000000000..022f22a9d --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/HttpNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.config.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Http config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum HttpNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new HttpNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + HttpNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the HttpNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the HttpNamespace + */ + public static HttpNamespace fromUri(String uri) { + return Util.fromUri(HttpNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(HttpNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-http:config", version); + } + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/NtlmAuthModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/NtlmAuthModel.java new file mode 100644 index 000000000..b2649c618 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/NtlmAuthModel.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.config.model; + +/** + * A NTLM Authentication Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface NtlmAuthModel extends BasicAuthModel { + + /** + * Get the NTLM domain. + * @return domain name + */ + public String getDomain(); + + /** + * Set the NTLM domain. + * @param domain the domain name + * @return this NTLMAuthModel + */ + public NtlmAuthModel setDomain(String domain); +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/ProxyModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/ProxyModel.java new file mode 100644 index 000000000..5d2eb275b --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/ProxyModel.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.config.model; + +import org.switchyard.config.model.Model; + +/** + * A Proxy Configuration Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface ProxyModel extends Model { + + /** + * Get host. + * @return authentication host + */ + public String getHost(); + + /** + * Set host. + * @param host the authentication host + * @return this ProxyModel + */ + public ProxyModel setHost(String host); + + /** + * Get authentication port. + * @return authentication port + */ + public String getPort(); + + /** + * Set authentication port. + * @param port the authentication port + * @return this ProxyModel + */ + public ProxyModel setPort(String port); + + /** + * Get user name. + * @return authentication username + */ + public String getUser(); + + /** + * Set user name. + * @param user the user name + * @return this ProxyModel + */ + public ProxyModel setUser(String user); + + /** + * Get user password. + * @return authentication password + */ + public String getPassword(); + + /** + * Set user password. + * @param password the user password + * @return this ProxyModel + */ + public ProxyModel setPassword(String password); + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1BasicAuthModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1BasicAuthModel.java new file mode 100644 index 000000000..9d5cdb02c --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1BasicAuthModel.java @@ -0,0 +1,183 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.config.model.v1; + +import org.switchyard.component.http.config.model.BasicAuthModel; +import org.switchyard.component.http.config.model.HttpNameValueModel; +import org.switchyard.component.http.config.model.HttpNameValueModel.HttpName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A BasicAuthModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1BasicAuthModel extends BaseModel implements BasicAuthModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + HttpName.user.name(), + HttpName.password.name(), + HttpName.realm.name(), + HttpName.host.name(), + HttpName.port.name() + }; + + private HttpNameValueModel _user; + private HttpNameValueModel _password; + private HttpNameValueModel _realm; + private HttpNameValueModel _host; + private HttpNameValueModel _port; + + /** + * Creates a new BasicAuthModel. + * @param namespace namespace + */ + public V1BasicAuthModel(String namespace) { + super(namespace, HttpName.basic.name()); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new BasicAuthModel. + * @param namespace namespace + * @param name the name of the model + */ + public V1BasicAuthModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new BasicAuthModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1BasicAuthModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * {@inheritDoc} + */ + public String getUser() { + if (_user == null) { + _user = getNameValue(HttpName.user); + } + return _user != null ? _user.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setUser(String user) { + _user = setNameValue(_user, HttpName.user, user); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPassword() { + if (_password == null) { + _password = getNameValue(HttpName.password); + } + return _password != null ? _password.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setPassword(String password) { + _password = setNameValue(_password, HttpName.password, password); + return this; + } + + /** + * {@inheritDoc} + */ + public String getRealm() { + if (_realm == null) { + _realm = getNameValue(HttpName.realm); + } + return _realm != null ? _realm.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setRealm(String realm) { + _realm = setNameValue(_realm, HttpName.realm, realm); + return this; + } + + /** + * {@inheritDoc} + */ + public String getHost() { + if (_host == null) { + _host = getNameValue(HttpName.host); + } + return _host != null ? _host.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setHost(String host) { + _host = setNameValue(_host, HttpName.host, host); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPort() { + if (_port == null) { + _port = getNameValue(HttpName.port); + } + return _port != null ? _port.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setPort(String port) { + _port = setNameValue(_port, HttpName.port, port); + return this; + } + + protected HttpNameValueModel getNameValue(HttpName name) { + return (HttpNameValueModel)getFirstChildModel(name.name()); + } + + protected HttpNameValueModel setNameValue(HttpNameValueModel model, HttpName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1HttpNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpBindingModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpBindingModel.java new file mode 100644 index 000000000..9b3bda6e9 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpBindingModel.java @@ -0,0 +1,288 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.component.http.config.model.BasicAuthModel; +import org.switchyard.component.http.config.model.HttpBindingModel; +import org.switchyard.component.http.config.model.HttpNameValueModel; +import org.switchyard.component.http.config.model.HttpNameValueModel.HttpName; +import org.switchyard.component.http.config.model.NtlmAuthModel; +import org.switchyard.component.http.config.model.ProxyModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1BindingModel; + +/** + * A HTTP binding model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1HttpBindingModel extends V1BindingModel implements HttpBindingModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + HttpName.address.name(), + HttpName.contextPath.name(), + HttpName.method.name(), + HttpName.contentType.name(), + HttpName.timeout.name(), + HttpName.basic.name(), + HttpName.ntlm.name(), + HttpName.proxy.name() + }; + + private Configuration _environment; + private QName _serviceName; + + private HttpNameValueModel _wsdl; + private HttpNameValueModel _contextPath; + private HttpNameValueModel _address; + private HttpNameValueModel _method; + private HttpNameValueModel _contentType; + private HttpNameValueModel _timeout; + private BasicAuthModel _basicAuth; + private NtlmAuthModel _ntlmAuth; + private ProxyModel _proxyConfig; + + /** + * Constructor. + * @param namespace namespace + */ + public V1HttpBindingModel(String namespace) { + super(HTTP, namespace); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Create a V1HttpBindingModel using configuration and descriptor. + * + * @param config the HttpGateway configuration + * @param desc the HttpGateway descriptor + */ + public V1HttpBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * {@inheritDoc} + */ + public QName getServiceName() { + if (_serviceName == null) { + _serviceName = isServiceBinding() ? getService().getQName() : getReference().getQName(); + } + return _serviceName; + } + + /** + * {@inheritDoc} + */ + public HttpBindingModel setServiceName(QName serviceName) { + _serviceName = serviceName; + return this; + } + + /** + * {@inheritDoc} + */ + public String getContextPath() { + if (_contextPath == null) { + _contextPath = getNameValue(HttpName.contextPath); + } + return _contextPath != null ? _contextPath.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public HttpBindingModel setContextPath(String contextPath) { + _contextPath = setNameValue(_contextPath, HttpName.contextPath, contextPath); + return this; + } + + /** + * {@inheritDoc} + */ + public String getAddress() { + if (_address == null) { + _address = getNameValue(HttpName.address); + } + return _address != null ? _address.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public HttpBindingModel setAddress(String address) { + _address = setNameValue(_address, HttpName.address, address); + return this; + } + + /** + * {@inheritDoc} + */ + public String getMethod() { + if (_method == null) { + _method = getNameValue(HttpName.method); + } + return _method != null ? _method.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public HttpBindingModel setMethod(String method) { + _method = setNameValue(_method, HttpName.method, method); + return this; + } + + /** + * {@inheritDoc} + */ + public String getContentType() { + if (_contentType == null) { + _contentType = getNameValue(HttpName.contentType); + } + return _contentType != null ? _contentType.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public HttpBindingModel setContentType(String contentType) { + _contentType = setNameValue(_contentType, HttpName.contentType, contentType); + return this; + } + + /** + * {@inheritDoc} + */ + public Integer getTimeout() { + if (_timeout == null) { + _timeout = getNameValue(HttpName.timeout); + } + return _timeout != null ? Integer.valueOf(_timeout.getValue()) : null; + } + + /** + * {@inheritDoc} + */ + public HttpBindingModel setTimeout(Integer timeout) { + _timeout = setNameValue(_timeout, HttpName.timeout, String.valueOf(timeout)); + return this; + } + + /** + * {@inheritDoc} + */ + public void setEnvironment(Configuration config) { + _environment = config; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel getBasicAuthConfig() { + if (_basicAuth == null) { + _basicAuth = (BasicAuthModel)getFirstChildModel(HttpName.basic.name()); + } + return _basicAuth; + } + + /** + * {@inheritDoc} + */ + public HttpBindingModel setBasicAuthConfig(BasicAuthModel config) { + setChildModel(config); + _basicAuth = config; + return this; + } + + /** + * {@inheritDoc} + */ + public NtlmAuthModel getNtlmAuthConfig() { + if (_ntlmAuth == null) { + _ntlmAuth = (NtlmAuthModel)getFirstChildModel(HttpName.ntlm.name()); + } + return _ntlmAuth; + } + + /** + * {@inheritDoc} + */ + public HttpBindingModel setNtlmAuthConfig(NtlmAuthModel config) { + setChildModel(config); + _ntlmAuth = config; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ProxyModel getProxyConfig() { + if (_proxyConfig == null) { + _proxyConfig = (ProxyModel)getFirstChildModel(HttpName.proxy.name()); + } + return _proxyConfig; + } + + /** + * {@inheritDoc} + */ + @Override + public HttpBindingModel setProxyConfig(ProxyModel proxyConfig) { + setChildModel(proxyConfig); + _proxyConfig = proxyConfig; + return this; + } + + /** + * {@inheritDoc} + */ + public Boolean isBasicAuth() { + return (getBasicAuthConfig() != null) ? true : false; + } + + /** + * {@inheritDoc} + */ + public Boolean hasAuthentication() { + return ((getBasicAuthConfig() != null) || (getNtlmAuthConfig() != null)) ? true : false; + } + + private HttpNameValueModel getNameValue(HttpName name) { + return (HttpNameValueModel)getFirstChildModel(name.name()); + } + + private HttpNameValueModel setNameValue(HttpNameValueModel model, HttpName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1HttpNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpMarshaller.java b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpMarshaller.java new file mode 100644 index 000000000..64cbb28df --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpMarshaller.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.config.model.v1; + +import org.switchyard.component.http.config.model.HttpNameValueModel.HttpName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.composer.v1.V1ContextMapperModel; +import org.switchyard.config.model.composer.v1.V1MessageComposerModel; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Marshaller for HTTP Gateway configurations. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class V1HttpMarshaller extends BaseMarshaller { + + /** + * Construct a HTTP Model Marshaller with help of a Descriptor. + * + * @param desc the Descriptor + */ + public V1HttpMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads a HTTP Model configuration. + * + * @param config the configuration + * @return the HTTP Binding Model + */ + @Override + public Model read(Configuration config) { + Descriptor desc = getDescriptor(); + String name = config.getName(); + if (name.startsWith(BindingModel.BINDING)) { + return new V1HttpBindingModel(config, getDescriptor()); + } else if (name.equals(ContextMapperModel.CONTEXT_MAPPER)) { + return new V1ContextMapperModel(config, getDescriptor()); + } else if (name.equals(MessageComposerModel.MESSAGE_COMPOSER)) { + return new V1MessageComposerModel(config, getDescriptor()); + } else if (name.equals(HttpName.basic.name())) { + return new V1BasicAuthModel(config, getDescriptor()); + } else if (name.equals(HttpName.ntlm.name())) { + return new V1NtlmAuthModel(config, getDescriptor()); + } else if (name.equals(HttpName.proxy.name())) { + return new V1ProxyModel(config, desc); + } else { + for (HttpName n : HttpName.values()) { + if (n.name().equals(name)) { + return new V1HttpNameValueModel(config, desc); + } + } + } + return null; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpNameValueModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpNameValueModel.java new file mode 100644 index 000000000..29369afe3 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1HttpNameValueModel.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.config.model.v1; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.http.config.model.HttpNameValueModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version HttpNameValueModel. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1HttpNameValueModel extends BaseModel implements HttpNameValueModel { + + /** + * Creates a new V1HttpNameValueModel. + * @param namespace namespace + * @param name the HttpName + */ + public V1HttpNameValueModel(String namespace, HttpName name) { + super(XMLHelper.createQName(namespace, name.name())); + } + + /** + * Creates a new V1HttpNameValueModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1HttpNameValueModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public HttpName getName() { + return HttpName.valueOf(getModelConfiguration().getName()); + } + + /** + * {@inheritDoc} + */ + @Override + public String getValue() { + return getModelValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public HttpNameValueModel setValue(String value) { + setModelValue(value); + return this; + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1NtlmAuthModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1NtlmAuthModel.java new file mode 100644 index 000000000..38d9d1efc --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1NtlmAuthModel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.config.model.v1; + +import org.switchyard.component.http.config.model.NtlmAuthModel; +import org.switchyard.component.http.config.model.HttpNameValueModel; +import org.switchyard.component.http.config.model.HttpNameValueModel.HttpName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A NtlmAuthModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1NtlmAuthModel extends V1BasicAuthModel implements NtlmAuthModel { + + private HttpNameValueModel _domain; + + /** + * Creates a new NtlmAuthModel. + * @param namespace namespace + */ + public V1NtlmAuthModel(String namespace) { + super(namespace, HttpName.ntlm.name()); + } + + /** + * Creates a new NtlmAuthModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1NtlmAuthModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + public String getDomain() { + if (_domain == null) { + _domain = getNameValue(HttpName.domain); + } + return _domain != null ? _domain.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public NtlmAuthModel setDomain(String domain) { + _domain = setNameValue(_domain, HttpName.domain, domain); + return this; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1ProxyModel.java b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1ProxyModel.java new file mode 100644 index 000000000..9e23cac3d --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/config/model/v1/V1ProxyModel.java @@ -0,0 +1,163 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.config.model.v1; + +import org.switchyard.component.http.config.model.HttpNameValueModel; +import org.switchyard.component.http.config.model.HttpNameValueModel.HttpName; +import org.switchyard.component.http.config.model.ProxyModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A ProxyModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1ProxyModel extends BaseModel implements ProxyModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + HttpName.host.name(), + HttpName.port.name(), + HttpName.user.name(), + HttpName.password.name() + }; + + private HttpNameValueModel _host; + private HttpNameValueModel _port; + private HttpNameValueModel _user; + private HttpNameValueModel _password; + + /** + * Creates a new ProxyModel. + * @param namespace namespace + */ + public V1ProxyModel(String namespace) { + super(namespace, HttpName.proxy.name()); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new ProxyModel. + * @param namespace namespace + * @param name the name of the model + */ + public V1ProxyModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new ProxyModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ProxyModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * {@inheritDoc} + */ + public String getHost() { + if (_host == null) { + _host = getNameValue(HttpName.host); + } + return _host != null ? _host.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setHost(String host) { + _host = setNameValue(_host, HttpName.host, host); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPort() { + if (_port == null) { + _port = getNameValue(HttpName.port); + } + return _port != null ? _port.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public String getUser() { + if (_user == null) { + _user = getNameValue(HttpName.user); + } + return _user != null ? _user.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setUser(String user) { + _user = setNameValue(_user, HttpName.user, user); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPassword() { + if (_password == null) { + _password = getNameValue(HttpName.password); + } + return _password != null ? _password.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setPassword(String password) { + _password = setNameValue(_password, HttpName.password, password); + return this; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setPort(String port) { + _port = setNameValue(_port, HttpName.port, port); + return this; + } + + protected HttpNameValueModel getNameValue(HttpName name) { + return (HttpNameValueModel)getFirstChildModel(name.name()); + } + + protected HttpNameValueModel setNameValue(HttpNameValueModel model, HttpName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1HttpNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/deploy/HttpActivator.java b/components/http/src/main/java/org/switchyard/component/http/deploy/HttpActivator.java new file mode 100644 index 000000000..91606a1dd --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/deploy/HttpActivator.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.component.http.InboundHandler; +import org.switchyard.component.http.OutboundHandler; +import org.switchyard.component.http.config.model.HttpBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; + + +/** + * HTTP Activator. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpActivator extends BaseActivator { + + static final String HTTP_TYPE = "http"; + private Configuration _environment; + + /** + * Creates a new activator for HTTP service. + */ + public HttpActivator() { + super(HTTP_TYPE); + } + + @Override + public ServiceHandler activateBinding(QName name, BindingModel config) { + HttpBindingModel binding = (HttpBindingModel)config; + binding.setEnvironment(_environment); + + if (binding.isServiceBinding()) { + return new InboundHandler(binding, getServiceDomain()); + } else { + return new OutboundHandler(binding, getServiceDomain()); + } + } + + @Override + public void deactivateBinding(QName name, ServiceHandler handler) { + // Nothing to do here + } + + /** + * Set the Environment configuration for the activator. + * @param config The global environment configuration. + */ + public void setEnvironment(Configuration config) { + _environment = config; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/deploy/HttpComponent.java b/components/http/src/main/java/org/switchyard/component/http/deploy/HttpComponent.java new file mode 100644 index 000000000..1bdd9653d --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/deploy/HttpComponent.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.deploy; + +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * An implementation of HTTP component. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpComponent extends BaseComponent { + + /** + * Default constructor. + */ + public HttpComponent() { + super(HttpActivator.HTTP_TYPE); + setName("HttpComponent"); + } + + /** + * {@inheritDoc} + */ + @Override + public Activator createActivator(ServiceDomain domain) { + HttpActivator activator = new HttpActivator(); + activator.setServiceDomain(domain); + activator.setEnvironment(getConfig()); + return activator; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/endpoint/EndpointPublisher.java b/components/http/src/main/java/org/switchyard/component/http/endpoint/EndpointPublisher.java new file mode 100644 index 000000000..cc16fe95e --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/endpoint/EndpointPublisher.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.endpoint; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.http.InboundHandler; + +/** + * Interface for allowing SwitchYard to publish HTTP endpoint. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public interface EndpointPublisher { + + /** + * Publish a HTTP endpoint. + * @param domain The ServiceDomain for the application + * @param context The web context root where the resource need to be published + * @param handler A handler instance + * @return The published endpoint holder + * @throws Exception if endpoint could not be published + */ + Endpoint publish(ServiceDomain domain, String context, InboundHandler handler) throws Exception; +} diff --git a/components/http/src/main/java/org/switchyard/component/http/endpoint/EndpointPublisherFactory.java b/components/http/src/main/java/org/switchyard/component/http/endpoint/EndpointPublisherFactory.java new file mode 100644 index 000000000..83e1a854a --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/endpoint/EndpointPublisherFactory.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.endpoint; + +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.component.http.HttpMessages; + +/** + * Factory for creating Resource publisher. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class EndpointPublisherFactory { + + private static EndpointPublisher PUBLISHER; + + + private EndpointPublisherFactory() { + } + + /** + * Creates an EndpointPublisher based on the environment. + * @return The EndpointPublisher + */ + public static EndpointPublisher getPublisher() { + return PUBLISHER; + } + + static { + try { + PUBLISHER = ProviderRegistry.getProvider(EndpointPublisher.class); + if (PUBLISHER == null) { + PUBLISHER = new StandaloneEndpointPublisher(); + } + } catch (Exception e) { + throw HttpMessages.MESSAGES.unableToFindPublisher(e); + } + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/endpoint/OsgiHttpEndpoint.java b/components/http/src/main/java/org/switchyard/component/http/endpoint/OsgiHttpEndpoint.java new file mode 100644 index 000000000..de2504bae --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/endpoint/OsgiHttpEndpoint.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.endpoint; + +import org.osgi.service.http.HttpService; +import org.switchyard.component.common.Endpoint; + +/** + * An OSGi HTTP endpoint. + */ +public class OsgiHttpEndpoint implements Endpoint { + + private HttpService _httpService; + private String _alias; + + /** + * Create a new OsgiHttpEndpoint. + * + * @param service the OSGi HTTP service + * @param alias the alias for which this endpoint was registered + */ + public OsgiHttpEndpoint(HttpService service, String alias) { + _httpService = service; + _alias = alias; + } + + @Override + public void start() { + } + + @Override + public void stop() { + _httpService.unregister(_alias); + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/endpoint/OsgiHttpEndpointPublisher.java b/components/http/src/main/java/org/switchyard/component/http/endpoint/OsgiHttpEndpointPublisher.java new file mode 100644 index 000000000..5d12e8f24 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/endpoint/OsgiHttpEndpointPublisher.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.endpoint; + +import org.osgi.service.http.HttpService; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.http.HttpGatewayServlet; +import org.switchyard.component.http.InboundHandler; + +/** + * Publishes HTTP endpoint via OSGi HttpService. + */ +public class OsgiHttpEndpointPublisher implements EndpointPublisher { + + private HttpService _httpService; + + /** + * @param httpService the OSGi HTTP service + */ + public void setHttpService(HttpService httpService) { + _httpService = httpService; + } + + @Override + public Endpoint publish(ServiceDomain domain, String context, InboundHandler handler) throws Exception { + String alias = "/" + context; + HttpGatewayServlet servlet = new HttpGatewayServlet(); + servlet.setHandler(handler); + servlet.setClassLoader(Classes.getTCCL()); + _httpService.registerServlet(alias, servlet, null, null); + return new OsgiHttpEndpoint(_httpService, alias); + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/endpoint/StandaloneEndpoint.java b/components/http/src/main/java/org/switchyard/component/http/endpoint/StandaloneEndpoint.java new file mode 100644 index 000000000..c53cec4b0 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/endpoint/StandaloneEndpoint.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.endpoint; + +import org.jboss.com.sun.net.httpserver.HttpContext; +import org.switchyard.component.common.Endpoint; + +/** + * A standalone HTTP endpoint. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class StandaloneEndpoint implements Endpoint { + + private HttpContext _httpContext; + private static Long _contextCount = 0L; + + /** + * Construct a StandaloneEndpoint with the given context. + * @param context The HttpContext + */ + public StandaloneEndpoint(final HttpContext context) { + _httpContext = context; + incrementContextCount(); + } + + private synchronized void incrementContextCount() { + _contextCount++; + } + + private synchronized void decrementContextCount() { + _contextCount--; + } + + /** + * {@inheritDoc} + */ + public void start() { + } + + /** + * {@inheritDoc} + */ + public void stop() { + if (_httpContext != null) { + _httpContext.getServer().removeContext(_httpContext); + decrementContextCount(); + } + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/endpoint/StandaloneEndpointPublisher.java b/components/http/src/main/java/org/switchyard/component/http/endpoint/StandaloneEndpointPublisher.java new file mode 100644 index 000000000..7665b1b3f --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/endpoint/StandaloneEndpointPublisher.java @@ -0,0 +1,225 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.endpoint; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.Charset; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.http.NameValuePair; +import org.apache.http.client.utils.URLEncodedUtils; +import org.jboss.logging.Logger; +import org.jboss.com.sun.net.httpserver.BasicAuthenticator; +import org.jboss.com.sun.net.httpserver.HttpContext; +import org.jboss.com.sun.net.httpserver.HttpExchange; +import org.jboss.com.sun.net.httpserver.HttpHandler; +import org.jboss.com.sun.net.httpserver.HttpServer; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.http.ContentType; +import org.switchyard.component.http.HttpLogger; +import org.switchyard.component.http.InboundHandler; +import org.switchyard.component.http.composer.HttpRequestBindingData; +import org.switchyard.component.http.composer.HttpRequestInfo; +import org.switchyard.component.http.composer.HttpResponseBindingData; +import org.switchyard.security.jboss.credential.extractor.HttpExchangeCredentialExtractor; + +/** + * Publishes standalone HTTP endpoint. + *

+ * By default it will be published in port {@value #DEFAULT_PORT}. This can be configured making use of + * {@value #DEFAULT_PORT_PROPERTY} system property. + *

+ * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class StandaloneEndpointPublisher implements EndpointPublisher { + + /** + * Default port in which the standalone publisher is started. + */ + public static final int DEFAULT_PORT = 8080; + + /** + * System property to adjust the port in which the standalone publisher is started. + */ + public static final String DEFAULT_PORT_PROPERTY = "org.switchyard.component.http.standalone.port"; + + private static final Logger LOGGER = Logger.getLogger(StandaloneEndpointPublisher.class); + + private static final String CONTENT_TYPE = "Content-Type"; + + // The global standalone HttpServer + private static HttpServer _httpServer; + + static { + try { + _httpServer = HttpServer.create(new InetSocketAddress(getPort()), 10); + _httpServer.setExecutor(null); // creates a default executor + _httpServer.start(); + } catch (IOException ioe) { + HttpLogger.ROOT_LOGGER.unableToLaunchStandaloneHttpServer(ioe); + } + } + + /** + * {@inheritDoc} + */ + public Endpoint publish(ServiceDomain domain, String context, InboundHandler handler) throws Exception { + HttpContext httpContext = null; + if (!context.startsWith("/")) { + context = "/" + context; + } + if (_httpServer != null) { + httpContext = _httpServer.createContext(context, new StandaloneHandler(handler)); + } + return new StandaloneEndpoint(httpContext); + } + + private static class StandaloneHandler implements HttpHandler { + + private InboundHandler _handler; + + public StandaloneHandler(InboundHandler handler) { + _handler = handler; + } + + public void handle(HttpExchange exchange) { + try { + HttpRequestBindingData httpRequest = new HttpRequestBindingData(); + byte[] responseBody = null; + try { + String contentTypeStr = exchange.getRequestHeaders().getFirst(CONTENT_TYPE); + ContentType contentType = new ContentType(contentTypeStr); + httpRequest.setContentType(contentType); + httpRequest.setBodyFromStream(exchange.getRequestBody()); + httpRequest.setHeaders(exchange.getRequestHeaders()); + httpRequest.setRequestInfo(getRequestInfo(exchange, contentType)); + } catch (IOException e) { + HttpLogger.ROOT_LOGGER.unexpectedExceptionWhileReadingRequest(e); + } + HttpResponseBindingData httpResponse = _handler.invoke(httpRequest); + try { + if (httpResponse != null) { + exchange.getResponseHeaders().putAll(httpResponse.getHeaders()); + if (httpResponse.getBodyBytes() != null) { + exchange.sendResponseHeaders(httpResponse.getStatus(), httpResponse.getBodyBytes().available()); + httpResponse.writeBodyToStream(exchange.getResponseBody()); + } else { + if (httpResponse.getStatus() != null) { + exchange.sendResponseHeaders(httpResponse.getStatus(), 0); + } else { + exchange.sendResponseHeaders(HttpServletResponse.SC_ACCEPTED, 0); + } + } + } else { + exchange.sendResponseHeaders(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0); + } + } catch (IOException e) { + HttpLogger.ROOT_LOGGER.unexpectedExceptionWhileWritingResponse(e); + } + } catch (Exception e) { + HttpLogger.ROOT_LOGGER.unexpectedExceptionWhileHandlingHttpRequest(e); + } + } + } + + /** + * Method for get request information from a http exchange. + * + * @param request HttpExchange + * @param type ContentType + * @return Request information from a http exchange + * @throws IOException when the request information could not be read + */ + public static HttpRequestInfo getRequestInfo(HttpExchange request, ContentType type) throws IOException { + HttpRequestInfo requestInfo = new HttpRequestInfo(); + + if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) { + requestInfo.setAuthType(HttpServletRequest.BASIC_AUTH); + } + URI u = request.getRequestURI(); + URI requestURI = null; + try { + requestURI = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), u.getPath(), null, null); + } catch (URISyntaxException e) { + // Strange that this could happen when copying from another URI. + LOGGER.debug(e); + } + requestInfo.setCharacterEncoding(type.getCharset()); + requestInfo.setContentType(type.toString()); + requestInfo.setContextPath(request.getHttpContext().getPath()); + requestInfo.setLocalAddr(request.getLocalAddress().getAddress().getHostAddress()); + requestInfo.setLocalName(request.getLocalAddress().getAddress().getHostName()); + requestInfo.setMethod(request.getRequestMethod()); + requestInfo.setProtocol(request.getProtocol()); + requestInfo.setQueryString(u.getQuery()); + requestInfo.setRemoteAddr(request.getRemoteAddress().getAddress().getHostAddress()); + requestInfo.setRemoteHost(request.getRemoteAddress().getAddress().getHostName()); + if (request.getHttpContext().getAuthenticator() instanceof BasicAuthenticator) { + requestInfo.setRemoteUser(request.getPrincipal().getUsername()); + } + requestInfo.setContentLength(request.getRequestBody().available()); + // requestInfo.setRequestSessionId(request.getRequestedSessionId()); + if (requestURI != null) { + requestInfo.setRequestURI(requestURI.toString()); + } + requestInfo.setScheme(u.getScheme()); + requestInfo.setServerName(u.getHost()); + requestInfo.setRequestPath(u.getPath()); + + // Http Query params... + if (requestInfo.getQueryString() != null) { + Charset charset = null; + if (type.getCharset() != null) { + try { + charset = Charset.forName(type.getCharset()); + } catch (Exception exception) { + LOGGER.debug(exception); + } + } + for (NameValuePair nameValuePair : URLEncodedUtils.parse(requestInfo.getQueryString(), charset)) { + requestInfo.addQueryParam(nameValuePair.getName(), nameValuePair.getValue()); + } + } + + // Credentials... + requestInfo.getCredentials().addAll(new HttpExchangeCredentialExtractor().extract(request)); + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace(requestInfo); + } + + return requestInfo; + } + + /** + * Returns the port where the standalone publisher will be started + * @return the port + */ + static int getPort() { + int port = DEFAULT_PORT; + final String portAsStr = System.getProperty(DEFAULT_PORT_PROPERTY); + if (portAsStr != null) { + port = Integer.parseInt(portAsStr); + } + return port; + } +} diff --git a/components/http/src/main/java/org/switchyard/component/http/selector/HttpOperationSelector.java b/components/http/src/main/java/org/switchyard/component/http/selector/HttpOperationSelector.java new file mode 100644 index 000000000..62b833c3a --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/selector/HttpOperationSelector.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.selector; + +import java.io.StringReader; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.switchyard.component.common.selector.BaseOperationSelector; +import org.switchyard.component.http.composer.HttpBindingData; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +/** + * OperationSelector implementation for HTTP binding. + */ +public class HttpOperationSelector extends BaseOperationSelector { + + /** + * Constructor. + * @param model OperationSelectorModel + */ + public HttpOperationSelector(OperationSelectorModel model) { + super(model); + } + + @Override + protected Document extractDomDocument(HttpBindingData content) + throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(extractString(content))); + return builder.parse(is); + } + + @Override + protected String extractString(HttpBindingData content) throws Exception { + return content.getBodyAsString(); + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/selector/HttpOperationSelectorFactory.java b/components/http/src/main/java/org/switchyard/component/http/selector/HttpOperationSelectorFactory.java new file mode 100644 index 000000000..f94a8c45e --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/selector/HttpOperationSelectorFactory.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.selector; + +import org.switchyard.component.common.selector.OperationSelectorFactory; +import org.switchyard.component.http.composer.HttpBindingData; +import org.switchyard.selector.OperationSelector; + +/** + * OperationSelectorFactory implementation for HTTP binding. + */ +public class HttpOperationSelectorFactory extends OperationSelectorFactory { + + @Override + public Class getTargetClass() { + return HttpBindingData.class; + } + + @Override + public Class> getDefaultOperationSelectorClass() { + return HttpOperationSelector.class; + } + +} diff --git a/components/http/src/main/java/org/switchyard/component/http/util/HttpContentTypeUtil.java b/components/http/src/main/java/org/switchyard/component/http/util/HttpContentTypeUtil.java new file mode 100644 index 000000000..523436200 --- /dev/null +++ b/components/http/src/main/java/org/switchyard/component/http/util/HttpContentTypeUtil.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http.util; + +import java.util.regex.Pattern; + +/** + * HTTP Content Type utility methods. + * + * @author tom.fennelly@jboss.com + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class HttpContentTypeUtil { + + private static Pattern[] textMimePatterns; + + static { + String[] textTypes = {"text/.*", "application/xml", "application/.*\\+xml"}; + + textMimePatterns = new Pattern[textTypes.length]; + for (int i = 0; i < textMimePatterns.length; i++) { + textMimePatterns[i] = Pattern.compile(textTypes[i]); + } + } + + private HttpContentTypeUtil() { + } + + /** + * Test if content type is of text types. + * @param contentType teh content type to test + * @return true if it is a text content type + */ + public static boolean isTextMimetype(String contentType) { + if (contentType == null) { + return false; + } + + final int separator = contentType.indexOf(';'); + if (separator >= 0) { + contentType = contentType.substring(0, separator); + } + for (int i = 0; i < textMimePatterns.length; i++) { + if (textMimePatterns[i].matcher(contentType).matches()) { + return true; + } + } + + return false; + } +} diff --git a/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory b/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory new file mode 100644 index 000000000..a2d0f7c3c --- /dev/null +++ b/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.http.composer.HttpContextMapperFactory diff --git a/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory b/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory new file mode 100644 index 000000000..bf453fd54 --- /dev/null +++ b/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.http.composer.HttpMessageComposerFactory diff --git a/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory b/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory new file mode 100644 index 000000000..3afce5da6 --- /dev/null +++ b/components/http/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.http.selector.HttpOperationSelectorFactory diff --git a/components/http/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/http/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..1128394d7 --- /dev/null +++ b/components/http/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.http.deploy.HttpComponent diff --git a/components/http/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/components/http/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 000000000..a707e1ea6 --- /dev/null +++ b/components/http/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/components/http/src/main/resources/org/switchyard/component/http/config/model/v1/http_1_0.xsd b/components/http/src/main/resources/org/switchyard/component/http/config/model/v1/http_1_0.xsd new file mode 100644 index 000000000..535701def --- /dev/null +++ b/components/http/src/main/resources/org/switchyard/component/http/config/model/v1/http_1_0.xsd @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + + + A context path where the HTTP endpoint will be exposed for Service bindings. + + + + + + + A URL that points to the HTTP endpoint in case of Reference bindings. + + + + + The HTTP method. + + + + + The HTTP request's content-type header that need to be set. + + + + + + + + + Http proxy settings. + + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + Authentication Realm. + + + + + Authentication Host. + + + + + Authentication Port. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Host. + + + + + Proxy Port. + + + + + Proxy user name. + + + + + Proxy password. + + + + + + + diff --git a/components/http/src/main/resources/org/switchyard/component/http/config/model/v1/http_1_1.xsd b/components/http/src/main/resources/org/switchyard/component/http/config/model/v1/http_1_1.xsd new file mode 100644 index 000000000..b5a7a9ce7 --- /dev/null +++ b/components/http/src/main/resources/org/switchyard/component/http/config/model/v1/http_1_1.xsd @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + + + A context path where the HTTP endpoint will be exposed for Service bindings. + + + + + + + A URL that points to the HTTP endpoint in case of Reference bindings. + + + + + The HTTP method. + + + + + The HTTP request's content-type header that need to be set. + + + + + The HTTP request's time-out value in milliseconds. + + + + + + + + + Http proxy settings. + + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + Authentication Realm. + + + + + Authentication Host. + + + + + Authentication Port. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Host. + + + + + Proxy Port. + + + + + Proxy user name. + + + + + Proxy password. + + + + + + + diff --git a/components/http/src/main/resources/org/switchyard/component/http/config/model/v2/http_2_0.xsd b/components/http/src/main/resources/org/switchyard/component/http/config/model/v2/http_2_0.xsd new file mode 100644 index 000000000..44ceeb184 --- /dev/null +++ b/components/http/src/main/resources/org/switchyard/component/http/config/model/v2/http_2_0.xsd @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + + + A context path where the HTTP endpoint will be exposed for Service bindings. + + + + + + + A URL that points to the HTTP endpoint in case of Reference bindings. + + + + + The HTTP method. + + + + + The HTTP request's content-type header that need to be set. + + + + + The HTTP request's time-out value in milliseconds. + + + + + + + + + Http proxy settings. + + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + Authentication Realm. + + + + + Authentication Host. + + + + + Authentication Port. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Host. + + + + + Proxy Port. + + + + + Proxy user name. + + + + + Proxy password. + + + + + + + diff --git a/components/http/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/http/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..a57258bd7 --- /dev/null +++ b/components/http/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +http_1_0.section=urn:switchyard-component-http:config +http_1_0.version=1.0 +http_1_0.namespace=urn:switchyard-component-http:config:1.0 +http_1_0.schema=http_1_0.xsd +http_1_0.location=/org/switchyard/component/http/config/model/v1/ +http_1_0.marshaller=org.switchyard.component.http.config.model.v1.V1HttpMarshaller + +http_1_1.section=urn:switchyard-component-http:config +http_1_1.version=1.1 +http_1_1.namespace=urn:switchyard-component-http:config:1.1 +http_1_1.schema=http_1_1.xsd +http_1_1.location=/org/switchyard/component/http/config/model/v1/ +http_1_1.marshaller=org.switchyard.component.http.config.model.v1.V1HttpMarshaller + +http_2_0.section=urn:switchyard-component-http:config +http_2_0.version=2.0 +http_2_0.namespace=urn:switchyard-component-http:config:2.0 +http_2_0.schema=http_2_0.xsd +http_2_0.location=/org/switchyard/component/http/config/model/v2/ +http_2_0.marshaller=org.switchyard.component.http.config.model.v1.V1HttpMarshaller diff --git a/components/http/src/test/java/org/switchyard/component/http/HttpBasicAuthenticator.java b/components/http/src/test/java/org/switchyard/component/http/HttpBasicAuthenticator.java new file mode 100644 index 000000000..dc8a7f1a1 --- /dev/null +++ b/components/http/src/test/java/org/switchyard/component/http/HttpBasicAuthenticator.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http; + +import org.jboss.com.sun.net.httpserver.BasicAuthenticator; + +/** + * A Basic authenticator. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class HttpBasicAuthenticator extends BasicAuthenticator { + + public HttpBasicAuthenticator() { + super("Any"); + } + + @Override + public boolean checkCredentials(String username, String password) { + if ((username == null) || (password == null) || !username.equals("Beal") || !password.equals("conjecture")) { + throw new RuntimeException("Invalid username or password!"); + } + return true; + } +} diff --git a/components/http/src/test/java/org/switchyard/component/http/HttpGatewayTest.java b/components/http/src/test/java/org/switchyard/component/http/HttpGatewayTest.java new file mode 100644 index 000000000..d379d2f0a --- /dev/null +++ b/components/http/src/test/java/org/switchyard/component/http/HttpGatewayTest.java @@ -0,0 +1,280 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.jboss.com.sun.net.httpserver.HttpContext; +import org.jboss.com.sun.net.httpserver.HttpExchange; +import org.jboss.com.sun.net.httpserver.HttpHandler; +import org.jboss.com.sun.net.httpserver.HttpServer; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.component.http.composer.HttpRequestBindingData; +import org.switchyard.component.http.composer.HttpComposition; +import org.switchyard.component.http.composer.HttpContextMapper; +import org.switchyard.component.http.config.model.HttpBindingModel; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +/** + * Contains tests for HTTP Gateway. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = HTTPMixIn.class) +public class HttpGatewayTest { + + private static final String METHOD_NAME = "sayHello"; + private static final String INPUT = "magesh"; + private static final String OUTPUT = "response to " + INPUT; + private static final QName STRING_QNAME = new QName("java:java.lang.String"); + private static ModelPuller _puller; + private ServiceDomain _domain; + private HTTPMixIn httpMixIn; + + @org.switchyard.test.ServiceOperation("{urn:http:test:1.1}SampleHttpConsumerService") + private Invoker _consumerService; + + @org.switchyard.test.ServiceOperation("{urn:http:test:1.1}InvalidHttpConsumerService") + private Invoker _consumerService2; + + @org.switchyard.test.ServiceOperation("{urn:http:test:1.1}AuthHttpConsumerService") + private Invoker _consumerService3; + + @org.switchyard.test.ServiceOperation("{urn:http:test:1.1}NtlmHttpConsumerService") + private Invoker _consumerService4; + + @org.switchyard.test.ServiceOperation("{urn:http:test:1.1}TimeoutHttpConsumerService") + private Invoker _consumerService5; + + @org.switchyard.test.ServiceOperation("{urn:http:test:1.1}OneWayHttpConsumerService") + private Invoker _inOnlyConsumerService; + + private InboundHandler _httpInbound; + private InboundHandler _httpInbound2; + private OutboundHandler _httpOutbound; + private OutboundHandler _httpOutbound2; + private OutboundHandler _httpOutbound3; + private OutboundHandler _httpOutbound4; + private OutboundHandler _httpOutbound5; + private final MockHandler mockService = new MockHandler().forwardInToOut(); + + @Before + public void setUp() throws Exception { + _puller = new ModelPuller(); + CompositeModel composite = _puller.pull("/HelloSwitchYard.xml", getClass()); + composite.assertModelValid(); + + CompositeServiceModel compositeService = composite.getServices().get(0); + HttpBindingModel config = (HttpBindingModel)compositeService.getBindings().get(0); + + // Massive hack for Test Runner. Register both a service and a reference binding. + _domain.registerService(config.getServiceName(), new InOutService(), mockService); + _domain.registerServiceReference(config.getServiceName(), new HelloInterface()); + _httpInbound = new InboundHandler(config, _domain); + _httpInbound.start(); + + compositeService = composite.getServices().get(1); + HttpBindingModel config2 = (HttpBindingModel)compositeService.getBindings().get(0); + + _domain.registerService(config2.getServiceName(), new InOnlyService(), new MockHandler()); + _domain.registerServiceReference(config2.getServiceName(), new HelloInterface()); + _httpInbound2 = new InboundHandler(config2, _domain); + _httpInbound2.start(); + + CompositeReferenceModel compositeReference = composite.getReferences().get(0); + HttpBindingModel configRef = (HttpBindingModel)compositeReference.getBindings().get(0); + + _httpOutbound = new OutboundHandler(configRef, null); + _domain.registerService(configRef.getServiceName(), new HelloInterface(), _httpOutbound); + _httpOutbound.start(); + + compositeReference = composite.getReferences().get(1); + HttpBindingModel configRef2 = (HttpBindingModel)compositeReference.getBindings().get(0); + _httpOutbound2 = new OutboundHandler(configRef2, null); + _domain.registerService(configRef2.getServiceName(), new HelloInterface(), _httpOutbound2); + _httpOutbound2.start(); + + compositeReference = composite.getReferences().get(2); + HttpBindingModel configRef3 = (HttpBindingModel)compositeReference.getBindings().get(0); + _httpOutbound3 = new OutboundHandler(configRef3, null); + _domain.registerService(configRef3.getServiceName(), new HelloInterface(), _httpOutbound3); + _httpOutbound3.start(); + + compositeReference = composite.getReferences().get(3); + HttpBindingModel configRef4 = (HttpBindingModel)compositeReference.getBindings().get(0); + _httpOutbound4 = new OutboundHandler(configRef4, null); + _domain.registerService(configRef4.getServiceName(), new HelloInterface(), _httpOutbound4); + _httpOutbound4.start(); + + compositeReference = composite.getReferences().get(4); + HttpBindingModel configRef5 = (HttpBindingModel)compositeReference.getBindings().get(0); + _httpOutbound5 = new OutboundHandler(configRef5, null); + _domain.registerService(configRef5.getServiceName(), new HelloInterface(), _httpOutbound5); + _httpOutbound5.start(); + } + + @After + public void tearDown() throws Exception { + _httpInbound.stop(); + _httpInbound2.stop(); + _httpOutbound.stop(); + _httpOutbound2.stop(); + _httpOutbound3.stop(); + _httpOutbound4.stop(); + _httpOutbound5.stop(); + } + + @Test + public void httpGatewayServiceTest() throws Exception { + String response = httpMixIn.sendString("http://localhost:8080/http", INPUT, HTTPMixIn.HTTP_POST); + //Test CSR - Composing a Service Request + Assert.assertEquals(String.class, mockService.getMessages().peek().getMessage().getContent().getClass()); + Assert.assertEquals(1, mockService.getMessages().size()); + Assert.assertEquals(INPUT, response); + } + + @Test + public void httpOneWayStatusTest() throws Exception { + int status = httpMixIn.sendStringAndGetStatus("http://localhost:8080/oneway", INPUT, HTTPMixIn.HTTP_POST); + Assert.assertEquals(202, status); + } + + @Test + public void httpGatewayReferenceTest() throws Exception { + Message responseMsg = _consumerService.operation(METHOD_NAME).sendInOut(INPUT); + //Test CRR - Composing an Reference Response + Assert.assertEquals(String.class, responseMsg.getContent().getClass()); + Assert.assertEquals(INPUT, responseMsg.getContent()); + } + + @Test + public void httpStatus() throws Exception { + MockHandler handler = new MockHandler(); + Exchange ex = _consumerService.operation(METHOD_NAME).createExchange(handler); + Message requestMsg = ex.createMessage().setContent(INPUT); + requestMsg.getContext().setProperty("SomeRequestHeader", "BAR"); + ex.send(requestMsg); + handler.waitForOKMessage(); + Assert.assertEquals(200, ex.getContext().getProperty(HttpContextMapper.HTTP_RESPONSE_STATUS).getValue()); + } + + @Test + public void httpFault() throws Exception { + MockHandler handler = new MockHandler(); + Exchange ex = _consumerService2.operation(METHOD_NAME).createExchange(handler); + Message requestMsg = ex.createMessage().setContent(INPUT); + ex.send(requestMsg); + handler.waitForFaultMessage(); + Assert.assertEquals(404, ex.getContext().getProperty(HttpContextMapper.HTTP_RESPONSE_STATUS).getValue()); + } + + @Test + public void httpTimeout() throws Exception { + HttpServer httpServer = HttpServer.create(new InetSocketAddress(8090), 10); + httpServer.setExecutor(null); // creates a default executor + httpServer.start(); + HttpContext httpContext = httpServer.createContext("/forever", new HttpHandler() { + public void handle(HttpExchange exchange) { + try { + Thread.sleep(10000); + } catch (InterruptedException ie) { + //Ignore + }}}); + try { + Message responseMsg = _consumerService5.operation(METHOD_NAME).sendInOut(INPUT); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("SocketTimeoutException: Read timed out")); + } + httpServer.stop(0); + } + + @Test + public void authentication() throws Exception { + HttpServer httpServer = HttpServer.create(new InetSocketAddress(8100), 10); + httpServer.setExecutor(null); // creates a default executor + httpServer.start(); + HttpContext context = httpServer.createContext("/basic-secured-endpoint", new StandaloneHandler()); + context.setAuthenticator(new HttpBasicAuthenticator()); + Message responseMsg = _consumerService3.operation(METHOD_NAME).sendInOut(INPUT); + Assert.assertEquals(OUTPUT, responseMsg.getContent(String.class)); + httpServer.stop(0); + } + + @Ignore // Exclusively for Magesh ;) + @Test + public void ntlmAuthentication() throws Exception { + Message responseMsg = _consumerService4.operation(METHOD_NAME).sendInOut(INPUT); + Assert.assertEquals(OUTPUT, responseMsg.getContent(String.class)); + } + + private static class HelloInterface extends BaseService { + private static Set _operations = new HashSet(2); + static { + _operations.add(new InOutOperation(METHOD_NAME, STRING_QNAME, STRING_QNAME)); + _operations.add(new InOnlyOperation("oneWay", STRING_QNAME)); + } + public HelloInterface() { + super(_operations); + } + } + + private static class StandaloneHandler implements HttpHandler { + + public void handle(HttpExchange exchange) { + try { + HttpRequestBindingData httpRequest = new HttpRequestBindingData(); + httpRequest.setBodyFromStream(exchange.getRequestBody()); + Assert.assertEquals(INPUT, httpRequest.getBodyAsString()); + httpRequest.setBody(OUTPUT); + exchange.sendResponseHeaders(200, httpRequest.getBodyBytes().available()); + httpRequest.writeBodyToStream(exchange.getResponseBody()); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} + diff --git a/components/http/src/test/java/org/switchyard/component/http/HttpProxyTest.java b/components/http/src/test/java/org/switchyard/component/http/HttpProxyTest.java new file mode 100644 index 000000000..88c5fedbc --- /dev/null +++ b/components/http/src/test/java/org/switchyard/component/http/HttpProxyTest.java @@ -0,0 +1,190 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.http; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.HashSet; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.littleshoot.proxy.DefaultHttpProxyServer; +import org.littleshoot.proxy.HttpProxyServer; +import org.littleshoot.proxy.ProxyAuthorizationHandler; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.component.http.config.model.HttpBindingModel; +import org.switchyard.component.http.config.model.HttpNamespace; +import org.switchyard.component.http.config.model.ProxyModel; +import org.switchyard.component.http.config.model.v1.V1HttpBindingModel; +import org.switchyard.component.http.config.model.v1.V1ProxyModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; + +/** + * Contains tests for Http proxy support on HTTP Gateway. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class HttpProxyTest { + + private static final int PROXYPORT = 9090; + private static final String PROXY_USER = "foo"; + private static final String PROXY_PWD = "bar"; + private static final String METHOD_NAME = "sayHello"; + private static final String INPUT = "Beal Conjecture"; + + private ServiceDomain _domain; + + @org.switchyard.test.ServiceOperation("unknown-host") + private Invoker _proxyConsumerService1; + @org.switchyard.test.ServiceOperation("proxy-auth-required") + private Invoker _proxyConsumerService2; + @org.switchyard.test.ServiceOperation("all-is-well") + private Invoker _proxyConsumerService3; + + private HttpBindingModel _config; + private InboundHandler _httpInbound; + + private static ModelPuller _puller; + private HttpProxyServer _proxyServer; + + + @Before + public void setUp() throws Exception { + String host = System.getProperty("org.switchyard.test.http.host", "localhost"); + String port = System.getProperty("org.switchyard.test.http.port", "8080"); + _proxyServer = new DefaultHttpProxyServer(PROXYPORT); + ProxyAuthorizationHandler authorizationHandler = new ProxyAuthorizationHandler() { + @Override + public boolean authenticate(String user, String pwd) { + return (PROXY_USER.equals(user) && PROXY_PWD.equals(pwd)); + } + }; + _proxyServer.addProxyAuthenticationHandler(authorizationHandler); + _proxyServer.start(); + + _puller = new ModelPuller(); + + // Provide a switchyard service + CompositeModel composite = _puller.pull("/HelloSwitchYard.xml", getClass()); + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (HttpBindingModel)compositeService.getBindings().get(0); + _domain.registerService(_config.getServiceName(), new HelloWebServiceInterface(), new MockHandler().forwardInToOut()); + _domain.registerServiceReference(_config.getServiceName(), new HelloWebServiceInterface()); + + // Service exposed as WS + _httpInbound = new InboundHandler(_config, _domain); + _httpInbound.start(); + + HttpBindingModel config = new V1HttpBindingModel(HttpNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config.setServiceName(_proxyConsumerService1.getServiceName()); + config.setName("proxy-test"); + config.setMethod("PUT"); + config.setAddress("http://unreachablehost/http"); + + // Service consumer or Reference binding + OutboundHandler httpProxyOutbound1 = new OutboundHandler(config, null); + httpProxyOutbound1.start(); + _domain.registerService(_proxyConsumerService1.getServiceName(), new HelloWebServiceInterface(), httpProxyOutbound1); + + ProxyModel proxy = new V1ProxyModel(HttpNamespace.DEFAULT.uri()); + proxy.setHost(host); + proxy.setPort("" + PROXYPORT); + config.setProxyConfig(proxy); + config.setAddress("http://" + host + ":" + port + "/http"); + config.setServiceName(_proxyConsumerService2.getServiceName()); + + // Service consumer or Reference binding + OutboundHandler httpProxyOutbound2 = new OutboundHandler(config, null); + httpProxyOutbound2.start(); + _domain.registerService(_proxyConsumerService2.getServiceName(), new HelloWebServiceInterface(), httpProxyOutbound2); + + proxy.setUser(PROXY_USER); + proxy.setPassword(PROXY_PWD); + config.setProxyConfig(proxy); + config.setServiceName(_proxyConsumerService3.getServiceName()); + + // Service consumer or Reference binding + OutboundHandler httpProxyOutbound3 = new OutboundHandler(config, null); + httpProxyOutbound3.start(); + _domain.registerService(_proxyConsumerService3.getServiceName(), new HelloWebServiceInterface(), httpProxyOutbound3); + + } + + @After + public void tearDown() throws Exception { + _httpInbound.stop(); + _proxyServer.stop(); + } + + @Test + public void unknownHost() throws Exception { + try { + Message responseMsg = _proxyConsumerService1.operation(METHOD_NAME).sendInOut(INPUT); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("org.apache.http.NoHttpResponseException: unreachablehost") + || baos.toString().contains("UnknownHostException: unreachablehost")); + } + } + + @Test + public void authenticationMissing() throws Exception { + MockHandler handler = new MockHandler(); + Exchange ex = _proxyConsumerService2.operation(METHOD_NAME).createExchange(handler); + Message requestMsg = ex.createMessage().setContent(INPUT); + ex.send(requestMsg); + handler.waitForFaultMessage(); + String response = ex.getMessage().getContent(String.class); + Assert.assertTrue(response.contains("407 Proxy Authentication Required")); + } + + @Test + public void allIsWell() throws Exception { + Message responseMsg = _proxyConsumerService3.operation(METHOD_NAME).sendInOut(INPUT); + Assert.assertEquals(INPUT, responseMsg.getContent(String.class)); + } + + private static class HelloWebServiceInterface extends BaseService { + private static Set _operations = new HashSet(1); + static { + _operations.add(new InOutOperation(METHOD_NAME)); + } + public HelloWebServiceInterface() { + super(_operations); + } + } +} diff --git a/components/http/src/test/java/org/switchyard/component/http/composer/HttpContextMapperTest.java b/components/http/src/test/java/org/switchyard/component/http/composer/HttpContextMapperTest.java new file mode 100644 index 000000000..a6385f3d6 --- /dev/null +++ b/components/http/src/test/java/org/switchyard/component/http/composer/HttpContextMapperTest.java @@ -0,0 +1,62 @@ +package org.switchyard.component.http.composer; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.internal.DefaultContext; + +public class HttpContextMapperTest { + private DefaultContext _context; + + @Before + public void setUp() throws Exception { + _context = new DefaultContext(Scope.EXCHANGE); + } + + @Test + public void mapStrings() throws Exception { + _context.setProperty("foo", "boo"); + HttpContextMapper hcm = new HttpContextMapper(); + HttpRequestBindingData bindingData = new HttpRequestBindingData(); + hcm.mapTo(_context, bindingData); + Map> headers = bindingData.getHeaders(); + Iterator it = headers.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry pairs = (Map.Entry)it.next(); + ArrayList list = (ArrayList) pairs.getValue(); + for (int i = 0; i < list.size(); i++) { + assertTrue(list.get(i) instanceof String); + } + it.remove(); + } + } + + @Test + public void mapObjects() throws Exception { + ArrayList obj = new ArrayList(); + obj.add(new Integer(3)); + _context.setProperty("foo", obj); + HttpContextMapper hcm = new HttpContextMapper(); + HttpRequestBindingData bindingData = new HttpRequestBindingData(); + hcm.mapTo(_context, bindingData); + Map> headers = bindingData.getHeaders(); + Iterator it = headers.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry pairs = (Map.Entry)it.next(); + ArrayList list = (ArrayList) pairs.getValue(); + for (int i = 0; i < list.size(); i++) { + assertTrue(list.get(i) instanceof String); + } + it.remove(); + } + } +} diff --git a/components/http/src/test/java/org/switchyard/component/http/config/model/HttpConfigModelTest.java b/components/http/src/test/java/org/switchyard/component/http/config/model/HttpConfigModelTest.java new file mode 100644 index 000000000..ca7449cba --- /dev/null +++ b/components/http/src/test/java/org/switchyard/component/http/config/model/HttpConfigModelTest.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.http.config.model; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.component.http.config.model.BasicAuthModel; +import org.switchyard.component.http.config.model.HttpBindingModel; +import org.switchyard.component.http.config.model.ProxyModel; +import org.switchyard.config.model.ModelPuller; + +/** + * Test of HTTP binding model. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class HttpConfigModelTest { + + private static final String HTTP_BINDING = "http-binding.xml"; + private static final String HTTP_BINDING2 = "http-binding2.xml"; + private static final String HTTP_BINDING_AUTH = "http-binding-auth.xml"; + private static final String HTTP_BINDING_PROXY = "http-binding-proxy.xml"; + + @Test + public void testReadConfigBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + HttpBindingModel model = puller.pull(HTTP_BINDING, getClass()); + Assert.assertTrue(model.isModelValid()); + model = puller.pull(HTTP_BINDING2, getClass()); + Assert.assertTrue(model.isModelValid()); + Assert.assertEquals(new Integer(5000), model.getTimeout()); + } + + @Test + public void authConfigBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + HttpBindingModel model = puller.pull(HTTP_BINDING_AUTH, getClass()); + Assert.assertTrue(model.isModelValid()); + Assert.assertTrue(model.isBasicAuth()); + BasicAuthModel authConfig = model.getBasicAuthConfig(); + Assert.assertNotNull(authConfig); + Assert.assertEquals("Beal", authConfig.getUser()); + Assert.assertEquals("conjecture", authConfig.getPassword()); + Assert.assertEquals("Any", authConfig.getRealm()); + } + + @Test + public void proxyConfigBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + HttpBindingModel model = puller.pull(HTTP_BINDING_PROXY, getClass()); + Assert.assertTrue(model.isModelValid()); + ProxyModel proxyConfig = model.getProxyConfig(); + Assert.assertNotNull(proxyConfig); + Assert.assertEquals("host", proxyConfig.getHost()); + Assert.assertEquals("8090", proxyConfig.getPort()); + Assert.assertEquals("Beal", proxyConfig.getUser()); + Assert.assertEquals("conjecture", proxyConfig.getPassword()); + } +} diff --git a/components/http/src/test/java/org/switchyard/component/http/endpoint/StandaloneEndpointPublisherTest.java b/components/http/src/test/java/org/switchyard/component/http/endpoint/StandaloneEndpointPublisherTest.java new file mode 100644 index 000000000..b2b0dcc49 --- /dev/null +++ b/components/http/src/test/java/org/switchyard/component/http/endpoint/StandaloneEndpointPublisherTest.java @@ -0,0 +1,36 @@ +package org.switchyard.component.http.endpoint; + +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +/** + * Test for StandaloneEndpointPublisher + * + * @author Luis del Toro + */ +public class StandaloneEndpointPublisherTest { + + private static final int TEST_PORT = 9191; + + @Before + public void setUp() { + // make sure that the system property is not set + System.clearProperty(StandaloneEndpointPublisher.DEFAULT_PORT_PROPERTY); + } + @Test + public void useDefaultPort() { + final int port = StandaloneEndpointPublisher.getPort(); + assertThat(port, is(equalTo(StandaloneEndpointPublisher.DEFAULT_PORT))); + } + + @Test + public void useConfiguredPort() { + System.setProperty(StandaloneEndpointPublisher.DEFAULT_PORT_PROPERTY, Integer.toString(TEST_PORT)); + final int port = StandaloneEndpointPublisher.getPort(); + assertThat(port, is(equalTo(TEST_PORT))); + } +} diff --git a/components/http/src/test/resources/HelloSwitchYard.xml b/components/http/src/test/resources/HelloSwitchYard.xml new file mode 100644 index 000000000..a32456294 --- /dev/null +++ b/components/http/src/test/resources/HelloSwitchYard.xml @@ -0,0 +1,81 @@ + + + + + + + + http + + + + + + + oneway + + + + + + http://localhost:8080/http?param=value&param1=value1&param1=value2 + POST + + + + + + http://localhost:8080/invalid + POST + + + + + + http://localhost:8100/basic-secured-endpoint + POST + + Beal + conjecture + Any + + + + + + + http://192.168.1.13/index.htm + GET + + SwitchYard + JBoss123! + JBOSS + + + + + + + http://localhost:8090/forever + GET + 1300 + + + + diff --git a/components/http/src/test/resources/log4j.xml b/components/http/src/test/resources/log4j.xml new file mode 100644 index 000000000..dacaebe66 --- /dev/null +++ b/components/http/src/test/resources/log4j.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding-auth.xml b/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding-auth.xml new file mode 100644 index 000000000..012dd7bef --- /dev/null +++ b/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding-auth.xml @@ -0,0 +1,8 @@ + + http://localhost:8080/basic-secured-endpoint + + Beal + conjecture + Any + + diff --git a/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding-proxy.xml b/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding-proxy.xml new file mode 100644 index 000000000..3a394b136 --- /dev/null +++ b/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding-proxy.xml @@ -0,0 +1,9 @@ + + http://localhost:8080/basic-secured-endpoint + + host + 8090 + Beal + conjecture + + diff --git a/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding.xml b/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding.xml new file mode 100644 index 000000000..3dfa0f7cd --- /dev/null +++ b/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding.xml @@ -0,0 +1,4 @@ + + + / + diff --git a/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding2.xml b/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding2.xml new file mode 100644 index 000000000..4f3d6d2f4 --- /dev/null +++ b/components/http/src/test/resources/org/switchyard/component/http/config/model/http-binding2.xml @@ -0,0 +1,5 @@ + + http://localhost:8080/http-binding + POST + 5000 + diff --git a/components/itests/pom.xml b/components/itests/pom.xml new file mode 100644 index 000000000..59792ce9b --- /dev/null +++ b/components/itests/pom.xml @@ -0,0 +1,81 @@ + + + + 4.0.0 + switchyard-component-itests + jar + SwitchYard: Component Integration Tests + SwitchYard component integration tests module + http://switchyard.org + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + + + + org.switchyard + switchyard-runtime + test + + + org.switchyard + switchyard-deploy + test + + + org.switchyard.components + switchyard-component-jca + test + + + org.switchyard.components + switchyard-component-camel + test + + + org.switchyard.components + switchyard-component-camel-jms + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-jca + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + test + + + junit + junit + test + + + diff --git a/components/itests/src/test/java/org/switchyard/component/itests/fault/CamelOutboundFaultPropagationTest.java b/components/itests/src/test/java/org/switchyard/component/itests/fault/CamelOutboundFaultPropagationTest.java new file mode 100644 index 000000000..46fc7489c --- /dev/null +++ b/components/itests/src/test/java/org/switchyard/component/itests/fault/CamelOutboundFaultPropagationTest.java @@ -0,0 +1,106 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.itests.fault; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.component.test.mixins.transaction.TransactionMixIn; + +/** + * Functional test for a fault propagation from camel outbound binding. + * + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig( + config = "switchyard-camel-outbound-fault-test.xml", + mixins = { CDIMixIn.class, TransactionMixIn.class, HornetQMixIn.class }) +public class CamelOutboundFaultPropagationTest { + @ServiceOperation("GreetingService.greet") + private Invoker _greet; + @ServiceOperation("StoreService.store") + private Invoker _store; + + @Test + public void testReferenceBindingInOut() throws Exception { + final String payload = "store/IN_OUT"; + Message msg = null; + try { + msg = _store.sendInOut(payload); + } catch (Throwable t) { + System.out.println("Received an Exception: " + formatThrowable(t)); + return; + } + Assert.fail("It succeeded while an Exception is expected: " + msg.getContent()); + } + + @Test + public void testReferenceBindingInOnly() throws Exception { + final String payload = "store/IN_ONLY"; + try { + _store.sendInOnly(payload); + } catch (Throwable t) { + System.out.println("Received an Exception: " + formatThrowable(t)); + return; + } + Assert.fail("It succeeded while an Exception is expected"); + } + + @Test + public void testBeanServiceInOut() throws Exception { + final String payload = "greet/IN_OUT"; + Message msg = null; + try { + msg = _greet.sendInOut(payload); + } catch (Throwable t) { + System.out.println("Received an Exception: " + formatThrowable(t)); + return; + } + Assert.fail("It succeeded while an Exception is expected: " + msg.getContent()); + } + + @Test + public void testBeanServiceInOnly() throws Exception { + final String payload = "greet/IN_ONLY"; + try { + _greet.sendInOnly(payload); + } catch (Throwable t) { + System.out.println("Received an Exception: " + formatThrowable(t)); + return; + } + Assert.fail("It succeeded while an Exception is expected"); + } + + private String formatThrowable(Throwable t) { + StringBuilder buf = new StringBuilder(t.getClass().getName()) + .append(" : ") + .append(t.getMessage()); + Throwable cause = t; + while((cause = cause.getCause()) != null) { + buf.append(" -- ") + .append(cause.getClass().getName()) + .append(" : ") + .append(cause.getMessage()); + } + return buf.toString(); + } +} + diff --git a/components/itests/src/test/java/org/switchyard/component/itests/fault/GreetingService.java b/components/itests/src/test/java/org/switchyard/component/itests/fault/GreetingService.java new file mode 100644 index 000000000..805d297d7 --- /dev/null +++ b/components/itests/src/test/java/org/switchyard/component/itests/fault/GreetingService.java @@ -0,0 +1,29 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.itests.fault; + +/** + * Simple interface for a Greeter Service. + */ +public interface GreetingService { + /** + * Prints a greeting message using the passed in name. + * + * @param name the name of the person to be greeted. + */ + void greet(String name); +} diff --git a/components/itests/src/test/java/org/switchyard/component/itests/fault/GreetingServiceBean.java b/components/itests/src/test/java/org/switchyard/component/itests/fault/GreetingServiceBean.java new file mode 100644 index 000000000..238a7e7ef --- /dev/null +++ b/components/itests/src/test/java/org/switchyard/component/itests/fault/GreetingServiceBean.java @@ -0,0 +1,40 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.itests.fault; + +import javax.inject.Inject; + +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; + +/** + * A POJO Service implementation. + * + */ +@Service(GreetingService.class) +public class GreetingServiceBean implements GreetingService { + + @Inject @Reference + private StoreService _store; + + @Override + public void greet(final String name) { + String greet = "Hello there " + name + " :-) "; + System.out.println(greet); + _store.store(greet); + } +} diff --git a/components/itests/src/test/java/org/switchyard/component/itests/fault/StoreService.java b/components/itests/src/test/java/org/switchyard/component/itests/fault/StoreService.java new file mode 100644 index 000000000..5b8e98d3b --- /dev/null +++ b/components/itests/src/test/java/org/switchyard/component/itests/fault/StoreService.java @@ -0,0 +1,29 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.itests.fault; + +/** + * Simple interface for a Store Service. + */ +public interface StoreService { + /** + * Store a greeting message using the passed in name. + * + * @param name the name of the person to be greeted. + */ + void store(String name); +} diff --git a/components/itests/src/test/java/org/switchyard/component/itests/validate/DeclarativeValidationTest.java b/components/itests/src/test/java/org/switchyard/component/itests/validate/DeclarativeValidationTest.java new file mode 100644 index 000000000..5ebfb0a2d --- /dev/null +++ b/components/itests/src/test/java/org/switchyard/component/itests/validate/DeclarativeValidationTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.itests.validate; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.test.Invoker; +import org.switchyard.test.ServiceOperation; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; + +/** + * Functional test for Message Validator. + * + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(config = "switchyard-declarative-validate-test.xml", mixins = CDIMixIn.class) +public class DeclarativeValidationTest { + + @ServiceOperation("ValidationService.testReconsumeStreamXml") + private Invoker _reconsume; + + private static final String INPUT = "xml/declarative-validate/input.xml"; + private static final QName TYPE = new QName("urn:validate-test:reconsume-stream-xml:1.0", "order"); + @Test + public void testReconsumeStreamXml() throws Exception { + InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(INPUT); + _reconsume.inputType(TYPE); + _reconsume.expectedOutputType(TYPE); + Message response = _reconsume.sendInOut(stream); + BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent(InputStream.class))); + StringBuilder buf = new StringBuilder(); + String line; + while((line = reader.readLine()) != null) { + buf.append(line); + } + reader.close(); + String actual = buf.toString(); + + stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(INPUT); + reader = new BufferedReader(new InputStreamReader(stream)); + buf = new StringBuilder(); + while((line = reader.readLine()) != null) { + buf.append(line); + } + reader.close(); + String expected = buf.toString(); + + Assert.assertEquals(expected, actual); + } +} + diff --git a/components/itests/src/test/java/org/switchyard/component/itests/validate/ValidationBean.java b/components/itests/src/test/java/org/switchyard/component/itests/validate/ValidationBean.java new file mode 100644 index 000000000..627529ee9 --- /dev/null +++ b/components/itests/src/test/java/org/switchyard/component/itests/validate/ValidationBean.java @@ -0,0 +1,23 @@ +package org.switchyard.component.itests.validate; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; + +import org.switchyard.component.bean.Service; + +@Service(ValidationService.class) +public class ValidationBean implements ValidationService { + + @Override + public InputStream testReconsumeStreamXml(InputStream input) throws Exception { + BufferedReader reader = new BufferedReader(new InputStreamReader(input)); + StringBuilder buf = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + buf.append(line); + } + return new ByteArrayInputStream(buf.toString().getBytes()); + } +} diff --git a/components/itests/src/test/java/org/switchyard/component/itests/validate/ValidationService.java b/components/itests/src/test/java/org/switchyard/component/itests/validate/ValidationService.java new file mode 100644 index 000000000..4231efd4c --- /dev/null +++ b/components/itests/src/test/java/org/switchyard/component/itests/validate/ValidationService.java @@ -0,0 +1,11 @@ +package org.switchyard.component.itests.validate; + +import java.io.InputStream; + +import org.switchyard.annotations.OperationTypes; + +public interface ValidationService { + @OperationTypes(in="{urn:validate-test:reconsume-stream-xml:1.0}order", + out="{urn:validate-test:reconsume-stream-xml:1.0}order") + public InputStream testReconsumeStreamXml(InputStream input) throws Exception; + } diff --git a/components/itests/src/test/resources/META-INF/beans.xml b/components/itests/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/itests/src/test/resources/hornetq-configuration.xml b/components/itests/src/test/resources/hornetq-configuration.xml new file mode 100644 index 000000000..45e066a04 --- /dev/null +++ b/components/itests/src/test/resources/hornetq-configuration.xml @@ -0,0 +1,25 @@ + + + target/data/paging + target/data/bindings + false + target/data/journal + 10 + target/data/large-messages + false + + + + org.hornetq.core.remoting.impl.invm.InVMConnectorFactory + + + + + + org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory + + + + + + diff --git a/components/itests/src/test/resources/hornetq-jms.xml b/components/itests/src/test/resources/hornetq-jms.xml new file mode 100644 index 000000000..d87f981c2 --- /dev/null +++ b/components/itests/src/test/resources/hornetq-jms.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + false + + + + diff --git a/components/itests/src/test/resources/org/switchyard/component/itests/fault/switchyard-camel-outbound-fault-test.xml b/components/itests/src/test/resources/org/switchyard/component/itests/fault/switchyard-camel-outbound-fault-test.xml new file mode 100644 index 000000000..b41403476 --- /dev/null +++ b/components/itests/src/test/resources/org/switchyard/component/itests/fault/switchyard-camel-outbound-fault-test.xml @@ -0,0 +1,41 @@ + + + + + + GreetingServiceQueue + #ConnectionFactory + true + true + #jtaTransactionManager + + + + + + + + + + + + + + + StoreQueue + #ConnectionFactory + true + true + #jtaTransactionManager + + + + + + + + + diff --git a/components/itests/src/test/resources/org/switchyard/component/itests/validate/switchyard-declarative-validate-test.xml b/components/itests/src/test/resources/org/switchyard/component/itests/validate/switchyard-declarative-validate-test.xml new file mode 100644 index 000000000..740d9782b --- /dev/null +++ b/components/itests/src/test/resources/org/switchyard/component/itests/validate/switchyard-declarative-validate-test.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/itests/src/test/resources/xml/declarative-validate/input.xml b/components/itests/src/test/resources/xml/declarative-validate/input.xml new file mode 100644 index 000000000..cc391ad07 --- /dev/null +++ b/components/itests/src/test/resources/xml/declarative-validate/input.xml @@ -0,0 +1,5 @@ + + PO-19838-XYZ + BUTTER + 200 + diff --git a/components/itests/src/test/resources/xsd/declarative-validate/catalog.xml b/components/itests/src/test/resources/xsd/declarative-validate/catalog.xml new file mode 100644 index 000000000..6b8426eeb --- /dev/null +++ b/components/itests/src/test/resources/xsd/declarative-validate/catalog.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/components/itests/src/test/resources/xsd/declarative-validate/orders-base.xsd b/components/itests/src/test/resources/xsd/declarative-validate/orders-base.xsd new file mode 100644 index 000000000..9e186933f --- /dev/null +++ b/components/itests/src/test/resources/xsd/declarative-validate/orders-base.xsd @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/components/itests/src/test/resources/xsd/declarative-validate/orders.xsd b/components/itests/src/test/resources/xsd/declarative-validate/orders.xsd new file mode 100644 index 000000000..45a9784e1 --- /dev/null +++ b/components/itests/src/test/resources/xsd/declarative-validate/orders.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/jca/pom.xml b/components/jca/pom.xml new file mode 100644 index 000000000..996981f21 --- /dev/null +++ b/components/jca/pom.xml @@ -0,0 +1,119 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-jca + jar + SwitchYard: JCA Component + http://www.switchyard.org + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-bean + + + org.jboss + jboss-common-core + + + org.jboss.spec.javax.resource + jboss-connector-api_1.6_spec + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + org.jboss.as + jboss-as-connector + + + org.jboss.ironjacamar + ironjacamar-core-api + + + org.jboss.logging + jboss-logging-spi + + + + + org.jboss.shrinkwrap + shrinkwrap-api + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-jca + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + org.switchyard.components + switchyard-component-test-mixin-naming + test + + + junit + junit + test + + + diff --git a/components/jca/src/main/java/org/switchyard/component/jca/EndpointProxy.java b/components/jca/src/main/java/org/switchyard/component/jca/EndpointProxy.java new file mode 100644 index 000000000..c07604ac8 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/EndpointProxy.java @@ -0,0 +1,418 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca; + +import java.lang.reflect.Method; +import java.lang.reflect.InvocationHandler; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +import javax.transaction.Status; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; +import javax.transaction.xa.XAResource; +import javax.resource.ResourceException; +import javax.resource.spi.endpoint.MessageEndpoint; +import javax.resource.spi.endpoint.MessageEndpointFactory; + +import org.jboss.logging.Logger; +import org.switchyard.component.jca.deploy.JCAInflowDeploymentMetaData; +import org.switchyard.component.jca.endpoint.AbstractInflowEndpoint; + +/** + * Message endpoint proxy to set up common facilities like transaction, concurrency control, + * and ClassLoader before/after delegating to the concrete endpoint class. + * + * The idea of this code originally came from org.jboss.soa.esb.listeners.jca.EndpointProxy. + * + * @author Bill Burke + * @author Tomohisa Igarashi + * + */ +public class EndpointProxy implements InvocationHandler, MessageEndpoint { + + private Logger _logger = Logger.getLogger(EndpointProxy.class); + + private final MessageEndpointFactory _messageEndpointFactory; + private final AbstractInflowEndpoint _delegate; + private final TransactionManager _transactionManager; + private final XAResource _xaResource; + private final ClassLoader _appClassLoader; + + private Transaction _suspendedTx; + private Transaction _startedTx; + private boolean _waitAfterDeliveryInvoked = false; + private Thread _inUseThread = null; + private boolean _beforeDeliveryInvoked; + private ClassLoader _origClassLoader; + + private boolean _useBatchCommit; + private int _batchSize; + private long _batchTimeout; + private static ThreadLocal _batchHelper = new ThreadLocal(); + + private ReentrantLock _deliveryThreadLock = new ReentrantLock(); + private ScheduledExecutorService _scheduler = Executors.newScheduledThreadPool(1); + + /** + * Constructor. + * + * @param metadata {@link JCAInflowDeploymentMetaData} + * @param factory {@link MessageEndpointFactory} + * @param xaResource {@link XAResource} + */ + public EndpointProxy(JCAInflowDeploymentMetaData metadata,MessageEndpointFactory factory, XAResource xaResource) { + _messageEndpointFactory = factory; + _delegate = metadata.getMessageEndpoint(); + _transactionManager = metadata.getTransactionManager(); + _xaResource = xaResource; + _appClassLoader = metadata.getApplicationClassLoader(); + _useBatchCommit = metadata.useBatchCommit(); + _batchSize = metadata.getBatchSize(); + _batchTimeout = metadata.getBatchTimeout(); + } + + @Override + public void beforeDelivery(Method method) throws NoSuchMethodException, ResourceException { + if (_beforeDeliveryInvoked) { + throw JCAMessages.MESSAGES.missingAfterDeliveryFromThePreviousBeforeDeliveryForMessageEndpoint(_delegate.toString()); + } + _beforeDeliveryInvoked = true; + + try { + before(method); + } catch (Exception e) { + throw new ResourceException(e); + } + } + + @Override + public void afterDelivery() throws ResourceException { + if (!_beforeDeliveryInvoked) { + // SWITCHYARD-1640 Avoid remaining thread lock when RM invokes afterDelivery twice for the same delivery + releaseThreadLock(); + throw JCAMessages.MESSAGES.afterDeliveryWithoutAPreviousBeforeDeliveryForMessageEndpoint(_delegate.toString()); + } + + try { + finish(true); + } catch (Throwable t) { + throw new ResourceException(t); + } finally { + _beforeDeliveryInvoked = false; + _waitAfterDeliveryInvoked = false; + } + } + + @Override + public void release() { + // JCA 1.6 spec 13.5 suggests the reuse of released proxy instance, + // so we won't prohibit to reuse this instance after release() is called. + + if (_beforeDeliveryInvoked) { + try { + finish(false); + } catch (Throwable t) { + JCALogger.ROOT_LOGGER.errorInRelease(t); + } finally { + _beforeDeliveryInvoked = false; + _waitAfterDeliveryInvoked = false; + } + } + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + if (_logger.isDebugEnabled()) { + _logger.debug(Thread.currentThread().getName() + " is invoking " + method.getName() + " on " + this); + } + + acquireThreadLock(); + + // beforeDelivery, afterDelivery, or release + if (method.getDeclaringClass().equals(MessageEndpoint.class)) { + return method.invoke(this, args); + } + + // actual delivery + Object ret = null; + try { + if (!_beforeDeliveryInvoked) { + before(method); + } + + ret = delivery(_delegate, method, args); + } catch (Throwable t) { + if (!_beforeDeliveryInvoked) { + finish(false); + } + throw t; + } + + if (!_beforeDeliveryInvoked) { + finish(true); + } + + return ret; + } + + private void before(Method method) throws Exception { + switchToApplicationClassLoader(); + + try { + startTransaction(method); + } catch (Exception e) { + resetContextClassLoader(); + throw e; + } + } + + private Object delivery(Object delegate, Method method, Object[] args) throws Exception { + if (_waitAfterDeliveryInvoked) { + throw JCAMessages.MESSAGES.multipleMessageDeliveryBetweenBeforeAndAfterDeliveryIsNotAllowedForMessageEndpoint(delegate.toString()); + } + + if (_beforeDeliveryInvoked) { + _waitAfterDeliveryInvoked = true; + } + + return method.invoke(delegate, args); + } + + private void finish(boolean commit) throws Exception { + try { + endTransaction(commit); + } finally { + resetContextClassLoader(); + releaseThreadLock(); + } + } + + private void switchToApplicationClassLoader() { + _origClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(_appClassLoader); + } + + private void resetContextClassLoader() { + if (_origClassLoader != null) { + _inUseThread.setContextClassLoader(_origClassLoader); + _origClassLoader = null; + } + } + + private void acquireThreadLock() { + if (_deliveryThreadLock.isHeldByCurrentThread()) { + return; + } + + if (_inUseThread != null && !_inUseThread.equals(Thread.currentThread())) { + throw JCAMessages.MESSAGES.threadCurrentThreadGetNameCouldnTAcquireAThreadLockSinceThisIsAlreadyInUseByAnotherThreadInUseThreadGetName(Thread.currentThread().getName(), this.toString(), _inUseThread.getName()); + } + _deliveryThreadLock.lock(); + _inUseThread = Thread.currentThread(); + + if (_logger.isDebugEnabled()) { + _logger.debug(Thread.currentThread().getName() + " acquired thread lock on " + this); + } + } + + private void releaseThreadLock() { + _inUseThread = null; + _deliveryThreadLock.unlock(); + + if (_logger.isDebugEnabled()) { + _logger.debug(Thread.currentThread().getName() + " released thread lock on " + this); + } + } + + private void startTransaction(Method method) throws Exception { + boolean endpointRequiresTx = _messageEndpointFactory.isDeliveryTransacted(method); + boolean hasSourceManagedTx; + + if (_logger.isDebugEnabled()) { + _logger.debug(Thread.currentThread().getName() + " is invoking startTransaction: currentTx=" + _transactionManager.getTransaction() + + ", _startedTx=" + _startedTx); + } + + if (_useBatchCommit) { + BatchTransactionHelper helper = _batchHelper.get(); + if (helper != null && helper.isTransactionActive()) { + // under batch processing ... just continue with existing transaction + _startedTx = helper.getAssociatedTransaction(); + return; + } + } + + int txStatus = _transactionManager.getStatus(); + switch (txStatus) { + case Status.STATUS_ACTIVE: + hasSourceManagedTx = true; + break; + case Status.STATUS_NO_TRANSACTION: + hasSourceManagedTx = false; + break; + case Status.STATUS_COMMITTED: + hasSourceManagedTx = false; + // possibly the one which has been commited by reaper thread. try to disassociate... + _transactionManager.suspend(); + break; + default: + throw JCAMessages.MESSAGES.methodNewTransactionCouldnTBeStartedDueToTheStatusOfExistingTransactionStatusCodeTxStatusSeeJavaxTransactionStatus(); + } + + if (hasSourceManagedTx && _useBatchCommit) { + throw JCAMessages.MESSAGES.batchCommitModeCannotBeUsedWithSourceManagedTransactionPleaseTurnOffTheBatchCommit(); + } + + // JCA1.6 SPEC 13.5.9 + if (endpointRequiresTx && !hasSourceManagedTx) { + _transactionManager.begin(); + _startedTx = _transactionManager.getTransaction(); + _startedTx.enlistResource(_xaResource); + if (_useBatchCommit) { + BatchTransactionHelper helper = new BatchTransactionHelper(_startedTx); + helper.scheduleReaperThread(_scheduler, _batchTimeout, TimeUnit.MILLISECONDS); + _batchHelper.set(helper); + } + } else if (!endpointRequiresTx && hasSourceManagedTx) { + _suspendedTx = _transactionManager.suspend(); + } + } + + private void endTransaction(boolean commit) throws Exception { + Transaction currentTx = null; + try { + if (_logger.isDebugEnabled()) { + _logger.debug(Thread.currentThread().getName() + " is invoking endTransaction: currentTx=" + _transactionManager.getTransaction() + + ", _startedTx=" + _startedTx); + } + + // If we started the transaction, commit it + if (_startedTx != null) { + // Suspend any bad transaction - there is bug somewhere, but we will try to tidy things up + currentTx = _transactionManager.getTransaction(); + if (currentTx == null || !currentTx.equals(_startedTx)) { + JCALogger.ROOT_LOGGER.currentTransactionIsNotSameAsThe(currentTx, _startedTx.toString()); + _transactionManager.suspend(); + _transactionManager.resume(_startedTx); + } else { + currentTx = null; + } + + BatchTransactionHelper helper = _batchHelper.get(); + // Commit or rollback depending on the status + if (!commit || _startedTx.getStatus() == Status.STATUS_MARKED_ROLLBACK) { + _transactionManager.rollback(); + if (_useBatchCommit) { + helper.cancelScheduledReaperThread(); + } + } else { + if (_useBatchCommit) { + if (helper.getCounter() + 1 < _batchSize) { + // keep the transaction active for next message + helper.setCounter(helper.getCounter()+1); + } else { + _transactionManager.commit(); + helper.cancelScheduledReaperThread(); + } + _startedTx = null; + return; + } else { + _transactionManager.commit(); + } + } + _startedTx = null; + } + + // If we suspended the incoming transaction, resume it + if (_suspendedTx != null) { + try { + _transactionManager.resume(_suspendedTx); + } finally { + _suspendedTx = null; + } + } + } finally { + // Resume any suspended transaction + if (currentTx != null) { + try { + _transactionManager.resume(currentTx); + } catch (Throwable t) { + JCALogger.ROOT_LOGGER.messageEndpointFailedToResumeOldTransaction(_delegate.toString(), currentTx.toString()); + } + } + } + } + + private class BatchTransactionHelper extends Thread { + private Transaction _transaction; + private int _counter = 0; + private ScheduledFuture _future; + + public BatchTransactionHelper(Transaction tx) { + _transaction = tx; + } + + public void setCounter(int counter) { + _counter = counter; + } + + public int getCounter() { + return _counter; + } + + public boolean isTransactionActive() { + try { + return _transaction.getStatus() == Status.STATUS_ACTIVE; + } catch (Exception e) { + JCALogger.ROOT_LOGGER.failedToRetrieveTransactionStatus(e); + return false; + } + } + + public Transaction getAssociatedTransaction() { + return _transaction; + } + + public void scheduleReaperThread(ScheduledExecutorService service, long delay, TimeUnit unit) { + _future = service.schedule(this, delay, unit); + } + + public void cancelScheduledReaperThread() { + if (_future != null) { + _future.cancel(true); + } + } + + public void run() { + _deliveryThreadLock.lock(); + try { + if (_transaction.getStatus() == Status.STATUS_ACTIVE) { + _transactionManager.resume(_transaction); + _transactionManager.commit(); + JCALogger.ROOT_LOGGER.transactionHasBeenCommittedByReaperThread(_counter); + _counter = 0; + } + } catch (Exception e) { + JCALogger.ROOT_LOGGER.failedToCommitExpiringTransaction(e); + } finally { + _deliveryThreadLock.unlock(); + } + } + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/JCAConstants.java b/components/jca/src/main/java/org/switchyard/component/jca/JCAConstants.java new file mode 100644 index 000000000..a89f7bfeb --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/JCAConstants.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca; + +/** + * Various constants and context variables. + * + * @author Tomohisa Igarashi + * + */ +public final class JCAConstants { + + /** component name. */ + public static final String COMPONENT_NAME = "JCAComponent"; + + /** binding. */ + public static final String BINDING = "binding"; + /** The 'JCA' implementation type. */ + public static final String JCA = "jca"; + + /** outbound conection. */ + public static final String OUTBOUND_CONNECTION = "outboundConnection"; + /** inbound connection. */ + public static final String INBOUND_CONNECTION = "inboundConnection"; + /** outbound interaction. */ + public static final String OUTBOUND_INTERACTION = "outboundInteraction"; + /** inbound interaction. */ + public static final String INBOUND_INTERACTION = "inboundInteraction"; + /** wire format. */ + public static final String WIRE_FORMAT = "wireFormat"; + + /** resource adapter. */ + public static final String RESOURCE_ADAPTER = "resourceAdapter"; + /** connection. */ + public static final String CONNECTION = "connection"; + /** activation spec. */ + public static final String ACTIVATION_SPEC = "activationSpec"; + /** connection spec. */ + public static final String CONNECTION_SPEC = "connectionSpec"; + /** interaction spec. */ + public static final String INTERACTION_SPEC = "interactionSpec"; + /** operation. */ + public static final String OPERATION = "operation"; + /** listener. */ + public static final String LISTENER = "listener"; + /** endpoint. */ + public static final String ENDPOINT = "endpoint"; + /** transacted. */ + public static final String TRANSACTED = "transacted"; + /** processor. */ + public static final String PROCESSOR = "processor"; + + /** batch commit. */ + public static final String BATCH_COMMIT = "batchCommit"; + /** delay limit. */ + public static final String BATCH_TIMEOUT = "batchTimeout"; + /** batch size. */ + public static final String BATCH_SIZE = "batchSize"; + + /** property. */ + public static final String PROPERTY = "property"; + /** name. */ + public static final String NAME = "name"; + /** value. */ + public static final String VALUE = "value"; + + /** default message listener class. */ + public static final String DEFAULT_LISTENER_CLASS = "javax.resource.cci.MessageListener"; + + /** CCI record name key. */ + public static final String CCI_RECORD_NAME_KEY = "recordName"; + /** CCI record short description key. */ + public static final String CCI_RECORD_SHORT_DESC_KEY = "recordShortDescription"; + + /** managed. */ + public static final String MANAGED = "managed"; + /** jndi name. */ + public static final String JNDI_NAME = "jndiName"; + /** type. */ + public static final String TYPE = "type"; + + + private JCAConstants() {} + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/JCALogger.java b/components/jca/src/main/java/org/switchyard/component/jca/JCALogger.java new file mode 100644 index 000000000..5857a88cd --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/JCALogger.java @@ -0,0 +1,144 @@ +package org.switchyard.component.jca; + +import javax.transaction.Transaction; + +import org.jboss.logging.Cause; +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 36800-37199 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface JCALogger { + /** + * A root logger with the category of the package name. + */ + JCALogger ROOT_LOGGER = Logger.getMessageLogger(JCALogger.class, JCALogger.class.getPackage().getName()); + + /** + * errorInRelease method definition. + * @param t the t + */ + @LogMessage(level = Level.WARN) + @Message(id = 36800, value = "Error in release ") + void errorInRelease(@Cause Throwable t); + + /** + * currentTransactionIsNotSameAsThe method definition. + * @param currentTx the currentTx + * @param _startedTx the _startedTx + */ + @LogMessage(level = Level.WARN) + @Message(id = 36801, value = "Current transaction %s is not same as the %s I have started. Replacing it.") + void currentTransactionIsNotSameAsThe(Transaction currentTx, String _startedTx); + + /** + * messageEndpointFailedToResumeOldTransaction method definition. + * @param delegate delegate + * @param currentTx the currentTx + */ + @LogMessage(level = Level.WARN) + @Message(id = 36802, value = "MessageEndpoint %s failed to resume old transaction %s") + void messageEndpointFailedToResumeOldTransaction(String delegate, String currentTx); + + /** + * failedToRetrieveTransactionStatus method definition. + * @param e the e + */ + @LogMessage(level = Level.WARN) + @Message(id = 36803, value = "Failed to retrieve transaction status") + void failedToRetrieveTransactionStatus(@Cause Exception e); + + /** + * transactionHasBeenCommittedByReaperThread method definition. + * @param counter counter + */ + @LogMessage(level = Level.INFO) + @Message(id = 36804, value = "Transaction has been committed by reaper thread [%s]") + void transactionHasBeenCommittedByReaperThread(int counter); + + /** + * failedToCommitExpiringTransaction method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 36805, value = "Failed to commit expiring transaction") + void failedToCommitExpiringTransaction(@Cause Exception e); + + /** + * failedToGetRecordFactory method definition. + * @param eMessage eMessage + */ + @LogMessage(level = Level.WARN) + @Message(id = 36806, value = "Failed to get RecordFactory: %s") + void failedToGetRecordFactory(String eMessage); + + /** + * failedToCloseInteraction/Connection method definition. + * @param eMessage eMessage + */ + @LogMessage(level = Level.WARN) + @Message(id = 36807, value = "Failed to close Interaction/Connection: %s") + void failedToCloseInteractionConnection(String eMessage); + + /** + * failedToCloseJMSSession/connection method definition. + * @param eMessage eMessage + */ + @LogMessage(level = Level.WARN) + @Message(id = 36808, value = "Failed to close JMS session/connection: %s") + void failedToCloseJMSSessionconnection(String eMessage); + + /** + * failedToLoadJndiPropertiesFile method definition. + * @param name file name + * @param e cause + */ + @LogMessage(level = Level.WARN) + @Message(id = 36809, value = "Failed to load JNDI properties from file: %s") + void failedToLoadJndiPropertiesFile(String name, @Cause Exception e); + + /** + * contextDestinationNotFound method definition. + * @param contextDest destination name retrieved from context property + * @param defaultDest default destination name + */ + @LogMessage(level = Level.WARN) + @Message(id = 36810, value = "Destination '%s' could not be found. using '%s' instead") + void contextDestinationNotFound(String contextDest, String defaultDest); + + /** + * destinationNotFound method definition. + * @param destination destination + * @param purpose purpose of the destination + */ + @LogMessage(level = Level.WARN) + @Message(id = 36811, value = "Destination '%s' was not found for '%s'. Ignoring...") + void destinationNotFound(String destination, String purpose); + + /** + * failedToSendMessage method definition. + * @param destination destination + * @param eMessage exception message + */ + @LogMessage(level = Level.WARN) + @Message(id = 36812, value = "Failed to send a message to '%s': %s") + void failedToSendMessage(String destination, String eMessage); + + /** + * invalidDestinationType method definition. + * @param type specified destination type + * @param alternative alternative destination type + */ + @LogMessage(level = Level.WARN) + @Message(id = 36813, value = "Invalid destination type '%s' - using '%s' instead") + void invalidDestinationType(String type, String alternative); + +} + diff --git a/components/jca/src/main/java/org/switchyard/component/jca/JCAMessages.java b/components/jca/src/main/java/org/switchyard/component/jca/JCAMessages.java new file mode 100644 index 000000000..9a72c0380 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/JCAMessages.java @@ -0,0 +1,309 @@ +package org.switchyard.component.jca; + +import javax.naming.NamingException; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; +/** + *

+ * This file is using the subset 37200-37599 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface JCAMessages { + /** + * The default messages. + */ + JCAMessages MESSAGES = Messages.getBundle(JCAMessages.class); + + /** + * theSizeOfMessageContentExceedsBytesThatIsNotSupportedByThisMessageComposer method definition. + * @param maxValue maxValue + * @return SwitchYardException + */ + @Message(id = 37200, value = "The size of message content exceeds %s bytes, that is not supported by this MessageComposer") + SwitchYardException theSizeOfMessageContentExceedsBytesThatIsNotSupportedByThisMessageComposer(String maxValue); + + /** + * resourceAdapterRepositoryMustBeInjectedToActivateJCAComponent method definition. + * @return IllegalStateException + */ + @Message(id = 37202, value = "ResourceAdapterRepository must be injected to activate JCA component.") + IllegalStateException resourceAdapterRepositoryMustBeInjectedToActivateJCAComponent(); + + /** + * unableToFindTransactionManagerInJNDIAt method definition. + * @param transactionManager transactionManager + * @param e the e + * @return IllegalArgumentException + */ + @Message(id = 37203, value = "Unable to find TransactionManager in JNDI at %s") + IllegalArgumentException unableToFindTransactionManagerInJNDIAt(String transactionManager, @Cause NamingException e); + + /** + * uniqueKeyForResourceAdapter method definition. + * @param raName the raName + * @return IllegalArgumentException + */ + @Message(id = 37204, value = "Unique key for ResourceAdapter '%s' couldn't be found.") + IllegalArgumentException uniqueKeyForResourceAdapter(String raName); + + /** + * listenerTypeIsNotSupportedByResourceAdapter method definition. + * @param listenerTypeName listenerTypeName + * @param raName the raName + * @return IllegalArgumentException + */ + @Message(id = 37206, value = "listener type %s is not supported by ResourceAdapter %s") + IllegalArgumentException listenerTypeIsNotSupportedByResourceAdapter(String listenerTypeName, String raName); + + /** + * couldnTAcquireTheResourceAdapter method definition. + * @param raName the raName + * @param e the e + * @return IllegalArgumentException + */ + @Message(id = 37207, value = "Couldn't acquire the ResourceAdapter '%s'.") + IllegalArgumentException couldnTAcquireTheResourceAdapter(String raName, @Cause Exception e); + + /** + * endpointClass method definition. + * @param endpointClassName the endpointClassName + * @param e the e + * @return IllegalArgumentException + */ + @Message(id = 37208, value = "Endpoint class '%s' couldn't be instantiated.") + IllegalArgumentException endpointClass(String endpointClassName, @Cause Exception e); + + /** + * nonManagedScenarioIsNotSupportedYet method definition. + * @return IllegalArgumentException + */ + @Message(id = 37209, value = "Non-Managed Scenario is not supported yet") + IllegalArgumentException nonManagedScenarioIsNotSupportedYet(); + + /** + * outboundProcessorClass method definition. + * @param processorClassName the processorClassName + * @param e the e + * @return IllegalArgumentException + */ + @Message(id = 37212, value = "Outbound Processor class '%s' couldn't be instantiated.") + IllegalArgumentException outboundProcessorClass(String processorClassName, @Cause Exception e); + + /** + * referenceBindingNotStarted method definition. + * @param referenceName the referenceName + * @param bindingName the bindingName + * @return HandlerException + */ + @Message(id = 37213, value = "Reference binding \"%s/%s\" is not started.") + HandlerException referenceBindingNotStarted(String referenceName, String bindingName); + + /** + * initializeMustBeCalledBeforeExchange method definition. + * @return IllegalStateException + */ + @Message(id = 37214, value = "initialize() must be called before exchange.") + IllegalStateException initializeMustBeCalledBeforeExchange(); + + /** + * missingAfterDeliveryFromThePreviousBeforeDeliveryForMessageEndpoint method definition. + * @param delegate the delegate + * @return IllegalStateException + */ + @Message(id = 37219, value = "Missing afterDelivery from the previous beforeDelivery for message endpoint %s") + IllegalStateException missingAfterDeliveryFromThePreviousBeforeDeliveryForMessageEndpoint(String delegate); + + /** + * afterDeliveryWithoutAPreviousBeforeDeliveryForMessageEndpoint method definition. + * @param delegate delegate + * @return IllegalStateException + */ + @Message(id = 37221, value = "afterDelivery without a previous beforeDelivery for message endpoint %s") + IllegalStateException afterDeliveryWithoutAPreviousBeforeDeliveryForMessageEndpoint(String delegate); + + /** + * multipleMessageDeliveryBetweenBeforeAndAfterDeliveryIsNotAllowedForMessageEndpoint method definition. + * @param delegate the delegate + * @return IllegalStateException + */ + @Message(id = 37223, value = "Multiple message delivery between before and after delivery is not allowed for message endpoint %s") + IllegalStateException multipleMessageDeliveryBetweenBeforeAndAfterDeliveryIsNotAllowedForMessageEndpoint(String delegate); + + /** + * threadCurrentThreadGetNameCouldnTAcquireAThreadLockSinceThisIsAlreadyInUseByAnotherThreadInUseThreadGetName method definition. + * @param threadName threadName + * @param objectName objectName + * @param inUseThreadName inUseThreadName + * @return IllegalStateException + */ + @Message(id = 37224, value = "%s couldn't acquire a thread lock since %s is already in use by another thread: %s") + IllegalStateException threadCurrentThreadGetNameCouldnTAcquireAThreadLockSinceThisIsAlreadyInUseByAnotherThreadInUseThreadGetName(String threadName, String objectName, String inUseThreadName); + + /** + * methodNewTransactionCouldnTBeStartedDueToTheStatusOfExistingTransactionStatusCodeTxStatusSeeJavaxTransactionStatus method definition. + * @return IllegalStateException + */ + @Message(id = 37225, value = "") + IllegalStateException methodNewTransactionCouldnTBeStartedDueToTheStatusOfExistingTransactionStatusCodeTxStatusSeeJavaxTransactionStatus(); + + /** + * batchCommitModeCannotBeUsedWithSourceManagedTransactionPleaseTurnOffTheBatchCommit method definition. + * @return IllegalStateException + */ + @Message(id = 37226, value = "Batch commit mode cannot be used with source managed transaction. Please turn off the batch commit.") + IllegalStateException batchCommitModeCannotBeUsedWithSourceManagedTransactionPleaseTurnOffTheBatchCommit(); + + /** + * recordTypeIsNotSupported method definition. + * @param recordTypeName the recordTypeName + * @return SwitchYardException + */ + @Message(id = 37227, value = "record type '%sis not supported") + SwitchYardException recordTypeIsNotSupported(String recordTypeName); + + /** + * couldNotInitializeConnectionSpec method definition. + * @param e the e + * @return IllegalArgumentException + */ + @Message(id = 37228, value = "Could not initialize ConnectionSpec") + IllegalArgumentException couldNotInitializeConnectionSpec(@Cause Exception e); + + /** + * couldNotInitializeInteractionSpec method definition. + * @param e the e + * @return IllegalArgumentException + */ + @Message(id = 37229, value = "Could not initialize InteractionSpec") + IllegalArgumentException couldNotInitializeInteractionSpec(@Cause Exception e); + + /** + * failedToInitialize method definition. + * @param className className + * @param e the e + * @return SwitchYardException + */ + @Message(id = 37230, value = "Failed to initialize %s") + SwitchYardException failedToInitialize(String className, @Cause Exception e); + + /** + * failedToProcessCCIOutboundInteraction method definition. + * @param e the e + * @return HandlerException + */ + @Message(id = 37231, value = "Failed to process CCI outbound interaction") + HandlerException failedToProcessCCIOutboundInteraction(@Cause Exception e); + + /** + * destinationPropertyMustBeSpecifiedInProcessorProperties method definition. + * @return SwitchYardException + */ + @Message(id = 37232, value = "destination property must be specified in Processor properties") + SwitchYardException destinationPropertyMustBeSpecifiedInProcessorProperties(); + + /** + * failedToProcessJMSOutboundInteraction method definition. + * @param e the e + * @return HandlerException + */ + @Message(id = 37234, value = "Failed to process JMS outbound interaction") + HandlerException failedToProcessJMSOutboundInteraction(@Cause Exception e); + + /** + * theSizeOfMessageContentExceedsBytesThatIsNotSupportedByThisOperationSelector method definition. + * @param maxValue maxValue + * @return Exception + */ + @Message(id = 37235, value = "The size of message content exceeds %s bytes, that is not supported by this OperationSelector") + Exception theSizeOfMessageContentExceedsBytesThatIsNotSupportedByThisOperationSelector(String maxValue); + + /** + * noOperationSelectorConfigured method definition. + * @param operations operations + * @return SwitchYardException + */ + @Message(id = 37236, value = "No operationSelector was configured for the JCA Component and the Service Interface contains more than one operation: " + + "%s. Please add an operationSelector element.") + SwitchYardException noOperationSelectorConfigured(String operations); + + /** + * noInboundConnectionConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37237, value = "No inboundConnection was configured for the JCA Component") + IllegalArgumentException noInboundConnectionConfigured(); + + /** + * noResourceAdapterConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37238, value = "No resourceAdapter was configured for the JCA Component") + IllegalArgumentException noResourceAdapterConfigured(); + + /** + * noResourceAdapterNameConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37239, value = "No resourceAdapter name was configured for the JCA Component") + IllegalArgumentException noResourceAdapterNameConfigured(); + + /** + * noInboundInteractionConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37240, value = "No inboundInteraction was configured for the JCA Component") + IllegalArgumentException noInboundInteractionConfigured(); + + /** + * noListenerClassFound method definition. + * @param listener listener class name + * @param e root cause + * @return IllegalArgumentException + */ + @Message(id = 37241, value = "Listener class '%s' could not be loaded.") + IllegalArgumentException noListenerClassFound(String listener, @Cause Exception e); + + /** + * noEndpointConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37242, value = "No endpoint was configured for the JCA Component") + IllegalArgumentException noEndpointConfigured(); + + /** + * noOutboundInteractionConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37243, value = "No outboundInteraction was configured for the JCA Component") + IllegalArgumentException noOutboundInteractionConfigured(); + + /** + * noProcessorConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37244, value = "No processor was configured for the JCA Component") + IllegalArgumentException noProcessorConfigured(); + + /** + * noConnectionConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37245, value = "No connection was configured for the JCA Component") + IllegalArgumentException noConnectionConfigured(); + + /** + * noOutboundConnectionConfigured method definition. + * @return IllegalArgumentException + */ + @Message(id = 37246, value = "No outboundConnection was configured for the JCA Component") + IllegalArgumentException noOutboundConnectionConfigured(); + +} + diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordBindingData.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordBindingData.java new file mode 100644 index 000000000..53be55443 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordBindingData.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import javax.resource.cci.IndexedRecord; + +/** + * Indexed record binding data. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class IndexedRecordBindingData implements RecordBindingData { + + private final IndexedRecord _record; + + /** + * Constructs a new indexed record binding data with the specified indexed record. + * @param record the specified indexed record + */ + public IndexedRecordBindingData(IndexedRecord record) { + _record = record; + } + + /** + * {@inheritDoc} + */ + @Override + public IndexedRecord getRecord() { + return _record; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordContextMapper.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordContextMapper.java new file mode 100644 index 000000000..486fe9a50 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordContextMapper.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import javax.resource.cci.IndexedRecord; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.component.common.composer.BaseRegexContextMapper; +import org.switchyard.component.common.label.ComponentLabel; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.component.jca.JCAConstants; + +/** + * ContextMapper for CCI IndexedRecord. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class IndexedRecordContextMapper extends BaseRegexContextMapper { + + private static final String[] INDEXED_RECORD_LABELS = new String[]{ComponentLabel.JCA.label(), EndpointLabel.JCA.label()}; + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(IndexedRecordBindingData source, Context context) throws Exception { + IndexedRecord record = source.getRecord(); + String recordName = record.getRecordName(); + if (recordName != null) { + context.setProperty(JCAConstants.CCI_RECORD_NAME_KEY, recordName).addLabels(INDEXED_RECORD_LABELS); + } + String recordDescription = record.getRecordShortDescription(); + if (recordDescription != null) { + context.setProperty(JCAConstants.CCI_RECORD_SHORT_DESC_KEY, recordDescription).addLabels(INDEXED_RECORD_LABELS); + } + } + + /** + * {@inheritDoc} + */ + @SuppressWarnings("unchecked") + @Override + public void mapTo(Context context, IndexedRecordBindingData target) throws Exception { + IndexedRecord record = target.getRecord(); + for (Property property : context.getProperties()) { + String name = property.getName(); + Object value = property.getValue(); + if (value == null) { + continue; + } + if (name.equals(JCAConstants.CCI_RECORD_NAME_KEY)) { + record.setRecordName(value.toString()); + } else if (name.equals(JCAConstants.CCI_RECORD_SHORT_DESC_KEY)) { + record.setRecordShortDescription(value.toString()); + } else if (matches(name)) { + record.add(name + "=" + value); + } + } + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordContextMapperFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordContextMapperFactory.java new file mode 100644 index 000000000..a7fc90a28 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordContextMapperFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.ContextMapperFactory; + +/** + * ContextMapperFactory for CCI IndexedRecord. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class IndexedRecordContextMapperFactory extends ContextMapperFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return IndexedRecordBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper newContextMapperDefault() { + return new IndexedRecordContextMapper(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordMessageComposer.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordMessageComposer.java new file mode 100644 index 000000000..fba1b4e7b --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordMessageComposer.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import java.util.ArrayList; +import java.util.List; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.common.composer.BaseMessageComposer; + +/** + * MessageComposer implementation for CCI IndexedRecord that is used by JCA component. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class IndexedRecordMessageComposer extends BaseMessageComposer { + + /** + * {@inheritDoc} + */ + @Override + public org.switchyard.Message compose(IndexedRecordBindingData source, Exchange exchange) throws Exception { + + final org.switchyard.Message message = exchange.createMessage(); + getContextMapper().mapFrom(source, exchange.getContext(message)); + List l = new ArrayList(); + l.addAll(source.getRecord()); + message.setContent(l); + return message; + } + + /** + * {@inheritDoc} + */ + @SuppressWarnings("unchecked") + @Override + public IndexedRecordBindingData decompose(Exchange exchange, IndexedRecordBindingData target) throws Exception { + Message sourceMessage = exchange.getMessage(); + + getContextMapper().mapTo(exchange.getContext(), target); + final List content = sourceMessage.getContent(List.class); + target.getRecord().addAll(content); + return target; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordMessageComposerFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordMessageComposerFactory.java new file mode 100644 index 000000000..1cd706e62 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/IndexedRecordMessageComposerFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.MessageComposerFactory; + +/** + * MessageComposerFactory for CCI IndexedRecord. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class IndexedRecordMessageComposerFactory extends MessageComposerFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return IndexedRecordBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer newMessageComposerDefault() { + return new IndexedRecordMessageComposer(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/JCABindingData.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/JCABindingData.java new file mode 100644 index 000000000..2d2f195b4 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/JCABindingData.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.BindingData; + +/** + * JCA binding data. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface JCABindingData extends BindingData {} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/JCAComposition.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/JCAComposition.java new file mode 100644 index 000000000..655038444 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/JCAComposition.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.Composition; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.config.model.JCABindingModel; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; + +/** + * Utility class for JCA-specific Composition. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class JCAComposition { + + /** + * Uses the {@link Composition} class to create a JCA-specific MessageComposer. + * @param bindingDataType {@link Class} for binding data type + * @param jca binding data type + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer(Class bindingDataType) { + return Composition.getMessageComposer(bindingDataType); + } + + /** + * Uses the {@link Composition} class to create a JCA-specific MessageComposer. + * @param jcabm a JCABindingModel to get configuration details from + * @param bindingDataType {@link Class} for binding data type + * @param jca binding data type + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer(JCABindingModel jcabm, Class bindingDataType) { + ContextMapperModel cmm = jcabm != null ? jcabm.getContextMapper() : null; + MessageComposerModel mcm = jcabm != null ? jcabm.getMessageComposer() : null; + return Composition.getMessageComposer(bindingDataType, cmm, mcm); + } + + private JCAComposition() {} + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSBindingData.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSBindingData.java new file mode 100644 index 000000000..f5156a32c --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSBindingData.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import javax.jms.Message; + +/** + * JMS binding data. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class JMSBindingData implements JCABindingData { + + private final Message _message; + + /** + * Constructs a new JMS binding data with the specified message. + * @param message the specified message + */ + public JMSBindingData(Message message) { + _message = message; + } + + /** + * Gets the message. + * @return the message + */ + public Message getMessage() { + return _message; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSContextMapper.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSContextMapper.java new file mode 100644 index 000000000..0e0f63c02 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSContextMapper.java @@ -0,0 +1,169 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import java.util.Enumeration; + +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Message; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.component.common.composer.BaseRegexContextMapper; +import org.switchyard.component.common.label.ComponentLabel; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.component.common.label.PropertyLabel; + +/** + * JMSContextMapper. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class JMSContextMapper extends BaseRegexContextMapper { + + /** JMSDestination header. */ + public static final String HEADER_JMS_DESTINATION = "javax.jms.JMSDestination"; + /** JMSDeliveryMode header. */ + public static final String HEADER_JMS_DELIVERY_MODE = "javax.jms.JMSDeliveryMode"; + /** JMSMessageID header. */ + public static final String HEADER_JMS_MESSAGE_ID = "javax.jms.JMSMessageID"; + /** JMSTimestamp header. */ + public static final String HEADER_JMS_TIMESTAMP = "javax.jms.JMSTimestamp"; + /** JMSCorrelationID header. */ + public static final String HEADER_JMS_CORRELATION_ID = "javax.jms.JMSCorrelationID"; + /** JMSReplyTo header. */ + public static final String HEADER_JMS_REPLY_TO = "javax.jms.JMSReplyTo"; + /** JMSRedelivered header. */ + public static final String HEADER_JMS_REDELIVERED = "javax.jms.JMSRedelivered"; + /** JMSType header. */ + public static final String HEADER_JMS_TYPE = "javax.jms.JMSType"; + /** JMSExpiration header. */ + public static final String HEADER_JMS_EXPIRATION = "javax.jms.JMSExpiration"; + /** JMSPriority header. */ + public static final String HEADER_JMS_PRIORITY = "javax.jms.JMSPriority"; + + private static final String[] JMS_HEADER_LABELS = new String[]{ComponentLabel.JCA.label(), EndpointLabel.JMS.label(), PropertyLabel.HEADER.label()}; + private static final String[] JMS_PROPERTY_LABELS = new String[]{ComponentLabel.JCA.label(), EndpointLabel.JMS.label(), PropertyLabel.PROPERTY.label()}; + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(JMSBindingData source, Context context) throws Exception { + Message message = source.getMessage(); + + // process JMS headers + if (matches(HEADER_JMS_DESTINATION)) { + context.setProperty(HEADER_JMS_DESTINATION, message.getJMSDestination()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_DELIVERY_MODE)) { + context.setProperty(HEADER_JMS_DELIVERY_MODE, message.getJMSDeliveryMode()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_EXPIRATION)) { + context.setProperty(HEADER_JMS_EXPIRATION, message.getJMSExpiration()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_PRIORITY)) { + context.setProperty(HEADER_JMS_PRIORITY, message.getJMSPriority()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_MESSAGE_ID)) { + context.setProperty(HEADER_JMS_MESSAGE_ID, message.getJMSMessageID()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_TIMESTAMP)) { + context.setProperty(HEADER_JMS_TIMESTAMP, message.getJMSTimestamp()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_CORRELATION_ID)) { + context.setProperty(HEADER_JMS_CORRELATION_ID, message.getJMSCorrelationID()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_REPLY_TO)) { + context.setProperty(HEADER_JMS_REPLY_TO, message.getJMSReplyTo()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_TYPE)) { + context.setProperty(HEADER_JMS_TYPE, message.getJMSType()).addLabels(JMS_HEADER_LABELS); + } + if (matches(HEADER_JMS_REDELIVERED)) { + context.setProperty(HEADER_JMS_REDELIVERED, message.getJMSRedelivered()).addLabels(JMS_HEADER_LABELS); + } + + // process JMS properties + Enumeration e = message.getPropertyNames(); + while (e.hasMoreElements()) { + String key = e.nextElement().toString(); + if (matches(key)) { + Object value = null; + try { + value = message.getObjectProperty(key); + } catch (JMSException pce) { + // ignore and keep going (here just to keep checkstyle happy) + pce.getMessage(); + } + if (value != null) { + context.setProperty(key, value).addLabels(JMS_PROPERTY_LABELS); + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mapTo(Context context, JMSBindingData target) throws Exception { + Message message = target.getMessage(); + for (Property property : context.getProperties()) { + String name = property.getName(); + + if (matches(name)) { + Object value = property.getValue(); + if (value == null) { + continue; + } + + try { + // process JMS headers + if (name.equals(HEADER_JMS_DESTINATION)) { + message.setJMSDestination(Destination.class.cast(value)); + } else if (name.equals(HEADER_JMS_DELIVERY_MODE)) { + message.setJMSDeliveryMode(Integer.parseInt(value.toString())); + } else if (name.equals(HEADER_JMS_EXPIRATION)) { + message.setJMSExpiration(Long.parseLong(value.toString())); + } else if (name.equals(HEADER_JMS_PRIORITY)) { + message.setJMSPriority(Integer.parseInt(value.toString())); + } else if (name.equals(HEADER_JMS_MESSAGE_ID)) { + message.setJMSMessageID(value.toString()); + } else if (name.equals(HEADER_JMS_TIMESTAMP)) { + message.setJMSTimestamp(Long.parseLong(value.toString())); + } else if (name.equals(HEADER_JMS_CORRELATION_ID)) { + message.setJMSCorrelationID(value.toString()); + } else if (name.equals(HEADER_JMS_REPLY_TO)) { + message.setJMSReplyTo(Destination.class.cast(value)); + } else if (name.equals(HEADER_JMS_TYPE)) { + message.setJMSType(value.toString()); + } else if (name.equals(HEADER_JMS_REDELIVERED)) { + message.setJMSRedelivered(Boolean.parseBoolean(value.toString())); + + // process JMS properties + } else { + message.setObjectProperty(name, value); + } + } catch (Throwable t) { + continue; + } + } + } + + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSContextMapperFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSContextMapperFactory.java new file mode 100644 index 000000000..2cf87972f --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSContextMapperFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.ContextMapperFactory; + +/** + * JCAJMSContextMapperFactory. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class JMSContextMapperFactory extends ContextMapperFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return JMSBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper newContextMapperDefault() { + return new JMSContextMapper(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSMessageComposer.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSMessageComposer.java new file mode 100644 index 000000000..5ad33bb94 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSMessageComposer.java @@ -0,0 +1,142 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import java.io.InputStream; +import java.io.Serializable; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +import javax.jms.BytesMessage; +import javax.jms.MapMessage; +import javax.jms.Message; +import javax.jms.ObjectMessage; +import javax.jms.StreamMessage; +import javax.jms.TextMessage; + +import org.switchyard.Exchange; +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.common.composer.BaseMessageComposer; + +/** + * MessageComposer implementation for JMS Message that is used by JCA component. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class JMSMessageComposer extends BaseMessageComposer { + + /** + * {@inheritDoc} + */ + @Override + public org.switchyard.Message compose(JMSBindingData source, Exchange exchange) throws Exception { + final org.switchyard.Message syMessage = exchange.createMessage(); + getContextMapper().mapFrom(source, exchange.getContext(syMessage)); + + Message jmsMessage = source.getMessage(); + if (jmsMessage instanceof BytesMessage) { + BytesMessage sourceBytes = BytesMessage.class.cast(jmsMessage); + if (sourceBytes.getBodyLength() > Integer.MAX_VALUE) { + throw JCAMessages.MESSAGES.theSizeOfMessageContentExceedsBytesThatIsNotSupportedByThisMessageComposer("" + Integer.MAX_VALUE); + } + byte[] bytearr = new byte[(int)sourceBytes.getBodyLength()]; + sourceBytes.readBytes(bytearr); + syMessage.setContent(bytearr); + + } else if (jmsMessage instanceof MapMessage) { + MapMessage sourceMap = MapMessage.class.cast(jmsMessage); + Map body = new HashMap(); + Enumeration e = sourceMap.getMapNames(); + while (e.hasMoreElements()) { + String key = String.class.cast(e.nextElement()); + body.put(key, sourceMap.getObject(key)); + } + syMessage.setContent(body); + + } else if (jmsMessage instanceof ObjectMessage) { + ObjectMessage sourceObj = ObjectMessage.class.cast(jmsMessage); + syMessage.setContent(sourceObj.getObject()); + + } else if (jmsMessage instanceof StreamMessage) { + StreamMessage sourceStream = StreamMessage.class.cast(jmsMessage); + syMessage.setContent(sourceStream); + + } else if (jmsMessage instanceof TextMessage) { + TextMessage sourceText = TextMessage.class.cast(jmsMessage); + syMessage.setContent(sourceText.getText()); + + } else { + // plain javax.jms.Message doesn't have body content + syMessage.setContent(null); + } + + return syMessage; + } + + /** + * {@inheritDoc} + */ + @Override + public JMSBindingData decompose(Exchange exchange, JMSBindingData target) throws Exception { + org.switchyard.Message syMessage = exchange.getMessage(); + getContextMapper().mapTo(exchange.getContext(), target); + Message jmsMessage = target.getMessage(); + + if (jmsMessage instanceof ObjectMessage) { + ObjectMessage msg = ObjectMessage.class.cast(jmsMessage); + // expect transformer to transform the content into Serializable ... + msg.setObject(syMessage.getContent(Serializable.class)); + + } else if (jmsMessage instanceof TextMessage) { + TextMessage msg = TextMessage.class.cast(jmsMessage); + msg.setText(syMessage.getContent(String.class)); + + } else if (jmsMessage instanceof BytesMessage) { + BytesMessage msg = BytesMessage.class.cast(jmsMessage); + msg.writeBytes(syMessage.getContent(byte[].class)); + + } else if (jmsMessage instanceof StreamMessage) { + StreamMessage msg = StreamMessage.class.cast(jmsMessage); + byte[] buffer = new byte[8192]; + int size = 0; + if (syMessage.getContent() instanceof StreamMessage) { + // in case the StreamMessage is passed through from JMS inbound + StreamMessage sm = syMessage.getContent(StreamMessage.class); + while ((size = sm.readBytes(buffer)) > 0) { + msg.writeBytes(buffer, 0, size); + } + } else { + InputStream is = syMessage.getContent(InputStream.class); + while ((size = is.read(buffer)) > 0) { + msg.writeBytes(buffer, 0, size); + } + } + + } else if (jmsMessage instanceof MapMessage) { + MapMessage msg = MapMessage.class.cast(jmsMessage); + Map map = syMessage.getContent(Map.class); + Iterator entries = (Iterator)map.entrySet().iterator(); + while (entries.hasNext()) { + Entry entry = (Entry) entries.next(); + msg.setObject((String) entry.getKey(), entry.getValue()); + } + } + return target; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSMessageComposerFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSMessageComposerFactory.java new file mode 100644 index 000000000..95c50c36d --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/JMSMessageComposerFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.MessageComposerFactory; + +/** + * JCAJMSMessageComposerFactory. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class JMSMessageComposerFactory extends MessageComposerFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return JMSBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer newMessageComposerDefault() { + return new JMSMessageComposer(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordBindingData.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordBindingData.java new file mode 100644 index 000000000..f8c34898c --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordBindingData.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import javax.resource.cci.MappedRecord; + +/** + * Mapped record binding data. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class MappedRecordBindingData implements RecordBindingData { + + private final MappedRecord _record; + + /** + * Constructs a new mapped record binding data with the specified mapped record. + * @param record the specified mapped record + */ + public MappedRecordBindingData(MappedRecord record) { + _record = record; + } + + /** + * {@inheritDoc} + */ + @Override + public MappedRecord getRecord() { + return _record; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordContextMapper.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordContextMapper.java new file mode 100644 index 000000000..d021765a2 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordContextMapper.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import javax.resource.cci.MappedRecord; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.component.common.composer.BaseRegexContextMapper; +import org.switchyard.component.common.label.ComponentLabel; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.component.jca.JCAConstants; + +/** + * ContextMapper for CCI MappedRecord. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class MappedRecordContextMapper extends BaseRegexContextMapper { + + private static final String[] MAPPED_RECORD_LABELS = new String[]{ComponentLabel.JCA.label(), EndpointLabel.JCA.label()}; + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(MappedRecordBindingData source, Context context) throws Exception { + MappedRecord record = source.getRecord(); + String recordName = record.getRecordName(); + if (recordName != null) { + context.setProperty(JCAConstants.CCI_RECORD_NAME_KEY, recordName).addLabels(MAPPED_RECORD_LABELS); + } + String recordDescription = record.getRecordShortDescription(); + if (recordDescription != null) { + context.setProperty(JCAConstants.CCI_RECORD_SHORT_DESC_KEY, recordDescription).addLabels(MAPPED_RECORD_LABELS); + } + } + + /** + * {@inheritDoc} + */ + @SuppressWarnings("unchecked") + @Override + public void mapTo(Context context, MappedRecordBindingData target) throws Exception { + MappedRecord record = target.getRecord(); + for (Property property : context.getProperties()) { + String name = property.getName(); + Object value = property.getValue(); + if (value == null) { + continue; + } + if (name.equals(JCAConstants.CCI_RECORD_NAME_KEY)) { + record.setRecordName(value.toString()); + } else if (name.equals(JCAConstants.CCI_RECORD_SHORT_DESC_KEY)) { + record.setRecordShortDescription(value.toString()); + } else if (matches(name)) { + record.put(name, value); + } + } + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordContextMapperFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordContextMapperFactory.java new file mode 100644 index 000000000..4c45372d7 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordContextMapperFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.ContextMapperFactory; + +/** + * ContextMapperFactory for CCI MappedRecord. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class MappedRecordContextMapperFactory extends ContextMapperFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return MappedRecordBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper newContextMapperDefault() { + return new MappedRecordContextMapper(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordMessageComposer.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordMessageComposer.java new file mode 100644 index 000000000..00067902d --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordMessageComposer.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import java.util.HashMap; +import java.util.Map; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.common.composer.BaseMessageComposer; + +/** + * MessageComposer implementation for CCI MappedRecord that is used by JCA component. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class MappedRecordMessageComposer extends BaseMessageComposer { + + /** + * {@inheritDoc} + */ + @Override + public org.switchyard.Message compose(MappedRecordBindingData source, Exchange exchange) throws Exception { + final org.switchyard.Message message = exchange.createMessage(); + getContextMapper().mapFrom(source, exchange.getContext(message)); + Map m = new HashMap(); + m.putAll(source.getRecord()); + message.setContent(m); + return message; + } + + /** + * {@inheritDoc} + */ + @SuppressWarnings("unchecked") + @Override + public MappedRecordBindingData decompose(Exchange exchange, MappedRecordBindingData target) throws Exception { + Message sourceMessage = exchange.getMessage(); + + getContextMapper().mapTo(exchange.getContext(), target); + final Map content = sourceMessage.getContent(Map.class); + target.getRecord().putAll(content); + return target; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordMessageComposerFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordMessageComposerFactory.java new file mode 100644 index 000000000..322368c16 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/MappedRecordMessageComposerFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.MessageComposerFactory; + +/** + * MessageComposerFactory for CCI MappedRecord. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + */ +public class MappedRecordMessageComposerFactory extends MessageComposerFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return MappedRecordBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer newMessageComposerDefault() { + return new MappedRecordMessageComposer(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/RecordBindingData.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/RecordBindingData.java new file mode 100644 index 000000000..26380e94d --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/RecordBindingData.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import javax.resource.cci.Record; + +/** + * Record binding data. + * + * @param the type of record + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface RecordBindingData extends JCABindingData { + + /** + * Gets the record. + * @return the record + */ + public R getRecord(); + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordBindingData.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordBindingData.java new file mode 100644 index 000000000..5171ec4a5 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordBindingData.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.jca.processor.cci.StreamableRecord; + +/** + * Streamable record binding data. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + * @author Antti Laisi + */ +public class StreamableRecordBindingData implements RecordBindingData { + + private final StreamableRecord _record; + + /** + * Constructs a new streamable record binding data with the specified record. + * @param record the specified streamable record + */ + public StreamableRecordBindingData(StreamableRecord record) { + _record = record; + } + + /** + * {@inheritDoc} + */ + @Override + public StreamableRecord getRecord() { + return _record; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordContextMapper.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordContextMapper.java new file mode 100644 index 000000000..b57590e86 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordContextMapper.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.component.common.composer.BaseRegexContextMapper; +import org.switchyard.component.common.label.ComponentLabel; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.processor.cci.StreamableRecord; + +/** + * ContextMapper for CCI Streamable Record. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + * @author Antti Laisi + */ +public class StreamableRecordContextMapper extends BaseRegexContextMapper { + + private static final String[] STREAMABLE_RECORD_LABELS = new String[]{ComponentLabel.JCA.label(), EndpointLabel.JCA.label()}; + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(StreamableRecordBindingData source, Context context) throws Exception { + StreamableRecord record = source.getRecord(); + String recordName = record.getRecordName(); + if (recordName != null) { + context.setProperty(JCAConstants.CCI_RECORD_NAME_KEY, recordName).addLabels(STREAMABLE_RECORD_LABELS); + } + String recordDescription = record.getRecordShortDescription(); + if (recordDescription != null) { + context.setProperty(JCAConstants.CCI_RECORD_SHORT_DESC_KEY, recordDescription).addLabels(STREAMABLE_RECORD_LABELS); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mapTo(Context context, StreamableRecordBindingData target) throws Exception { + StreamableRecord record = target.getRecord(); + for (Property property : context.getProperties()) { + String name = property.getName(); + Object value = property.getValue(); + if (value == null) { + continue; + } + if (name.equals(JCAConstants.CCI_RECORD_NAME_KEY)) { + record.setRecordName(value.toString()); + } else if (name.equals(JCAConstants.CCI_RECORD_SHORT_DESC_KEY)) { + record.setRecordShortDescription(value.toString()); + } + } + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordContextMapperFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordContextMapperFactory.java new file mode 100644 index 000000000..5e689a28c --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordContextMapperFactory.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.ContextMapperFactory; + +/** + * ContextMapperFactory for CCI Streamable Record. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + * @author Antti Laisi + */ +public class StreamableRecordContextMapperFactory extends ContextMapperFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return StreamableRecordBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper newContextMapperDefault() { + return new StreamableRecordContextMapper(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordMessageComposer.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordMessageComposer.java new file mode 100644 index 000000000..c4e8eabf1 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordMessageComposer.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.common.composer.BaseMessageComposer; + +/** + * MessageComposer implementation for CCI Streamable Record that is used by JCA component. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + * @author Antti Laisi + */ +public class StreamableRecordMessageComposer extends BaseMessageComposer { + + /** + * {@inheritDoc} + */ + @Override + public Message compose(StreamableRecordBindingData source, Exchange exchange) throws Exception { + final org.switchyard.Message message = exchange.createMessage(); + getContextMapper().mapFrom(source, exchange.getContext(message)); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + source.getRecord().write(baos); + message.setContent(new ByteArrayInputStream(baos.toByteArray())); + return message; + } + + /** + * {@inheritDoc} + */ + @Override + public StreamableRecordBindingData decompose(Exchange exchange, StreamableRecordBindingData target) throws Exception { + Message sourceMessage = exchange.getMessage(); + + getContextMapper().mapTo(exchange.getContext(), target); + final InputStream content = sourceMessage.getContent(InputStream.class); + target.getRecord().read(content); + return target; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordMessageComposerFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordMessageComposerFactory.java new file mode 100644 index 000000000..897de92a8 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/composer/StreamableRecordMessageComposerFactory.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.composer; + +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.MessageComposerFactory; + +/** + * MessageComposerFactory for CCI Streamable Record. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Tomohisa Igarashi + * @author Antti Laisi + */ +public class StreamableRecordMessageComposerFactory extends MessageComposerFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return StreamableRecordBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer newMessageComposerDefault() { + return new StreamableRecordMessageComposer(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/ActivationSpecModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ActivationSpecModel.java new file mode 100644 index 000000000..bd647e7d4 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ActivationSpecModel.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +/** + * binding.jca/inboundConnection/activationSpec model. + * + * @author Tomohisa Igarashi + * + */ +public interface ActivationSpecModel extends BasePropertyContainerModel { +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/BasePropertyContainerModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/BasePropertyContainerModel.java new file mode 100644 index 000000000..9e56b35cf --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/BasePropertyContainerModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import java.util.Properties; + +import org.switchyard.config.model.Model; + +/** + * base property container model. + * + * @author Tomohisa Igarashi + * + */ +public interface BasePropertyContainerModel extends Model { + + /** + * get property value. + * + * @param key key of property to get + * @return value of property + */ + String getProperty(String key); + + /** + * set property model. + * + * @param key key of property to set + * @param value value of property to set + * @return {@ResourceAdapterModel} to support method chaining + */ + BasePropertyContainerModel setProperty(String key, String value); + + /** + * get all properties as {@link Properties} object. + * + * @return {@link Properties} + */ + Properties getProperties(); + + /** + * set Properties object. + * + * @param properties {@link Properties} to set + * @return {@link BasePropertyContainerModel} to support method chaining + */ + BasePropertyContainerModel setProperties(final Properties properties); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/BatchCommitModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/BatchCommitModel.java new file mode 100644 index 000000000..a121b441b --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/BatchCommitModel.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Model; + +/** + * binding.jca/inboundInteraction/batchCommit model. + */ +public interface BatchCommitModel extends Model { + + /** + * get batch timeout. + * @return batch timeout in milliseconds + */ + long getBatchTimeout(); + + /** + * set batch timeout. + * @param timeout batch timeout in milliseconds + * @return {@link BatchCommitModel} to support method chaining + */ + BatchCommitModel setBatchTimeout(long timeout); + + /** + * get batch size. + * @return batch size + */ + int getBatchSize(); + + /** + * set batch size. + * @param size batch size. + * @return {@link BatchCommitModel} to support method chaining + */ + BatchCommitModel setBatchSize(int size); + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/ConnectionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ConnectionModel.java new file mode 100644 index 000000000..ae0d009c8 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ConnectionModel.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +/** + * binding.jca/OutboundConnection/connection model. + * + * @author Tomohisa Igarashi + * + */ +public interface ConnectionModel extends BasePropertyContainerModel { + + /** + * Set connection factory JNDI name. + * + * @return connection factory JNDI name + */ + String getConnectionFactoryJNDIName(); + + /** + * Set connection factory JNDI name. + * + * @param name connection factory JNDI name + * @return {@link ConnectionModel} to support method chaining + */ + ConnectionModel setConnectionFactoryJNDIName(String name); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/ConnectionSpecModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ConnectionSpecModel.java new file mode 100644 index 000000000..39e6c1b32 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ConnectionSpecModel.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +/** + * binding.jca/outboundInteraction/connectionSpec model. + * + * @author Tomohisa Igarashi + * + */ +public interface ConnectionSpecModel extends BasePropertyContainerModel { + + /** + * Get connection spec class name. + * + * @return connection spec class name + */ + String getConnectionSpecClassName(); + + /** + * Set connection spec class name. + * + * @param name connection spec class name + * @return {@ConnectionSpecModel} to support method chaining + */ + ConnectionSpecModel setConnectionSpecClassName(String name); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/EndpointModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/EndpointModel.java new file mode 100644 index 000000000..727e7f654 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/EndpointModel.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +/** + * binding.jca/inboundInteraction/endpoint model. + * + * @author Tomohisa Igarashi + * + */ +public interface EndpointModel extends BasePropertyContainerModel { + + /** + * get Endpoint class name. + * + * @return Endpoint class name + */ + String getEndpointClassName(); + + /** + * set Endpoint class name. + * + * @param endpoint Endpoint class name to set + * @return {@link EndpointModel} to suport method chaining + */ + EndpointModel setEndpointClassName(final String endpoint); + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/InboundConnectionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/InboundConnectionModel.java new file mode 100644 index 000000000..8f0b9c6aa --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/InboundConnectionModel.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Model; + +/** + * binding.jca/inboundConnection model. + * + * @author Tomohisa Igarashi + * + */ +public interface InboundConnectionModel extends Model { + + /** + * get ResouceAdapter model. + * + * @return {@link ResourceAdamterModel} + */ + ResourceAdapterModel getResourceAdapter(); + + /** + * set ResourceAdapter model. + * + * @param config {@link ResourceAdapterModel} to set + * @return [@link InboundConnectionModel} to support method chaining + */ + InboundConnectionModel setResourceAdapter(final ResourceAdapterModel config); + + /** + * get ActivationSpec model. + * + * @return {@link ActivationSpecModel} + */ + ActivationSpecModel getActivationSpec(); + + /** + * set ActivationSpec model. + * + * @param config {@link ActivationSpecModel} to set + * @return {@link InboundConnectionModel} to support method chaining + */ + InboundConnectionModel setActivationSpec(final ActivationSpecModel config); + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/InboundInteractionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/InboundInteractionModel.java new file mode 100644 index 000000000..0c6067e4b --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/InboundInteractionModel.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Model; + +/** + * binding.jca/inboundInteraction model. + * + * @author Tomohisa Igarashi + * + */ +public interface InboundInteractionModel extends Model { + + /** + * get Listener model. + * + * @return {@link ListenerModel} + */ + ListenerModel getListener(); + + /** + * set Listener model. + * + * @param listener {@link ListenerModel} to set + * @return {@link InboundInteractionModel} to support method chaining + */ + InboundInteractionModel setListener(final ListenerModel listener); + + /** + * get Endpoint model. + * + * @return {@link EndpointModel} + */ + EndpointModel getEndpoint(); + + /** + * set Endpoint model. + * + * @param endpoint {@link EndpointModel} to set + * @return {@link InboundInteractionModel} to support method chaining + */ + InboundInteractionModel setEndpoint(final EndpointModel endpoint); + + /** + * get transacted. + * + * @return true if transacted + */ + boolean isTransacted(); + + /** + * set transacted. + * + * @param transacted true if transacted + * @return {@link InboundInteractionModel} to suport method chaining + */ + InboundInteractionModel setTransacted(boolean transacted); + + /** + * get BatchCommitModel. + * @return {@link BatchCommitModel} + */ + BatchCommitModel getBatchCommit(); + + /** + * set BatchCommitModel. + * @param batchCommit {@link BatchCommitModel} to set + * @return {@link InboundInteractionModel} to support method chaining + */ + InboundInteractionModel setBatchCommit(final BatchCommitModel batchCommit); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/InteractionSpecModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/InteractionSpecModel.java new file mode 100644 index 000000000..fe0b03553 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/InteractionSpecModel.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +/** + * binding.jca/outboundInteraction/interactionSpec model. + * + * @author Tomohisa Igarashi + * + */ +public interface InteractionSpecModel extends BasePropertyContainerModel { + + /** + * Get interaction spec class name. + * + * @return interaction spec class name + */ + String getInteractionSpecClassName(); + + /** + * Set interaction spec class name. + * + * @param name interaction spec class name + * @return {@link InteractionSpecModel} to support method chaining + */ + InteractionSpecModel setInteractionSpecClassName(String name); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/JCABindingModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/JCABindingModel.java new file mode 100644 index 000000000..c32313dab --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/JCABindingModel.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.composite.BindingModel; + +/** + * A binding definition for JCA gateway. + * + * @author Tomohisa Igarashi + * + */ +public interface JCABindingModel extends BindingModel { + + /** + * get OutboundConnection model. + * + * @return {@link OutboundConnectionModel} + */ + OutboundConnectionModel getOutboundConnection(); + + /** + * set OutboundConnection model. + * + * @param config {@link OutboundConnectionModel} to set + * @return {@JCABindingModel} to support method chaining + */ + JCABindingModel setOutboundConnection(final OutboundConnectionModel config); + + /** + * get InboundConnection model. + * + * @return {@link InboundConnectionModel} + */ + InboundConnectionModel getInboundConnection(); + + /** + * set InboundConnection model. + * + * @param config {@link InboundConnectionModel} to set + * @return {@link JCABindingModel} to support method chaining + */ + JCABindingModel setInboundConnection(final InboundConnectionModel config); + + /** + * get OutboundInteraction model. + * + * @return {@link OutboundInteractionModel} + */ + OutboundInteractionModel getOutboundInteraction(); + + /** + * set OutboundInteraction model. + * + * @param config {@link OutboundInteractionModel} to set + * @return {@link JCABindingModel} to support method chaining + */ + JCABindingModel setOutboundInteraction(final OutboundInteractionModel config); + + /** + * get InboundInteraction model. + * + * @return {@link InboundInteractionModel} + */ + InboundInteractionModel getInboundInteraction(); + + /** + * set InboundInteraction model. + * + * @param config {@link InboundInteractionModel} to set + * @return {@link JCABinding} to support method chaining + */ + JCABindingModel setInboundInteraction(final InboundInteractionModel config); + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/JCANamespace.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/JCANamespace.java new file mode 100644 index 000000000..18331277b --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/JCANamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A JCA config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum JCANamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new JCANamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + JCANamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the JCANamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the JCANamespace + */ + public static JCANamespace fromUri(String uri) { + return Util.fromUri(JCANamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(JCANamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-jca:config", version); + } + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/ListenerModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ListenerModel.java new file mode 100644 index 000000000..c78db2b8c --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ListenerModel.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Model; + +/** + * binding.jca/inboundInteraction/listener model. + * + * @author Tomohisa Igarashi + * + */ +public interface ListenerModel extends Model { + /** + * get message listener class name. + * + * @return message listener class name + */ + String getClassName(); + + /** + * set message listener class name. + * + * @param name message listener class name + * @return {@link ListenerModel} to support method chaining + */ + ListenerModel setClassName(String name); + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/OperationModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/OperationModel.java new file mode 100644 index 000000000..e16b569c2 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/OperationModel.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Model; + +/** + * binding.jca/outboundInteraction/operation model. + * + * @author Tomohisa Igarashi + * + */ +public interface OperationModel extends Model { + + /** + * get operation name. + * + * @return operation name + */ + String getName(); + + /** + * set operation name. + * + * @param name operation name to set + * @return {@link OperationModel} to support method chaining + */ + OperationModel setName(String name); + + /** + * get InteractionSpec model. + * + * @return {@link InteractionSpecModel} + */ + InteractionSpecModel getInteractionSpec(); + + /** + * set InteractionSpec model. + * + * @param model {@link InteractionSpecModel} to set + * @return {@link OperationModel} to support method chaining + */ + OperationModel setInteractionSpec(final InteractionSpecModel model); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/OutboundConnectionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/OutboundConnectionModel.java new file mode 100644 index 000000000..f4581ac4d --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/OutboundConnectionModel.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Model; + +/** + * OutboundConnection model. + * + * @author Tomohisa Igarashi + */ +public interface OutboundConnectionModel extends Model { + + /** + * get ResourceAdapter model. + * + * @return {@link ResourceAdapterModel} + */ + ResourceAdapterModel getResourceAdapter(); + + /** + * set ResourceAdapter model. + * + * @param model {@link ResourceAdapterModel} to set + * @return {@link OutboundConnectionModel} to support method chaining + */ + OutboundConnectionModel setResourceAdapter(final ResourceAdapterModel model); + + /** + * get Connection model. + * + * @return {@link ConnectionModel} + */ + ConnectionModel getConnection(); + + /** + * set Connection model. + * + * @param model {@link ConnectionModel} to set + * @return {@link OutboundConnectionModel} to support method chaining + */ + OutboundConnectionModel setConnection(final ConnectionModel model); + + /** + * get whether the interaction with EIS is managed or not. + * + * @return true if managed + */ + boolean isManaged(); + + /** + * set whether the interaction with EIS is managed or not. + * + * @param managed true if managed + * @return {@link OutboundConnectionModel} to support method chaining + */ + OutboundConnectionModel setManaged(final boolean managed); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/OutboundInteractionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/OutboundInteractionModel.java new file mode 100644 index 000000000..af02bed0f --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/OutboundInteractionModel.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Model; + +/** + * OutboundInteraction model. + * + * @author Tomohisa Igarashi + */ +public interface OutboundInteractionModel extends Model { + + /** + * get ConnectionSpec model. + * + * @return {@link ConnectionSpecModel} + */ + ConnectionSpecModel getConnectionSpec(); + + /** + * set ConnectionSpec model. + * + * @param model {@link ConnectionSpecModel} to set + * @return {@link OutboundInteractionModel} to support method chaining + */ + OutboundInteractionModel setConnectionSpec(final ConnectionSpecModel model); + + /** + * get InteractionSpec model. + * + * @return {@link InteractionSpecModel} + */ + InteractionSpecModel getInteractionSpec(); + + /** + * set InteractionSpec model. + * + * @param model {@link InteractionSpecModel} to set + * @return {@link OutboundInteractionModel} to support method chaining + */ + OutboundInteractionModel setInteractionSpec(final InteractionSpecModel model); + + /** + * get Operation model. + * + * @return {@link OperationModel} + */ + OperationModel getOperation(); + + /** + * set Operation model. + * + * @param model {@link OperationModel} to set + * @return {@link OutboundInteractionModel} to support method chaining + */ + OutboundInteractionModel setOperation(final OperationModel model); + + /** + * get Processor model. + * + * @return {@link ProcessorModel} + */ + ProcessorModel getProcessor(); + + /** + * set Processor model. + * + * @param model {@link ProcessorModel} to set + * @return {@link OutboundInteractionModel} to support method chaining + */ + OutboundInteractionModel setProcessor(ProcessorModel model); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/ProcessorModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ProcessorModel.java new file mode 100644 index 000000000..f93b7fcbc --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ProcessorModel.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +/** + * binding.jca/outboundInteraction/processor model. + * + * @author Tomohisa Igarashi + * + */ +public interface ProcessorModel extends BasePropertyContainerModel { + + /** + * get Processor class name. + * + * @return Endpoint class name + */ + String getProcessorClassName(); + + /** + * set Processor class name. + * + * @param processor Processor class name to set + * @return {@link ProcessorModel} to suport method chaining + */ + ProcessorModel setProcessorClassName(final String processor); + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/PropertyModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/PropertyModel.java new file mode 100644 index 000000000..9406b24df --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/PropertyModel.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +import org.switchyard.config.model.Model; +/** + * sca property model. + * + * @author Tomohisa Igarashi + * + */ +public interface PropertyModel extends Model { + + /** + * get property name. + * + * @return name + */ + String getName(); + + /** + * set property name. + * + * @param name name to set + * @return {@link PropertyModel} to support method chaining + */ + PropertyModel setName(String name); + + /** + * get property value. + * + * @return value + */ + String getValue(); + + /** + * set property value. + * + * @param value value to set + * @return {@link PropertyModel} to support method chaining + */ + PropertyModel setValue(String value); +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/ResourceAdapterModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ResourceAdapterModel.java new file mode 100644 index 000000000..c9d7f3995 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/ResourceAdapterModel.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model; + +/** + * binding.jca/*Connection/resourceAdapter model. + * + * @author Tomohisa Igarashi + * + */ +public interface ResourceAdapterModel extends BasePropertyContainerModel { + + /** + * get resource adapter name. + * + * @return name + */ + String getName(); + + /** + * set resource adapter name. + * + * @param name resource adapter name to set + * @return {@link ResourceAdapterModel} to support method chaining + */ + ResourceAdapterModel setName(String name); + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ActivationSpecModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ActivationSpecModel.java new file mode 100644 index 000000000..ffb97f232 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ActivationSpecModel.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ActivationSpecModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V1 activationSpec model. + * + * @author Tomohisa Igarashi + * + */ +public class V1ActivationSpecModel extends V1BasePropertyContainerModel implements ActivationSpecModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1ActivationSpecModel(String namespace) { + super(namespace, JCAConstants.ACTIVATION_SPEC); + setModelChildrenOrder(JCAConstants.PROPERTY); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1ActivationSpecModel(Configuration config, Descriptor desc) { + super(config, desc); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1BasePropertyContainerModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1BasePropertyContainerModel.java new file mode 100644 index 000000000..0ff6af22d --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1BasePropertyContainerModel.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import java.util.Enumeration; +import java.util.List; +import java.util.Properties; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.BasePropertyContainerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 BasePropertyContainer model. + * + * @author Tomohisa Igarashi + * + */ +public abstract class V1BasePropertyContainerModel extends BaseModel implements BasePropertyContainerModel { + + protected V1BasePropertyContainerModel(String namespace, String name) { + super(namespace, name); + } + + protected V1BasePropertyContainerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getProperty(String key) { + List properties = getModelConfiguration().getChildren(JCAConstants.PROPERTY); + for (Configuration prop : properties) { + if (key.equals(prop.getAttribute(JCAConstants.NAME))) { + return prop.getAttribute(JCAConstants.VALUE); + } + } + return null; + } + + @Override + public BasePropertyContainerModel setProperty(String key, String value) { + List properties = getModelConfiguration().getChildren(JCAConstants.PROPERTY); + for (Configuration prop : properties) { + if (key.equals(prop.getAttribute(JCAConstants.NAME))) { + prop.setAttribute(JCAConstants.VALUE, value != null ? value : ""); + return this; + } + } + V1PropertyModel model = new V1PropertyModel(getNamespaceURI(), key, value != null ? value : ""); + setChildModel(model); + return this; + } + + @Override + public Properties getProperties() { + Properties properties = new Properties(); + List modelProperties = getModelConfiguration().getChildren(JCAConstants.PROPERTY); + for (Configuration prop : modelProperties) { + String name = prop.getAttribute(JCAConstants.NAME); + String value = prop.getAttribute(JCAConstants.VALUE); + if (name != null) { + properties.put(name, value != null ? value : ""); + } + } + return properties; + } + + @Override + public BasePropertyContainerModel setProperties(Properties properties) { + getModelConfiguration().removeChildren(JCAConstants.PROPERTY); + Enumeration e = properties.keys(); + while (e.hasMoreElements()) { + String key = e.nextElement().toString(); + String value = properties.getProperty(key); + V1PropertyModel model = new V1PropertyModel(getNamespaceURI(), key, value); + setChildModel(model); + } + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1BatchCommitModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1BatchCommitModel.java new file mode 100644 index 000000000..eaab5ea9e --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1BatchCommitModel.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.BatchCommitModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 BatchCommitModel. + */ +public class V1BatchCommitModel extends BaseModel implements BatchCommitModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1BatchCommitModel(String namespace) { + super(namespace, JCAConstants.BATCH_COMMIT); + } + + /** + * Constructor. + * @param config configuration + * @param desc description + */ + public V1BatchCommitModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public long getBatchTimeout() { + return Long.parseLong(getModelAttribute(JCAConstants.BATCH_TIMEOUT)); + } + + @Override + public BatchCommitModel setBatchTimeout(long delay) { + setModelAttribute(JCAConstants.BATCH_TIMEOUT, Long.toString(delay)); + return this; + } + + @Override + public int getBatchSize() { + return Integer.parseInt(getModelAttribute(JCAConstants.BATCH_SIZE)); + } + + @Override + public BatchCommitModel setBatchSize(int size) { + setModelAttribute(JCAConstants.BATCH_SIZE, Integer.toString(size)); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ConnectionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ConnectionModel.java new file mode 100644 index 000000000..d8edf37c5 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ConnectionModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ConnectionModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V1 Connection model. + * + * @author Tomohisa Igarashi + * + */ +public class V1ConnectionModel extends V1BasePropertyContainerModel implements ConnectionModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1ConnectionModel(String namespace) { + super(namespace, JCAConstants.CONNECTION); + setModelChildrenOrder(JCAConstants.PROPERTY); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1ConnectionModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getConnectionFactoryJNDIName() { + return getModelAttribute(JCAConstants.JNDI_NAME); + } + + @Override + public ConnectionModel setConnectionFactoryJNDIName(String name) { + setModelAttribute(JCAConstants.JNDI_NAME, name); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ConnectionSpecModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ConnectionSpecModel.java new file mode 100644 index 000000000..eb765b8c2 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ConnectionSpecModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ConnectionSpecModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V1 ConnectionSpec model. + * + * @author Tomohisa Igarashi + * + */ +public class V1ConnectionSpecModel extends V1BasePropertyContainerModel implements ConnectionSpecModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1ConnectionSpecModel(String namespace) { + super(namespace, JCAConstants.CONNECTION_SPEC); + setModelChildrenOrder(JCAConstants.PROPERTY); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1ConnectionSpecModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getConnectionSpecClassName() { + return getModelAttribute(JCAConstants.TYPE); + } + + @Override + public ConnectionSpecModel setConnectionSpecClassName(String name) { + setModelAttribute(JCAConstants.TYPE, name); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1EndpointModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1EndpointModel.java new file mode 100644 index 000000000..2a6fc0196 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1EndpointModel.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.EndpointModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V1 Endpoint model. + * + * @author Tomohisa Igarashi + * + */ +public class V1EndpointModel extends V1BasePropertyContainerModel implements EndpointModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1EndpointModel(String namespace) { + super(namespace, JCAConstants.ENDPOINT); + setModelChildrenOrder(JCAConstants.PROPERTY); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1EndpointModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getEndpointClassName() { + return getModelAttribute(JCAConstants.TYPE); + } + + @Override + public EndpointModel setEndpointClassName(String endpoint) { + setModelAttribute(JCAConstants.TYPE, endpoint); + return this; + } + + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InboundConnectionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InboundConnectionModel.java new file mode 100644 index 000000000..fb7785e2d --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InboundConnectionModel.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ActivationSpecModel; +import org.switchyard.component.jca.config.model.InboundConnectionModel; +import org.switchyard.component.jca.config.model.ResourceAdapterModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 InboundConnection model. + * + * @author Tomohisa Igarashi + * + */ +public class V1InboundConnectionModel extends BaseModel implements InboundConnectionModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1InboundConnectionModel(String namespace) { + super(namespace, JCAConstants.INBOUND_CONNECTION); + setModelChildrenOrder(JCAConstants.RESOURCE_ADAPTER, JCAConstants.ACTIVATION_SPEC); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1InboundConnectionModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public ResourceAdapterModel getResourceAdapter() { + return (ResourceAdapterModel) getFirstChildModel(JCAConstants.RESOURCE_ADAPTER); + } + + @Override + public InboundConnectionModel setResourceAdapter(ResourceAdapterModel config) { + setChildModel(config); + return this; + } + + @Override + public ActivationSpecModel getActivationSpec() { + return (ActivationSpecModel) getFirstChildModel(JCAConstants.ACTIVATION_SPEC); + } + + @Override + public InboundConnectionModel setActivationSpec(ActivationSpecModel config) { + setChildModel(config); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InboundInteractionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InboundInteractionModel.java new file mode 100644 index 000000000..ec02afc93 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InboundInteractionModel.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.BatchCommitModel; +import org.switchyard.component.jca.config.model.EndpointModel; +import org.switchyard.component.jca.config.model.InboundInteractionModel; +import org.switchyard.component.jca.config.model.ListenerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 InboundInteraction model. + * + * @author Tomohisa Igarashi + * + */ +public class V1InboundInteractionModel extends BaseModel implements InboundInteractionModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1InboundInteractionModel(String namespace) { + super(namespace, JCAConstants.INBOUND_INTERACTION); + setModelChildrenOrder(JCAConstants.LISTENER, JCAConstants.ENDPOINT, JCAConstants.TRANSACTED, JCAConstants.BATCH_COMMIT); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc description + */ + public V1InboundInteractionModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public ListenerModel getListener() { + return (ListenerModel) getFirstChildModel(JCAConstants.LISTENER); + } + + @Override + public InboundInteractionModel setListener(ListenerModel listener) { + setChildModel(listener); + return this; + } + + @Override + public EndpointModel getEndpoint() { + return (EndpointModel) getFirstChildModel(JCAConstants.ENDPOINT); + } + + @Override + public InboundInteractionModel setEndpoint(EndpointModel endpoint) { + setChildModel(endpoint); + return this; + } + + @Override + public boolean isTransacted() { + Configuration config = getModelConfiguration().getFirstChild(JCAConstants.TRANSACTED); + return config != null ? Boolean.parseBoolean(config.getValue()) : false; + } + + @Override + public InboundInteractionModel setTransacted(boolean transacted) { + Configuration config = getModelConfiguration().getFirstChild(JCAConstants.TRANSACTED); + if (config != null) { + config.setValue(Boolean.toString(transacted)); + } else { + V1NameValueModel model = new V1NameValueModel(getNamespaceURI(), JCAConstants.TRANSACTED); + model.setValue(Boolean.toString(transacted)); + setChildModel(model); + } + return this; + } + + @Override + public BatchCommitModel getBatchCommit() { + return (BatchCommitModel) getFirstChildModel(JCAConstants.BATCH_COMMIT); + } + + @Override + public InboundInteractionModel setBatchCommit(BatchCommitModel batchCommit) { + setChildModel(batchCommit); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InteractionSpecModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InteractionSpecModel.java new file mode 100644 index 000000000..4f6791c02 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1InteractionSpecModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.InteractionSpecModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V1 InteractionSpec model. + * + * @author Tomohisa Igarashi + * + */ +public class V1InteractionSpecModel extends V1BasePropertyContainerModel implements InteractionSpecModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1InteractionSpecModel(String namespace) { + super(namespace, JCAConstants.INTERACTION_SPEC); + setModelChildrenOrder(JCAConstants.PROPERTY); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1InteractionSpecModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getInteractionSpecClassName() { + return getModelAttribute(JCAConstants.TYPE); + } + + @Override + public InteractionSpecModel setInteractionSpecClassName(String name) { + setModelAttribute(JCAConstants.TYPE, name); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModel.java new file mode 100644 index 000000000..b2709c9e0 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModel.java @@ -0,0 +1,106 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.InboundConnectionModel; +import org.switchyard.component.jca.config.model.InboundInteractionModel; +import org.switchyard.component.jca.config.model.JCABindingModel; +import org.switchyard.component.jca.config.model.OutboundConnectionModel; +import org.switchyard.component.jca.config.model.OutboundInteractionModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1BindingModel; + +/** + * + * @author Tomohisa Igarashi + * + */ +public class V1JCABindingModel extends V1BindingModel implements JCABindingModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1JCABindingModel(String namespace) { + super(JCAConstants.JCA, namespace); + setModelChildrenOrder(JCAConstants.OUTBOUND_CONNECTION, + JCAConstants.INBOUND_CONNECTION, + JCAConstants.OUTBOUND_INTERACTION, + JCAConstants.INBOUND_INTERACTION, + JCAConstants.WIRE_FORMAT); + } + + /** + * Constractor. + * + * @param config configuration + * @param desc description + */ + public V1JCABindingModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(JCAConstants.OUTBOUND_CONNECTION, + JCAConstants.INBOUND_CONNECTION, + JCAConstants.OUTBOUND_INTERACTION, + JCAConstants.INBOUND_INTERACTION, + JCAConstants.WIRE_FORMAT); + } + + @Override + public OutboundConnectionModel getOutboundConnection() { + return (OutboundConnectionModel)getFirstChildModel(JCAConstants.OUTBOUND_CONNECTION); + } + + @Override + public JCABindingModel setOutboundConnection(final OutboundConnectionModel config) { + setChildModel(config); + return this; + } + + @Override + public InboundConnectionModel getInboundConnection() { + return (InboundConnectionModel)getFirstChildModel(JCAConstants.INBOUND_CONNECTION); + } + + @Override + public JCABindingModel setInboundConnection(InboundConnectionModel config) { + setChildModel(config); + return this; + } + + @Override + public OutboundInteractionModel getOutboundInteraction() { + return (OutboundInteractionModel)getFirstChildModel(JCAConstants.OUTBOUND_INTERACTION); + } + + @Override + public JCABindingModel setOutboundInteraction(OutboundInteractionModel config) { + setChildModel(config); + return this; + } + + @Override + public InboundInteractionModel getInboundInteraction() { + return (InboundInteractionModel)getFirstChildModel(JCAConstants.INBOUND_INTERACTION); + } + + @Override + public JCABindingModel setInboundInteraction(InboundInteractionModel config) { + setChildModel(config); + return this; + } + + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1JCAModelMarshaller.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1JCAModelMarshaller.java new file mode 100644 index 000000000..640270434 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1JCAModelMarshaller.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.composer.v1.V1ContextMapperModel; +import org.switchyard.config.model.composer.v1.V1MessageComposerModel; + +/** + * V1 model marshaller for jca binding. + * + * @author Tomohisa Igarashi + * + */ +public class V1JCAModelMarshaller extends BaseMarshaller { + + /** + * Constructor. + * + * @param desc The descriptor for this model. + */ + public V1JCAModelMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(final Configuration config) { + final String name = config.getName(); + + if (name.equals(JCAConstants.BINDING + "." + JCAConstants.JCA)) { + return new V1JCABindingModel(config, getDescriptor()); + } + if (name.equals(ContextMapperModel.CONTEXT_MAPPER)) { + return new V1ContextMapperModel(config, getDescriptor()); + } + if (name.equals(MessageComposerModel.MESSAGE_COMPOSER)) { + return new V1MessageComposerModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.OUTBOUND_CONNECTION)) { + return new V1OutboundConnectionModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.INBOUND_CONNECTION)) { + return new V1InboundConnectionModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.OUTBOUND_INTERACTION)) { + return new V1OutboundInteractionModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.INBOUND_INTERACTION)) { + return new V1InboundInteractionModel(config, getDescriptor()); + } + + if (name.equals(JCAConstants.RESOURCE_ADAPTER)) { + return new V1ResourceAdapterModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.CONNECTION)) { + return new V1ConnectionModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.ACTIVATION_SPEC)) { + return new V1ActivationSpecModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.CONNECTION_SPEC)) { + return new V1ConnectionSpecModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.INTERACTION_SPEC)) { + return new V1InteractionSpecModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.OPERATION)) { + return new V1OperationModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.LISTENER)) { + return new V1ListenerModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.ENDPOINT)) { + return new V1EndpointModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.PROCESSOR)) { + return new V1ProcessorModel(config, getDescriptor()); + } + if (name.equals(JCAConstants.BATCH_COMMIT)) { + return new V1BatchCommitModel(config, getDescriptor()); + } + return null; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ListenerModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ListenerModel.java new file mode 100644 index 000000000..601546002 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ListenerModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ListenerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 Listener model. + * + * @author Tomohisa Igarashi + * + */ +public class V1ListenerModel extends BaseModel implements ListenerModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1ListenerModel(String namespace) { + super(namespace, JCAConstants.LISTENER); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1ListenerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getClassName() { + return getModelConfiguration().getValue(); + } + + @Override + public ListenerModel setClassName(String name) { + getModelConfiguration().setValue(name); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1NameValueModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1NameValueModel.java new file mode 100644 index 000000000..389ebcd0f --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1NameValueModel.java @@ -0,0 +1,50 @@ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; + +/** + * Generic configuration interface used to represent a basic name to value mapping + * for a child configuration, e.g. + *

+ *
+ *    value
+ * 
+ *
+ */ +public class V1NameValueModel extends BaseModel { + + /** + * Create a new NameValueModel with the specified name. + * @param namespace namespace + * @param name config name + */ + public V1NameValueModel(String namespace, String name) { + super(namespace, name); + } + + /** + * Create a new NameValueModel based on an existing config element. + * @param config configuration element + */ + public V1NameValueModel(Configuration config) { + super(config); + } + + /** + * Get the config value. + * @return config value + */ + public String getValue() { + return super.getModelValue(); + } + + /** + * Set the config value. + * @param value config value + */ + public void setValue(String value) { + super.setModelValue(value); + } +} + diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OperationModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OperationModel.java new file mode 100644 index 000000000..d6a9a85d8 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OperationModel.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.InteractionSpecModel; +import org.switchyard.component.jca.config.model.OperationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 Operation model. + * + * @author Tomohisa Igarashi + * + */ +public class V1OperationModel extends BaseModel implements OperationModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1OperationModel(String namespace) { + super(namespace, JCAConstants.OPERATION); + setModelChildrenOrder(JCAConstants.INTERACTION_SPEC); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1OperationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getName() { + return getModelAttribute(JCAConstants.NAME); + } + + @Override + public OperationModel setName(String name) { + setModelAttribute(JCAConstants.NAME, name); + return this; + } + + @Override + public InteractionSpecModel getInteractionSpec() { + return (InteractionSpecModel) getFirstChildModel(JCAConstants.INTERACTION_SPEC); + } + + @Override + public OperationModel setInteractionSpec(InteractionSpecModel model) { + setChildModel(model); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OutboundConnectionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OutboundConnectionModel.java new file mode 100644 index 000000000..67edac227 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OutboundConnectionModel.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ConnectionModel; +import org.switchyard.component.jca.config.model.OutboundConnectionModel; +import org.switchyard.component.jca.config.model.ResourceAdapterModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 OutboundConnection Model. + * + * @author Tomohisa Igarashi + * + */ +public class V1OutboundConnectionModel extends BaseModel implements OutboundConnectionModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1OutboundConnectionModel(String namespace) { + super(namespace, JCAConstants.OUTBOUND_CONNECTION); + setModelChildrenOrder(JCAConstants.RESOURCE_ADAPTER, JCAConstants.CONNECTION); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1OutboundConnectionModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public ResourceAdapterModel getResourceAdapter() { + return (ResourceAdapterModel) getFirstChildModel(JCAConstants.RESOURCE_ADAPTER); + } + + @Override + public OutboundConnectionModel setResourceAdapter(ResourceAdapterModel model) { + setChildModel(model); + return this; + } + + @Override + public ConnectionModel getConnection() { + return (ConnectionModel) getFirstChildModel(JCAConstants.CONNECTION); + } + + @Override + public OutboundConnectionModel setConnection(ConnectionModel model) { + setChildModel(model); + return this; + } + + @Override + public boolean isManaged() { + String managed = getModelAttribute(JCAConstants.MANAGED); + if (managed == null) { + setManaged(true); + managed = "true"; + } + + return Boolean.parseBoolean(managed); + } + + @Override + public OutboundConnectionModel setManaged(boolean managed) { + setModelAttribute(JCAConstants.MANAGED, Boolean.toString(managed)); + return this; + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OutboundInteractionModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OutboundInteractionModel.java new file mode 100644 index 000000000..70a862118 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1OutboundInteractionModel.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ConnectionSpecModel; +import org.switchyard.component.jca.config.model.InteractionSpecModel; +import org.switchyard.component.jca.config.model.OperationModel; +import org.switchyard.component.jca.config.model.OutboundInteractionModel; +import org.switchyard.component.jca.config.model.ProcessorModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 OutboundInteraction model. + * + * @author Tomohisa Igarashi + * + */ +public class V1OutboundInteractionModel extends BaseModel implements OutboundInteractionModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1OutboundInteractionModel(String namespace) { + super(namespace, JCAConstants.OUTBOUND_INTERACTION); + setModelChildrenOrder(JCAConstants.CONNECTION_SPEC, + JCAConstants.INTERACTION_SPEC, + JCAConstants.OPERATION, + JCAConstants.PROCESSOR); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1OutboundInteractionModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public ConnectionSpecModel getConnectionSpec() { + return (ConnectionSpecModel) getFirstChildModel(JCAConstants.CONNECTION_SPEC); + } + + @Override + public OutboundInteractionModel setConnectionSpec(ConnectionSpecModel model) { + setChildModel(model); + return this; + } + + @Override + public InteractionSpecModel getInteractionSpec() { + return (InteractionSpecModel) getFirstChildModel(JCAConstants.INTERACTION_SPEC); + } + + @Override + public OutboundInteractionModel setInteractionSpec(InteractionSpecModel model) { + setChildModel(model); + return this; + } + + @Override + public OperationModel getOperation() { + return (OperationModel) getFirstChildModel(JCAConstants.OPERATION); + } + + @Override + public OutboundInteractionModel setOperation(OperationModel model) { + setChildModel(model); + return this; + } + + @Override + public ProcessorModel getProcessor() { + return (ProcessorModel) getFirstChildModel(JCAConstants.PROCESSOR); + } + + @Override + public OutboundInteractionModel setProcessor(ProcessorModel model) { + setChildModel(model); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ProcessorModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ProcessorModel.java new file mode 100644 index 000000000..e8f51144f --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ProcessorModel.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ProcessorModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V1 Processor model. + * + * @author Tomohisa Igarashi + * + */ +public class V1ProcessorModel extends V1BasePropertyContainerModel implements ProcessorModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1ProcessorModel(String namespace) { + super(namespace, JCAConstants.PROCESSOR); + setModelChildrenOrder(JCAConstants.PROPERTY); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1ProcessorModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getProcessorClassName() { + return getModelAttribute(JCAConstants.TYPE); + } + + @Override + public ProcessorModel setProcessorClassName(String processor) { + setModelAttribute(JCAConstants.TYPE, processor); + return this; + } + + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1PropertyModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1PropertyModel.java new file mode 100644 index 000000000..d338a0ac5 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1PropertyModel.java @@ -0,0 +1,62 @@ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.PropertyModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * V1 Property model. + * + * @author Tomohisa Igarashi + * + */ +public class V1PropertyModel extends BaseModel implements PropertyModel { + + /** + * Constructor. + * + * @param namespace namespace + * @param key key of property + * @param value value of property + */ + public V1PropertyModel(String namespace, String key, String value) { + super(namespace, JCAConstants.PROPERTY); + setModelAttribute(JCAConstants.NAME, key); + setModelAttribute(JCAConstants.VALUE, value); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc descriptor + */ + public V1PropertyModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getName() { + return getModelAttribute(JCAConstants.NAME); + } + + @Override + public PropertyModel setName(String name) { + setModelAttribute(JCAConstants.NAME, name); + return this; + } + + @Override + public String getValue() { + return getModelAttribute(JCAConstants.VALUE); + } + + @Override + public PropertyModel setValue(String value) { + setModelAttribute(JCAConstants.VALUE, value); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ResourceAdapterModel.java b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ResourceAdapterModel.java new file mode 100644 index 000000000..1f210b699 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/config/model/v1/V1ResourceAdapterModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ResourceAdapterModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * V1 ResourceAdapter model. + * + * @author Tomohisa Igarashi + * + */ +public class V1ResourceAdapterModel extends V1BasePropertyContainerModel implements ResourceAdapterModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1ResourceAdapterModel(String namespace) { + super(namespace, JCAConstants.RESOURCE_ADAPTER); + setModelChildrenOrder(JCAConstants.PROPERTY); + } + + /** + * Constructor. + * + * @param config configuration + * @param desc description + */ + public V1ResourceAdapterModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getName() { + return getModelAttribute(JCAConstants.NAME); + } + + @Override + public ResourceAdapterModel setName(String name) { + setModelAttribute(JCAConstants.NAME, name); + return this; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/deploy/InboundHandler.java b/components/jca/src/main/java/org/switchyard/component/jca/deploy/InboundHandler.java new file mode 100644 index 000000000..6f16cf414 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/deploy/InboundHandler.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.deploy; + +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +import javax.resource.ResourceException; +import javax.resource.spi.UnavailableException; +import javax.resource.spi.endpoint.MessageEndpoint; +import javax.resource.spi.endpoint.MessageEndpointFactory; +import javax.transaction.xa.XAResource; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.jca.EndpointProxy; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.SwitchYardException; + +/** + * An ExchangeHandler for JCA message inflow that create and activate an MessageEndpoint. + * + * @author Tomohisa Igarashi + * + */ +public class InboundHandler extends BaseServiceHandler implements MessageEndpointFactory { + + private final JCAInflowDeploymentMetaData _metadata; + + /** + * Constructor. + * + * @param metadata {@link JCAInflowDeploymentMetaData} + * @param domain the service domain + */ + public InboundHandler(JCAInflowDeploymentMetaData metadata, ServiceDomain domain) { + super(domain); + _metadata = metadata; + } + + /** + * Activate JCA message inflow endpoint. + */ + @Override + protected void doStart() { + _metadata.getMessageEndpoint().initialize(); + try { + _metadata.getResourceAdapter().endpointActivation(this, _metadata.getActivationSpec()); + } catch (ResourceException e) { + throw new SwitchYardException(e); + } + } + + @Override + protected void doStop() { + _metadata.getResourceAdapter().endpointDeactivation(this, _metadata.getActivationSpec()); + _metadata.getMessageEndpoint().uninitialize(); + } + + @Override + public MessageEndpoint createEndpoint(XAResource xaResource, long timeout) + throws UnavailableException { + EndpointProxy handler = new EndpointProxy(_metadata, this, xaResource); + return (MessageEndpoint) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), + new Class[] {_metadata.getListenerInterface(),MessageEndpoint.class}, + handler); + } + + @Override + public MessageEndpoint createEndpoint(XAResource xaResource) + throws UnavailableException { + return createEndpoint(xaResource, 0); + } + + @Override + public boolean isDeliveryTransacted(Method arg0) + throws NoSuchMethodException { + return _metadata.isDeliveryTransacted(); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAActivator.java b/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAActivator.java new file mode 100644 index 000000000..7116ed9cd --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAActivator.java @@ -0,0 +1,327 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.deploy; + +import java.util.List; +import java.util.Properties; + +import javax.xml.namespace.QName; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.resource.spi.ActivationSpec; +import javax.resource.spi.ResourceAdapter; +import javax.transaction.TransactionManager; + +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.component.jca.config.model.ActivationSpecModel; +import org.switchyard.component.jca.config.model.BatchCommitModel; +import org.switchyard.component.jca.config.model.ConnectionModel; +import org.switchyard.component.jca.config.model.ConnectionSpecModel; +import org.switchyard.component.jca.config.model.EndpointModel; +import org.switchyard.component.jca.config.model.InboundConnectionModel; +import org.switchyard.component.jca.config.model.InboundInteractionModel; +import org.switchyard.component.jca.config.model.InteractionSpecModel; +import org.switchyard.component.jca.config.model.JCABindingModel; +import org.switchyard.component.jca.config.model.ListenerModel; +import org.switchyard.component.jca.config.model.OutboundConnectionModel; +import org.switchyard.component.jca.config.model.OutboundInteractionModel; +import org.switchyard.component.jca.config.model.ProcessorModel; +import org.switchyard.component.jca.config.model.ResourceAdapterModel; +import org.switchyard.component.jca.endpoint.AbstractInflowEndpoint; +import org.switchyard.component.jca.processor.AbstractOutboundProcessor; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; +import org.jboss.jca.core.spi.rar.Activation; +import org.jboss.jca.core.spi.rar.MessageListener; +import org.jboss.jca.core.spi.rar.ResourceAdapterRepository; +import org.jboss.util.propertyeditor.PropertyEditors; +import org.jboss.as.connector.util.ConnectorServices; + + +/** + * Activator for JCA message inflow binding. + * + * @author Tomohisa Igarashi + * + */ +public class JCAActivator extends BaseActivator { + + private static final String JBOSS_TRANSACTION_MANAGER = "java:jboss/TransactionManager"; + + static final String[] TYPES = new String[] {"jca"}; + + private final ClassLoader _appClassLoader; + + private TransactionManager _transactionManager; + + private ResourceAdapterRepository _raRepository; + + /** + * Sole constructor . + */ + public JCAActivator() { + super(TYPES); + _appClassLoader = Thread.currentThread().getContextClassLoader(); + } + + @Override + public ServiceHandler activateBinding(QName name, BindingModel config) { + if (_raRepository == null) { + throw JCAMessages.MESSAGES.resourceAdapterRepositoryMustBeInjectedToActivateJCAComponent(); + } + + if (_transactionManager == null) { + try { + _transactionManager = (TransactionManager)new InitialContext().lookup(JBOSS_TRANSACTION_MANAGER); + } catch (NamingException e) { + throw JCAMessages.MESSAGES.unableToFindTransactionManagerInJNDIAt(JBOSS_TRANSACTION_MANAGER, e); + } + } + + if (config.isServiceBinding()) { + return handleServiceBinding((JCABindingModel)config, name); + } else { + return handleReferenceBinding((JCABindingModel)config, name); + } + } + + @Override + public void deactivateBinding(QName name, ServiceHandler handler) { + // Nothing to do here + } + + /** + * set ResourceAdapterRepository. + * + * @param repository ResourceAdapterRepository to set + */ + public void setResourceAdapterRepository(ResourceAdapterRepository repository) { + _raRepository = repository; + } + + private InboundHandler handleServiceBinding(JCABindingModel config, QName name) { + + JCABindingModel jcaconfig = (JCABindingModel)config; + InboundConnectionModel inboundConnectionModel = jcaconfig.getInboundConnection(); + if (inboundConnectionModel == null) { + throw JCAMessages.MESSAGES.noInboundConnectionConfigured(); + } + ResourceAdapterModel resourceAdapterModel = inboundConnectionModel.getResourceAdapter(); + if (resourceAdapterModel == null) { + throw JCAMessages.MESSAGES.noResourceAdapterConfigured(); + } + String raName = resourceAdapterModel.getName(); + if (raName == null) { + throw JCAMessages.MESSAGES.noResourceAdapterNameConfigured(); + } + String raid = ConnectorServices.getRegisteredResourceAdapterIdentifier(raName); + if (raid == null && raName.endsWith(".rar")) { + // AS7 registers adapter's name with stripping .rar suffix unlike WildFly + raid = ConnectorServices.getRegisteredResourceAdapterIdentifier(stripDotRarSuffix(raName)); + } + if (raid == null) { + throw JCAMessages.MESSAGES.uniqueKeyForResourceAdapter(raName); + } + + Properties raProps = resourceAdapterModel.getProperties(); + Properties activationProps = null; + ActivationSpecModel activationSpecModel = inboundConnectionModel.getActivationSpec(); + if (activationSpecModel != null) { + activationProps = activationSpecModel.getProperties(); + } + InboundInteractionModel inboundInteractionModel = jcaconfig.getInboundInteraction(); + if (inboundInteractionModel == null) { + throw JCAMessages.MESSAGES.noInboundInteractionConfigured(); + } + + String listener = null; + ListenerModel listenerModel = inboundInteractionModel.getListener(); + if (listenerModel != null) { + listener = listenerModel.getClassName(); + } + Class listenerType = null; + try { + listenerType = _appClassLoader.loadClass(listener != null ? listener : JCAConstants.DEFAULT_LISTENER_CLASS); + } catch (Exception e) { + throw JCAMessages.MESSAGES.noListenerClassFound(listener, e); + } + + EndpointModel endpointModel = inboundInteractionModel.getEndpoint(); + if (endpointModel == null) { + throw JCAMessages.MESSAGES.noEndpointConfigured(); + } + String endpointClassName = endpointModel.getEndpointClassName(); + Properties endpointProps = endpointModel.getProperties(); + + ActivationSpec activationSpec = null; + ResourceAdapter resourceAdapter = null; + MessageListener listenerContainer = null; + try { + List listeners = _raRepository.getMessageListeners(raid); + for (MessageListener l : listeners) { + if (listenerType.equals(l.getType())) { + listenerContainer = l; + } + } + if (listenerContainer == null) { + throw JCAMessages.MESSAGES.listenerTypeIsNotSupportedByResourceAdapter(listenerType.getName(), raName); + } + + Activation activation = listenerContainer.getActivation(); + activationSpec = activation.createInstance(); + if (activationProps != null && !activationProps.isEmpty()) { + PropertyEditors.mapJavaBeanProperties(activationSpec, activationProps); + } + + resourceAdapter = _raRepository.getResourceAdapter(raid); + if (!raProps.isEmpty()) { + PropertyEditors.mapJavaBeanProperties(resourceAdapter, raProps); + } + } catch (Exception e) { + throw JCAMessages.MESSAGES.couldnTAcquireTheResourceAdapter(raName, e); + } + + AbstractInflowEndpoint endpoint = null; + Class endpointClass = null; + try { + endpointClass = (Class)_appClassLoader.loadClass(endpointClassName); + endpoint = (AbstractInflowEndpoint) endpointClass.newInstance(); + if (!endpointProps.isEmpty()) { + PropertyEditors.mapJavaBeanProperties(endpoint, endpointProps); + } + } catch (Exception e) { + throw JCAMessages.MESSAGES.endpointClass(endpointClassName, e); + } + + boolean transacted = inboundInteractionModel.isTransacted(); + endpoint.setApplicationClassLoader(_appClassLoader) + .setServiceDomain(getServiceDomain()) + .setServiceQName(name) + .setDeliveryTransacted(transacted) + .setJCABindingModel(jcaconfig); + + JCAInflowDeploymentMetaData inflowMetaData = new JCAInflowDeploymentMetaData() + .setActivationSpec(activationSpec) + .setApplicationClassLoader(_appClassLoader) + .setListenerInterface(listenerType) + .setMessageEndpoint(endpoint) + .setResourceAdapter(resourceAdapter) + .setTransactionManager(_transactionManager) + .setDeliveryTransacted(transacted); + + BatchCommitModel batchCommit = inboundInteractionModel.getBatchCommit(); + if (transacted && batchCommit != null) { + inflowMetaData.setUseBatchCommit(true); + inflowMetaData.setBatchTimeout(batchCommit.getBatchTimeout()); + inflowMetaData.setBatchSize(batchCommit.getBatchSize()); + } + + return new InboundHandler(inflowMetaData, getServiceDomain()); + + } + + private OutboundHandler handleReferenceBinding(JCABindingModel config, QName name) { + JCABindingModel jcaconfig = (JCABindingModel)config; + OutboundConnectionModel outboundConnectionModel = jcaconfig.getOutboundConnection(); + if (outboundConnectionModel == null) { + throw JCAMessages.MESSAGES.noOutboundConnectionConfigured(); + } + boolean managed = outboundConnectionModel.isManaged(); + if (!managed) { + throw JCAMessages.MESSAGES.nonManagedScenarioIsNotSupportedYet(); + } + + ResourceAdapterModel resourceAdapterModel = outboundConnectionModel.getResourceAdapter(); + if (resourceAdapterModel != null) { + Properties raProps = resourceAdapterModel.getProperties(); + if (!raProps.isEmpty()) { + String raName = resourceAdapterModel.getName(); + String raid = ConnectorServices.getRegisteredResourceAdapterIdentifier(stripDotRarSuffix(raName)); + if (raid == null) { + throw JCAMessages.MESSAGES.uniqueKeyForResourceAdapter(raName); + } + + ResourceAdapter resourceAdapter = null; + try { + resourceAdapter = _raRepository.getResourceAdapter(raid); + PropertyEditors.mapJavaBeanProperties(resourceAdapter, raProps); + } catch (Exception e) { + throw JCAMessages.MESSAGES.couldnTAcquireTheResourceAdapter(raName, e); + } + } + } + + OutboundInteractionModel outboundInteractionModel = jcaconfig.getOutboundInteraction(); + if (outboundInteractionModel == null) { + throw JCAMessages.MESSAGES.noOutboundInteractionConfigured(); + } + ProcessorModel processorModel = outboundInteractionModel.getProcessor(); + if (processorModel == null) { + throw JCAMessages.MESSAGES.noProcessorConfigured(); + } + Properties processorProps = processorModel.getProperties(); + AbstractOutboundProcessor processor = null; + String processorClassName = processorModel.getProcessorClassName(); + Class processorClass = null; + try { + processorClass = (Class)_appClassLoader.loadClass(processorClassName); + processor = (AbstractOutboundProcessor) processorClass.newInstance(); + if (!processorProps.isEmpty()) { + PropertyEditors.mapJavaBeanProperties(processor, processorProps); + } + } catch (Exception e) { + throw JCAMessages.MESSAGES.outboundProcessorClass(processorClassName, e); + } + + ConnectionModel connectionModel = outboundConnectionModel.getConnection(); + if (connectionModel == null) { + throw JCAMessages.MESSAGES.noConnectionConfigured(); + } + String cfJndiName = connectionModel.getConnectionFactoryJNDIName(); + Properties connProps = connectionModel.getProperties(); + processor.setApplicationClassLoader(_appClassLoader) + .setMCFProperties(connProps) + .setConnectionFactoryJNDIName(cfJndiName) + .setJCABindingModel(jcaconfig); + + ConnectionSpecModel connectionSpecModel = outboundInteractionModel.getConnectionSpec(); + if (connectionSpecModel != null) { + String connSpecClassName = connectionSpecModel.getConnectionSpecClassName(); + Properties connSpecProps = connectionSpecModel.getProperties(); + processor.setConnectionSpec(connSpecClassName, connSpecProps); + } + InteractionSpecModel interactionSpecModel = outboundInteractionModel.getInteractionSpec(); + if (interactionSpecModel != null) { + String interactSpecClassName = interactionSpecModel.getInteractionSpecClassName(); + Properties interactSpecProps = interactionSpecModel.getProperties(); + processor.setInteractionSpec(interactSpecClassName, interactSpecProps); + } + + return new OutboundHandler(processor, getServiceDomain()); + } + + private String stripDotRarSuffix(final String raName) { + if (raName == null) { + return null; + } + // See RaDeploymentParsingProcessor + if (raName.endsWith(".rar")) { + return raName.substring(0, raName.indexOf(".rar")); + } + return raName; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAComponent.java b/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAComponent.java new file mode 100644 index 000000000..23c6c1e38 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAComponent.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.deploy; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.jca.JCAConstants; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; +import org.jboss.jca.core.spi.rar.ResourceAdapterRepository; + +/** + * An implementation of JCA component. + * + * @author Tomohisa Igarashi + */ +public class JCAComponent extends BaseComponent { + + private ResourceAdapterRepository _raRepository = null; + + /** + * Default constructor. + */ + public JCAComponent() { + super(JCAActivator.TYPES); + setName(JCAConstants.COMPONENT_NAME); + } + + /* (non-Javadoc) + * @see org.switchyard.deploy.Component#createActivator(org.switchyard.ServiceDomain) + */ + @Override + public Activator createActivator(ServiceDomain domain) { + JCAActivator activator = new JCAActivator(); + activator.setServiceDomain(domain); + activator.setResourceAdapterRepository(_raRepository); + return activator; + } + + @Override + public void addResourceDependency(Object repository) { + if (repository instanceof ResourceAdapterRepository) { + _raRepository = (ResourceAdapterRepository)repository; + } + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAInflowDeploymentMetaData.java b/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAInflowDeploymentMetaData.java new file mode 100644 index 000000000..c59fe83cb --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAInflowDeploymentMetaData.java @@ -0,0 +1,237 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.deploy; + +import javax.resource.spi.ActivationSpec; +import javax.resource.spi.ResourceAdapter; +import javax.transaction.TransactionManager; + +import org.switchyard.component.jca.endpoint.AbstractInflowEndpoint; + +/** + * JCA inflow deployment metadata. + * + * @author Tomohisa Igarashi + */ +public class JCAInflowDeploymentMetaData { + + private Class _listenerInterface = null; + + private AbstractInflowEndpoint _messageEndpoint = null; + + private ResourceAdapter _resourceAdapter = null; + + private ActivationSpec _activationSpec = null; + + private ClassLoader _applicationClassLoader = null; + + private TransactionManager _transactionManager = null; + + private boolean _transacted = false; + + private boolean _useBatchCommit = false; + + private int _batchSize = 0; + + private long _batchTimeout = 0; + + /** + * get listener interface. + * + * @return listener interface + */ + public Class getListenerInterface() { + return _listenerInterface; + } + + /** + * set listener interface. + * + * @param listenerInterface listener interface + * @return {@link JCAInflowDeploymentMetaData} to support method chaining + */ + public JCAInflowDeploymentMetaData setListenerInterface(Class listenerInterface) { + this._listenerInterface = listenerInterface; + return this; + } + + /** + * get message endpoint. + * + * @return concrete subclass of {@link AbstractInflowEndpoint} + */ + public AbstractInflowEndpoint getMessageEndpoint() { + return _messageEndpoint; + } + + /** + * set message endpoint. + * + * @param messageEndpoint concrete subclass of {@link AbstractInflowEndpoint} to set + * @return {@link JCAInflowDeploymentMetaData} to support method chaining + */ + public JCAInflowDeploymentMetaData setMessageEndpoint(AbstractInflowEndpoint messageEndpoint) { + this._messageEndpoint = messageEndpoint; + return this; + } + + /** + * get {@link ResourceAdapter}. + * + * @return [@link ResourceAdapter} + */ + public ResourceAdapter getResourceAdapter() { + return _resourceAdapter; + } + + /** + * set {@link ResourceAdapter}. + * + * @param resourceAdapter {@link ResourceAdapter} to set + * @return {@link JCAInflowDeploymentMetaData} to support method chaining + */ + public JCAInflowDeploymentMetaData setResourceAdapter(ResourceAdapter resourceAdapter) { + this._resourceAdapter = resourceAdapter; + return this; + } + + /** + * get {@link ActivationSpec}. + * + * @return {@link ActivationSpec} + */ + public ActivationSpec getActivationSpec() { + return _activationSpec; + } + + /** + * set {@link ActivationSpec}. + * + * @param activationSpec {@link ActivationSpec} to set. + * @return {@link JCAInflowDeploymentMetaData} to support method chaining + */ + public JCAInflowDeploymentMetaData setActivationSpec(ActivationSpec activationSpec) { + this._activationSpec = activationSpec; + return this; + } + + /** + * get application class loader. + * + * @return application class loader + */ + public ClassLoader getApplicationClassLoader() { + return _applicationClassLoader; + } + + /** + * set application class loader. + * + * @param applicationClassLoader {@link ClassLoader} to set + * @return {@link JCAInflowDeploymentMetaData} to support method chaining + */ + public JCAInflowDeploymentMetaData setApplicationClassLoader(ClassLoader applicationClassLoader) { + this._applicationClassLoader = applicationClassLoader; + return this; + } + + /** + * get {@link TransactionManager}. + * + * @return {@link TransactionManager} + */ + public TransactionManager getTransactionManager() { + return _transactionManager; + } + + /** + * set {@link TransactionManager}. + * + * @param transactionManager {@link TransactionManager} to set + * @return {@link JCAInflowDeploymentMetaData} to support method chaining + */ + public JCAInflowDeploymentMetaData setTransactionManager(TransactionManager transactionManager) { + this._transactionManager = transactionManager; + return this; + } + + /** + * get is delivery transacted. + * + * @return true if transacted + */ + public boolean isDeliveryTransacted() { + return _transacted; + } + + /** + * set delivery transacted. + * + * @param transacted true if transacted + * @return {@link JCAInflowDeploymentMetaData} to support method chaining + */ + public JCAInflowDeploymentMetaData setDeliveryTransacted(boolean transacted) { + _transacted = transacted; + return this; + } + + /** + * get if bacth commit is enabled. + * @return true if bactch commit is enabled + */ + public boolean useBatchCommit() { + return _useBatchCommit; + } + + /** + * set if batch commit is enabled. + * @param useBatchCommit true if batch commit should be enabled + */ + public void setUseBatchCommit(boolean useBatchCommit) { + this._useBatchCommit = useBatchCommit; + } + + /** + * get batch size. + * @return batch size + */ + public int getBatchSize() { + return _batchSize; + } + + /** + * set batch size. + * @param batchSize batch size + */ + public void setBatchSize(int batchSize) { + this._batchSize = batchSize; + } + + /** + * get batch timeout. + * @return batch timeout in milliseconds + */ + public long getBatchTimeout() { + return _batchTimeout; + } + + /** + * set batch timeout. + * @param batchTimeout batch timeout in milliseconds + */ + public void setBatchTimeout(long batchTimeout) { + this._batchTimeout = batchTimeout; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAOutboundDeploymentMetaData.java b/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAOutboundDeploymentMetaData.java new file mode 100644 index 000000000..926600529 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/deploy/JCAOutboundDeploymentMetaData.java @@ -0,0 +1,128 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.deploy; + +import java.util.Properties; + +/** + * JCA outbound deployment metadata. + * + * @author Tomohisa Igarashi + */ +public class JCAOutboundDeploymentMetaData { + + private Class _connectionFactoryClass; + private String _connectionFactoryJNDIName; + private Properties _connectionProperties; + private Object _connectionSpec; + private Object _interactionSpec; + + /** + * Set connection factory class. + * + * @param cfClass connection factory class + * @return {@link JCAOutboundDeploymentMetaData} to support method chaining + */ + public JCAOutboundDeploymentMetaData setConnectionFactoryClass(Class cfClass) { + _connectionFactoryClass = cfClass; + return this; + } + + /** + * Get connection factory class. + * @return connection factory class + */ + public Class getConnectionFactoryClass() { + return _connectionFactoryClass; + } + + /** + * Set connection factory JNDI name. + * + * @param cfJndiName connection factory JNDI name + * @return {@link JCAOutboundDeploymentMetaData} to support method chaining + */ + public JCAOutboundDeploymentMetaData setConnectionFactoryJNDIName(String cfJndiName) { + _connectionFactoryJNDIName = cfJndiName; + return this; + } + + /** + * Get connection factory JNDI name. + * + * @return connection factory JNDI name + */ + public String getConnectionFactoryJNDIName() { + return _connectionFactoryJNDIName; + } + + /** + * Set connection properties. + * + * @param props connection properties + * @return {@link JCAOutboundDeploymentMetaData} to support method chaining + */ + public JCAOutboundDeploymentMetaData setConnectionProperties(Properties props) { + _connectionProperties = props; + return this; + } + + /** + * Get connection properties. + * @return connection properties + */ + public Properties getConnectionProperties() { + return _connectionProperties; + } + + /** + * Set connection spec. + * + * @param connSpec connection spec + * @return {@link JCAOutboundDeploymentMetaData} to support method chaining + */ + public JCAOutboundDeploymentMetaData setConnectionSpec(Object connSpec) { + _connectionSpec = connSpec; + return this; + } + + /** + * Get connection spec. + * + * @return connection spec + */ + public Object getConnectionSpec() { + return _connectionSpec; + } + + /** + * Set interaction spec. + * + * @return interaction spec + */ + public Object getInteractionSpec() { + return _interactionSpec; + } + + /** + * Get interaction spec. + * + * @param interactSpec interaction spec + * @return {@link JCAOutboundDeploymentMetaData} to support method chaining + */ + public JCAOutboundDeploymentMetaData setInteractionSpec(Object interactSpec) { + _interactionSpec = interactSpec; + return this; + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/deploy/OutboundHandler.java b/components/jca/src/main/java/org/switchyard/component/jca/deploy/OutboundHandler.java new file mode 100644 index 000000000..00cc3ed50 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/deploy/OutboundHandler.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.deploy; + +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.jca.processor.AbstractOutboundProcessor; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * An ExchangeHandler for JCA outbound binding. + * + * @author Tomohisa Igarashi + * + */ +public class OutboundHandler extends BaseServiceHandler { + + private AbstractOutboundProcessor _processor; + private final String _bindingName; + private final String _referenceName; + + /** + * Constructor. + * + * @param processor {@link AbstractOutboundProcessor} + * @param domain the service domain + */ + public OutboundHandler(AbstractOutboundProcessor processor, ServiceDomain domain) { + super(domain); + _processor = processor; + _bindingName = processor.getJCABindingModel().getName(); + _referenceName = processor.getJCABindingModel().getReference().getName(); + } + + @Override + protected void doStart() { + _processor.initialize(); + } + + @Override + protected void doStop() { + _processor.uninitialize(); + } + + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + // identify ourselves + exchange.getContext() + .setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, + Scope.EXCHANGE).addLabels(BehaviorLabel.TRANSIENT.label()); + if (getState() != State.STARTED) { + throw JCAMessages.MESSAGES.referenceBindingNotStarted(_referenceName, _bindingName); + } + + Message out = _processor.process(exchange); + if (exchange.getContract().getProviderOperation().getExchangePattern() == ExchangePattern.IN_OUT) { + exchange.send(out); + } + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/endpoint/AbstractInflowEndpoint.java b/components/jca/src/main/java/org/switchyard/component/jca/endpoint/AbstractInflowEndpoint.java new file mode 100644 index 000000000..f1e33494d --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/endpoint/AbstractInflowEndpoint.java @@ -0,0 +1,223 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.endpoint; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.selector.OperationSelectorFactory; +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.jca.composer.JCABindingData; +import org.switchyard.component.jca.composer.JCAComposition; +import org.switchyard.component.jca.config.model.JCABindingModel; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.policy.PolicyUtil; +import org.switchyard.policy.TransactionPolicy; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.selector.OperationSelector; + +/** + * Abstract message endpoint class for JCA inflow. + * + * @author Tomohisa Igarashi + * + */ +public abstract class AbstractInflowEndpoint { + + private JCABindingModel _jcaBindingModel; + private ServiceDomain _domain; + private QName _serviceQName; + private ServiceReference _serviceRef; + private boolean _transacted = false; + private ClassLoader _appClassLoader; + private String _gatewayName; + + /** + * initialize. + */ + public void initialize() { + _serviceRef = _domain.getServiceReference(_serviceQName); + } + + /** + * uninitialize. + */ + public void uninitialize() { + } + + /** + * set {@link JCABindingModel}. + * + * @param model {@link JCABindingModel} + * @return {@link AbstractInflowEndpoint} to support method chaining + */ + public AbstractInflowEndpoint setJCABindingModel(JCABindingModel model) { + _jcaBindingModel = model; + _gatewayName = model.getName(); + return this; + } + + /** + * get {@link JCABindingModel}. + * + * @return {@link JCABindingModel} + */ + public JCABindingModel getJCABindingModel() { + return _jcaBindingModel; + } + + /** + * set ServiceDomain. + * @param domain ServiceDomain + * @return this instance + */ + public AbstractInflowEndpoint setServiceDomain(ServiceDomain domain) { + _domain = domain; + return this; + } + + /** + * get ServiceDomain. + * @return ServiceDomain + */ + public ServiceDomain getServiceDomain() { + return _domain; + } + + /** + * set service QName. + * @param qname service QName + * @return this instance + */ + public AbstractInflowEndpoint setServiceQName(QName qname) { + _serviceQName = qname; + return this; + } + + /** + * get Service QName. + * @return Service QName + */ + public QName getServiceQName() { + return _serviceQName; + } + + /** + * set service reference. + * @param ref service reference + * @return this instance + */ + public AbstractInflowEndpoint setServiceReference(ServiceReference ref) { + _serviceRef = ref; + return this; + } + + /** + * get ServiceReference. + * @return ServiceReference + */ + public ServiceReference getServiceReference() { + return _serviceRef; + } + + /** + * return whether the delivery is transacted or not. + * + * @return true if transacted + */ + public boolean isDeliveryTransacted() { + return _transacted; + } + + /** + * set whether the delivery is transacted or not. + * + * @param transacted true if transacted + * @return this instance + */ + public AbstractInflowEndpoint setDeliveryTransacted(boolean transacted) { + _transacted = transacted; + return this; + } + + /** + * set application class loader. + * + * @param loader application class loader + * @return this instance + */ + public AbstractInflowEndpoint setApplicationClassLoader(ClassLoader loader) { + _appClassLoader = loader; + return this; + } + + /** + * get application class loader. + * + * @return application class loader + */ + public ClassLoader getApplicationClassLoader() { + return _appClassLoader; + } + + protected Exchange createExchange(String operation, ExchangeHandler handler) { + if (_serviceRef == null) { + throw JCAMessages.MESSAGES.initializeMustBeCalledBeforeExchange(); + } + + if (operation == null) { + final Set operations = _serviceRef.getInterface().getOperations(); + if (operations.size() != 1) { + throw JCAMessages.MESSAGES.noOperationSelectorConfigured(operations.toString()); + } + final ServiceOperation serviceOperation = operations.iterator().next(); + operation = serviceOperation.getName(); + } + + Exchange exchange = _serviceRef.createExchange(operation, handler); + if (_transacted) { + PolicyUtil.provide(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + PolicyUtil.provide(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + } + + // identify ourselves + exchange.getContext() + .setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _gatewayName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + + return exchange; + + } + + protected Exchange createExchange(String operation) { + return createExchange(operation, null); + } + + protected MessageComposer getMessageComposer(Class clazz) { + return JCAComposition.getMessageComposer(_jcaBindingModel, clazz); + } + + protected OperationSelector getOperationSelector(Class clazz) { + return OperationSelectorFactory.getOperationSelectorFactory(clazz) + .newOperationSelector(_jcaBindingModel.getOperationSelector()); + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/endpoint/CCIEndpoint.java b/components/jca/src/main/java/org/switchyard/component/jca/endpoint/CCIEndpoint.java new file mode 100644 index 000000000..e182d5e53 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/endpoint/CCIEndpoint.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.endpoint; + +import javax.naming.InitialContext; +import javax.resource.cci.ConnectionFactory; +import javax.resource.cci.MappedRecord; +import javax.resource.cci.MessageListener; +import javax.resource.cci.Record; +import javax.resource.cci.RecordFactory; + +import org.switchyard.Exchange; +import org.switchyard.SwitchYardException; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.composer.MappedRecordBindingData; +import org.switchyard.selector.OperationSelector; +/** + * Concrete message endpoint class for JCA message inflow using JCA CCI MessageListener interface. + * + * @author Tomohisa Igarashi + * + */ +public class CCIEndpoint extends AbstractInflowEndpoint implements MessageListener { + + private static final long DEFAULT_TIMEOUT = 15000; + private static final String DEFAULT_RECORD_NAME = "DefaultMappedRecord"; + private static final String DEFAULT_DESCRIPTION = "Default MappedRecord implementation by " + CCIEndpoint.class.getName(); + + private String _connectionFactoryJNDIName; + private long _waitTimeout = DEFAULT_TIMEOUT; + private String _recordName = DEFAULT_RECORD_NAME; + private String _description = DEFAULT_DESCRIPTION; + private MessageComposer _composer; + private OperationSelector _selector; + private RecordFactory _recordFactory; + + @Override + public void initialize() { + super.initialize(); + + _composer = getMessageComposer(MappedRecordBindingData.class); + _selector = getOperationSelector(MappedRecordBindingData.class); + + try { + ConnectionFactory factory = (ConnectionFactory) new InitialContext().lookup(_connectionFactoryJNDIName); + _recordFactory = factory.getRecordFactory(); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + @Override + public Record onMessage(Record record) { + SynchronousInOutHandler inOutHandler = new SynchronousInOutHandler(); + MappedRecord sourceRecord = MappedRecord.class.cast(record); + try { + MappedRecordBindingData bindingData = new MappedRecordBindingData(sourceRecord); + String operation = _selector != null ? _selector.selectOperation(bindingData).getLocalPart() : null; + Exchange exchange = createExchange(operation, inOutHandler); + exchange.send(_composer.compose(bindingData, exchange)); + + exchange = inOutHandler.waitForOut(_waitTimeout); + MappedRecord returnRecord = _recordFactory.createMappedRecord(_recordName); + returnRecord.setRecordShortDescription(_description); + return _composer.decompose(exchange, new MappedRecordBindingData(returnRecord)).getRecord(); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + /** + * set implementation class name for {@link RecordFactory}. + * + * @param name class name + */ + public void setConnectionFactoryJNDIName(String name) { + _connectionFactoryJNDIName = name; + } + + /** + * get implementation class name for {@link RecordFactory}. + * + * @return class name + */ + public String getConnectionFactoryJNDIName() { + return _connectionFactoryJNDIName; + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/endpoint/JMSEndpoint.java b/components/jca/src/main/java/org/switchyard/component/jca/endpoint/JMSEndpoint.java new file mode 100644 index 000000000..518a31689 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/endpoint/JMSEndpoint.java @@ -0,0 +1,549 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.endpoint; + +import java.io.InputStream; +import java.util.Properties; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.Destination; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.naming.InitialContext; + +import org.jboss.logging.Logger; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangeState; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.JCALogger; +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.jca.composer.JMSBindingData; +import org.switchyard.SwitchYardException; +import org.switchyard.selector.OperationSelector; + +/** + * Concrete message endpoint class for JCA message inflow using JMS MessageListener interface. + * + * @author Tomohisa Igarashi + * + */ +public class JMSEndpoint extends AbstractInflowEndpoint implements MessageListener { + + /** prefix for the context property. */ + public static final String CONTEXT_PROPERTY_PREFIX = "org.switchyard.component.jca.endpoint."; + /** key for JNDI properties file. */ + public static final String KEY_JNDI_PROPERTIES_FILE = "jndiPropertiesFileName"; + /** key for JNDI properties file to look up the JMS destination. */ + public static final String KEY_DESTINATION_JNDI_PROPERTIES_FILE = "destinationJndiPropertiesFileName"; + /** key for ConnectionFactory JNDI name. */ + public static final String KEY_CONNECTION_FACTORY_JNDI_NAME = "connectionFactoryJndiName"; + /** key for replyTo/faultTo destination type. */ + public static final String KEY_DESTINATION_TYPE = "destinationType"; + /** key for replyTo destination name. */ + public static final String KEY_REPLY_TO = "replyTo"; + /** key for faultTo destination name. */ + public static final String KEY_FAULT_TO = "faultTo"; + /** key for output message type. */ + public static final String KEY_MESSAGE_TYPE = "messageType"; + /** key for user name. */ + public static final String KEY_USERNAME = "userName"; + /** key for password. */ + public static final String KEY_PASSWORD = "password"; + + private Logger _logger = Logger.getLogger(JMSEndpoint.class); + private MessageComposer _composer; + private OperationSelector _selector; + private String _jndiPropertiesFileName; + private String _destinationJndiPropertiesFileName; + private String _connectionFactoryJNDIName; + private DestinationType _defaultDestinationType = DestinationType.JNDI; + private String _defaultFaultTo; + private String _defaultReplyTo; + + private String _userName; + private String _password; + private Properties _jndiProperties; + private Properties _destinationJndiProperties; + private ConnectionFactory _connectionFactory; + private Destination _defaultFaultToJMSDestination; + private Destination _defaultReplyToJMSDestination; + private MessageType _defaultOutMessageType = MessageType.Object; + + private enum DestinationType { + Queue, Topic, JNDI + } + + private enum MessageType { + Stream, Map, Text, Object, Bytes, Plain + } + + @Override + public void initialize() { + super.initialize(); + _composer = getMessageComposer(JMSBindingData.class); + _selector = getOperationSelector(JMSBindingData.class); + + try { + InitialContext cfic = null; + if (getJndiProperties() != null) { + cfic = new InitialContext(getJndiProperties()); + } else { + cfic = new InitialContext(); + } + if (_connectionFactoryJNDIName != null) { + _connectionFactory = (ConnectionFactory) cfic.lookup(_connectionFactoryJNDIName); + } + + // caching replyTo/faultTo destination if its type is JNDI + if (_defaultDestinationType == DestinationType.JNDI) { + InitialContext destic = null; + if (getDestinationJndiProperties() != null) { + cfic.close(); + destic = new InitialContext(getDestinationJndiProperties()); + } else { + destic = cfic; + } + + if (_defaultFaultTo != null) { + try { + _defaultFaultToJMSDestination = (Destination) destic.lookup(_defaultFaultTo); + } catch (Exception e) { + JCALogger.ROOT_LOGGER.destinationNotFound(_defaultFaultTo, "faultTo"); + } + } + if (_defaultReplyTo != null) { + try { + _defaultReplyToJMSDestination = (Destination) destic.lookup(_defaultReplyTo); + } catch (Exception e) { + JCALogger.ROOT_LOGGER.destinationNotFound(_defaultReplyTo, "replyTo"); + } + } + destic.close(); + } + } catch (Exception e) { + throw JCAMessages.MESSAGES.failedToInitialize(this.getClass().getName(), e); + } + + if (_logger.isDebugEnabled()) { + StringBuilder msg = new StringBuilder() + .append("Initialized with: {") + .append("Connection Factory:").append(_connectionFactoryJNDIName) + .append(", Destination Type:").append(_defaultDestinationType) + .append(", replyTo Name:").append(_defaultReplyTo) + .append(", faultTo Name:").append(_defaultReplyTo) + .append(", User Name:").append(_userName) + .append(", Output Message Type:").append(_defaultOutMessageType) + .append(", JNDI Properties File:").append(_jndiPropertiesFileName) + .append(", Destination JNDI Properties File:").append(_destinationJndiPropertiesFileName) + .append("}"); + _logger.debug(msg.toString()); + } + } + + @Override + public void onMessage(Message message) { + + try { + JMSBindingData bindingData = new JMSBindingData(message); + final String operation = _selector != null ? _selector.selectOperation(bindingData).getLocalPart() : null; + SynchronousInOutHandler replyHandler = new SynchronousInOutHandler(); + Exchange exchange = createExchange(operation, replyHandler); + exchange.send(_composer.compose(bindingData, exchange)); + + if (_connectionFactory == null) { + return; + } + + // Process replyTo and faultTo if ConnectionFactory is available + Context context = exchange.getContext(); + Connection connection = null; + + try { + if (_userName != null) { + connection = _connectionFactory.createConnection(_userName, _password); + } else { + connection = _connectionFactory.createConnection(); + } + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + + Destination faultTo = getFaultToDestinationFromContext(session, context); + Destination replyTo = getReplyToDestinationFromContext(session, context); + if (faultTo != null && ExchangeState.FAULT.equals(exchange.getState())) { + if (exchange.getMessage() != null) { + sendJMSMessage(session, faultTo, exchange, getOutputMessageTypeFromContext(context)); + } + } else if (replyTo != null && ExchangePattern.IN_OUT.equals(exchange.getPattern())) { + exchange = replyHandler.waitForOut(); + if (exchange.getMessage() != null) { + sendJMSMessage(session, replyTo, exchange, getOutputMessageTypeFromContext(context)); + } + } + } finally { + if (connection != null) { + connection.close(); + } + } + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + protected void sendJMSMessage(Session session, Destination destination, Exchange exchange, MessageType type) { + try { + MessageProducer producer = session.createProducer(destination); + + Message msg; + switch (type) { + case Stream: + msg = session.createStreamMessage(); + break; + case Map: + msg = session.createMapMessage(); + break; + case Text: + msg = session.createTextMessage(); + break; + case Bytes: + msg = session.createBytesMessage(); + break; + case Plain: + msg = session.createMessage(); + break; + default: + msg = session.createObjectMessage(); + } + producer.send(_composer.decompose(exchange, new JMSBindingData(msg)).getMessage()); + } catch (Exception e) { + JCALogger.ROOT_LOGGER.failedToSendMessage(destination.toString(), e.getMessage()); + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + + protected Destination getReplyToDestinationFromContext(Session session, Context ctx) { + Destination replyToDestination = null; + + String key = CONTEXT_PROPERTY_PREFIX + KEY_REPLY_TO; + if (ctx.getProperty(key) != null) { + String replyToName = ctx.getPropertyValue(key); + DestinationType replyToType = getDestinationTypeFromContext(ctx); + + try { + switch (replyToType) { + case JNDI: + replyToDestination = lookupDestinationFromJNDI(replyToName); + break; + case Queue: + replyToDestination = session.createQueue(replyToName); + break; + case Topic: + replyToDestination = session.createTopic(replyToName); + break; + } + if (_logger.isDebugEnabled()) { + _logger.debug("replyTo is set to '" + replyToName + "'"); + } + } catch (Exception e) { + JCALogger.ROOT_LOGGER.contextDestinationNotFound(replyToName, _defaultReplyTo); + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + + // No valid replyTo is specified in a context property - use default + if (replyToDestination == null) { + try { + switch (_defaultDestinationType) { + case JNDI: + replyToDestination = _defaultReplyToJMSDestination; + break; + case Queue: + replyToDestination = session.createQueue(_defaultReplyTo); + break; + case Topic: + replyToDestination = session.createTopic(_defaultReplyTo); + break; + } + } catch (Exception e) { + JCALogger.ROOT_LOGGER.destinationNotFound(_defaultReplyTo, "replyTo"); + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + return replyToDestination; + } + + protected Destination getFaultToDestinationFromContext(Session session, Context ctx) { + Destination faultToDestination = null; + + String key = CONTEXT_PROPERTY_PREFIX + KEY_FAULT_TO; + if (ctx.getProperty(key) != null) { + String faultToName = ctx.getPropertyValue(key); + DestinationType faultToType = getDestinationTypeFromContext(ctx); + + try { + switch (faultToType) { + case JNDI: + faultToDestination = lookupDestinationFromJNDI(faultToName); + break; + case Queue: + faultToDestination = session.createQueue(faultToName); + break; + case Topic: + faultToDestination = session.createTopic(faultToName); + break; + } + if (_logger.isDebugEnabled()) { + _logger.debug("faultTo is set to '" + faultToName + "'"); + } + } catch (Exception e) { + JCALogger.ROOT_LOGGER.contextDestinationNotFound(faultToName, _defaultFaultTo); + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + + // No valid faultTo is specified in a context property - use default + if (faultToDestination == null) { + try { + switch (_defaultDestinationType) { + case JNDI: + faultToDestination = _defaultFaultToJMSDestination; + break; + case Queue: + faultToDestination = session.createQueue(_defaultFaultTo); + break; + case Topic: + faultToDestination = session.createTopic(_defaultFaultTo); + break; + } + } catch (Exception e) { + JCALogger.ROOT_LOGGER.destinationNotFound(_defaultFaultTo, "faultTo"); + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + return faultToDestination; + } + + protected DestinationType getDestinationTypeFromContext(Context ctx) { + DestinationType destType = _defaultDestinationType; + String key = CONTEXT_PROPERTY_PREFIX + KEY_DESTINATION_TYPE; + if (ctx.getProperty(key) != null) { + String type = ctx.getPropertyValue(key); + DestinationType ctxType = parseDestinationType(type); + if (ctxType != null) { + destType = ctxType; + if (_logger.isDebugEnabled()) { + _logger.debug("Destination type is set to '" + destType.toString() + "'"); + } + } + } + return destType; + } + + protected Destination lookupOrCreateDestination(Session session, DestinationType type, String destName) throws Exception { + switch (type) { + case JNDI: + return lookupDestinationFromJNDI(destName); + case Queue: + return session.createQueue(destName); + case Topic: + return session.createTopic(destName); + default: + return null; + } + } + + protected Destination lookupDestinationFromJNDI(String destName) throws Exception { + InitialContext ic = null; + try { + if (getDestinationJndiProperties() != null) { + ic = new InitialContext(getDestinationJndiProperties()); + } else if (getJndiProperties() != null) { + ic = new InitialContext(getJndiProperties()); + } else { + ic = new InitialContext(); + } + return (Destination) ic.lookup(destName); + } finally { + if (ic != null) { + try { + ic.close(); + } catch (Exception e) { + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + } + } + + protected MessageType getOutputMessageTypeFromContext(Context ctx) { + String key = CONTEXT_PROPERTY_PREFIX + KEY_MESSAGE_TYPE; + if (ctx.getProperty(key) != null) { + MessageType type = MessageType.valueOf(ctx.getPropertyValue(key).toString()); + if (_logger.isDebugEnabled()) { + _logger.debug("Output message type is set to '" + type.toString() + "'"); + } + return type; + } + return _defaultOutMessageType; + } + + /** + * set ConnectionFactory JNDI name. + * + * @param name ConnectionFactory JNDI name + */ + public void setConnectionFactoryJNDIName(String name) { + _connectionFactoryJNDIName = name; + } + + /** + * Set destination type. + * @param type destination type + */ + public void setDestinationType(String type) { + DestinationType destType = parseDestinationType(type); + if (destType == null) { + JCALogger.ROOT_LOGGER.invalidDestinationType(type, DestinationType.JNDI.toString()); + destType = DestinationType.JNDI; + } + _defaultDestinationType = destType; + } + + protected DestinationType parseDestinationType(String type) { + DestinationType destType = null; + if (type.equals(javax.jms.Queue.class.getName()) || type.equalsIgnoreCase("queue")) { + destType = DestinationType.Queue; + } else if (type.equals(javax.jms.Topic.class.getName()) || type.equalsIgnoreCase("Topic")) { + destType = DestinationType.Topic; + } else if (type.equalsIgnoreCase("JNDI")) { + destType = DestinationType.JNDI; + } + return destType; + } + + /** + * set replyTo destination name. + * + * @param name replyTo destination name + */ + public void setReplyTo(String name) { + _defaultReplyTo = name; + } + + /** + * set faultTo destination name. + * + * @param name faultTo destination name + */ + public void setFaultTo(String name) { + _defaultFaultTo = name; + } + + /** + * set user name. + * + * @param user user name + */ + public void setUsername(String user) { + _userName = user; + } + + /** + * set password. + * + * @param passwd password + */ + public void setPassword(String passwd) { + _password = passwd; + } + + /** + * set message type. + * @param type message type + */ + public void setMessageType(String type) { + _defaultOutMessageType = MessageType.valueOf(type); + } + + /** + * set JNDI properties file name. + * @param name file name + */ + public void setJndiPropertiesFileName(String name) { + _jndiPropertiesFileName = name; + } + + /** + * get JNDI properties. + * @return JNDI properties + */ + public Properties getJndiProperties() { + if (_jndiPropertiesFileName != null && _jndiProperties == null) { + try { + InputStream is = Classes.getResourceAsStream(_jndiPropertiesFileName); + Properties props = new Properties(); + props.load(is); + is.close(); + _jndiProperties = props; + } catch (Exception e) { + JCALogger.ROOT_LOGGER.failedToLoadJndiPropertiesFile(_jndiPropertiesFileName, e); + } + } + return _jndiProperties; + } + + /** + * set JNDI properties file name for destination lookup. + * @param name filename + */ + public void setDestinationJndiPropertiesFileName(String name) { + _destinationJndiPropertiesFileName = name; + } + + /** + * get JNDI properties for destination lookup. + * @return InitialContext properties for destination lookup + */ + public Properties getDestinationJndiProperties() { + if (_destinationJndiPropertiesFileName != null && _destinationJndiProperties == null) { + try { + InputStream is = Classes.getResourceAsStream(_destinationJndiPropertiesFileName); + Properties props = new Properties(); + props.load(is); + is.close(); + _destinationJndiProperties = props; + } catch (Exception e) { + JCALogger.ROOT_LOGGER.failedToLoadJndiPropertiesFile(_destinationJndiPropertiesFileName, e); + } + } + return _destinationJndiProperties; + } +} + diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/AbstractOutboundProcessor.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/AbstractOutboundProcessor.java new file mode 100644 index 000000000..fba62aaa7 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/AbstractOutboundProcessor.java @@ -0,0 +1,199 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor; + +import java.io.InputStream; +import java.util.Properties; + +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.JCALogger; +import org.switchyard.component.jca.composer.JCABindingData; +import org.switchyard.component.jca.composer.JCAComposition; +import org.switchyard.component.jca.config.model.JCABindingModel; + +/** + * Abstract class for processing outbound delivery regarding to JCA outbound contract. + * + * @author Tomohisa Igarashi + */ +public abstract class AbstractOutboundProcessor { + + /** key for JNDI properties file. */ + public static final String KEY_JNDI_PROPERTIES_FILE = "jndiPropertiesFileName"; + + private String _connectionFactoryJNDIName; + private Properties _mcfProperties; + private String _jndiPropertiesFileName; + private Properties _jndiProperties; + private ClassLoader _appClassLoader; + private JCABindingModel _jcaBindingModel; + + /** + * process outbound delivery. + * + * @param exchange {@link Exchange} + * @return response message + * @throws HandlerException failed to deliver + */ + public abstract Message process(Exchange exchange) throws HandlerException; + + /** + * initialize the processor. + */ + public abstract void initialize(); + + /** + * uninitialize the processor. + */ + public abstract void uninitialize(); + + /** + * set connection information. + * + * @param name name of the class which represents connection information + * @param props connection properties + * @return {@link AbstractOutboundProcessor} to support method chaining + */ + public abstract AbstractOutboundProcessor setConnectionSpec(String name, Properties props); + + /** + * set interaction information. + * + * @param name name of the class which represents interaction information + * @param props interaction properties + * @return {@link AbstractOutboundProcessor} to support method chaining + */ + public abstract AbstractOutboundProcessor setInteractionSpec(String name, Properties props); + + /** + * set connection factory JNDI name. + * + * @param name connection factory JNDI name + * @return {@link AbstractOutboundProcessor} to support method chaining + */ + public AbstractOutboundProcessor setConnectionFactoryJNDIName(String name) { + _connectionFactoryJNDIName = name; + return this; + } + + /** + * get connection factory JNDI name. + * + * @return connection factory JNDI name + */ + public String getConnectionFactoryJNDIName() { + return _connectionFactoryJNDIName; + } + + /** + * set managed connection factory properties. + * + * @param props {@link Properties} for managed connection factory + * @return {@link AbstractOutboundProcessor} to support method chaining + */ + public AbstractOutboundProcessor setMCFProperties(Properties props) { + _mcfProperties = props; + return this; + } + + /** + * get managed connection factory properties. + * + * @return {@link Properties} for managed connection factory + */ + public Properties getMCFProperties() { + return _mcfProperties; + } + + /** + * set application class loader. + * + * @param loader application class loader + * @return {@link AbstractOutboundProcessor} to support method chaining + */ + public AbstractOutboundProcessor setApplicationClassLoader(ClassLoader loader) { + _appClassLoader = loader; + return this; + } + + /** + * get application class loader. + * + * @return application class loader + */ + public ClassLoader getApplicationClassLoader() { + return _appClassLoader; + } + + /** + * set JCA binding model. + * @param model JCA binding model + * @return {@link AbstractOutboundProcessor} to support method chaining + */ + public AbstractOutboundProcessor setJCABindingModel(JCABindingModel model) { + _jcaBindingModel = model; + return this; + } + + /** + * get JCA binding model. + * @return JCA binding model + */ + public JCABindingModel getJCABindingModel() { + return _jcaBindingModel; + } + + protected MessageComposer getMessageComposer(Class clazz) { + return JCAComposition.getMessageComposer(_jcaBindingModel, clazz); + } + + /** + * set JNDI properties file name. + * @param name file name + */ + public void setJndiPropertiesFileName(String name) { + _jndiPropertiesFileName = name; + } + + /** + * get JNDI properties file name. + * @return file name + */ + public String getJndiPropertiesFileName() { + return _jndiPropertiesFileName; + } + + /** + * get JNDI properties. + * @return JNDI properties + */ + public Properties getJndiProperties() { + if (_jndiPropertiesFileName != null && _jndiProperties == null) { + try { + InputStream is = Classes.getResourceAsStream(_jndiPropertiesFileName); + Properties props = new Properties(); + props.load(is); + is.close(); + _jndiProperties = props; + } catch (Exception e) { + JCALogger.ROOT_LOGGER.failedToLoadJndiPropertiesFile(_jndiPropertiesFileName, e); + } + } + return _jndiProperties; + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/CCIProcessor.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/CCIProcessor.java new file mode 100644 index 000000000..85546badf --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/CCIProcessor.java @@ -0,0 +1,155 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor; + +import java.util.Properties; + +import javax.naming.InitialContext; +import javax.resource.ResourceException; +import javax.resource.cci.ConnectionFactory; +import javax.resource.cci.ConnectionSpec; +import javax.resource.cci.InteractionSpec; +import javax.resource.cci.Connection; +import javax.resource.cci.Interaction; +import javax.resource.cci.RecordFactory; + +import org.jboss.logging.Logger; +import org.jboss.util.propertyeditor.PropertyEditors; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.component.jca.JCALogger; +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.jca.processor.cci.RecordHandler; +import org.switchyard.component.jca.processor.cci.RecordHandlerFactory; + +/** + * A concrete outbound processor class for CCI. + * + * @author Tomohisa Igarashi + * + */ +public class CCIProcessor extends AbstractOutboundProcessor { + /** default record type. */ + public static final String DEFAULT_RECORD_TYPE = "javax.resource.cci.MappedRecord"; + + private Logger _logger = Logger.getLogger(CCIProcessor.class); + private String _recordClassName; + private ConnectionSpec _connectionSpec; + private InteractionSpec _interactionSpec; + private ConnectionFactory _connectionFactory; + private RecordHandler _recordHandler; + + @Override + public AbstractOutboundProcessor setConnectionSpec(String name, Properties props) { + try { + Class clazz = getApplicationClassLoader().loadClass(name); + _connectionSpec = (ConnectionSpec) clazz.newInstance(); + if (!props.isEmpty()) { + PropertyEditors.mapJavaBeanProperties(_connectionSpec, props); + } + } catch (Exception e) { + throw JCAMessages.MESSAGES.couldNotInitializeConnectionSpec(e); + } + + return this; + } + + @Override + public AbstractOutboundProcessor setInteractionSpec(String name, Properties props) { + try { + Class clazz = getApplicationClassLoader().loadClass(name); + _interactionSpec = (InteractionSpec) clazz.newInstance(); + + if (!props.isEmpty()) { + PropertyEditors.mapJavaBeanProperties(_interactionSpec, props); + } + } catch (Exception e) { + throw JCAMessages.MESSAGES.couldNotInitializeInteractionSpec(e); + } + + return this; + } + + @Override + public void initialize() { + try { + Class clazz = getApplicationClassLoader().loadClass(_recordClassName); + _recordHandler = RecordHandlerFactory.createRecordHandler(clazz, getApplicationClassLoader()) + .setJCABindingModel(getJCABindingModel()) + .setInteractionSpec(_interactionSpec); + + InitialContext ic = null; + if (getJndiProperties() != null) { + ic = new InitialContext(getJndiProperties()); + } else { + ic = new InitialContext(); + } + _connectionFactory = (ConnectionFactory) ic.lookup(getConnectionFactoryJNDIName()); + } catch (Exception e) { + throw JCAMessages.MESSAGES.failedToInitialize(this.getClass().getName(), e); + } + try { + RecordFactory factory = _connectionFactory.getRecordFactory(); + _recordHandler.setRecordFactory(factory); + } catch (ResourceException e) { + JCALogger.ROOT_LOGGER.failedToGetRecordFactory(e.getMessage()); + } + } + + @Override + public void uninitialize() { + _connectionFactory = null; + } + + @Override + public Message process(Exchange exchange) throws HandlerException { + Connection connection = null; + Interaction interaction = null; + try { + if (_connectionSpec != null) { + connection = _connectionFactory.getConnection(_connectionSpec); + } else { + connection = _connectionFactory.getConnection(); + } + interaction = connection.createInteraction(); + return _recordHandler.handle(exchange, connection, interaction); + } catch (Exception e) { + throw JCAMessages.MESSAGES.failedToProcessCCIOutboundInteraction(e); + } finally { + try { + if (interaction != null) { + interaction.close(); + } + if (connection != null) { + connection.close(); + } + } catch (ResourceException e) { + JCALogger.ROOT_LOGGER.failedToCloseInteractionConnection(e.getMessage()); + if (_logger.isDebugEnabled()) { + e.printStackTrace(); + } + } + } + } + + /** + * set {@link RecordFactory} implementation class name. + * + * @param name class name + */ + public void setRecordClassName(String name) { + _recordClassName = name; + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/JMSProcessor.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/JMSProcessor.java new file mode 100644 index 000000000..95f962e14 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/JMSProcessor.java @@ -0,0 +1,469 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor; + +import java.io.InputStream; +import java.util.Properties; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.naming.InitialContext; + +import org.jboss.logging.Logger; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.JCALogger; +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.jca.composer.JMSBindingData; + +/** + * A concrete outbound processor class for JMS. + * + * @author Tomohisa Igarashi + * + */ +public class JMSProcessor extends AbstractOutboundProcessor { + /** prefix for the context property. */ + public static final String CONTEXT_PROPERTY_PREFIX = "org.switchyard.component.jca.processor."; + /** key for username property. */ + public static final String KEY_USERNAME = "userName"; + /** key for password property. */ + public static final String KEY_PASSWORD = "password"; + /** key for transacted property. */ + public static final String KEY_TRANSACTED = "transacted"; + /** key for acknowledge mode property. */ + public static final String KEY_ACKNOWLEDGE_MODE = "acknowledgeMode"; + /** key for destination type property. */ + public static final String KEY_DESTINATION_TYPE = "destinationType"; + /** key for destination property. */ + public static final String KEY_DESTINATION = "destination"; + /** key for message type property. */ + public static final String KEY_MESSAGE_TYPE = "messageType"; + /** key for JNDI properties file to look up the JMS destination. */ + public static final String KEY_DESTINATION_JNDI_PROPERTIES_FILE = "destinationJndiPropertiesFileName"; + + private Logger _logger = Logger.getLogger(JMSProcessor.class); + private String _userName; + private String _password; + private String _transacted; + private boolean _defaultTxEnabled; + private DestinationType _defaultDestinationType = DestinationType.JNDI; + private String _defaultDestination; + private String _acknowledgeMode; + private int _defaultAckMode; + private ConnectionFactory _connectionFactory; + private Destination _defaultJmsDestination; + private MessageComposer _composer; + private MessageType _defaultOutMessageType = MessageType.Object; + private String _destinationJndiPropertiesFileName; + private Properties _destinationJndiProperties; + + private enum DestinationType { + Queue, Topic, JNDI + } + + private enum MessageType { + Stream, Map, Text, Object, Bytes, Plain + } + + @Override + public AbstractOutboundProcessor setConnectionSpec(String name, Properties props) { + // JMSProcessor doesn't need ConnectionSpec properties + return this; + } + + @Override + public AbstractOutboundProcessor setInteractionSpec(String name, Properties props) { + // JMSProcessor doesn't need InteractionSpec properties + return this; + } + + @Override + public void initialize() { + _defaultTxEnabled = Boolean.parseBoolean(_transacted); + + if (_acknowledgeMode == null || _acknowledgeMode.equals("")) { + _defaultAckMode = Session.AUTO_ACKNOWLEDGE; + } else { + _defaultAckMode = Integer.parseInt(_acknowledgeMode); + } + + if (_defaultDestination == null) { + throw JCAMessages.MESSAGES.destinationPropertyMustBeSpecifiedInProcessorProperties(); + } + + _composer = getMessageComposer(JMSBindingData.class); + + try { + InitialContext cfic = null; + if (getJndiProperties() != null) { + cfic = new InitialContext(getJndiProperties()); + } else { + cfic = new InitialContext(); + } + _connectionFactory = (ConnectionFactory) cfic.lookup(getConnectionFactoryJNDIName()); + + // caching destination if its type is JNDI + if (_defaultDestinationType == DestinationType.JNDI) { + InitialContext destic = null; + if (getDestinationJndiProperties() != null) { + cfic.close(); + destic = new InitialContext(getDestinationJndiProperties()); + } else { + destic = cfic; + } + _defaultJmsDestination = (Destination) destic.lookup(_defaultDestination); + destic.close(); + } + } catch (Exception e) { + throw JCAMessages.MESSAGES.failedToInitialize(this.getClass().getName(), e); + } + + if (_logger.isDebugEnabled()) { + StringBuilder msg = new StringBuilder() + .append("Initialized with: {") + .append("Connection Factory:").append(getConnectionFactoryJNDIName()) + .append(", Destination Type:").append(_defaultDestinationType) + .append(", Destination Name:").append(_defaultDestination) + .append(", User Name:").append(_userName) + .append(", Output Message Type:").append(_defaultOutMessageType) + .append(", JNDI Properties File:").append(getJndiPropertiesFileName()) + .append(", Destination JNDI Properties File:").append(_destinationJndiPropertiesFileName) + .append("}"); + _logger.debug(msg.toString()); + } + + } + + @Override + public void uninitialize() { + _connectionFactory = null; + } + + @Override + public org.switchyard.Message process(Exchange exchange) throws HandlerException { + Connection connection = null; + Session session = null; + try { + if (_userName != null) { + connection = _connectionFactory.createConnection(_userName, _password); + } else { + connection = _connectionFactory.createConnection(); + } + connection.start(); + + Context context = exchange.getContext(); + session = connection.createSession(getTxEnabledFromContext(context), getAcknowledgeModeFromContext(context)); + MessageProducer producer = session.createProducer(getDestinationFromContext(session, context)); + + Message msg; + switch (getOutputMessageTypeFromContext(context)) { + case Stream: + msg = session.createStreamMessage(); + break; + case Map: + msg = session.createMapMessage(); + break; + case Text: + msg = session.createTextMessage(); + break; + case Bytes: + msg = session.createBytesMessage(); + break; + case Plain: + msg = session.createMessage(); + break; + default: + msg = session.createObjectMessage(); + } + + producer.send(_composer.decompose(exchange, new JMSBindingData(msg)).getMessage()); + + if (session.getTransacted()) { + try { + session.commit(); + } catch (Exception e) { + // managed by global transaction. ignoring... + if (_logger.isDebugEnabled()) { + e.printStackTrace(); + } + } + } + return null; + } catch (Exception e) { + try { + if (session != null && session.getTransacted()) { + session.rollback(); + } + } catch (Exception e2) { + // managed by global transaction. ignoring... + if (_logger.isDebugEnabled()) { + e2.printStackTrace(); + } + } + throw JCAMessages.MESSAGES.failedToProcessJMSOutboundInteraction(e); + } finally { + try { + if (session != null) { + session.close(); + } + if (connection != null) { + connection.close(); + } + } catch (JMSException e) { + JCALogger.ROOT_LOGGER.failedToCloseJMSSessionconnection(e.getMessage()); + if (_logger.isDebugEnabled()) { + e.printStackTrace(); + } + } + } + } + + protected boolean getTxEnabledFromContext(Context ctx) { + String key = CONTEXT_PROPERTY_PREFIX + KEY_TRANSACTED; + if (ctx.getProperty(key) != null) { + boolean transacted = Boolean.parseBoolean(ctx.getPropertyValue(key).toString()); + if (_logger.isDebugEnabled()) { + _logger.debug("transacted is set to '" + transacted + "'"); + } + return transacted; + } + return _defaultTxEnabled; + } + + protected int getAcknowledgeModeFromContext(Context ctx) { + String key = CONTEXT_PROPERTY_PREFIX + KEY_ACKNOWLEDGE_MODE; + if (ctx.getProperty(key) != null) { + int ackMode = Integer.parseInt(ctx.getPropertyValue(key).toString()); + if (_logger.isDebugEnabled()) { + _logger.debug("Acknowledge Mode is set to '" + ackMode + "'"); + } + return ackMode; + } + return _defaultAckMode; + } + + protected Destination getDestinationFromContext(Session session, Context ctx) throws Exception { + Destination destination = null; + + String key = CONTEXT_PROPERTY_PREFIX + KEY_DESTINATION; + if (ctx.getProperty(key) != null) { + String destName = ctx.getPropertyValue(key); + DestinationType destType = getDestinationTypeFromContext(ctx); + + try { + switch (destType) { + case JNDI: + destination = lookupDestinationFromJNDI(destName); + break; + case Queue: + destination = session.createQueue(destName); + break; + case Topic: + destination = session.createTopic(destName); + break; + } + if (_logger.isDebugEnabled()) { + _logger.debug("Destination is set to '" + destName + "'"); + } + } catch (Exception e) { + JCALogger.ROOT_LOGGER.contextDestinationNotFound(destName, _defaultDestination); + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + + // No valid destination is specified in a context property - use default + if (destination == null) { + switch (_defaultDestinationType) { + case JNDI: + destination = _defaultJmsDestination; + break; + case Queue: + destination = session.createQueue(_defaultDestination); + break; + case Topic: + destination = session.createTopic(_defaultDestination); + break; + } + } + return destination; + } + + protected Destination lookupDestinationFromJNDI(String destName) throws Exception { + InitialContext ic = null; + try { + if (getDestinationJndiProperties() != null) { + ic = new InitialContext(getDestinationJndiProperties()); + } else if (getJndiProperties() != null) { + ic = new InitialContext(getJndiProperties()); + } else { + ic = new InitialContext(); + } + return (Destination) ic.lookup(destName); + } finally { + if (ic != null) { + try { + ic.close(); + } catch (Exception e) { + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + } + } + + protected DestinationType getDestinationTypeFromContext(Context ctx) { + DestinationType destType = _defaultDestinationType; + String key = CONTEXT_PROPERTY_PREFIX + KEY_DESTINATION_TYPE; + if (ctx.getProperty(key) != null) { + String type = ctx.getPropertyValue(key); + DestinationType ctxType = parseDestinationType(type); + if (ctxType != null) { + destType = ctxType; + if (_logger.isDebugEnabled()) { + _logger.debug("Destination type is set to '" + destType.toString() + "'"); + } + } + } + return destType; + } + + protected MessageType getOutputMessageTypeFromContext(Context ctx) { + String key = CONTEXT_PROPERTY_PREFIX + KEY_MESSAGE_TYPE; + if (ctx.getProperty(key) != null) { + MessageType msgType = MessageType.valueOf(ctx.getPropertyValue(key).toString()); + if (_logger.isDebugEnabled()) { + _logger.debug("Output message type is set to '" + msgType.toString() + "'"); + } + return msgType; + } + return _defaultOutMessageType; + } + + /** + * Set destination type. + * @param type destination type + */ + public void setDestinationType(String type) { + DestinationType destType = parseDestinationType(type); + if (destType == null) { + JCALogger.ROOT_LOGGER.invalidDestinationType(type, DestinationType.JNDI.toString()); + destType = DestinationType.JNDI; + } + _defaultDestinationType = destType; + } + + protected DestinationType parseDestinationType(String type) { + DestinationType destType = null; + if (type.equals(javax.jms.Queue.class.getName()) || type.equalsIgnoreCase("queue")) { + destType = DestinationType.Queue; + } else if (type.equals(javax.jms.Topic.class.getName()) || type.equalsIgnoreCase("Topic")) { + destType = DestinationType.Topic; + } else if (type.equalsIgnoreCase("JNDI")) { + destType = DestinationType.JNDI; + } + return destType; + } + + /** + * set destination name. + * @param name destination name + */ + public void setDestination(String name) { + _defaultDestination = name; + } + + /** + * set user name. + * + * @param user user name + */ + public void setUsername(String user) { + _userName = user; + } + + /** + * set password. + * + * @param passwd password + */ + public void setPassword(String passwd) { + _password = passwd; + } + + /** + * set transacted. + * + * @param tx "false" when disable transaction + */ + public void setTransacted(String tx) { + _transacted = tx; + } + + /** + * acknowledge mode. + * + * @param ack integer value of acknowledge mode. + * @see javax.jms.Session + */ + public void setAcknowledgeMode(String ack) { + _acknowledgeMode = ack; + } + + /** + * set message type. + * @param type message type + */ + public void setMessageType(String type) { + _defaultOutMessageType = MessageType.valueOf(type); + } + + /** + * set JNDI properties file name for destination lookup. + * @param name filename + */ + public void setDestinationJndiPropertiesFileName(String name) { + _destinationJndiPropertiesFileName = name; + } + + /** + * get JNDI properties for destination lookup. + * @return InitialContext properties for destination lookup + */ + public Properties getDestinationJndiProperties() { + if (_destinationJndiPropertiesFileName != null && _destinationJndiProperties == null) { + try { + InputStream is = Classes.getResourceAsStream(_destinationJndiPropertiesFileName); + Properties props = new Properties(); + props.load(is); + is.close(); + _destinationJndiProperties = props; + } catch (Exception e) { + JCALogger.ROOT_LOGGER.failedToLoadJndiPropertiesFile(_destinationJndiPropertiesFileName, e); + } + } + return _destinationJndiProperties; + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/IndexedRecordHandler.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/IndexedRecordHandler.java new file mode 100644 index 000000000..638416804 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/IndexedRecordHandler.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor.cci; + +import javax.resource.cci.Connection; +import javax.resource.cci.IndexedRecord; +import javax.resource.cci.Interaction; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.composer.IndexedRecordBindingData; + +/** + * IndexedRecordHandler. + * + * @author Tomohisa Igarashi + * + */ +public class IndexedRecordHandler extends RecordHandler { + + private MessageComposer _composer; + + /** + * Constructor which creates the message composer. + */ + public IndexedRecordHandler() { + _composer = getMessageComposer(IndexedRecordBindingData.class); + } + + @Override + public Message handle(Exchange exchange, Connection conn, Interaction interact) throws Exception { + IndexedRecord record = getRecordFactory().createIndexedRecord(IndexedRecordHandler.class.getName()); + IndexedRecord outRecord = (IndexedRecord) interact.execute(getInteractionSpec(), getMessageComposer(IndexedRecordBindingData.class).decompose(exchange, new IndexedRecordBindingData(record)).getRecord()); + return _composer.compose(new IndexedRecordBindingData(outRecord), exchange); + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/MappedRecordHandler.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/MappedRecordHandler.java new file mode 100644 index 000000000..2902b9d0f --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/MappedRecordHandler.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor.cci; + +import javax.resource.cci.Connection; +import javax.resource.cci.Interaction; +import javax.resource.cci.MappedRecord; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.composer.MappedRecordBindingData; + +/** + * MappedRecord handler. + * + * @author Tomohisa Igarashi + * + */ +public class MappedRecordHandler extends RecordHandler { + + private MessageComposer _composer; + + /** + * Constructor which creates the message composer. + */ + public MappedRecordHandler() { + _composer = getMessageComposer(MappedRecordBindingData.class); + } + + @Override + public Message handle(Exchange exchange, Connection conn, Interaction interact) throws Exception { + MappedRecord record = getRecordFactory().createMappedRecord(MappedRecordHandler.class.getName()); + MappedRecord outRecord = (MappedRecord) interact.execute(getInteractionSpec(), getMessageComposer(MappedRecordBindingData.class).decompose(exchange, new MappedRecordBindingData(record)).getRecord()); + return _composer.compose(new MappedRecordBindingData(outRecord), exchange); + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/RecordHandler.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/RecordHandler.java new file mode 100644 index 000000000..d10fb04f6 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/RecordHandler.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor.cci; + +import javax.resource.cci.Connection; +import javax.resource.cci.Interaction; +import javax.resource.cci.InteractionSpec; +import javax.resource.cci.RecordFactory; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.composer.JCAComposition; +import org.switchyard.component.jca.composer.RecordBindingData; +import org.switchyard.component.jca.config.model.JCABindingModel; + +/** + * RecordHandler. + * + * @author Tomohisa Igarashi + * + * @param record binding data type + */ +public abstract class RecordHandler> { + + private MessageComposer _composer; + private JCABindingModel _jcaBindingModel; + private RecordFactory _recordFactory; + private InteractionSpec _interactionSpec; + + /** + * handle interaction. + * + * @param exchange SwitchYard Exchange instance + * @param conn Connection instance + * @param interaction Interaction instance + * @return reply message + * @throws Exception when interaction failed + */ + public abstract Message handle(Exchange exchange, Connection conn, Interaction interaction) throws Exception; + + /** + * set JCA binding model. + * @param model JCA binding model + * @return this instance for method chaining + */ + public RecordHandler setJCABindingModel(JCABindingModel model) { + _jcaBindingModel = model; + return this; + } + + /** + * get JCA binding model. + * @return JCA binding model + */ + public JCABindingModel getJCABindingModel() { + return _jcaBindingModel; + } + + /** + * set RecordFactory. + * @param factory RecordFactory + * @return this instance for method chaining + */ + public RecordHandler setRecordFactory(RecordFactory factory) { + _recordFactory = factory; + return this; + } + + /** + * get RecordFactory. + * @return RecordFactory + */ + public RecordFactory getRecordFactory() { + return _recordFactory; + } + + /** + * set InteractionSpec. + * @param interactionSpec InteractionSpec + * @return this instance for method chaining + */ + public RecordHandler setInteractionSpec(InteractionSpec interactionSpec) { + _interactionSpec = interactionSpec; + return this; + } + + /** + * get InteractionSpec. + * @return InteractionSpec + */ + public InteractionSpec getInteractionSpec() { + return _interactionSpec; + } + + protected MessageComposer getMessageComposer(Class clazz) { + if (_composer == null) { + _composer = JCAComposition.getMessageComposer(_jcaBindingModel, clazz); + } + return _composer; + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/RecordHandlerFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/RecordHandlerFactory.java new file mode 100644 index 000000000..67c1c4338 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/RecordHandlerFactory.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor.cci; + +import javax.resource.cci.IndexedRecord; +import javax.resource.cci.MappedRecord; +import javax.resource.cci.Streamable; + +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.jca.composer.RecordBindingData; + +/** + * RecordHandler factory. + * + * @author Tomohisa Igarashi + * + */ +public final class RecordHandlerFactory { + + private RecordHandlerFactory() { + } + + /** + * create RecordHandler instance which supports the record type passed by parameter. + * + * @param recordType record type + * @param loader ClassLoader for application + * @return RecordHandler instance + */ + public static RecordHandler> createRecordHandler(Class recordType, ClassLoader loader) { + if (recordType.equals(MappedRecord.class)) { + return new MappedRecordHandler(); + } else if (recordType.equals(IndexedRecord.class)) { + return new IndexedRecordHandler(); + } else if (recordType.equals(Streamable.class)) { + return new StreamableRecordHandler(); + } else { + try { + Class clazz = loader.loadClass(RecordHandlerFactory.class.getPackage().getName() + "." + recordType.getSimpleName() + "RecordHandler"); + return (RecordHandler)clazz.newInstance(); + } catch (ClassNotFoundException e) { + throw JCAMessages.MESSAGES.recordTypeIsNotSupported(recordType.getName()); + } catch (InstantiationException e) { + throw JCAMessages.MESSAGES.recordTypeIsNotSupported(recordType.getName()); + } catch (IllegalAccessException iae) { + throw JCAMessages.MESSAGES.recordTypeIsNotSupported(recordType.getName()); + } + } + } +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/StreamableRecord.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/StreamableRecord.java new file mode 100644 index 000000000..660865ed7 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/StreamableRecord.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor.cci; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; + +import javax.resource.cci.Record; +import javax.resource.cci.Streamable; + +/** + * Record for raw byte content. + * + * @author Antti Laisi + */ +public class StreamableRecord implements Streamable, Record { + + private static final long serialVersionUID = 1L; + + private String _recordName; + private String _recordShortDescription; + + private byte[] _bytes; + + @Override + public String getRecordName() { + return _recordName; + } + + @Override + public String getRecordShortDescription() { + return _recordShortDescription; + } + + @Override + public void setRecordName(String recordName) { + _recordName = recordName; + } + + @Override + public void setRecordShortDescription(String recordShortDescription) { + _recordShortDescription = recordShortDescription; + } + + @Override + public void read(InputStream in) throws IOException { + _bytes = new byte[in.available()]; + in.read(_bytes); + } + + @Override + public void write(OutputStream out) throws IOException { + if (_bytes != null) { + out.write(_bytes); + } + } + + @Override + public Object clone() throws CloneNotSupportedException { + StreamableRecord clone = (StreamableRecord) super.clone(); + clone._recordName = _recordName; + clone._recordShortDescription = _recordShortDescription; + if (_bytes != null) { + clone._bytes = Arrays.copyOf(_bytes, _bytes.length); + } + return clone; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/StreamableRecordHandler.java b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/StreamableRecordHandler.java new file mode 100644 index 000000000..df5293479 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/processor/cci/StreamableRecordHandler.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.processor.cci; + +import javax.resource.cci.Connection; +import javax.resource.cci.Interaction; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.jca.composer.StreamableRecordBindingData; + +/** + * StreamableRecordHandler. + * + * @author Tomohisa Igarashi + * @author Antti Laisi + */ +public class StreamableRecordHandler extends RecordHandler { + + private MessageComposer _composer; + + /** + * Constructor which creates the message composer. + */ + public StreamableRecordHandler() { + _composer = getMessageComposer(StreamableRecordBindingData.class); + } + + @Override + public Message handle(Exchange exchange, Connection conn, Interaction interact) throws Exception { + StreamableRecord record = new StreamableRecord(); + StreamableRecord outRecord = new StreamableRecord(); + interact.execute(getInteractionSpec(), getMessageComposer(StreamableRecordBindingData.class).decompose(exchange, new StreamableRecordBindingData(record)).getRecord(), outRecord); + return _composer.compose(new StreamableRecordBindingData(outRecord), exchange); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/selector/CCIOperationSelector.java b/components/jca/src/main/java/org/switchyard/component/jca/selector/CCIOperationSelector.java new file mode 100644 index 000000000..8bc4c6471 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/selector/CCIOperationSelector.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.selector; + +import java.io.StringReader; + +import javax.resource.cci.MappedRecord; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.switchyard.component.common.selector.BaseOperationSelector; +import org.switchyard.component.jca.composer.MappedRecordBindingData; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +/** + * An example of OperationSelector implementation for CCI MappedRecord. + */ +public class CCIOperationSelector extends BaseOperationSelector { + + /** key name for lookup the operation from map. */ + public static final String KEY = "operationSelector"; + + /** + * Constructor. + * @param model OperationSelectorModel + */ + public CCIOperationSelector(OperationSelectorModel model) { + super(model); + } + + @Override + protected Document extractDomDocument(MappedRecordBindingData binding) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(extractString(binding))); + return builder.parse(is); + } + + @Override + protected String extractString(MappedRecordBindingData binding) throws Exception { + MappedRecord content = binding.getRecord(); + return String.class.cast(content.get(KEY)); + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/selector/CCIOperationSelectorFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/selector/CCIOperationSelectorFactory.java new file mode 100644 index 000000000..76fcef8a8 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/selector/CCIOperationSelectorFactory.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.selector; + +import org.switchyard.component.common.selector.OperationSelectorFactory; +import org.switchyard.component.jca.composer.MappedRecordBindingData; +import org.switchyard.selector.OperationSelector; + +/** + * An example of OperationSelectorFactory implementation for CCI MappedRecord. + */ +public class CCIOperationSelectorFactory extends OperationSelectorFactory { + + @Override + public Class getTargetClass() { + return MappedRecordBindingData.class; + } + + @Override + public Class> getDefaultOperationSelectorClass() { + return CCIOperationSelector.class; + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/selector/JMSOperationSelector.java b/components/jca/src/main/java/org/switchyard/component/jca/selector/JMSOperationSelector.java new file mode 100644 index 000000000..c023beca7 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/selector/JMSOperationSelector.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.selector; + +import java.io.StringReader; + +import javax.jms.BytesMessage; +import javax.jms.MapMessage; +import javax.jms.Message; +import javax.jms.ObjectMessage; +import javax.jms.TextMessage; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.switchyard.component.common.selector.BaseOperationSelector; +import org.switchyard.component.jca.JCAMessages; +import org.switchyard.component.jca.composer.JMSBindingData; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +/** + * OperationSelector for JMS Message. + */ +public class JMSOperationSelector extends BaseOperationSelector { + + /** key name for lookup the operation from map. */ + public static final String KEY = "operationSelector"; + + /** + * Constructor. + * @param model OperationSelectorModel. + */ + public JMSOperationSelector(OperationSelectorModel model) { + super(model); + } + + @Override + protected Document extractDomDocument(JMSBindingData binding) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource is = new InputSource(new StringReader(extractString(binding))); + return builder.parse(is); + } + + @Override + protected String extractString(JMSBindingData binding) throws Exception { + Message content = binding.getMessage(); + if (content instanceof TextMessage) { + return TextMessage.class.cast(content).getText(); + + } else if (content instanceof BytesMessage) { + BytesMessage sourceBytes = BytesMessage.class.cast(content); + if (sourceBytes.getBodyLength() > Integer.MAX_VALUE) { + throw JCAMessages.MESSAGES.theSizeOfMessageContentExceedsBytesThatIsNotSupportedByThisOperationSelector("" + Integer.MAX_VALUE); + } + byte[] bytearr = new byte[(int)sourceBytes.getBodyLength()]; + sourceBytes.readBytes(bytearr); + return new String(bytearr); + + } else if (content instanceof ObjectMessage) { + ObjectMessage sourceObj = ObjectMessage.class.cast(content); + return String.class.cast(sourceObj.getObject()); + + } else if (content instanceof MapMessage) { + MapMessage sourceMap = MapMessage.class.cast(content); + return sourceMap.getString(KEY); + } else { + return content.getStringProperty(KEY); + } + } + +} diff --git a/components/jca/src/main/java/org/switchyard/component/jca/selector/JMSOperationSelectorFactory.java b/components/jca/src/main/java/org/switchyard/component/jca/selector/JMSOperationSelectorFactory.java new file mode 100644 index 000000000..8b50cd583 --- /dev/null +++ b/components/jca/src/main/java/org/switchyard/component/jca/selector/JMSOperationSelectorFactory.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.selector; + +import org.switchyard.component.common.selector.OperationSelectorFactory; +import org.switchyard.component.jca.composer.JMSBindingData; +import org.switchyard.selector.OperationSelector; + +/** + * OperatoinSelectorFactory for JMS Message. + */ +public class JMSOperationSelectorFactory extends OperationSelectorFactory { + + @Override + public Class getTargetClass() { + return JMSBindingData.class; + } + + @Override + public Class> getDefaultOperationSelectorClass() { + return JMSOperationSelector.class; + } + +} diff --git a/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory b/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory new file mode 100644 index 000000000..49f47cf99 --- /dev/null +++ b/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory @@ -0,0 +1,15 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.jca.composer.MappedRecordContextMapperFactory +org.switchyard.component.jca.composer.IndexedRecordContextMapperFactory +org.switchyard.component.jca.composer.StreamableRecordContextMapperFactory +org.switchyard.component.jca.composer.JMSContextMapperFactory diff --git a/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory b/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory new file mode 100644 index 000000000..c453f03d3 --- /dev/null +++ b/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory @@ -0,0 +1,15 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.jca.composer.MappedRecordMessageComposerFactory +org.switchyard.component.jca.composer.IndexedRecordMessageComposerFactory +org.switchyard.component.jca.composer.StreamableRecordMessageComposerFactory +org.switchyard.component.jca.composer.JMSMessageComposerFactory diff --git a/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory b/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory new file mode 100644 index 000000000..ed07876b2 --- /dev/null +++ b/components/jca/src/main/resources/META-INF/services/org.switchyard.component.common.selector.OperationSelectorFactory @@ -0,0 +1,13 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.jca.selector.CCIOperationSelectorFactory +org.switchyard.component.jca.selector.JMSOperationSelectorFactory diff --git a/components/jca/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/jca/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..0067d7bb6 --- /dev/null +++ b/components/jca/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.jca.deploy.JCAComponent diff --git a/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v1/jca_1_0.xsd b/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v1/jca_1_0.xsd new file mode 100644 index 000000000..ddf212e17 --- /dev/null +++ b/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v1/jca_1_0.xsd @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v1/jca_1_1.xsd b/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v1/jca_1_1.xsd new file mode 100644 index 000000000..940f0c4e6 --- /dev/null +++ b/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v1/jca_1_1.xsd @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v2/jca_2_0.xsd b/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v2/jca_2_0.xsd new file mode 100644 index 000000000..5d6fe2edd --- /dev/null +++ b/components/jca/src/main/resources/org/switchyard/component/jca/config/model/v2/jca_2_0.xsd @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/jca/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/jca/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..be3b578a9 --- /dev/null +++ b/components/jca/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +jca_1_0.section=urn:switchyard-component-jca:config +jca_1_0.version=1.0 +jca_1_0.namespace=urn:switchyard-component-jca:config:1.0 +jca_1_0.schema=jca_1_0.xsd +jca_1_0.location=/org/switchyard/component/jca/config/model/v1/ +jca_1_0.marshaller=org.switchyard.component.jca.config.model.v1.V1JCAModelMarshaller + +jca_1_1.section=urn:switchyard-component-jca:config +jca_1_1.version=1.1 +jca_1_1.namespace=urn:switchyard-component-jca:config:1.1 +jca_1_1.schema=jca_1_1.xsd +jca_1_1.location=/org/switchyard/component/jca/config/model/v1/ +jca_1_1.marshaller=org.switchyard.component.jca.config.model.v1.V1JCAModelMarshaller + +jca_2_0.section=urn:switchyard-component-jca:config +jca_2_0.version=2.0 +jca_2_0.namespace=urn:switchyard-component-jca:config:2.0 +jca_2_0.schema=jca_2_0.xsd +jca_2_0.location=/org/switchyard/component/jca/config/model/v2/ +jca_2_0.marshaller=org.switchyard.component.jca.config.model.v1.V1JCAModelMarshaller diff --git a/components/jca/src/test/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModelInboundTest.java b/components/jca/src/test/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModelInboundTest.java new file mode 100644 index 000000000..7c8bf4777 --- /dev/null +++ b/components/jca/src/test/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModelInboundTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import java.io.IOException; +import java.net.URL; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.component.jca.config.model.JCABindingModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.selector.StaticOperationSelectorModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Test for {@link V1JCABindingModel}. + * + * @author Tomohisa Igarashi + * + */ +public class V1JCABindingModelInboundTest { + private JCABindingModel jbm; + + @Before + public void parseJCABindingModel() throws IOException { + final ModelPuller modelPuller = new ModelPuller(); + final URL xml = getClass().getResource("jca-inbound-binding.xml"); + final SwitchYardModel switchYardModel = modelPuller.pull(xml); + jbm = (JCABindingModel) switchYardModel.getComposite().getServices().get(0).getBindings().get(0); + } + + @Test + public void testInboundConnection() { + Assert.assertNotNull(jbm.getInboundConnection()); + + Assert.assertNotNull(jbm.getInboundConnection().getResourceAdapter()); + Assert.assertEquals("hornetq-ra.rar", jbm.getInboundConnection().getResourceAdapter().getName()); + Assert.assertEquals("value1", jbm.getInboundConnection().getResourceAdapter().getProperty("prop1")); + + Assert.assertNotNull(jbm.getInboundConnection().getActivationSpec()); + Assert.assertEquals("javax.jms.Queue", jbm.getInboundConnection().getActivationSpec().getProperty("destinationType")); + Assert.assertEquals("queue/TestQueue", jbm.getInboundConnection().getActivationSpec().getProperty("destination")); + } + + @Test + public void testInboundInteraction() { + Assert.assertNotNull(jbm.getInboundInteraction()); + + Assert.assertNotNull(jbm.getInboundInteraction().getListener()); + Assert.assertEquals("javax.jms.MessageListener", jbm.getInboundInteraction().getListener().getClassName()); + Assert.assertEquals("onMessage", ((StaticOperationSelectorModel)jbm.getOperationSelector()).getOperationName()); + Assert.assertEquals("org.switchyard.component.jca.endpoint.JMSEndpoint", jbm.getInboundInteraction().getEndpoint().getEndpointClassName()); + Assert.assertEquals("value2", jbm.getInboundInteraction().getEndpoint().getProperty("prop2")); + Assert.assertEquals(true, jbm.getInboundInteraction().isTransacted()); + Assert.assertEquals(5, jbm.getInboundInteraction().getBatchCommit().getBatchSize()); + Assert.assertEquals(5000, jbm.getInboundInteraction().getBatchCommit().getBatchTimeout()); + } + +} diff --git a/components/jca/src/test/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModelOutboundTest.java b/components/jca/src/test/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModelOutboundTest.java new file mode 100644 index 000000000..758659c0e --- /dev/null +++ b/components/jca/src/test/java/org/switchyard/component/jca/config/model/v1/V1JCABindingModelOutboundTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.jca.config.model.v1; + +import java.io.IOException; +import java.net.URL; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.component.jca.config.model.JCABindingModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Test for {@link V1JCABindingModel}. + * + * @author Tomohisa Igarashi + * + */ +public class V1JCABindingModelOutboundTest { + private JCABindingModel jbm; + + @Before + public void parseJCABindingModel() throws IOException { + final ModelPuller modelPuller = new ModelPuller(); + final URL xml = getClass().getResource("jca-outbound-binding.xml"); + final SwitchYardModel switchYardModel = modelPuller.pull(xml); + jbm = (JCABindingModel) switchYardModel.getComposite().getReferences().get(0).getBindings().get(0); + } + + @Test + public void testOutboundConnection() { + Assert.assertNotNull(jbm.getOutboundConnection()); + + Assert.assertNotNull(jbm.getOutboundConnection().getResourceAdapter()); + Assert.assertEquals("hornetq-ra.rar", jbm.getOutboundConnection().getResourceAdapter().getName()); + Assert.assertEquals("value1", jbm.getOutboundConnection().getResourceAdapter().getProperty("prop1")); + + Assert.assertNotNull(jbm.getOutboundConnection().getConnection()); + Assert.assertEquals("value2", jbm.getOutboundConnection().getConnection().getProperty("prop2")); + } + + @Test + public void testOutboundInteraction() { + Assert.assertNotNull(jbm.getOutboundInteraction()); + + Assert.assertNotNull(jbm.getOutboundInteraction().getConnectionSpec()); + Assert.assertEquals("value3", jbm.getOutboundInteraction().getConnectionSpec().getProperty("prop3")); + + Assert.assertNotNull(jbm.getOutboundInteraction().getInteractionSpec()); + Assert.assertEquals("value4", jbm.getOutboundInteraction().getInteractionSpec().getProperty("prop4")); + + Assert.assertNotNull(jbm.getOutboundInteraction().getOperation()); + Assert.assertEquals("operationName", jbm.getOutboundInteraction().getOperation().getName()); + Assert.assertNotNull(jbm.getOutboundInteraction().getOperation().getInteractionSpec()); + Assert.assertEquals("value5", jbm.getOutboundInteraction().getOperation().getInteractionSpec().getProperty("prop5")); + Assert.assertEquals("value6", jbm.getOutboundInteraction().getProcessor().getProperty("prop6")); + } +} diff --git a/components/jca/src/test/resources/META-INF/beans.xml b/components/jca/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/jca/src/test/resources/org/switchyard/component/jca/config/model/v1/jca-inbound-binding.xml b/components/jca/src/test/resources/org/switchyard/component/jca/config/model/v1/jca-inbound-binding.xml new file mode 100644 index 000000000..d07b3726a --- /dev/null +++ b/components/jca/src/test/resources/org/switchyard/component/jca/config/model/v1/jca-inbound-binding.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + javax.jms.MessageListener + + + + true + + + + + + diff --git a/components/jca/src/test/resources/org/switchyard/component/jca/config/model/v1/jca-outbound-binding.xml b/components/jca/src/test/resources/org/switchyard/component/jca/config/model/v1/jca-outbound-binding.xml new file mode 100644 index 000000000..dba997007 --- /dev/null +++ b/components/jca/src/test/resources/org/switchyard/component/jca/config/model/v1/jca-outbound-binding.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/pom.xml b/components/pom.xml new file mode 100755 index 000000000..30c510862 --- /dev/null +++ b/components/pom.xml @@ -0,0 +1,105 @@ + + + + 4.0.0 + + org.switchyard + switchyard-parent + 2.1.0-SNAPSHOT + .. + + org.switchyard.components + switchyard-components-parent + SwitchYard: Components + SwitchYard: Components + http://switchyard.org + pom + + JBoss by Red Hat + http://jboss.org + + + localhost + 48080 + + + scm:git:https://github.com/jboss-switchyard/components.git + scm:git:ssh://git@github.com:jboss-switchyard/components.git + http://github.com/jboss-switchyard/components + + + common + test + sca + bean + rules + bpm + resteasy + soap + bpel + camel + clojure + http + jca + itests + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + https://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-test + test + + + org.jboss.logging + jboss-logging + + + org.jboss.logging + jboss-logging-processor + + provided + true + + + diff --git a/components/resteasy/pom.xml b/components/resteasy/pom.xml new file mode 100644 index 000000000..aca145852 --- /dev/null +++ b/components/resteasy/pom.xml @@ -0,0 +1,157 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-resteasy + SwitchYard: RESTEasy Component + bundle + + + org.switchyard.component.resteasy.* + + + com.sun.net.httpserver;resolution:=optional, + org.apache.http*;resolution:=optional, + org.jboss.netty*;resolution:=optional, + org.jboss.resteasy.plugins.providers, + org.jboss.resteasy.plugins.providers.jaxb, + org.jboss.resteasy.plugins.interceptors, + org.jboss.resteasy.plugins.interceptors.encoding, + org.jboss.resteasy.plugins.server.netty;resolution:=optional, + org.jboss.resteasy.plugins.server.sun.http;resolution:=optional, + org.jboss.resteasy.specimpl, + org.switchyard.security.jboss.credential.extractor;resolution:=optional;${switchyard.osgi.import.switchyard.version}, + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + org.jboss.spec.javax.servlet + jboss-servlet-api_2.5_spec + provided + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-security + + + org.switchyard + switchyard-security-jboss + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + io.netty + netty + + + org.javassist + javassist + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-jaxrs + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-netty + + + org.jboss.resteasy + resteasy-jdk-http + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents + httpcore + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-mapper-asl + + + org.littleshoot + littleproxy + test + + + org.osgi + org.osgi.core + provided + + + org.osgi + org.osgi.compendium + provided + + + diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/InboundHandler.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/InboundHandler.java new file mode 100644 index 000000000..0c82fcead --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/InboundHandler.java @@ -0,0 +1,176 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.WebApplicationException; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.resteasy.composer.RESTEasyBindingData; +import org.switchyard.component.resteasy.composer.RESTEasyComposition; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.resteasy.resource.ResourcePublisherFactory; +import org.switchyard.component.resteasy.util.ClassUtil; +import org.switchyard.component.resteasy.util.RESTEasyUtil; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.security.context.SecurityContextManager; + +/** + * Handles RESTEasy requests to invoke a SwitchYard service. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class InboundHandler extends BaseServiceHandler { + + private final RESTEasyBindingModel _config; + private final String _gatewayName; + private ServiceDomain _domain; + private ServiceReference _service; + private Endpoint _resource; + private MessageComposer _messageComposer; + private SecurityContextManager _securityContextManager; + private Map, Class> _exceptionMappers; + + /** + * Constructor for unit test. + */ + protected InboundHandler() { + _config = null; + _gatewayName = null; + } + + /** + * Constructor. + * @param config the configuration settings + * @param domain the service domain + */ + public InboundHandler(final RESTEasyBindingModel config, ServiceDomain domain) { + super(domain); + _config = config; + _gatewayName = config.getName(); + _domain = domain; + _securityContextManager = new SecurityContextManager(_domain); + } + + /** + * Start lifecycle. + * + * @throws RESTEasyPublishException If unable to publish the service + */ + @Override + protected void doStart() throws RESTEasyPublishException { + String[] resourceIntfs = _config.getInterfacesAsArray(); + try { + _service = _domain.getServiceReference(_config.getServiceName()); + List instances = ClassUtil.generateSingletons(resourceIntfs, this); + String contextPath = _config.getContextPath(); + if ((contextPath == null) || (ResourcePublisherFactory.ignoreContext())) { + contextPath = "/"; + } + Map contextParams = _config.getContextParamsConfig() == null ? null : _config.getContextParamsConfig().toMap(); + _exceptionMappers = RESTEasyUtil.getExceptionProviderMap(contextParams); + // Add as singleton instances + _resource = ResourcePublisherFactory.getPublisher().publish(_domain, contextPath, instances, contextParams); + // Create and configure the RESTEasy message composer + _messageComposer = RESTEasyComposition.getMessageComposer(_config); + } catch (Exception e) { + throw new RESTEasyPublishException(e); + } + _resource.start(); + } + + /** + * Invokes the SwitchYard service. + * + * @param restMessageRequest the request RESTEasyMessage + * @param oneWay true of this is a oneway request + * @return the response from invocation + * @throws Exception for RESTEasy to handle if any error + */ + public RESTEasyBindingData invoke(final RESTEasyBindingData restMessageRequest, final boolean oneWay) throws Exception { + RESTEasyBindingData output = new RESTEasyBindingData(); + SynchronousInOutHandler inOutHandler = new SynchronousInOutHandler(); + Exchange exchange = _service.createExchange(restMessageRequest.getOperationName(), inOutHandler); + + // identify ourselves + exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _gatewayName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + + _securityContextManager.addCredentials(exchange, restMessageRequest.extractCredentials()); + + Message message = null; + try { + message = _messageComposer.compose(restMessageRequest, exchange); + } catch (Exception e) { + if (_exceptionMappers.containsKey(e.getClass()) || (e instanceof WebApplicationException)) { + throw e; + } else { + RestEasyLogger.ROOT_LOGGER.unexpectedExceptionComposingInboundMessage(e); + throw new WebApplicationException(e); + } + } + try { + if (oneWay) { + exchange.send(message); + if (exchange.getState().equals(ExchangeState.FAULT)) { + output = _messageComposer.decompose(exchange, output); + } + } else { + exchange.send(message); + exchange = inOutHandler.waitForOut(); + output = _messageComposer.decompose(exchange, output); + } + } catch (Exception e) { + if (_exceptionMappers.containsKey(e.getClass()) || (e instanceof WebApplicationException)) { + throw e; + } else { + RestEasyLogger.ROOT_LOGGER.unexpectedExceptionComposingOutboundRESTResponse(e); + throw new WebApplicationException(e); + } + } + return output; + } + + /** + * Stop lifecycle. + */ + @Override + protected void doStop() { + _resource.stop(); + } + + @Override + public void handleFault(Exchange exchange) { + throw RestEasyMessages.MESSAGES.unexpected(); + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + throw RestEasyMessages.MESSAGES.unexpected(); + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/OutboundHandler.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/OutboundHandler.java new file mode 100644 index 000000000..36f2a50d1 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/OutboundHandler.java @@ -0,0 +1,155 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.StringTokenizer; + +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.resteasy.composer.RESTEasyComposition; +import org.switchyard.component.resteasy.composer.RESTEasyBindingData; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.resteasy.resource.ResourcePublisherFactory; +import org.switchyard.component.resteasy.util.DefaultMethodInvokerFactory; +import org.switchyard.component.resteasy.util.MethodInvoker; +import org.switchyard.component.resteasy.util.MethodInvokerFactory; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * Handles invoking external RESTEasy services. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class OutboundHandler extends BaseServiceHandler { + + private static final Logger LOGGER = Logger.getLogger(OutboundHandler.class); + private static final Class[] CLASS_ARG_ARRAY = {Class.class}; + + private final RESTEasyBindingModel _config; + private final String _bindingName; + private final String _referenceName; + private String _baseAddress = "http://localhost:8080"; + private Map _methodMap = new HashMap(); + private MessageComposer _messageComposer; + + + /** + * Constructor. + * @param config the configuration settings + * @param domain the service domain. + */ + public OutboundHandler(final RESTEasyBindingModel config, final ServiceDomain domain) { + super(domain); + _config = config; + _bindingName = config.getName(); + _referenceName = config.getReference().getName(); + } + + /** + * Start lifecycle. + * + * @throws RESTEasyConsumeException If unable to load the REST interface + */ + protected void doStart() throws RESTEasyConsumeException { + if (_methodMap.isEmpty()) { + String resourceIntfs = _config.getInterfaces(); + String address = _config.getAddress(); + if (address != null) { + _baseAddress = address; + } + String path = _baseAddress; + String contextPath = _config.getContextPath(); + if ((contextPath != null) && !ResourcePublisherFactory.ignoreContext()) { + path = path + "/" + contextPath; + } + MethodInvokerFactory invokerFactory = ProviderRegistry.getProvider(MethodInvokerFactory.class); + if (invokerFactory == null) { + invokerFactory = new DefaultMethodInvokerFactory(); + } + StringTokenizer st = new StringTokenizer(resourceIntfs, ","); + while (st.hasMoreTokens()) { + String className = st.nextToken().trim(); + Class clazz = Classes.forName(className); + for (Method method : clazz.getMethods()) { + // ignore the as method to allow declaration in client interfaces + if (!("as".equals(method.getName()) && Arrays.equals(method.getParameterTypes(), CLASS_ARG_ARRAY))) { + _methodMap.put(method.getName(), invokerFactory.createInvoker(path, clazz, method, _config)); + } + } + } + // Create and configure the RESTEasy message composer + _messageComposer = RESTEasyComposition.getMessageComposer(_config); + } + } + + /** + * The handler method that invokes the actual RESTEasy service when the + * component is used as a RESTEasy consumer. + * @param exchange the Exchange + * @throws HandlerException handler exception + */ + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + // identify ourselves + exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + if (getState() != State.STARTED) { + throw RestEasyMessages.MESSAGES.referenceBindingNotStarted(_referenceName, _bindingName); + } + + final String opName = exchange.getContract().getProviderOperation().getName(); + + RESTEasyBindingData restRequest = null; + try { + restRequest = _messageComposer.decompose(exchange, new RESTEasyBindingData()); + } catch (Exception e) { + final String m = RestEasyMessages.MESSAGES.unexpectedExceptionComposingRESTRequest(); + LOGGER.error(m, e); + throw new HandlerException(m, e); + } + + Object response = null; + MethodInvoker methodInvoker = _methodMap.get(opName); + if (methodInvoker == null) { + final String m = RestEasyMessages.MESSAGES.unableToMapAmongResources(opName, _methodMap.keySet().toString()); + throw new HandlerException(m); + } + + try { + RESTEasyBindingData restResponse = methodInvoker.invoke(restRequest.getParameters(), restRequest.getHeaders()); + restResponse.setOperationName(opName); + Message out = _messageComposer.compose(restResponse, exchange); + // Our transformer magic transforms the entity appropriately here :) + exchange.send(out); + } catch (Exception e) { + final String m = RestEasyMessages.MESSAGES.unexpectedExceptionComposingRESTResponse(); + LOGGER.error(m, e); + throw new HandlerException(m, e); + } + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/RESTEasyConsumeException.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/RESTEasyConsumeException.java new file mode 100644 index 000000000..e8cf46f25 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/RESTEasyConsumeException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy; + +import org.switchyard.SwitchYardException; + +/** + * Wrapper for RESTEasy consumer exceptions. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyConsumeException extends SwitchYardException { + private static final long serialVersionUID = 1L; + + /** + * Public constructor. + * @param message Exception message. + */ + public RESTEasyConsumeException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Exception cause. + */ + public RESTEasyConsumeException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Public constructor. + * @param cause Exception cause. + */ + public RESTEasyConsumeException(final Throwable cause) { + super(cause); + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/RESTEasyPublishException.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/RESTEasyPublishException.java new file mode 100644 index 000000000..1d2c29142 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/RESTEasyPublishException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy; + +import org.switchyard.SwitchYardException; + +/** + * Wrapper for RESTEasy creation exceptions. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyPublishException extends SwitchYardException { + private static final long serialVersionUID = 1L; + + /** + * Public constructor. + * @param message Exception message. + */ + public RESTEasyPublishException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Exception cause. + */ + public RESTEasyPublishException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Public constructor. + * @param cause Exception cause. + */ + public RESTEasyPublishException(final Throwable cause) { + super(cause); + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/RestEasyLogger.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/RestEasyLogger.java new file mode 100644 index 000000000..c3dd4be7d --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/RestEasyLogger.java @@ -0,0 +1,63 @@ +package org.switchyard.component.resteasy; + +import java.io.IOException; +import org.jboss.logging.Cause; +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 37600-37999 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface RestEasyLogger { + /** + * A root logger with the category of the package name. + */ + RestEasyLogger ROOT_LOGGER = Logger.getMessageLogger(RestEasyLogger.class, RestEasyLogger.class.getPackage().getName()); + + /** + * defaultRESTEasyMessageComposerDoesnTHandleMultipleInputParameters method definition. + */ + @LogMessage(level = Level.WARN) + @Message(id = 37600, value = "Default RESTEasy Message Composer doesn't handle multiple input parameters.") + void defaultRESTEasyMessageComposerDoesnTHandleMultipleInputParameters(); + + /** + * unexpectedExceptionComposingInboundMessage method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 37601, value = "Unexpected exception composing inbound Message") + void unexpectedExceptionComposingInboundMessage(@Cause Exception e); + + /** + * unexpectedExceptionComposingOutboundRESTResponse method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 37602, value = "Unexpected exception composing outbound REST response") + void unexpectedExceptionComposingOutboundRESTResponse(@Cause Exception e); + + /** + * unableToLaunchStandaloneHttpServer method definition. + * @param ioe the ioe + */ + @LogMessage(level = Level.ERROR) + @Message(id = 37605, value = "Unable to launch standalone http server") + void unableToLaunchStandaloneHttpServer(@Cause IOException ioe); + + /** + * unableToFindURIBuilder method definition. + * @param cnfe the cnfe + */ + @LogMessage(level = Level.ERROR) + @Message(id = 37606, value = "Unable to find URI builder") + void unableToFindURIBuilder(@Cause ClassNotFoundException cnfe); + +} + diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/RestEasyMessages.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/RestEasyMessages.java new file mode 100644 index 000000000..e1dd64502 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/RestEasyMessages.java @@ -0,0 +1,83 @@ +package org.switchyard.component.resteasy; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +/** + *

+ * This file is using the subset 38000-38399 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface RestEasyMessages { + /** + * The default messages. + */ + RestEasyMessages MESSAGES = Messages.getBundle(RestEasyMessages.class); + + /** + * unexpected method definition. + * @return IllegalStateException + */ + @Message(id = 38007, value = "Unexpected") + IllegalStateException unexpected(); + + /** + * referenceBindingNotStarted method definition. + * @param referenceName referenceName + * @param bindingName bindingName + * @return HandlerException + */ + @Message(id = 38009, value = "Reference binding \"%s/%s\" is not started.") + HandlerException referenceBindingNotStarted(String referenceName, String bindingName); + + /** + * m method definition. + * @param e the e + * @return HandlerException + */ + @Message(id = 38010, value = "m") + HandlerException m(@Cause Exception e); + + /** + * youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn method definition. + * @param method method + * @return RuntimeException + */ + @Message(id = 38015, value = "You must use at least one, but no more than one http method annotation on: %s") + RuntimeException youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(String method); + + /** + * youHaveNotSetABaseURIForTheClientProxy method definition. + * @return RuntimeException + */ + @Message(id = 38016, value = "You have not set a base URI for the client proxy") + RuntimeException youHaveNotSetABaseURIForTheClientProxy(); + + /** + * unexpectedExceptionComposingRESTRequest method definition. + * @return String + */ + @Message(id = 38017, value = "Unexpected exception composing outbound REST request") + String unexpectedExceptionComposingRESTRequest(); + + /** + * unableToMapAmongResources method definition. + * @param opName opName + * @param keySet keySet + * @return String + */ + @Message(id = 38018, value = "Unable to map %s among resources %s") + String unableToMapAmongResources(String opName, String keySet); + + /** + * unexpectedExceptionComposingRESTResponse method definition. + * @return String + */ + @Message(id = 38019, value = "Unexpected exception composing inbound REST response") + String unexpectedExceptionComposingRESTResponse(); +} + diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyBindingData.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyBindingData.java new file mode 100644 index 000000000..0db6f6739 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyBindingData.java @@ -0,0 +1,247 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.composer; + +import java.security.Principal; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.servlet.ServletRequest; +import javax.ws.rs.core.MultivaluedMap; + +import org.jboss.resteasy.util.CaseInsensitiveMap; +import org.switchyard.common.lang.Strings; +import org.switchyard.component.common.composer.SecurityBindingData; +import org.switchyard.security.SecurityServices; +import org.switchyard.security.credential.ConfidentialityCredential; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.PrincipalCredential; +import org.switchyard.security.credential.extractor.AuthorizationHeaderCredentialExtractor; + +/** + * Wrapper for RESTEasy messages. + * + * @author Magesh Kumar B © 2012 Red Hat Inc. + */ +public class RESTEasyBindingData implements SecurityBindingData { + private Object[] _args = new Object[0]; + private MultivaluedMap _headers; + private String _operationName; + private Integer _statusCode; + private ServletRequest _servletRequest; + private Boolean _secured = false; + private Principal _principal; + + /** + * Creates a new RESTEasy message. + */ + public RESTEasyBindingData() {} + + /** + * Creates a new RESTEasy message, given the specified content. + * @param content the specified content + */ + public RESTEasyBindingData(Object content) { + _args = new Object[]{content}; + } + + /** + * Gets the operation name to be invoked. + * @return the operations name + */ + public String getOperationName() { + return _operationName; + } + + /** + * Sets the operation name to be invoked. + * @param operationName the operations name + */ + public void setOperationName(String operationName) { + _operationName = operationName; + } + + /** + * Gets the method parameters as passed from RESTEasy. + * @return the method parameters + */ + public Object[] getParameters() { + return _args; + } + + /** + * Sets the method parameters. + * @param args the method parameters + */ + public void setParameters(Object[] args) { + if (args != null) { + _args = args; + } + } + + /** + * Get the HTTP headers map. + * @return a Map of headers + */ + public MultivaluedMap getHeaders() { + if (_headers == null) { + _headers = new CaseInsensitiveMap(); + } + return _headers; + } + + /** + * Set the HTTP headers map. + * @param headers a Map of headers + */ + public void setHeaders(MultivaluedMap headers) { + _headers = headers; + } + + /** + * Add a HTTP header. + * @param name the name of the header + * @param values a List of header values + */ + public void addHeader(String name, List values) { + if (_headers == null) { + _headers = new CaseInsensitiveMap(); + } + _headers.put(name, values); + } + + /** + * Add a HTTP header. + * @param name the name of the header + * @param value a header value + */ + public void addHeader(String name, String value) { + if (_headers == null) { + _headers = new CaseInsensitiveMap(); + } + List values = _headers.get(name); + if (values == null) { + values = new ArrayList(); + _headers.put(name, values); + } + values.add(value); + } + + /** + * Gets the HTTP response status code. + * @return the response status code + */ + public Integer getStatusCode() { + return _statusCode; + } + + /** + * Sets the HTTP response status code. + * @param statusCode the response status code + */ + public void setStatusCode(Integer statusCode) { + _statusCode = statusCode; + } + + /** + * Gets the ServletRequest associated with this request. + * @return the ServletRequest + */ + public ServletRequest getServletRequest() { + return _servletRequest; + } + + /** + * Sets the ServletRequest associated with this request. + * @param servletRequest the ServletRequest to set + */ + public void setServletRequest(ServletRequest servletRequest) { + _servletRequest = servletRequest; + } + + /** + * Returns a boolean stating if this request was made using a secure channel. + * @return the true if secure, false otherwise + */ + public Boolean isSecured() { + return _secured; + } + + /** + * Sets, the boolean, if this request was made through a secure channel or not. + * @param secured the boolean to set + */ + public void setSecured(Boolean secured) { + _secured = secured; + } + + /** + * Gets the User Principal associated with this request. + * @return the Principal + */ + public Principal getPrincipal() { + return _principal; + } + + /** + * Sets the User Principal associated with this request. + * @param principal the Principal to set + */ + public void setPrincipal(Principal principal) { + _principal = principal; + } + + /** + * {@inheritDoc} + */ + @Override + public Set extractCredentials() { + Set credentials = new HashSet(); + if (_servletRequest != null) { + credentials.addAll(SecurityServices.getServletRequestCredentialExtractor().extract(_servletRequest)); + } else { + if (_secured) { + credentials.add(new ConfidentialityCredential(true)); + } + if (_principal != null) { + credentials.add(new PrincipalCredential(_principal, true)); + } + String charsetName = null; + List contentTypes = _headers.get("content-type"); + String contentType = null; + if ((contentTypes != null) && (contentTypes.size() > 0)) { + contentType = contentTypes.get(0); + } + if (contentType != null) { + int pos = contentType.lastIndexOf("charset="); + if (pos > -1) { + charsetName = Strings.trimToNull(contentType.substring(pos+8, contentType.length())); + } + } + List authorizations = _headers.get("authorization"); + if ((authorizations != null) && (authorizations.size() > 0)) { + AuthorizationHeaderCredentialExtractor ahce; + if (charsetName != null) { + ahce = new AuthorizationHeaderCredentialExtractor(charsetName); + } else { + ahce = new AuthorizationHeaderCredentialExtractor(); + } + credentials.addAll(ahce.extract(authorizations.get(0))); + } + } + return credentials; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyComposition.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyComposition.java new file mode 100644 index 000000000..84d8d6310 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyComposition.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.composer; + +import org.switchyard.component.common.composer.Composition; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; + +/** + * Utility class for RESTEasy-specific Composition. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class RESTEasyComposition { + + /** + * Uses the {@link Composition} class to create a RESTEasy-specific MessageComposer. + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer() { + return Composition.getMessageComposer(RESTEasyBindingData.class); + } + + /** + * Uses the {@link Composition} class to create a RESTEasy-specific MessageComposer. + * @param rebm a RESTEasyBindingModel to get configuration details from + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer(RESTEasyBindingModel rebm) { + ContextMapperModel cmm = rebm != null ? rebm.getContextMapper() : null; + MessageComposerModel mcm = rebm != null ? rebm.getMessageComposer() : null; + return Composition.getMessageComposer(RESTEasyBindingData.class, cmm, mcm); + } + + private RESTEasyComposition() {} + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapper.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapper.java new file mode 100644 index 000000000..f9763b20e --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapper.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.composer; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.component.common.composer.BaseRegexContextMapper; +import org.switchyard.component.common.label.ComponentLabel; +import org.switchyard.component.common.label.EndpointLabel; + +/** + * RESTEasyContextMapper. + * + * @author Magesh Kumar B © 2012 Red Hat Inc. + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RESTEasyContextMapper extends BaseRegexContextMapper { + + /** + * The HTTP responce code. + */ + public static final String HTTP_RESPONSE_STATUS = "http_response_status"; + + private static final String[] RESTEASY_LABELS = new String[]{ComponentLabel.RESTEASY.label(), EndpointLabel.REST.label(), EndpointLabel.HTTP.label()}; + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(RESTEasyBindingData source, Context context) throws Exception { + Iterator>> entries = source.getHeaders().entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry> entry = entries.next(); + String name = entry.getKey(); + if (matches(name)) { + List values = entry.getValue(); + if ((values != null) && (values.size() == 1)) { + context.setProperty(name, values.get(0)).addLabels(RESTEASY_LABELS); + } else if ((values != null) && (values.size() > 1)) { + context.setProperty(name, values).addLabels(RESTEASY_LABELS); + } + } + } + if (source.getStatusCode() != null) { + context.setProperty(HTTP_RESPONSE_STATUS, source.getStatusCode()).addLabels(RESTEASY_LABELS); + } + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public void mapTo(Context context, RESTEasyBindingData target) throws Exception { + Map> httpHeaders = target.getHeaders(); + for (Property property : context.getProperties()) { + String name = property.getName(); + Object value = property.getValue(); + if ((value != null) && (matches(name) || property.hasLabel(EndpointLabel.HTTP.label()))) { + if (HTTP_RESPONSE_STATUS.equals(name)) { + target.setStatusCode((Integer)property.getValue()); + } else { + if (value instanceof List) { + List stringList = new ArrayList(); + for (Object obj : ((List)value)) { + if (obj != null) { + stringList.add(obj.toString()); + } else { + stringList.add(null); + } + } + httpHeaders.put(name, stringList); + } else if (value instanceof String) { + List list = new ArrayList(); + list.add(String.valueOf(value)); + httpHeaders.put(name, list); + } + } + } + } + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapperFactory.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapperFactory.java new file mode 100644 index 000000000..700047ca1 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapperFactory.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.composer; + +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.ContextMapperFactory; + +/** + * RESTEasyContextMapperFactory. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RESTEasyContextMapperFactory extends ContextMapperFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return RESTEasyBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper newContextMapperDefault() { + return new RESTEasyContextMapper(); + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyMessageComposer.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyMessageComposer.java new file mode 100644 index 000000000..85df315d7 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyMessageComposer.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.composer; + +import javax.ws.rs.WebApplicationException; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.component.common.composer.BaseMessageComposer; +import org.switchyard.component.resteasy.RestEasyLogger; + +/** + * Composes/decomposes RESTEasy messages. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class RESTEasyMessageComposer extends BaseMessageComposer { + + /** + * {@inheritDoc} + */ + @Override + public Message compose(RESTEasyBindingData source, Exchange exchange) throws Exception { + final Message message = exchange.createMessage(); + getContextMapper().mapFrom(source, exchange.getContext(message)); + Object content = null; + if (source.getParameters().length > 0) { + content = source.getParameters()[0]; + } + message.setContent(content); + + if (source.getParameters().length > 1) { + RestEasyLogger.ROOT_LOGGER.defaultRESTEasyMessageComposerDoesnTHandleMultipleInputParameters(); + } + return message; + } + + /** + * {@inheritDoc} + */ + @Override + public RESTEasyBindingData decompose(Exchange exchange, RESTEasyBindingData target) throws Exception { + Message sourceMessage = exchange.getMessage(); + Object content = sourceMessage.getContent(); + if (exchange.getContract().getProviderOperation() != null) { + target.setOperationName(exchange.getContract().getProviderOperation().getName()); + } else if (exchange.getContract().getConsumerOperation() != null) { + target.setOperationName(exchange.getContract().getConsumerOperation().getName()); + } + + if (exchange.getState().equals(ExchangeState.FAULT)) { + if (content instanceof WebApplicationException) { + throw (WebApplicationException)content; + } else if (content instanceof HandlerException) { + Throwable throwable = ((HandlerException) content).getCause(); + if (throwable != null) { + if (throwable instanceof WebApplicationException) { + throw (WebApplicationException) throwable; + } else { + throw new WebApplicationException(throwable); + } + } else { + throw new WebApplicationException((HandlerException) content); + } + } else if (content instanceof Exception) { + throw (Exception) content; + } else if (content instanceof Throwable) { + throw new WebApplicationException((Throwable)content); + } else { + throw new WebApplicationException(new Exception(sourceMessage.getContent(String.class))); + } + } + if (content != null) { + target.setParameters(new Object[]{content}); + } + getContextMapper().mapTo(exchange.getContext(), target); + return target; + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyMessageComposerFactory.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyMessageComposerFactory.java new file mode 100644 index 000000000..9302a5183 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/composer/RESTEasyMessageComposerFactory.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.composer; + +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.MessageComposerFactory; + +/** + * RESTEasyMessageComposerFactory. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RESTEasyMessageComposerFactory extends MessageComposerFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return RESTEasyBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer newMessageComposerDefault() { + return new RESTEasyMessageComposer(); + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/BasicAuthModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/BasicAuthModel.java new file mode 100644 index 000000000..423d52b69 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/BasicAuthModel.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model; + +import org.switchyard.config.model.Model; + +/** + * A Basic Authentication Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface BasicAuthModel extends Model { + + /** + * Get user name. + * @return authentication username + */ + public String getUser(); + + /** + * Set user name. + * @param user the user name + * @return this BasicAuthModel + */ + public BasicAuthModel setUser(String user); + + /** + * Get user password. + * @return authentication password + */ + public String getPassword(); + + /** + * Set user password. + * @param password the user password + * @return this BasicAuthModel + */ + public BasicAuthModel setPassword(String password); + + /** + * Get authentication realm. + * @return authentication realm + */ + public String getRealm(); + + /** + * Set authentication realm. + * @param realm the authentication realm + * @return this BasicAuthModel + */ + public BasicAuthModel setRealm(String realm); + + /** + * Get host. + * @return authentication host + */ + public String getHost(); + + /** + * Set host. + * @param host the authentication host + * @return this BasicAuthModel + */ + public BasicAuthModel setHost(String host); + + /** + * Get authentication port. + * @return authentication port + */ + public String getPort(); + + /** + * Set authentication port. + * @param port the authentication port + * @return this BasicAuthModel + */ + public BasicAuthModel setPort(String port); + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ContextParamModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ContextParamModel.java new file mode 100644 index 000000000..6d85871bc --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ContextParamModel.java @@ -0,0 +1,58 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model; + +import org.switchyard.config.model.Model; + +/** + * The "contextParam" configuration model. + */ +public interface ContextParamModel extends Model { + + /** The "contextParam" name. */ + public static final String CONTEXT_PARAM = "contextParam"; + + /** + * Gets the parent contextParams model. + * @return the parent contextParams model. + */ + public ContextParamsModel getContextParamsModel(); + + /** + * Gets the name attribute. + * @return the name attribute + */ + public String getName(); + + /** + * Sets the name attribute. + * @param name the name attribute + * @return this PropertyModel (useful for chaining) + */ + public ContextParamModel setName(String name); + + /** + * Gets the value attribute. + * @return the value attribute + */ + public String getValue(); + + /** + * Sets the value attribute. + * @param value the value attribute + * @return this PropertyModel (useful for chaining) + */ + public ContextParamModel setValue(String value); + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ContextParamsModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ContextParamsModel.java new file mode 100644 index 000000000..0e695cfae --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ContextParamsModel.java @@ -0,0 +1,41 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model; + +import java.util.List; +import java.util.Map; + +import org.switchyard.config.model.Model; + +/** + * The "contextParams" configuration model. + */ +public interface ContextParamsModel extends Model { + + /** The "contextParams" name. */ + public static final String CONTEXT_PARAMS = "contextParams"; + + /** + * Gets the child contextParam models. + * @return the child contextParam models + */ + public List getContextParams(); + + /** + * Converts this ContextParamsModel to a Map. + * @return the Map + */ + public Map toMap(); + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/NtlmAuthModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/NtlmAuthModel.java new file mode 100644 index 000000000..62189fd21 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/NtlmAuthModel.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model; + +/** + * A NTLM Authentication Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface NtlmAuthModel extends BasicAuthModel { + + /** + * Get the NTLM domain. + * @return domain name + */ + public String getDomain(); + + /** + * Set the NTLM domain. + * @param domain the domain name + * @return this NTLMAuthModel + */ + public NtlmAuthModel setDomain(String domain); +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ProxyModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ProxyModel.java new file mode 100644 index 000000000..3a9b83327 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/ProxyModel.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model; + +import org.switchyard.config.model.Model; + +/** + * A Proxy Configuration Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface ProxyModel extends Model { + + /** + * Get host. + * @return authentication host + */ + public String getHost(); + + /** + * Set host. + * @param host the authentication host + * @return this ProxyModel + */ + public ProxyModel setHost(String host); + + /** + * Get authentication port. + * @return authentication port + */ + public String getPort(); + + /** + * Set authentication port. + * @param port the authentication port + * @return this ProxyModel + */ + public ProxyModel setPort(String port); + + /** + * Get user name. + * @return authentication username + */ + public String getUser(); + + /** + * Set user name. + * @param user the user name + * @return this ProxyModel + */ + public ProxyModel setUser(String user); + + /** + * Get user password. + * @return authentication password + */ + public String getPassword(); + + /** + * Set user password. + * @param password the user password + * @return this ProxyModel + */ + public ProxyModel setPassword(String password); + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyBindingModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyBindingModel.java new file mode 100644 index 000000000..fb23dd77f --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyBindingModel.java @@ -0,0 +1,197 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.config.model; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.composite.BindingModel; + +/** + * A RESTEasy binding model. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public interface RESTEasyBindingModel extends BindingModel { + + /** + * Prefix for RESTEasy Gateway Configuration. + */ + public static final String RESTEASY = "rest"; + + /** + * Returns the RESTEasy Service name. + * + * @return the serviceName + */ + public QName getServiceName(); + + /** + * Sets the RESTEasy Service name. + * + * @param serviceName the serviceName to set + */ + public void setServiceName(QName serviceName); + + /** + * Gets the REST endpoint address invoked by the Reference binding. + * + * @return the endpoint address + */ + public String getAddress(); + + /** + * Sets the REST endpoint address invoked by the Reference binding. + * + * @param address the endpoint address + * @return RESTEasyBindingModel + */ + public RESTEasyBindingModel setAddress(String address); + + /** + * Gets the REST interfaces exposed by this Service binding. + * + * @return the comma seperated list of RESTEasy interfaces + */ + public String getInterfaces(); + + /** + * Gets the REST interfaces exposed by this Service binding. + * + * @return the list of RESTEasy interfaces as an array + */ + public String[] getInterfacesAsArray(); + + /** + * Sets the REST interfaces exposed by this Service binding. + * + * @param interfaces a comma separated list of JAVA class names + * @return RESTEasyBindingModel + */ + public RESTEasyBindingModel setInterfaces(String interfaces); + + /** + * Gets the context path of the Resource interfaces. + * + * This is applicable only if getPublish is true. + * + * @return the contextPath + */ + public String getContextPath(); + + /** + * Sets the context path of the Resource interfaces. + * + * This is applicable only if getPublish() is true. + * + * @param contextPath the contextPath to set + * @return RESTEasyBindingModel + */ + public RESTEasyBindingModel setContextPath(String contextPath); + + /** + * Gets the request's time-out value. + * + * @return the time-out value + */ + public Integer getTimeout(); + + /** + * Sets the request's time-out value. + * + * @param timeout the time-out value + * @return this RESTEasyBindingModel + */ + public RESTEasyBindingModel setTimeout(Integer timeout); + + /** + * Gets the proxy config. + * @return the proxy config + */ + public ProxyModel getProxyConfig(); + + /** + * Sets the proxy config. + * @param proxyConfig the proxy config + * @return this RESTEasyBindingModel + */ + public RESTEasyBindingModel setProxyConfig(ProxyModel proxyConfig); + + /** + * Gets the basic config. + * @return the basic config + */ + public BasicAuthModel getBasicAuthConfig(); + + /** + * Sets the basic config. + * @param config the basic config + * @return this RESTEasyBindingModel + */ + public RESTEasyBindingModel setBasicAuthConfig(BasicAuthModel config); + + /** + * Gets the ntlm config. + * @return the ntlm config + */ + public NtlmAuthModel getNtlmAuthConfig(); + + /** + * Sets the ntlm config. + * @param config the ntlm config + * @return this RESTEasyBindingModel + */ + public RESTEasyBindingModel setNtlmAuthConfig(NtlmAuthModel config); + + /** + * Check if Basic authentication is set. + * @return true if Basic, false otherwise + */ + public Boolean isBasicAuth(); + + /** + * Check if authentication is set. + * @return true if set, false otherwise + */ + public Boolean hasAuthentication(); + + /** + * Gets the contextParams config. + * @return the contextParams config + */ + public ContextParamsModel getContextParamsConfig(); + + /** + * Sets the contextParams config. + * @param contextParamsConfig the contextParams config + * @return this RESTEasyBindingModel + */ + public RESTEasyBindingModel setContextParamsConfig(ContextParamsModel contextParamsConfig); + + /** + * Gets the global configuration. + * + * @return the environment/global config + */ + public Configuration getEnvironment(); + + /** + * Sets the global configuration. + * + * @param config the environment/global config + * @return RESTEasyBindingModel + */ + public RESTEasyBindingModel setEnvironment(Configuration config); +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyNameValueModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyNameValueModel.java new file mode 100644 index 000000000..da750f296 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyNameValueModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.config.model; + +import org.switchyard.config.model.Model; + +/** + * A RESTEasy value model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface RESTEasyNameValueModel extends Model { + + /** Known XML element names. */ + public enum RESTEasyName { + /** Known XML element names. */ + interfaces, address, contextPath, basic, ntlm, user, password, realm, domain, host, port, proxy, timeout; + } + + /** + * Gets the name. + * @return the name + */ + public RESTEasyName getName(); + + /** + * Gets the value. + * @return the value + */ + public String getValue(); + + /** + * Sets the value. + * @param value the value + * @return this RESTEasyValueModel (useful for chaining) + */ + public RESTEasyNameValueModel setValue(String value); + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyNamespace.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyNamespace.java new file mode 100644 index 000000000..51f1df983 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/RESTEasyNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A RESTEasy config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum RESTEasyNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new RESTEasyNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + RESTEasyNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the RESTEasyNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the RESTEasyNamespace + */ + public static RESTEasyNamespace fromUri(String uri) { + return Util.fromUri(RESTEasyNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(RESTEasyNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-resteasy:config", version); + } + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1BasicAuthModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1BasicAuthModel.java new file mode 100644 index 000000000..f1c43ddbe --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1BasicAuthModel.java @@ -0,0 +1,183 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model.v1; + +import org.switchyard.component.resteasy.config.model.BasicAuthModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel.RESTEasyName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A BasicAuthModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1BasicAuthModel extends BaseModel implements BasicAuthModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + RESTEasyName.user.name(), + RESTEasyName.password.name(), + RESTEasyName.realm.name(), + RESTEasyName.host.name(), + RESTEasyName.port.name() + }; + + private RESTEasyNameValueModel _user; + private RESTEasyNameValueModel _password; + private RESTEasyNameValueModel _realm; + private RESTEasyNameValueModel _host; + private RESTEasyNameValueModel _port; + + /** + * Creates a new BasicAuthModel. + * @param namespace namespace + */ + public V1BasicAuthModel(String namespace) { + super(namespace, RESTEasyName.basic.name()); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new BasicAuthModel. + * @param namespace namespace + * @param name the name of teh model + */ + public V1BasicAuthModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new BasicAuthModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1BasicAuthModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * {@inheritDoc} + */ + public String getUser() { + if (_user == null) { + _user = getNameValue(RESTEasyName.user); + } + return _user != null ? _user.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setUser(String user) { + _user = setNameValue(_user, RESTEasyName.user, user); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPassword() { + if (_password == null) { + _password = getNameValue(RESTEasyName.password); + } + return _password != null ? _password.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setPassword(String password) { + _password = setNameValue(_password, RESTEasyName.password, password); + return this; + } + + /** + * {@inheritDoc} + */ + public String getRealm() { + if (_realm == null) { + _realm = getNameValue(RESTEasyName.realm); + } + return _realm != null ? _realm.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setRealm(String realm) { + _realm = setNameValue(_realm, RESTEasyName.realm, realm); + return this; + } + + /** + * {@inheritDoc} + */ + public String getHost() { + if (_host == null) { + _host = getNameValue(RESTEasyName.host); + } + return _host != null ? _host.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setHost(String host) { + _host = setNameValue(_host, RESTEasyName.host, host); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPort() { + if (_port == null) { + _port = getNameValue(RESTEasyName.port); + } + return _port != null ? _port.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setPort(String port) { + _port = setNameValue(_port, RESTEasyName.port, port); + return this; + } + + protected RESTEasyNameValueModel getNameValue(RESTEasyName name) { + return (RESTEasyNameValueModel)getFirstChildModel(name.name()); + } + + protected RESTEasyNameValueModel setNameValue(RESTEasyNameValueModel model, RESTEasyName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1RESTEasyNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1NtlmAuthModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1NtlmAuthModel.java new file mode 100644 index 000000000..832c34189 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1NtlmAuthModel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model.v1; + +import org.switchyard.component.resteasy.config.model.NtlmAuthModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel.RESTEasyName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A NtlmAuthModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1NtlmAuthModel extends V1BasicAuthModel implements NtlmAuthModel { + + private RESTEasyNameValueModel _domain; + + /** + * Creates a new NtlmAuthModel. + * @param namespace namespace + */ + public V1NtlmAuthModel(String namespace) { + super(namespace, RESTEasyName.ntlm.name()); + } + + /** + * Creates a new NtlmAuthModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1NtlmAuthModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + public String getDomain() { + if (_domain == null) { + _domain = getNameValue(RESTEasyName.domain); + } + return _domain != null ? _domain.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public NtlmAuthModel setDomain(String domain) { + _domain = setNameValue(_domain, RESTEasyName.domain, domain); + return this; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1ProxyModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1ProxyModel.java new file mode 100644 index 000000000..5642910f6 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1ProxyModel.java @@ -0,0 +1,163 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model.v1; + +import org.switchyard.component.resteasy.config.model.ProxyModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel.RESTEasyName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A ProxyModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1ProxyModel extends BaseModel implements ProxyModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + RESTEasyName.host.name(), + RESTEasyName.port.name(), + RESTEasyName.user.name(), + RESTEasyName.password.name() + }; + + private RESTEasyNameValueModel _host; + private RESTEasyNameValueModel _port; + private RESTEasyNameValueModel _user; + private RESTEasyNameValueModel _password; + + /** + * Creates a new ProxyModel. + * @param namespace namespace + */ + public V1ProxyModel(String namespace) { + super(namespace, RESTEasyName.proxy.name()); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new ProxyModel. + * @param namespace namespace + * @param name the name of the model + */ + public V1ProxyModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new ProxyModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ProxyModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * {@inheritDoc} + */ + public String getHost() { + if (_host == null) { + _host = getNameValue(RESTEasyName.host); + } + return _host != null ? _host.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setHost(String host) { + _host = setNameValue(_host, RESTEasyName.host, host); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPort() { + if (_port == null) { + _port = getNameValue(RESTEasyName.port); + } + return _port != null ? _port.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public String getUser() { + if (_user == null) { + _user = getNameValue(RESTEasyName.user); + } + return _user != null ? _user.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setUser(String user) { + _user = setNameValue(_user, RESTEasyName.user, user); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPassword() { + if (_password == null) { + _password = getNameValue(RESTEasyName.password); + } + return _password != null ? _password.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setPassword(String password) { + _password = setNameValue(_password, RESTEasyName.password, password); + return this; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setPort(String port) { + _port = setNameValue(_port, RESTEasyName.port, port); + return this; + } + + protected RESTEasyNameValueModel getNameValue(RESTEasyName name) { + return (RESTEasyNameValueModel)getFirstChildModel(name.name()); + } + + protected RESTEasyNameValueModel setNameValue(RESTEasyNameValueModel model, RESTEasyName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1RESTEasyNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyBindingModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyBindingModel.java new file mode 100644 index 000000000..ff4f75f29 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyBindingModel.java @@ -0,0 +1,304 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.component.resteasy.config.model.BasicAuthModel; +import org.switchyard.component.resteasy.config.model.ContextParamsModel; +import org.switchyard.component.resteasy.config.model.NtlmAuthModel; +import org.switchyard.component.resteasy.config.model.ProxyModel; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel.RESTEasyName; +import org.switchyard.config.Configuration; +import org.switchyard.config.Configurations; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1BindingModel; + +/** + * A model that holds the RESTEasy gateway configuration V1. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1RESTEasyBindingModel extends V1BindingModel implements RESTEasyBindingModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + RESTEasyName.interfaces.name(), + RESTEasyName.contextPath.name(), + RESTEasyName.address.name(), + RESTEasyName.timeout.name(), + RESTEasyName.basic.name(), + RESTEasyName.ntlm.name(), + RESTEasyName.proxy.name(), + ContextParamsModel.CONTEXT_PARAMS + }; + + private QName _serviceName; + private Configuration _environment; + + private RESTEasyNameValueModel _address; + private RESTEasyNameValueModel _interfaces; + private RESTEasyNameValueModel _contextPath; + private RESTEasyNameValueModel _timeout; + private BasicAuthModel _basicAuth; + private NtlmAuthModel _ntlmAuth; + private ProxyModel _proxyConfig; + + /** + * Constructor. + * @param namespace namespace + */ + public V1RESTEasyBindingModel(String namespace) { + super(RESTEASY, namespace); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Create a RESTEasyBindingModel using configuration and descriptor. + * + * @param config the RESTEasyGateway configuration + * @param desc the RESTEasyGateway descriptor + */ + public V1RESTEasyBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + public QName getServiceName() { + if (_serviceName == null) { + _serviceName = isServiceBinding() ? getService().getQName() : getReference().getQName(); + } + return _serviceName; + } + + /** + * {@inheritDoc} + */ + public void setServiceName(QName serviceName) { + _serviceName = serviceName; + } + + /** + * {@inheritDoc} + */ + public String getAddress() { + if (_address == null) { + _address = getNameValue(RESTEasyName.address); + } + return _address != null ? _address.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public RESTEasyBindingModel setAddress(String address) { + _address = setNameValue(_address, RESTEasyName.address, address); + return this; + } + + /** + * {@inheritDoc} + */ + public String getInterfaces() { + if (_interfaces == null) { + _interfaces = getNameValue(RESTEasyName.interfaces); + } + return _interfaces != null ? _interfaces.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public RESTEasyBindingModel setInterfaces(String interfaces) { + _interfaces = setNameValue(_interfaces, RESTEasyName.interfaces, interfaces); + return this; + } + + /** + * {@inheritDoc} + */ + public String[] getInterfacesAsArray() { + String interfaces = getInterfaces(); + if (interfaces != null) { + return interfaces.split(","); + } else { + return new String[0]; + } + } + + /** + * {@inheritDoc} + */ + public String getContextPath() { + if (_contextPath == null) { + _contextPath = getNameValue(RESTEasyName.contextPath); + } + return _contextPath != null ? _contextPath.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public RESTEasyBindingModel setContextPath(String contextPath) { + _contextPath = setNameValue(_contextPath, RESTEasyName.contextPath, contextPath); + return this; + } + + /** + * {@inheritDoc} + */ + public Integer getTimeout() { + if (_timeout == null) { + _timeout = getNameValue(RESTEasyName.timeout); + } + return _timeout != null ? Integer.valueOf(_timeout.getValue()) : null; + } + + /** + * {@inheritDoc} + */ + public RESTEasyBindingModel setTimeout(Integer timeout) { + _timeout = setNameValue(_timeout, RESTEasyName.timeout, String.valueOf(timeout)); + return this; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel getBasicAuthConfig() { + if (_basicAuth == null) { + _basicAuth = (BasicAuthModel)getFirstChildModel(RESTEasyName.basic.name()); + } + return _basicAuth; + } + + /** + * {@inheritDoc} + */ + public RESTEasyBindingModel setBasicAuthConfig(BasicAuthModel config) { + setChildModel(config); + _basicAuth = config; + return this; + } + + /** + * {@inheritDoc} + */ + public NtlmAuthModel getNtlmAuthConfig() { + if (_ntlmAuth == null) { + _ntlmAuth = (NtlmAuthModel)getFirstChildModel(RESTEasyName.ntlm.name()); + } + return _ntlmAuth; + } + + /** + * {@inheritDoc} + */ + public RESTEasyBindingModel setNtlmAuthConfig(NtlmAuthModel config) { + setChildModel(config); + _ntlmAuth = config; + return this; + } + + /** + * {@inheritDoc} + */ + public Boolean isBasicAuth() { + return (getBasicAuthConfig() != null) ? true : false; + } + + /** + * {@inheritDoc} + */ + public Boolean hasAuthentication() { + return ((getBasicAuthConfig() != null) || (getNtlmAuthConfig() != null)) ? true : false; + } + + @Override + public ContextParamsModel getContextParamsConfig() { + // introduced in v2 + return null; + } + + @Override + public RESTEasyBindingModel setContextParamsConfig(ContextParamsModel contextParamsConfig) { + // introduced in v2 + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ProxyModel getProxyConfig() { + if (_proxyConfig == null) { + _proxyConfig = (ProxyModel)getFirstChildModel(RESTEasyName.proxy.name()); + } + return _proxyConfig; + } + + /** + * {@inheritDoc} + */ + @Override + public RESTEasyBindingModel setProxyConfig(ProxyModel proxyConfig) { + setChildModel(proxyConfig); + _proxyConfig = proxyConfig; + return this; + } + + /** + * {@inheritDoc} + */ + public Configuration getEnvironment() { + if (_environment == null) { + _environment = Configurations.newConfiguration(); + } + return _environment; + } + + /** + * {@inheritDoc} + */ + @Override + public RESTEasyBindingModel setEnvironment(Configuration environment) { + _environment = environment; + return this; + } + + private RESTEasyNameValueModel getNameValue(RESTEasyName name) { + return (RESTEasyNameValueModel)getFirstChildModel(name.name()); + } + + private RESTEasyNameValueModel setNameValue(RESTEasyNameValueModel model, RESTEasyName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1RESTEasyNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyMarshaller.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyMarshaller.java new file mode 100644 index 000000000..6d8324dab --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyMarshaller.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.config.model.v1; + +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel.RESTEasyName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.composer.v1.V1ContextMapperModel; +import org.switchyard.config.model.composer.v1.V1MessageComposerModel; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Marshaller for RESTEasy Gateway configurations. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class V1RESTEasyMarshaller extends BaseMarshaller { + + /** + * Construct a RESTEasy Model Marshaller with help of a Descriptor. + * + * @param desc the Descriptor + */ + public V1RESTEasyMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads a RESTEasy Model configuration. + * + * @param config the configuration + * @return the RESTEasy Binding Model + */ + @Override + public Model read(Configuration config) { + Descriptor desc = getDescriptor(); + String name = config.getName(); + if (name.startsWith(BindingModel.BINDING)) { + return new V1RESTEasyBindingModel(config, desc); + } else if (name.equals(ContextMapperModel.CONTEXT_MAPPER)) { + return new V1ContextMapperModel(config, desc); + } else if (name.equals(MessageComposerModel.MESSAGE_COMPOSER)) { + return new V1MessageComposerModel(config, desc); + } else if (name.equals(RESTEasyName.basic.name())) { + return new V1BasicAuthModel(config, desc); + } else if (name.equals(RESTEasyName.ntlm.name())) { + return new V1NtlmAuthModel(config, desc); + } else if (name.equals(RESTEasyName.proxy.name())) { + return new V1ProxyModel(config, desc); + } else { + for (RESTEasyName n : RESTEasyName.values()) { + if (n.name().equals(name)) { + return new V1RESTEasyNameValueModel(config, desc); + } + } + } + return null; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyNameValueModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyNameValueModel.java new file mode 100644 index 000000000..8d256c78d --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v1/V1RESTEasyNameValueModel.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model.v1; + +import org.switchyard.component.resteasy.config.model.RESTEasyNameValueModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version RESTEasyNameValueModel. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1RESTEasyNameValueModel extends BaseModel implements RESTEasyNameValueModel { + + /** + * Creates a new V1RESTEasyNameValueModel. + * @param namespace namespace + * @param name the RESTEasyName + */ + public V1RESTEasyNameValueModel(String namespace, RESTEasyName name) { + super(namespace, name.name()); + } + + /** + * Creates a new V1RESTEasyNameValueModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1RESTEasyNameValueModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public RESTEasyName getName() { + return RESTEasyName.valueOf(getModelConfiguration().getName()); + } + + /** + * {@inheritDoc} + */ + @Override + public String getValue() { + return getModelValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public RESTEasyNameValueModel setValue(String value) { + setModelValue(value); + return this; + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2ContextParamModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2ContextParamModel.java new file mode 100644 index 000000000..0f5a19bef --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2ContextParamModel.java @@ -0,0 +1,91 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model.v2; + +import javax.xml.namespace.QName; + +import org.switchyard.component.resteasy.config.model.ContextParamModel; +import org.switchyard.component.resteasy.config.model.ContextParamsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 2 ContextParamModel. + */ +public class V2ContextParamModel extends BaseModel implements ContextParamModel { + + private static final String NAME = "name"; + private static final String VALUE = "value"; + + /** + * Creates a new ContextParamModel in the specified namespace. + * @param namespace the specified namespace + */ + public V2ContextParamModel(String namespace) { + super(new QName(namespace, CONTEXT_PARAM)); + } + + /** + * Creates a new ContextParamModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V2ContextParamModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public ContextParamsModel getContextParamsModel() { + return (ContextParamsModel) getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return getModelAttribute(NAME); + } + + /** + * {@inheritDoc} + */ + @Override + public ContextParamModel setName(String name) { + setModelAttribute(NAME, name); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getValue() { + return getModelAttribute(VALUE); + } + + /** + * {@inheritDoc} + */ + @Override + public ContextParamModel setValue(String value) { + setModelAttribute(VALUE, value); + return this; + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2ContextParamsModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2ContextParamsModel.java new file mode 100644 index 000000000..118678f9d --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2ContextParamsModel.java @@ -0,0 +1,87 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model.v2; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.component.resteasy.config.model.ContextParamModel; +import org.switchyard.component.resteasy.config.model.ContextParamsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 2 ContextParamsModel. + */ +public class V2ContextParamsModel extends BaseModel implements ContextParamsModel { + + private List _contextParams = new ArrayList(); + + /** + * Creates a new ContextParamsModel in the specified namespace. + * @param namespace the specified namespace + */ + public V2ContextParamsModel(String namespace) { + super(new QName(namespace, CONTEXT_PARAMS)); + setModelChildrenOrder(ContextParamModel.CONTEXT_PARAM); + } + + /** + * Creates a new ContextParamsModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V2ContextParamsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration property_config : config.getChildren(ContextParamModel.CONTEXT_PARAM)) { + ContextParamModel contextParam = (ContextParamModel) readModel(property_config); + if (contextParam != null) { + _contextParams.add(contextParam); + } + } + setModelChildrenOrder(ContextParamModel.CONTEXT_PARAM); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getContextParams() { + return Collections.unmodifiableList(_contextParams); + } + + /** + * {@inheritDoc} + */ + @Override + public Map toMap() { + List contextParams = getContextParams(); + Map map = new HashMap(contextParams.size()); + + for (ContextParamModel cp : contextParams) { + String name = cp.getName(); + String value = cp.getValue(); + if (name != null && value != null) { + map.put(name, value); + } + } + return map; + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2RESTEasyBindingModel.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2RESTEasyBindingModel.java new file mode 100644 index 000000000..9eda939bd --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2RESTEasyBindingModel.java @@ -0,0 +1,62 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model.v2; + +import org.switchyard.component.resteasy.config.model.ContextParamsModel; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.resteasy.config.model.v1.V1RESTEasyBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A model that holds the RESTEasy gateway configuration V2. + */ +public class V2RESTEasyBindingModel extends V1RESTEasyBindingModel { + + private ContextParamsModel _contextParamsConfig; + + /** + * Constructor. + * @param namespace namespace + */ + public V2RESTEasyBindingModel(String namespace) { + super(namespace); + } + + /** + * Create a RESTEasyBindingModel using configuration and descriptor. + * + * @param config the RESTEasyGateway configuration + * @param desc the RESTEasyGateway descriptor + */ + public V2RESTEasyBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public ContextParamsModel getContextParamsConfig() { + if (_contextParamsConfig == null) { + _contextParamsConfig = (ContextParamsModel) getFirstChildModel(ContextParamsModel.CONTEXT_PARAMS); + } + return _contextParamsConfig; + } + + @Override + public RESTEasyBindingModel setContextParamsConfig(ContextParamsModel contextParamsConfig) { + setChildModel(contextParamsConfig); + _contextParamsConfig = contextParamsConfig; + return this; + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2RESTEasyMarshaller.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2RESTEasyMarshaller.java new file mode 100644 index 000000000..0a2ca84ca --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/config/model/v2/V2RESTEasyMarshaller.java @@ -0,0 +1,58 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.config.model.v2; + +import org.switchyard.component.resteasy.config.model.ContextParamModel; +import org.switchyard.component.resteasy.config.model.ContextParamsModel; +import org.switchyard.component.resteasy.config.model.v1.V1RESTEasyMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * Marshaller (v2) for RESTEasy Gateway configurations. + */ +public class V2RESTEasyMarshaller extends V1RESTEasyMarshaller { + + /** + * Construct a RESTEasy Model Marshaller (v2) with help of a Descriptor. + * + * @param desc the Descriptor + */ + public V2RESTEasyMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads a RESTEasy Model configuration. + * + * @param config the configuration + * @return the RESTEasy Binding Model + */ + @Override + public Model read(Configuration config) { + Descriptor desc = getDescriptor(); + String name = config.getName(); + if (name.startsWith(BindingModel.BINDING)) { + return new V2RESTEasyBindingModel(config, desc); + } else if (name.equals(ContextParamsModel.CONTEXT_PARAMS)) { + return new V2ContextParamsModel(config, desc); + } else if (name.equals(ContextParamModel.CONTEXT_PARAM)) { + return new V2ContextParamModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/deploy/RESTEasyActivator.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/deploy/RESTEasyActivator.java new file mode 100644 index 000000000..da955db40 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/deploy/RESTEasyActivator.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.component.resteasy.InboundHandler; +import org.switchyard.component.resteasy.OutboundHandler; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; + + +/** + * RESTEasy Activator. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyActivator extends BaseActivator { + + static final String RESTEASY_TYPE = "rest"; + private Configuration _environment; + + /** + * Creates a new activator for RESTEasy service. + */ + public RESTEasyActivator() { + super(RESTEASY_TYPE); + } + + @Override + public ServiceHandler activateBinding(QName name, BindingModel config) { + RESTEasyBindingModel binding = (RESTEasyBindingModel)config; + binding.setEnvironment(_environment); + + if (binding.isServiceBinding()) { + return new InboundHandler(binding, getServiceDomain()); + } else { + return new OutboundHandler(binding, getServiceDomain()); + } + } + + @Override + public void deactivateBinding(QName name, ServiceHandler handler) { + // Nothing to do here + } + + /** + * Set the Environment configuration for the activator. + * @param config The global environment configuration. + */ + public void setEnvironment(Configuration config) { + _environment = config; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/deploy/RESTEasyComponent.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/deploy/RESTEasyComponent.java new file mode 100644 index 000000000..e0c40c4ed --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/deploy/RESTEasyComponent.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.deploy; + +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * An implementation of RESTEasy component. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyComponent extends BaseComponent { + + /** + * Default constructor. + */ + public RESTEasyComponent() { + super(RESTEasyActivator.RESTEASY_TYPE); + setName("RESTEasyComponent"); + } + + /** + * {@inheritDoc} + */ + @Override + public Activator createActivator(ServiceDomain domain) { + RESTEasyActivator activator = new RESTEasyActivator(); + activator.setServiceDomain(domain); + activator.setEnvironment(getConfig()); + return activator; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiMethodInvokerFactory.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiMethodInvokerFactory.java new file mode 100644 index 000000000..64ed95486 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiMethodInvokerFactory.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.osgi; + +import java.lang.reflect.Method; + +import org.jboss.resteasy.spi.ResteasyProviderFactory; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.resteasy.util.ClientInvoker; +import org.switchyard.component.resteasy.util.MethodInvoker; +import org.switchyard.component.resteasy.util.MethodInvokerFactory; + +/** + * A factory class to create MethodInvoker with registering RESTEasy providers explicitly. + * This is a workaround for https://issues.jboss.org/browse/RESTEASY-640 + */ +public class OsgiMethodInvokerFactory implements MethodInvokerFactory { + + @Override + public MethodInvoker createInvoker(String basePath, Class resourceClass, Method method, RESTEasyBindingModel model) { + ClientInvoker invoker = new ClientInvoker(basePath, resourceClass, method, model); + ResteasyProviderFactory repFactory = invoker.getResteasyProviderFactory(); + for (Class provider : RESTEasyProviders.PROVIDERS) { + repFactory.registerProvider(provider); + } + return invoker; + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyResource.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyResource.java new file mode 100644 index 000000000..64dcf87a1 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyResource.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.osgi; + +import java.util.List; + +import org.jboss.logging.Logger; +import org.switchyard.component.common.Endpoint; + +/** + * An OSGi RESTEasy resource. + */ +public class OsgiRESTEasyResource implements Endpoint { + + private static final Logger LOGGER = Logger.getLogger(OsgiRESTEasyResource.class); + + private OsgiRESTEasyServletRegistry _registry; + private String _alias; + private List> _classes; + + /** + * Sets OsgiRESTEasyServletRegistry. + * @param registry OsgiRESTEasyServletRegistry + * @return this OsgiRESTEasyResource (useful for chaining) + */ + public OsgiRESTEasyResource setServletRegistry(OsgiRESTEasyServletRegistry registry) { + _registry = registry; + return this; + } + + /** + * Sets alias. + * @param alias alias + * @return this OsgiRESTEasyResource (useful for chaining) + */ + public OsgiRESTEasyResource setAlias(String alias) { + _alias = alias; + return this; + } + + /** + * Sets resource class. + * @param classes resource class + * @return this OsgiRESTEasyResource (useful for chaining) + */ + public OsgiRESTEasyResource setResourceClasses(List> classes) { + _classes = classes; + return this; + } + + @Override + public void start() { + } + + @Override + public void stop() { + _registry.unregisterRESTEasyResources(_alias, _classes); + OsgiRESTEasyServletWrapper servlet = _registry.getRegisteredRESTEasyServlet(_alias); + if (servlet != null && servlet.getDispatcher().getRegistry().getSize() == 0) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Unregistering RESTEasy servlet with an alias '" + _alias + "'"); + } + _registry.unregisterRESTEasyServlet(_alias); + } + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyResourcePublisher.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyResourcePublisher.java new file mode 100644 index 000000000..d0af79ded --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyResourcePublisher.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.osgi; + +import java.util.Dictionary; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +import org.jboss.logging.Logger; +import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; +import org.jboss.resteasy.spi.ResteasyProviderFactory; +import org.osgi.service.http.HttpService; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.resteasy.resource.ResourcePublisher; +import org.switchyard.component.resteasy.util.RESTEasyUtil; + +/** + * Creates a RESTEasy Resource on karaf. + */ +public class OsgiRESTEasyResourcePublisher implements ResourcePublisher { + + private static final String KEY_SERVLET_REGISTRY = "org.switchyard.deploy.osgi.internal.resteasy.RESTEasyServletRegistry"; + private static final String KEY_SERVLET_MAPPING_PREFIX = "resteasy.servlet.mapping.prefix"; + private static final Logger LOGGER = Logger.getLogger(OsgiRESTEasyResourcePublisher.class); + + private HttpService _httpService; + + /** + * Sets HttpService. + * @param httpService HttpService + */ + public void setHttpService(HttpService httpService) { + _httpService = httpService; + } + + @Override + public Endpoint publish(ServiceDomain domain, String context, List instances, Map contextParams) throws Exception { + OsgiRESTEasyServletRegistry servletRegistry = (OsgiRESTEasyServletRegistry) domain.getProperty(KEY_SERVLET_REGISTRY); + if (servletRegistry == null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Creating OsgiRESTEasyServletRegistry"); + } + servletRegistry = new OsgiRESTEasyServletRegistry().setOsgiHttpService(_httpService); + domain.setProperty(KEY_SERVLET_REGISTRY, servletRegistry); + } + + String alias = context.startsWith("/") ? context : "/" + context; + OsgiRESTEasyServletWrapper servlet = servletRegistry.getRegisteredRESTEasyServlet(alias); + if (servlet == null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Registering RESTEasy servlet with an alias '" + alias + "'"); + } + servlet = new OsgiRESTEasyServletWrapper().setClassLoader(Classes.getTCCL()); + Dictionary initparams = new Hashtable(); + initparams.put(KEY_SERVLET_MAPPING_PREFIX, alias); + if (contextParams != null) { + for (Map.Entry cp : contextParams.entrySet()) { + // @Provider must be registered manually by bundle class loader + if (!cp.getKey().equals(ResteasyContextParameters.RESTEASY_PROVIDERS)) { + initparams.put(cp.getKey(), cp.getValue()); + } + } + } + servletRegistry.registerRESTEasyServlet(alias, servlet, initparams, null); + + // A workaround for https://issues.jboss.org/browse/RESTEASY-640 + ResteasyProviderFactory repFactory = servlet.getDispatcher().getProviderFactory(); + for (Class provider : RESTEasyProviders.PROVIDERS) { + repFactory.registerProvider(provider); + } + + // Register @Provider classes + List> providerClasses = RESTEasyUtil.getProviderClasses(contextParams); + if (providerClasses != null) { + for (Class pc : providerClasses) { + repFactory.registerProvider(pc); + } + } + } + + List> resourceClasses = servletRegistry.registerRESTEasyResources(alias, instances); + return new OsgiRESTEasyResource() + .setServletRegistry(servletRegistry) + .setAlias(alias) + .setResourceClasses(resourceClasses); + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyServletRegistry.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyServletRegistry.java new file mode 100644 index 000000000..0637c8313 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyServletRegistry.java @@ -0,0 +1,120 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.osgi; + +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import org.jboss.resteasy.spi.Registry; +import org.osgi.service.http.HttpContext; +import org.osgi.service.http.HttpService; + +/** + * A registry for RESTEasy servlet. + */ +public class OsgiRESTEasyServletRegistry { + + private final ConcurrentHashMap _servlets = new ConcurrentHashMap(); + private HttpService _httpService; + + /** + * Sets OSGi HttpService. + * @param service OSGi HttpService + * @return this OsgiRESTEasyServletRegistry (useful for chaining) + */ + public OsgiRESTEasyServletRegistry setOsgiHttpService(HttpService service) { + _httpService = service; + return this; + } + + /** + * Registers a RESTEasy servlet. + * @param alias alias + * @param servlet RESTEasy servlet + * @param initparams servlet init params + * @param context HttpContext + * @throws Exception if it fails to register a servlet + */ + public void registerRESTEasyServlet(String alias, OsgiRESTEasyServletWrapper servlet, Dictionary initparams, HttpContext context) throws Exception { + _httpService.registerServlet(alias, servlet, initparams, context); + _servlets.put(alias, servlet); + } + + /** + * Gets registered RESTEasy servlet. + * @param alias alias + * @return servlet + */ + public OsgiRESTEasyServletWrapper getRegisteredRESTEasyServlet(String alias) { + return _servlets.get(alias); + } + + /** + * Unregisters a RESTEasy servlet. + * @param alias alias + */ + public void unregisterRESTEasyServlet(String alias) { + OsgiRESTEasyServletWrapper servlet = getRegisteredRESTEasyServlet(alias); + if (servlet == null) { + throw new IllegalArgumentException("No RESTEasy servlet is registered for the alias '" + alias + "'"); + } + + if (servlet.getDispatcher().getRegistry().getSize() != 0) { + throw new IllegalStateException("Cannot remove RESTEasy Servlet '" + alias + "' - registry is not empty"); + } + + _httpService.unregister(alias); + _servlets.remove(alias); + } + + /** + * Registers RESTEasy resources to the registered RESTEasy servlet. + * @param alias alias + * @param resources resource instances + * @return classes of the registered resources + */ + public List> registerRESTEasyResources(String alias, List resources) { + OsgiRESTEasyServletWrapper servlet = getRegisteredRESTEasyServlet(alias); + if (servlet == null) { + throw new IllegalArgumentException("No servlet is registered for the alias '" + alias + "'"); + } + + Registry registry = servlet.getDispatcher().getRegistry(); + List> classes = new ArrayList>(); + for (Object instance : resources) { + registry.addSingletonResource(instance); + classes.add(instance.getClass()); + } + return classes; + } + + /** + * Unregisters RESTEasy resources from the servlet. + * @param alias alias + * @param resourceClasses resource classes + */ + public void unregisterRESTEasyResources(String alias, List> resourceClasses) { + OsgiRESTEasyServletWrapper servlet = getRegisteredRESTEasyServlet(alias); + if (servlet == null) { + throw new IllegalArgumentException("No servlet is registered for the alias '" + alias + "'"); + } + + Registry registry = servlet.getDispatcher().getRegistry(); + for (Class clazz : resourceClasses) { + registry.removeRegistrations(clazz); + } + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyServletWrapper.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyServletWrapper.java new file mode 100644 index 000000000..420f2f5da --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/OsgiRESTEasyServletWrapper.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.osgi; + +import java.io.IOException; +import java.util.Enumeration; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.jboss.logging.Logger; +import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher; +import org.switchyard.common.type.Classes; + +/** + * A wrapper servlet to plug it into RESTEasy. + */ +public class OsgiRESTEasyServletWrapper extends HttpServletDispatcher { + + private static final long serialVersionUID = 8811690971687086278L; + private static final Logger LOGGER = Logger.getLogger(OsgiRESTEasyServletWrapper.class); + + private transient ClassLoader _classLoader; + + /** + * Sets a class loader to be used for TCCL on execution. + * @param loader class loader + * @return this OsgiRESTEasyServletWrapper (useful for chaining) + */ + public OsgiRESTEasyServletWrapper setClassLoader(ClassLoader loader) { + _classLoader = loader; + return this; + } + + @Override + public void service(String httpMethod, HttpServletRequest request, HttpServletResponse response) throws IOException { + ClassLoader origCL = null; + try { + origCL = Classes.setTCCL(_classLoader); + if (LOGGER.isDebugEnabled()) { + String br = System.getProperty("line.separator"); + StringBuilder buf = new StringBuilder() + .append("Executing RESTEasy servlet:").append(br) + .append("\tClassLoader:\t").append(_classLoader).append(br) + .append("\tHTTP Headers:\t"); + Enumeration headerenum = request.getHeaderNames(); + while (headerenum.hasMoreElements()) { + String key = headerenum.nextElement().toString(); + buf.append(key).append("={"); + Enumeration e = request.getHeaders(key); + while (e.hasMoreElements()) { + buf.append(e.nextElement().toString()).append(";"); + } + buf.append("} "); + } + buf.append(br) + .append("\tHTTP Request:\t").append(request.toString()).append(br) + .append("\tContent Type:\t").append(request.getContentType()).append(br) + .append("\tContent Length:\t").append(request.getContentLength()).append(br) + .append("\tHTTP Parameters:\t").append(request.getParameterMap()); + LOGGER.debug(buf.toString()); + } + super.service(httpMethod, request, response); + } finally { + Classes.setTCCL(origCL); + } + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/RESTEasyProviders.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/RESTEasyProviders.java new file mode 100644 index 000000000..0f2526d43 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/osgi/RESTEasyProviders.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.osgi; + +/** + * Defines a list of RESTEasy providers to be registered. + * This is a workaround for https://issues.jboss.org/browse/RESTEASY-640 + */ +public final class RESTEasyProviders { + + /** A list of RESTEasy providers to be registered. */ + static final Class[] PROVIDERS = { + // from resteasy-jaxrs + org.jboss.resteasy.plugins.providers.DataSourceProvider.class, + org.jboss.resteasy.plugins.providers.DocumentProvider.class, + org.jboss.resteasy.plugins.providers.DefaultTextPlain.class, + org.jboss.resteasy.plugins.providers.StringTextStar.class, + org.jboss.resteasy.plugins.providers.InputStreamProvider.class, + org.jboss.resteasy.plugins.providers.ByteArrayProvider.class, + org.jboss.resteasy.plugins.providers.FormUrlEncodedProvider.class, + org.jboss.resteasy.plugins.providers.FileProvider.class, + org.jboss.resteasy.plugins.providers.StreamingOutputProvider.class, + org.jboss.resteasy.plugins.providers.IIOImageProvider.class, + org.jboss.resteasy.plugins.interceptors.CacheControlInterceptor.class, + org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPInterceptor.class, + org.jboss.resteasy.plugins.interceptors.encoding.ClientContentEncodingHeaderInterceptor.class, + org.jboss.resteasy.plugins.interceptors.encoding.GZIPDecodingInterceptor.class, + org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor.class, + org.jboss.resteasy.plugins.interceptors.encoding.ServerContentEncodingHeaderInterceptor.class, + // from resteasy-jaxb-provider + org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlSeeAlsoProvider.class, + org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlRootElementProvider.class, + org.jboss.resteasy.plugins.providers.jaxb.JAXBElementProvider.class, + org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlTypeProvider.class, + org.jboss.resteasy.plugins.providers.jaxb.CollectionProvider.class, + org.jboss.resteasy.plugins.providers.jaxb.MapProvider.class, + org.jboss.resteasy.plugins.providers.jaxb.XmlJAXBContextFinder.class, + }; + + private RESTEasyProviders() { + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/NettyJaxrsServer.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/NettyJaxrsServer.java new file mode 100644 index 000000000..c80f01149 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/NettyJaxrsServer.java @@ -0,0 +1,165 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.resource; + +import org.jboss.netty.bootstrap.ServerBootstrap; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; +import org.jboss.resteasy.core.SynchronousDispatcher; +import org.jboss.resteasy.plugins.server.embedded.EmbeddedJaxrsServer; +import org.jboss.resteasy.plugins.server.embedded.SecurityDomain; +import org.jboss.resteasy.plugins.server.netty.HttpServerPipelineFactory; +import org.jboss.resteasy.plugins.server.netty.HttpsServerPipelineFactory; +import org.jboss.resteasy.plugins.server.netty.RequestDispatcher; +import org.jboss.resteasy.spi.ResteasyDeployment; + +import java.net.InetSocketAddress; +import java.util.concurrent.Executors; + +import javax.net.ssl.SSLContext; + +/** + * An HTTP server that sends back the content of the received HTTP request + * in a pretty plaintext form. + * + * Keep this class untill https://issues.jboss.org/browse/RESTEASY-794 moves to AS7 + * + * @author The Netty Project + * @author Andy Taylor (andy.taylor@jboss.org) + * @author Trustin Lee + * @author Norman Maurer + * @version $Rev: 2080 $, $Date: 2010-01-26 18:04:19 +0900 (Tue, 26 Jan 2010) $ + */ +public class NettyJaxrsServer implements EmbeddedJaxrsServer +{ + protected ServerBootstrap bootstrap; + protected Channel channel; + protected int port = ResourcePublisher.DEFAULT_PORT; + protected ResteasyDeployment deployment = new ResteasyDeployment(); + protected String root = ""; + protected SecurityDomain domain; + private int ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2; + private int executorThreadCount = 16; + private SSLContext sslContext; + private int maxRequestSize = 1024 * 1024 * 10; + + public void setSSLContext(SSLContext sslContext) + { + this.sslContext = sslContext; + } + + /** + * Specify the worker count to use. For more informations about this please see the javadocs of {@link NioServerSocketChannelFactory} + * + * @param ioWorkerCount + */ + public void setIoWorkerCount(int ioWorkerCount) + { + this.ioWorkerCount = ioWorkerCount; + } + + /** + * Set the number of threads to use for the Executor. For more informations please see the javadocs of {@link OrderedMemoryAwareThreadPoolExecutor}. + * If you want to disable the use of the {@link ExecutionHandler} specify a value <= 0. This should only be done if you are 100% sure that you don't have any blocking + * code in there. + * + * + * @param executorThreadCount + */ + public void setExecutorThreadCount(int executorThreadCount) + { + this.executorThreadCount = executorThreadCount; + } + + /** + * Set the max. request size in bytes. If this size is exceed we will send a "413 Request Entity Too Large" to the client. + * + * @param maxRequestSize the max request size. This is 10mb by default. + */ + public void setMaxRequestSize(int maxRequestSize) + { + this.maxRequestSize = maxRequestSize; + } + + public int getPort() + { + return Integer.getInteger(ResourcePublisher.DEFAULT_PORT_PROPERTY, this.port); + } + + public void setPort(int port) + { + this.port = port; + } + + @Override + public void setDeployment(ResteasyDeployment deployment) + { + this.deployment = deployment; + } + + @Override + public void setRootResourcePath(String rootResourcePath) + { + root = rootResourcePath; + if (root != null && root.equals("/")) root = ""; + } + + @Override + public ResteasyDeployment getDeployment() + { + return deployment; + } + + @Override + public void setSecurityDomain(SecurityDomain sc) + { + this.domain = sc; + } + + @Override + public void start() + { + deployment.start(); + RequestDispatcher dispatcher = new RequestDispatcher((SynchronousDispatcher)deployment.getDispatcher(), deployment.getProviderFactory(), domain); + + // Configure the server. + bootstrap = new ServerBootstrap( + new NioServerSocketChannelFactory( + Executors.newCachedThreadPool(), + Executors.newCachedThreadPool(), + ioWorkerCount)); + + ChannelPipelineFactory factory; + if (sslContext == null) { + factory = new HttpServerPipelineFactory(dispatcher, root, executorThreadCount, maxRequestSize); + } else { + factory = new HttpsServerPipelineFactory(dispatcher, root, executorThreadCount, maxRequestSize, sslContext); + } + // Set up the event pipeline factory. + bootstrap.setPipelineFactory(factory); + + // Bind and start to accept incoming connections. + channel = bootstrap.bind(new InetSocketAddress(getPort())); + } + + @Override + public void stop() + { + channel.close().awaitUninterruptibly(); + bootstrap.releaseExternalResources(); + deployment.stop(); + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/NettyResourcePublisher.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/NettyResourcePublisher.java new file mode 100644 index 000000000..36353a9a5 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/NettyResourcePublisher.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.resource; + +import java.util.List; +import java.util.Map; + +import org.jboss.resteasy.spi.ResteasyDeployment; +import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.resteasy.util.RESTEasyUtil; + +/** + * Publishes standalone RESTEasy resource to Netty. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class NettyResourcePublisher implements ResourcePublisher { + /** + * The global standalone NettyServer. + * + * Keep org.switchyard.component.resteasy.resource.NettyJaxrsServer class untill + * https://issues.jboss.org/browse/RESTEASY-794 moves to a released AS7 version that we can use. + */ + private static NettyJaxrsServer _nettyServer; + + static { + ResteasyDeployment deployment = new ResteasyDeployment(); + _nettyServer = new NettyJaxrsServer(); + _nettyServer.setRootResourcePath(""); + _nettyServer.setSecurityDomain(null); + _nettyServer.setDeployment(deployment); + _nettyServer.start(); + } + + /** + * {@inheritDoc} + */ + public Endpoint publish(ServiceDomain domain, String context, List instances, Map contextParams) throws Exception { + _nettyServer.stop(); + // CAUTION: Note that this publisher ignores context. Use it only for test purpose. + for (Object instance : instances) { + _nettyServer.getDeployment().getResources().add(instance); + } + List providers = RESTEasyUtil.getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS); + if (providers != null) { + _nettyServer.getDeployment().getScannedProviderClasses().addAll(providers); + } + _nettyServer.start(); + return new StandaloneResource(); + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/ResourcePublisher.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/ResourcePublisher.java new file mode 100644 index 000000000..c5a560b5e --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/ResourcePublisher.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.resource; + +import java.util.List; +import java.util.Map; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; + +/** + * Interface for allowing SwitchYard to publish RESTEasy resources. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public interface ResourcePublisher { + + /** + * Default port in which the standalone publisher is started. + */ + public static final int DEFAULT_PORT = 8080; + + /** + * System property to adjust the port in which the standalone publisher is started. + */ + public static final String DEFAULT_PORT_PROPERTY = "org.switchyard.component.resteasy.standalone.port"; + + /** + * Publish a RESTEasy resource. + * @param domain The ServiceDomain for the application/deployment + * @param context The web context root where the resource need to be published + * @param instances The a list of JAX-RS resource instances + * @param contextParams The map of endpoint context parameters + * @return The published resource holder + * @throws Exception if resource could not be published + */ + Endpoint publish(ServiceDomain domain, String context, List instances, Map contextParams) throws Exception; +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/ResourcePublisherFactory.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/ResourcePublisherFactory.java new file mode 100644 index 000000000..6504e72ed --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/ResourcePublisherFactory.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.resource; + +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.component.resteasy.RESTEasyPublishException; + +/** + * Factory for creating Resource publisher. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class ResourcePublisherFactory { + + private static ResourcePublisher PUBLISHER; + + private static Boolean IGNORE_CONTEXT = false; + + static { + try { + PUBLISHER = ProviderRegistry.getProvider(ResourcePublisher.class); + if (PUBLISHER == null) { + PUBLISHER = new StandaloneResourcePublisher(); + } + } catch (Exception e) { + throw new RESTEasyPublishException(e); + } + if (PUBLISHER instanceof NettyResourcePublisher) { + // Context paths are irrelevent for NettyJaxrs server + IGNORE_CONTEXT = true; + } + } + + private ResourcePublisherFactory() { + } + + /** + * Should the context path be ignored? + * + * @return true if using NettyJaxrsServer + */ + public static Boolean ignoreContext() { + return IGNORE_CONTEXT; + } + + /** + * Creates a ResourcePublisher based on the environment. + * @return The ResourcePublisher + */ + public static ResourcePublisher getPublisher() { + return PUBLISHER; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/StandaloneResource.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/StandaloneResource.java new file mode 100644 index 000000000..cb882c77c --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/StandaloneResource.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.resource; + +import org.switchyard.component.common.Endpoint; + +/** + * A standalone RESTEasy resource. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class StandaloneResource implements Endpoint { + + /** + * {@inheritDoc} + */ + public void start() { + // NO OP + } + + /** + * {@inheritDoc} + */ + public void stop() { + // NO OP + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/StandaloneResourcePublisher.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/StandaloneResourcePublisher.java new file mode 100644 index 000000000..3580a35d4 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/resource/StandaloneResourcePublisher.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.resource; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import com.sun.net.httpserver.HttpServer; +import org.jboss.logging.Logger; +import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; +import org.jboss.resteasy.plugins.server.sun.http.HttpContextBuilder; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.resteasy.RestEasyLogger; +import org.switchyard.component.resteasy.util.RESTEasyUtil; + +/** + * Publishes standalone RESTEasy resource. + *

+ * By default it will be published in port {@value #DEFAULT_PORT}. This can be configured making use of + * {@value #DEFAULT_PORT_PROPERTY} system property. + *

+ * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class StandaloneResourcePublisher implements ResourcePublisher { + + private static final Logger LOGGER = Logger.getLogger(StandaloneResourcePublisher.class); + + // The global standalone HttpServer + private static HttpServer _httpServer; + private static HttpContextBuilder _contextBuilder; + + static { + try { + _contextBuilder = new HttpContextBuilder(); + _httpServer = HttpServer.create(new InetSocketAddress(getPort()), 10); + _httpServer.setExecutor(null); // creates a default executor + _httpServer.start(); + } catch (IOException ioe) { + RestEasyLogger.ROOT_LOGGER.unableToLaunchStandaloneHttpServer(ioe); + } + } + + /** + * {@inheritDoc} + */ + public Endpoint publish(ServiceDomain domain, String context, List instances, Map contextParams) throws Exception { + List resourceInstances = new ArrayList(); + String path = _contextBuilder.getPath(); + if (path.startsWith("/")) { + path = path.substring(1); + } + if (path.equals(context)) { + _contextBuilder.cleanup(); + try { + _httpServer.removeContext(_contextBuilder.getPath()); + } catch (IllegalArgumentException iae) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(iae); + } + } + resourceInstances = _contextBuilder.getDeployment().getResources(); + _contextBuilder.getDeployment().getDefaultContextObjects().clear(); + } + // Add as singleton instance + for (Object instance : instances) { + resourceInstances.add(instance); + } + _contextBuilder.getDeployment().setResources(resourceInstances); + // Register @Provider classes + List providers = RESTEasyUtil.getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS); + _contextBuilder.getDeployment().setScannedProviderClasses(providers != null ? providers : Collections.emptyList()); + _contextBuilder.setPath(context); + _contextBuilder.bind(_httpServer); + return new StandaloneResource(); + } + + /** + * Returns the port where the standalone publisher will be started + * @return the port + */ + static int getPort() { + return Integer.getInteger(DEFAULT_PORT_PROPERTY, DEFAULT_PORT); + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/ClassUtil.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/ClassUtil.java new file mode 100644 index 000000000..5a9e600b3 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/ClassUtil.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.util; + +import java.util.ArrayList; +import java.util.List; + +import org.jboss.logging.Logger; +import org.switchyard.common.type.Classes; +import org.switchyard.component.resteasy.InboundHandler; + +/** + * Utility class that generates RESTEasy singleton instances. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class ClassUtil { + + private static final Logger LOGGER = Logger.getLogger(ClassUtil.class); + + private ClassUtil() { + } + + /** + * Generate a singleton class for a JAX-RS Resource interface and create an instance. + * + * @param resourceIntfs an array of JAX-RS Resource interface names + * @param handler a SwitchYard service handler that invokes the respective service + * @return a List of Resource implementations + * @throws Exception if generation fails + */ + public static List generateSingletons(String[] resourceIntfs, InboundHandler handler) throws Exception { + List instances = new ArrayList(); + for (String resourceIntf : resourceIntfs) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Generating instance for " + resourceIntf); + } + Class clazz = Classes.forName(resourceIntf); + Object instance = RESTEasyProxy.newInstance(handler, clazz); + instances.add(instance); + } + return instances; + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/ClientInvoker.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/ClientInvoker.java new file mode 100644 index 000000000..94dc3920f --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/ClientInvoker.java @@ -0,0 +1,462 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.util; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.ext.Providers; + +import org.jboss.logging.Logger; + +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.ChallengeState; +import org.apache.http.auth.Credentials; +import org.apache.http.auth.NTCredentials; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.AuthCache; +import org.apache.http.client.HttpClient; +import org.apache.http.client.protocol.ClientContext; +import org.apache.http.conn.params.ConnRoutePNames; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.BasicHttpContext; +import org.jboss.resteasy.client.ClientExecutor; +import org.jboss.resteasy.client.ClientRequest; +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.client.ClientResponseFailure; +import org.jboss.resteasy.client.core.BaseClientResponse; +import org.jboss.resteasy.client.core.ClientErrorInterceptor; +import org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl; +import org.jboss.resteasy.client.core.ClientInvokerInterceptorFactory; +import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; +import org.jboss.resteasy.client.core.extractors.ClientErrorHandler; +import org.jboss.resteasy.client.core.extractors.ClientRequestContext; +import org.jboss.resteasy.client.core.extractors.DefaultEntityExtractorFactory; +import org.jboss.resteasy.client.core.extractors.EntityExtractor; +import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory; +import org.jboss.resteasy.client.core.marshallers.ClientMarshallerFactory; +import org.jboss.resteasy.client.core.marshallers.Marshaller; +import org.jboss.resteasy.client.exception.mapper.ApacheHttpClient4ExceptionMapper; +import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper; +import org.jboss.resteasy.plugins.providers.RegisterBuiltin; +import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; +import org.jboss.resteasy.spi.ResteasyProviderFactory; +import org.jboss.resteasy.util.MediaTypeHelper; +import org.jboss.resteasy.util.IsHttpMethod; +import org.jboss.resteasy.util.Types; +import org.switchyard.component.resteasy.RestEasyLogger; +import org.switchyard.component.resteasy.RestEasyMessages; +import org.switchyard.component.resteasy.composer.RESTEasyBindingData; +import org.switchyard.component.resteasy.config.model.ProxyModel; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; + +/** + * Client Invoker for RESTEasy gateway. Code lifted from RESTEasy. + * + * @author Bill Burke + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class ClientInvoker extends ClientInterceptorRepositoryImpl implements MethodInvoker { + + private static final Logger LOGGER = Logger.getLogger(ClientInvoker.class); + + private static final String AS7_URIBUILDER = "org.jboss.resteasy.specimpl.UriBuilderImpl"; + private static final String WFLY_URIBUILDER = "org.jboss.resteasy.specimpl.ResteasyUriBuilder"; + private static Class URIBUILDER_CLASS = null; + + private String _subResourcePath; + private Class _resourceClass; + private Method _method; + private String _httpMethod; + private UriBuilder _uri; + private MediaType _accepts; + private Marshaller[] _marshallers; + private ClientExecutor _executor; + private boolean _followRedirects; + private EntityExtractor _extractor; + private EntityExtractorFactory _extractorFactory; + private ResteasyProviderFactory _providerFactory; + private URI _baseUri; + private Map _attributes = new HashMap(); + + static { + try { + URIBUILDER_CLASS = Class.forName(AS7_URIBUILDER); + } catch (ClassNotFoundException cnfe) { + try { + URIBUILDER_CLASS = Class.forName(WFLY_URIBUILDER); + } catch (ClassNotFoundException e) { + RestEasyLogger.ROOT_LOGGER.unableToFindURIBuilder(e); + } + } + } + + private static URI createUri(String base) { + try { + return new URI(base); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + /** + * Create a RESTEasy invoker client. + * + * @param basePath The base path for the class + * @param resourceClass The JAX-RS Resource Class + * @param method The JAX-RS Resource Class's method + */ + public ClientInvoker(String basePath, Class resourceClass, Method method) { + + this(basePath, resourceClass, method, null); + } + + /** + * Create a RESTEasy invoker client. + * + * @param basePath The base path for the class + * @param resourceClass The JAX-RS Resource Class + * @param method The JAX-RS Resource Class's method + * @param model Configuration model + */ + public ClientInvoker(String basePath, Class resourceClass, Method method, RESTEasyBindingModel model) { + Set httpMethods = IsHttpMethod.getHttpMethods(method); + _baseUri = createUri(basePath); + if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) { + _subResourcePath = createSubResourcePath(basePath, method); + } else if (httpMethods == null || httpMethods.size() != 1) { + throw RestEasyMessages.MESSAGES.youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString()); + } + _httpMethod = httpMethods.iterator().next(); + _resourceClass = resourceClass; + _method = method; + try { + _uri = (UriBuilder)URIBUILDER_CLASS.newInstance(); + } catch (InstantiationException ie) { + throw new RuntimeException(ie); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae); + } + _uri.uri(_baseUri); + if (_resourceClass.isAnnotationPresent(Path.class)) { + _uri.path(_resourceClass); + } + if (_method.isAnnotationPresent(Path.class)) { + _uri.path(_method); + } + + _providerFactory = new ResteasyProviderFactory(); + + boolean useBuiltins = true; // use builtin @Provider classes by default + if (model.getContextParamsConfig() != null) { + Map contextParams = model.getContextParamsConfig().toMap(); + + // Set use builtin @Provider classes + String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS); + if (registerBuiltins != null) { + useBuiltins = Boolean.parseBoolean(registerBuiltins); + } + + // Register @Provider classes + List> providerClasses = RESTEasyUtil.getProviderClasses(contextParams); + if (providerClasses != null) { + for (Class pc : providerClasses) { + _providerFactory.registerProvider(pc); + } + } + + List interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams); + if (interceptors != null) { + for (ClientErrorInterceptor interceptor : interceptors) { + _providerFactory.addClientErrorInterceptor(interceptor); + } + } + } + if (useBuiltins) { + _providerFactory.setRegisterBuiltins(true); + RegisterBuiltin.register(_providerFactory); + } + + _extractorFactory = new DefaultEntityExtractorFactory(); + _extractor = _extractorFactory.createExtractor(_method); + _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null); + _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null); + ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method); + + // Client executor + SchemeRegistry schemeRegistry = new SchemeRegistry(); + int port = _baseUri.getPort(); + if (_baseUri.getScheme().startsWith("https")) { + if (port == -1) { + port = 443; + } + schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, SSLSocketFactory.getSocketFactory())); + } else { + if (port == -1) { + port = 80; + } + schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory())); + } + PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); + cm.setMaxTotal(200); + cm.setDefaultMaxPerRoute(20); + HttpClient httpClient = new DefaultHttpClient(cm); + _executor = new ApacheHttpClient4Executor(httpClient); + // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory + Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0]; + _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType); + + // Authentication settings + if (model.hasAuthentication()) { + // Set authentication + AuthScope authScope = null; + Credentials credentials = null; + if (model.isBasicAuth()) { + authScope = createAuthScope(model.getBasicAuthConfig().getHost(), model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm()); + credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(), model.getBasicAuthConfig().getPassword()); + // Create AuthCache instance + AuthCache authCache = new BasicAuthCache(); + authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()), new BasicScheme(ChallengeState.TARGET)); + BasicHttpContext context = new BasicHttpContext(); + context.setAttribute(ClientContext.AUTH_CACHE, authCache); + ((ApacheHttpClient4Executor)_executor).setHttpContext(context); + } else { + authScope = createAuthScope(model.getNtlmAuthConfig().getHost(), model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm()); + credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(), + model.getNtlmAuthConfig().getPassword(), + "", + model.getNtlmAuthConfig().getDomain()); + } + ((DefaultHttpClient)httpClient).getCredentialsProvider().setCredentials(authScope, credentials); + } else { + ProxyModel proxy = model.getProxyConfig(); + if (proxy != null) { + HttpHost proxyHost = null; + if (proxy.getPort() != null) { + proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue()); + } else { + proxyHost = new HttpHost(proxy.getHost(), -1); + } + if (proxy.getUser() != null) { + AuthScope authScope = new AuthScope(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM); + Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()); + AuthCache authCache = new BasicAuthCache(); + authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY)); + ((DefaultHttpClient)httpClient).getCredentialsProvider().setCredentials(authScope, credentials); + BasicHttpContext context = new BasicHttpContext(); + context.setAttribute(ClientContext.AUTH_CACHE, authCache); + ((ApacheHttpClient4Executor)_executor).setHttpContext(context); + } + httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); + } + } + Integer timeout = model.getTimeout(); + if (timeout != null) { + HttpParams httpParams = httpClient.getParams(); + HttpConnectionParams.setConnectionTimeout(httpParams, timeout); + HttpConnectionParams.setSoTimeout(httpParams, timeout); + } + } + + /** + * Gets a ResteasyProviderFactory instance. + * @return ResteasyProviderFactory + */ + public ResteasyProviderFactory getResteasyProviderFactory() { + return _providerFactory; + } + + private AuthScope createAuthScope(String host, String portStr, String realm) throws RuntimeException { + if (realm == null) { + realm = AuthScope.ANY_REALM; + } + int port = -1; + if (portStr != null) { + port = Integer.valueOf(portStr).intValue(); + } + return new AuthScope(host, port, realm); + } + + private static String createSubResourcePath(String base, Method method) { + if (!base.endsWith("/")) { + base = base + "/"; + } + String path = method.getAnnotation(Path.class).value(); + if (path.startsWith("/")) { + path = path.substring(1); + } + Annotation[][] params = method.getParameterAnnotations(); + int index = 1; + for (Annotation[] param : params) { + for (Annotation a : param) { + if (a instanceof PathParam) { + String name = ((PathParam) a).value(); + path = path.replace("{" + name + "}", "%" + index + "$s"); + break; + } + } + index++; + } + return base + path; + } + + /*public Map getAttributes() { + return _attributes; + } + + public MediaType getAccepts() { + return _accepts; + } + + public Method getMethod() { + return _method; + } + + public Class getDeclaring() { + return _resourceClass; + } + + public ResteasyProviderFactory getProviderFactory() { + return _providerFactory; + }*/ + + @Override + public RESTEasyBindingData invoke(Object[] args, MultivaluedMap headers) { + boolean isProvidersSet = ResteasyProviderFactory.getContextData(Providers.class) != null; + if (!isProvidersSet) { + ResteasyProviderFactory.pushContext(Providers.class, _providerFactory); + } + + try { + if (_uri == null) { + throw RestEasyMessages.MESSAGES.youHaveNotSetABaseURIForTheClientProxy(); + } + + ClientRequest request = null; + + BaseClientResponse clientResponse = null; + try { + request = createRequest(args, headers); + clientResponse = (BaseClientResponse) request.httpMethod(_httpMethod); + } catch (ClientResponseFailure crf) { + clientResponse = (BaseClientResponse) crf.getResponse(); + } catch (Exception e) { + ClientExceptionMapper mapper = _providerFactory.getClientExceptionMapper(Exception.class); + if (mapper != null) { + throw mapper.toException(e); + } else { + throw new RuntimeException(e); + } + } + ClientErrorHandler errorHandler = new ClientErrorHandler(_providerFactory.getClientErrorInterceptors()); + clientResponse.setAttributeExceptionsTo(_method.toString()); + clientResponse.setAnnotations(_method.getAnnotations()); + ClientRequestContext clientRequestContext = new ClientRequestContext(request, clientResponse, errorHandler, _extractorFactory, _baseUri); + Object response = _extractor.extractEntity(clientRequestContext); + RESTEasyBindingData restResponse = new RESTEasyBindingData(); + if (response != null) { + restResponse.setParameters(new Object[]{response}); + } + // Propagate outgoing headers + restResponse.setHeaders(clientResponse.getHeaders()); + restResponse.setStatusCode(clientResponse.getStatus()); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Incoming Headers to SwitchYard through OutboundHandler ["); + RESTEasyProxy.traceLog(LOGGER, clientResponse.getHeaders()); + LOGGER.trace("]"); + } + return restResponse; + } finally { + if (!isProvidersSet) { + ResteasyProviderFactory.popContextData(Providers.class); + } + } + } + + private ClientRequest createRequest(Object[] args, MultivaluedMap headers) { + UriBuilder uriBuilder = _uri; + if (_subResourcePath != null) { + uriBuilder = UriBuilder.fromUri(String.format(_subResourcePath, args)); + } + ClientRequest request = new ClientRequest(uriBuilder, _executor, _providerFactory); + if (_accepts != null) { + request.header(HttpHeaders.ACCEPT, _accepts.toString()); + } + for (Map.Entry> entry : headers.entrySet()) { + String name = entry.getKey(); + List values = entry.getValue(); + for (String value : values) { + request.header(name, value); + } + } + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Outgoing Headers from SwitchYard through OutboundHandler ["); + RESTEasyProxy.traceLog(LOGGER, headers); + LOGGER.trace("]"); + } + this.copyClientInterceptorsTo(request); + + boolean isClientResponseResult = ClientResponse.class.isAssignableFrom(_method.getReturnType()); + request.followRedirects(!isClientResponseResult); + + for (int i = 0; i < _marshallers.length; i++) { + _marshallers[i].build(request, args[i]); + } + return request; + } + + /*public String getHttpMethod() { + return _httpMethod; + } + + public void setHttpMethod(String httpMethod) { + _httpMethod = httpMethod; + } + + public boolean isFollowRedirects() { + return _followRedirects; + } + + public void setFollowRedirects(boolean followRedirects) { + _followRedirects = followRedirects; + } + + public void followRedirects() { + setFollowRedirects(true); + }*/ +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/DefaultMethodInvokerFactory.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/DefaultMethodInvokerFactory.java new file mode 100644 index 000000000..88afe5f75 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/DefaultMethodInvokerFactory.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.util; + +import java.lang.reflect.Method; + +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; + +/** + * A default factory class to create MInvoker for the RESTEasy outbound invocation. + */ +public class DefaultMethodInvokerFactory implements MethodInvokerFactory { + + @Override + public MethodInvoker createInvoker(String basePath, Class resourceClass, Method method, RESTEasyBindingModel model) { + return new ClientInvoker(basePath, resourceClass, method, model); + } + +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/MethodInvoker.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/MethodInvoker.java new file mode 100644 index 000000000..c5b16fa37 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/MethodInvoker.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.util; + +import javax.ws.rs.core.MultivaluedMap; + +import org.switchyard.component.resteasy.composer.RESTEasyBindingData; + +/** + * Client Invoker interface for RESTEasy. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface MethodInvoker { + + /** + * Invokes the JAX-RS method. + * + * @param args the method arguments + * @param headers the HTTP headers to be set on the request + * @return the method's response entity and headers wrapped in RESTEasyBindingData + */ + RESTEasyBindingData invoke(Object[] args, MultivaluedMap headers); +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/MethodInvokerFactory.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/MethodInvokerFactory.java new file mode 100644 index 000000000..627b6dd00 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/MethodInvokerFactory.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.util; + +import java.lang.reflect.Method; + +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; + +/** + * A factory class to create MethodInvoker for the resteasy outbound invocation. + */ +public interface MethodInvokerFactory { + + /** + * Creates a MethodInvoker instance. + * @param basePath base path + * @param resourceClass resource class + * @param method method + * @param model RESTEasyBindingModel + * @return MethodInvoker + */ + public MethodInvoker createInvoker(String basePath, Class resourceClass, Method method, RESTEasyBindingModel model); +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/RESTEasyProxy.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/RESTEasyProxy.java new file mode 100644 index 000000000..472eef001 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/RESTEasyProxy.java @@ -0,0 +1,166 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.util; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; + +import org.jboss.logging.Logger; +import org.jboss.resteasy.plugins.server.servlet.ServletSecurityContext; +import org.jboss.resteasy.spi.ResteasyProviderFactory; +import org.switchyard.common.type.reflect.Access; +import org.switchyard.common.type.reflect.FieldAccess; +import org.switchyard.component.resteasy.InboundHandler; +import org.switchyard.component.resteasy.composer.RESTEasyBindingData; + +/** + * A proxy for RESTEasy instances. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public final class RESTEasyProxy implements InvocationHandler { + + private static final Logger LOGGER = Logger.getLogger(RESTEasyProxy.class); + + private static final Access SERVLET_REQUEST_ACCESS; + static { + final Access servletRequestAccess = new FieldAccess(ServletSecurityContext.class, "request"); + SERVLET_REQUEST_ACCESS = servletRequestAccess.isReadable() ? servletRequestAccess : null; + } + + private InboundHandler _serviceConsumer; + + /** + * Create a RESTEasy proxy instance. + * + * @param serviceConsumer the SwitchYard handler + * @param interfaze the RESTEasy resource class + * @return the proxy instance + */ + public static Object newInstance(final InboundHandler serviceConsumer, Class interfaze) { + return Proxy.newProxyInstance(interfaze.getClassLoader(), + new Class[] {interfaze}, + new RESTEasyProxy(serviceConsumer)); + } + + private RESTEasyProxy(final InboundHandler serviceConsumer) { + _serviceConsumer = serviceConsumer; + } + + /** + * Sets the service handler. + * @param serviceConsumer the service handler. + */ + public void setConsumer(final InboundHandler serviceConsumer) { + _serviceConsumer = serviceConsumer; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String methodName = method.getName(); + if (methodName.equals("toString")) { + return this.toString(); + } else if (methodName.equals("equals")) { + return this.equals(proxy); + } else if (methodName.equals("hashCode")) { + return this.hashCode(); + } + RESTEasyBindingData requestData = new RESTEasyBindingData(); + HttpHeaders headers = ResteasyProviderFactory.getContextData(HttpHeaders.class); + if (headers != null) { + requestData.setHeaders(headers.getRequestHeaders()); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Incoming Headers to SwitchYard through InboundHandler ["); + traceLog(LOGGER, headers.getRequestHeaders()); + LOGGER.trace("]"); + } + } + SecurityContext securityContext = ResteasyProviderFactory.getContextData(SecurityContext.class); + if (securityContext != null) { + if (securityContext instanceof ServletSecurityContext && SERVLET_REQUEST_ACCESS != null) { + HttpServletRequest servletRequest = SERVLET_REQUEST_ACCESS.read((ServletSecurityContext)securityContext); + requestData.setServletRequest(servletRequest); + } + requestData.setSecured(securityContext.isSecure()); + requestData.setPrincipal(securityContext.getUserPrincipal()); + } + requestData.setOperationName(methodName); + if ((args != null) && (args.length > 0)) { + requestData.setParameters(args); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace(args); + } + } + RESTEasyBindingData responseData = _serviceConsumer.invoke(requestData, method.getReturnType().equals(Void.TYPE)); + Response.ResponseBuilder builder = Response.ok(); + if (responseData != null) { + if (method.getReturnType().equals(Response.class)) { + if (responseData.getParameters().length > 0) { + Object param = responseData.getParameters()[0]; + if (param instanceof Response) { + // In future use builder = Response.ResponseBuilder.fromResponse((Response)param); + Response response = (Response)param; + builder.entity(response.getEntity()); + builder.status(response.getStatus()); + } else { + builder.entity(param); + } + } + // Data overrides status + if (responseData.getStatusCode() != null) { + builder.status(responseData.getStatusCode()); + } + for (Map.Entry> entry : responseData.getHeaders().entrySet()) { + String name = entry.getKey(); + List values = entry.getValue(); + for (String value : values) { + builder.header(name, value); + } + } + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Outgoing Headers from SwitchYard through InboundHandler ["); + traceLog(LOGGER, responseData.getHeaders()); + LOGGER.trace("]"); + } + } else if (responseData.getParameters().length > 0) { + return responseData.getParameters()[0]; + } + } + return builder.build(); + } + + /** + * Trace log header keys and values. + * @param logger The Logger + * @param headers The header map + */ + public static void traceLog(final Logger logger, final Map> headers) { + for (Map.Entry> entry : headers.entrySet()) { + String name = entry.getKey(); + List values = entry.getValue(); + for (String value : values) { + logger.trace(name + " = " + value); + } + } + } +} diff --git a/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/RESTEasyUtil.java b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/RESTEasyUtil.java new file mode 100644 index 000000000..0f7280006 --- /dev/null +++ b/components/resteasy/src/main/java/org/switchyard/component/resteasy/util/RESTEasyUtil.java @@ -0,0 +1,131 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.util; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.ext.ExceptionMapper; + +import org.jboss.logging.Logger; +import org.jboss.resteasy.client.core.ClientErrorInterceptor; +import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; +import org.jboss.resteasy.util.Types; +import org.switchyard.common.type.Classes; + +/** + * Utility class that recognizes RESTEasy providers and client interceptors from context params. + */ +public final class RESTEasyUtil { + + private static final Logger LOGGER = Logger.getLogger(RESTEasyUtil.class); + + private static final String CLIENT_ERROR_INTERCEPTORS = "resteasy.client.error.interceptors"; + + private RESTEasyUtil() { + } + + /** + * Finds the RESTEasy parameter and return its value as list of class names. + * + * @param contextParams the map of all context parameters + * @param paramName the name of the context parameter + * @return a List of RESTEasy parmaters or null if not present + */ + public static List getParamValues(Map contextParams, String paramName) { + if (contextParams != null) { + String providers = contextParams.get(paramName); + if (providers != null) { + return Arrays.asList(providers.split(",")); + } + } + return null; + } + + /** + * Finds the RESTEasy providers parameter and return its value as list of classes. + * + * @param contextParams the map of all context parameters + * @return a List of RESTEasy provider classes or null if not present + */ + public static List> getProviderClasses(Map contextParams) { + List providers = getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS); + if (providers != null) { + List> providerClasses = new ArrayList>(providers.size()); + for (String provider : providers) { + Class pc = Classes.forName(provider.trim()); + if (pc != null) { + providerClasses.add(pc); + } + } + return providerClasses.isEmpty() ? null : providerClasses; + } + return null; + } + + /** + * Finds the RESTEasy providers parameter and return its value as map of classes with its generic types. + * + * @param contextParams the map of all context parameters + * @return a Map of RESTEasy exception-provider classes + */ + public static Map, Class> getExceptionProviderMap(Map contextParams) { + Map, Class> providerMap = new HashMap, Class>(); + List providers = getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS); + if (providers != null) { + for (String provider : providers) { + Class providerClass = Classes.forName(provider.trim()); + if (providerClass != null) { + Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(providerClass, ExceptionMapper.class)[0]; + Class exceptionClass = Types.getRawType(exceptionType); + providerMap.put(exceptionClass, providerClass); + } + } + } + return providerMap; + } + + /** + * Finds the RESTEasy client error interceptor parameter and return its value as list of instances. + * + * @param contextParams the map of all context parameters + * @return a List of RESTEasy client interceptor instances or null if not present + */ + public static List getClientErrorInterceptors(Map contextParams) { + List interceptorInstances = null; + List interceptors = getParamValues(contextParams, CLIENT_ERROR_INTERCEPTORS); + if (interceptors != null) { + interceptorInstances = new ArrayList(interceptors.size()); + for (String interceptor : interceptors) { + Class ic = Classes.forName(interceptor.trim()); + if (ic != null) { + try { + ClientErrorInterceptor instance = (ClientErrorInterceptor) ic.newInstance(); + interceptorInstances.add(instance); + } catch (InstantiationException ie) { + LOGGER.warn(ie); + } catch (IllegalAccessException iae) { + LOGGER.warn(iae); + } + } + } + } + return interceptorInstances; + } + +} diff --git a/components/resteasy/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory b/components/resteasy/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory new file mode 100644 index 000000000..cba38e8ab --- /dev/null +++ b/components/resteasy/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.resteasy.composer.RESTEasyContextMapperFactory diff --git a/components/resteasy/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory b/components/resteasy/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory new file mode 100644 index 000000000..5ecae24df --- /dev/null +++ b/components/resteasy/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.resteasy.composer.RESTEasyMessageComposerFactory diff --git a/components/resteasy/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/resteasy/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..e28706196 --- /dev/null +++ b/components/resteasy/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.resteasy.deploy.RESTEasyComponent diff --git a/components/resteasy/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/components/resteasy/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 000000000..283b64573 --- /dev/null +++ b/components/resteasy/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v1/resteasy_1_0.xsd b/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v1/resteasy_1_0.xsd new file mode 100644 index 000000000..5aa5fe201 --- /dev/null +++ b/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v1/resteasy_1_0.xsd @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + A comma separated list of interfaces or abstract/empty classes with REST annotations. + + + + + + A URI string that represents the root context where this service is hosted. + + + + + + A URL that points to the root path of resources. This is only applicable for Reference bindings. It is optional and if not specified will default to http://127.0.0.1:8080/. + + + + + + + + + Http proxy settings. + + + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + Authentication Realm. + + + + + Authentication Host. + + + + + Authentication Port. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Host. + + + + + Proxy Port. + + + + + + + + diff --git a/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v1/resteasy_1_1.xsd b/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v1/resteasy_1_1.xsd new file mode 100644 index 000000000..1fa0486fb --- /dev/null +++ b/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v1/resteasy_1_1.xsd @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + A comma separated list of interfaces or abstract/empty classes with REST annotations. + + + + + + A URI string that represents the root context where this service is hosted. + + + + + + A URL that points to the root path of resources. This is only applicable for Reference bindings. It is optional and if not specified will default to http://127.0.0.1:8080/. + + + + + The request's time-out value in milliseconds. + + + + + + + + + Http proxy settings. + + + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + Authentication Realm. + + + + + Authentication Host. + + + + + Authentication Port. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Host. + + + + + Proxy Port. + + + + + Proxy user name. + + + + + Proxy password. + + + + + + + + diff --git a/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v2/resteasy_2_0.xsd b/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v2/resteasy_2_0.xsd new file mode 100644 index 000000000..e09bfac0b --- /dev/null +++ b/components/resteasy/src/main/resources/org/switchyard/component/resteasy/config/model/v2/resteasy_2_0.xsd @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + A comma separated list of interfaces or abstract/empty classes with REST annotations. + + + + + + A URI string that represents the root context where this service is hosted. + + + + + + A URL that points to the root path of resources. This is only applicable for Reference bindings. It is optional and if not specified will default to http://127.0.0.1:8080/. + + + + + The request's time-out value in milliseconds. + + + + + + + + + Http proxy settings. + + + + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + Authentication Realm. + + + + + Authentication Host. + + + + + Authentication Port. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Host. + + + + + Proxy Port. + + + + + Proxy user name. + + + + + Proxy password. + + + + + + + + + + + + + + Context parameters. + + + + + + + + + + + + diff --git a/components/resteasy/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/resteasy/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..5e7c6dca0 --- /dev/null +++ b/components/resteasy/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +resteasy_1_0.section=urn:switchyard-component-resteasy:config +resteasy_1_0.version=1.0 +resteasy_1_0.namespace=urn:switchyard-component-resteasy:config:1.0 +resteasy_1_0.schema=resteasy_1_0.xsd +resteasy_1_0.location=/org/switchyard/component/resteasy/config/model/v1/ +resteasy_1_0.marshaller=org.switchyard.component.resteasy.config.model.v1.V1RESTEasyMarshaller + +resteasy_1_1.section=urn:switchyard-component-resteasy:config +resteasy_1_1.version=1.1 +resteasy_1_1.namespace=urn:switchyard-component-resteasy:config:1.1 +resteasy_1_1.schema=resteasy_1_1.xsd +resteasy_1_1.location=/org/switchyard/component/resteasy/config/model/v1/ +resteasy_1_1.marshaller=org.switchyard.component.resteasy.config.model.v1.V1RESTEasyMarshaller + +resteasy_2_0.section=urn:switchyard-component-resteasy:config +resteasy_2_0.version=2.0 +resteasy_2_0.namespace=urn:switchyard-component-resteasy:config:2.0 +resteasy_2_0.schema=resteasy_2_0.xsd +resteasy_2_0.location=/org/switchyard/component/resteasy/config/model/v2/ +resteasy_2_0.marshaller=org.switchyard.component.resteasy.config.model.v2.V2RESTEasyMarshaller diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/AnotherCustomMapper.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/AnotherCustomMapper.java new file mode 100644 index 000000000..241db085c --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/AnotherCustomMapper.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy; + +import org.switchyard.Context; +import org.switchyard.component.resteasy.composer.RESTEasyBindingData; +import org.switchyard.component.resteasy.composer.RESTEasyContextMapper; + + +/** + * Custom ContextMapper. + * + * @author Magesh Kumar B © 2013 Red Hat Inc. + */ +public class AnotherCustomMapper extends RESTEasyContextMapper { + + /** + * {@inheritDoc} + */ + @Override + public void mapTo(Context context, RESTEasyBindingData target) throws Exception { + // delegate to parent to pick up existing context mapping logic for RESTEasy + super.mapTo(context, target); + // add a custom header + target.addHeader("bar", "123"); + target.addHeader("bar", "456"); + } + +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/AuthenticationTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/AuthenticationTest.java new file mode 100644 index 000000000..685d0da9f --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/AuthenticationTest.java @@ -0,0 +1,157 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.HashSet; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.component.resteasy.config.model.NtlmAuthModel; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNamespace; +import org.switchyard.component.resteasy.config.model.v1.V1NtlmAuthModel; +import org.switchyard.component.resteasy.config.model.v1.V1RESTEasyBindingModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; + +/** + * Contains tests for Http authentication support on RESTEasyGateway. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class AuthenticationTest { + + private static final String METHOD_NAME = "addGreeter"; + + private static final String input = "Magesh"; + private static final String output = ""; + + private ServiceDomain _domain; + + @org.switchyard.test.ServiceOperation("auth-required") + private Invoker _authConsumerService1; + @org.switchyard.test.ServiceOperation("all-is-well") + private Invoker _authConsumerService2; + + private RESTEasyBindingModel _config; + private InboundHandler _resteasyInbound; + + private static ModelPuller _puller; + + + @Before + public void setUp() throws Exception { + String host = System.getProperty("org.switchyard.test.resteasy.host", "localhost"); + String port = System.getProperty("org.switchyard.test.resteasy.port", "8080"); + + _puller = new ModelPuller(); + + // Provide a switchyard service + CompositeModel composite = _puller.pull("/HelloSwitchYard.xml", getClass()); + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (RESTEasyBindingModel)compositeService.getBindings().get(0); + _domain.registerService(_config.getServiceName(), new HelloWebServiceInterface(), new MockHandler().forwardInToOut()); + _domain.registerServiceReference(_config.getServiceName(), new HelloWebServiceInterface()); + + // Service exposed as WS + _resteasyInbound = new InboundHandler(_config, _domain); + _resteasyInbound.start(); + + RESTEasyBindingModel config = new V1RESTEasyBindingModel(RESTEasyNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config.setServiceName(_authConsumerService1.getServiceName()); + config.setName("auth-test"); + config.setInterfaces("org.switchyard.component.resteasy.HelloResource"); + config.setAddress("http://192.168.169.4/"); + + // Service consumer or Reference binding + OutboundHandler resteasyProxyOutbound1 = new OutboundHandler(config, null); + resteasyProxyOutbound1.start(); + _domain.registerService(_authConsumerService1.getServiceName(), new HelloWebServiceInterface(), resteasyProxyOutbound1); + + NtlmAuthModel auth = new V1NtlmAuthModel(RESTEasyNamespace.DEFAULT.uri()); + auth.setUser("SwitchYard"); + auth.setPassword("JBoss123!"); + auth.setDomain("JBOSS"); + config.setNtlmAuthConfig(auth); + config.setServiceName(_authConsumerService2.getServiceName()); + + // Service consumer or Reference binding + OutboundHandler resteasyProxyOutbound2 = new OutboundHandler(config, null); + resteasyProxyOutbound2.start(); + _domain.registerService(_authConsumerService2.getServiceName(), new HelloWebServiceInterface(), resteasyProxyOutbound2); + } + + @After + public void tearDown() throws Exception { + _resteasyInbound.stop(); + } + + @Ignore // This can be tested only offline. + @Test + public void authenticationMissing() throws Exception { + try { + Message responseMsg = _authConsumerService1.operation(METHOD_NAME).sendInOut(input); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("401 Unauthorized")); + } + } + + @Ignore // This can be tested only offline. + @Test + public void allIsWell() throws Exception { + try { + Message responseMsg = _authConsumerService2.operation(METHOD_NAME).sendInOut(input); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("Error status 501")); + } + } + + private static class HelloWebServiceInterface extends BaseService { + private static Set _operations = new HashSet(1); + static { + _operations.add(new InOutOperation(METHOD_NAME)); + } + public HelloWebServiceInterface() { + super(_operations); + } + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/CustomMapper.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/CustomMapper.java new file mode 100644 index 000000000..8eb9c690a --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/CustomMapper.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy; + +import org.switchyard.Context; +import org.switchyard.component.resteasy.composer.RESTEasyBindingData; +import org.switchyard.component.resteasy.composer.RESTEasyContextMapper; + + +/** + * Custom ContextMapper. + * + * @author Magesh Kumar B © 2013 Red Hat Inc. + */ +public class CustomMapper extends RESTEasyContextMapper { + + /** + * {@inheritDoc} + */ + @Override + public void mapTo(Context context, RESTEasyBindingData target) throws Exception { + // delegate to parent to pick up existing context mapping logic for RESTEasy + super.mapTo(context, target); + // add a custom header + target.addHeader("foo", "123"); + } + +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/HelloResource.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/HelloResource.java new file mode 100644 index 000000000..56be1badd --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/HelloResource.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +/** + * A Greeter Resource. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +@Path("/greeters") +@Consumes("text/plain") +public interface HelloResource { + + @PUT + @Path("{name}") + String addGreeter(@PathParam("name") String name); + + @GET + @Path("{name}") + String greeterInfo(@PathParam("name") String name); + + @GET + @Path("/response") + Response testReponse(); + + /** + * A multi parameter test. A url will be of the form /greeters/name and anotherName will be in the request body. + */ + @POST + @Path("{name}") + String sayHello(String anotherName); +} \ No newline at end of file diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/HttpProxyTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/HttpProxyTest.java new file mode 100644 index 000000000..ad912fa52 --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/HttpProxyTest.java @@ -0,0 +1,202 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.littleshoot.proxy.DefaultHttpProxyServer; +import org.littleshoot.proxy.HttpProxyServer; +import org.littleshoot.proxy.ProxyAuthorizationHandler; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.component.resteasy.config.model.ProxyModel; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.resteasy.config.model.RESTEasyNamespace; +import org.switchyard.component.resteasy.config.model.v1.V1ProxyModel; +import org.switchyard.component.resteasy.config.model.v1.V1RESTEasyBindingModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; + +/** + * Contains tests for Http proxy support on RESTEasy Gateway. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class HttpProxyTest { + + private static final QName STRING_QNAME = new QName("java:java.lang.String"); + private static final int PROXYPORT = 9090; + private static final String PROXY_USER = "foo"; + private static final String PROXY_PWD = "bar"; + private static final String METHOD_NAME = "addGreeter"; + private static final String INPUT = "Beal"; + + private ServiceDomain _domain; + + @org.switchyard.test.ServiceOperation("unknown-host") + private Invoker _proxyConsumerService1; + @org.switchyard.test.ServiceOperation("proxy-auth-required") + private Invoker _proxyConsumerService2; + @org.switchyard.test.ServiceOperation("all-is-well") + private Invoker _proxyConsumerService3; + + private RESTEasyBindingModel _config; + private InboundHandler _resteasyInbound; + private OutboundHandler _resteasyProxyOutbound1; + private OutboundHandler _resteasyProxyOutbound2; + private OutboundHandler _resteasyProxyOutbound3; + + private static ModelPuller _puller; + private HttpProxyServer _proxyServer; + + + @Before + public void setUp() throws Exception { + String host = System.getProperty("org.switchyard.test.resteasy.host", "localhost"); + String port = System.getProperty("org.switchyard.test.resteasy.port", "8080"); + _proxyServer = new DefaultHttpProxyServer(PROXYPORT); + ProxyAuthorizationHandler authorizationHandler = new ProxyAuthorizationHandler() { + @Override + public boolean authenticate(String user, String pwd) { + return (PROXY_USER.equals(user) && PROXY_PWD.equals(pwd)); + } + }; + _proxyServer.addProxyAuthenticationHandler(authorizationHandler); + _proxyServer.start(); + + _puller = new ModelPuller(); + + // Provide a switchyard service + CompositeModel composite = _puller.pull("/HelloSwitchYard.xml", getClass()); + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (RESTEasyBindingModel)compositeService.getBindings().get(0); + _domain.registerService(_config.getServiceName(), new HelloRESTEasyInterface(), new MockHandler().forwardInToOut()); + _domain.registerServiceReference(_config.getServiceName(), new HelloRESTEasyInterface()); + + // Service exposed as WS + _resteasyInbound = new InboundHandler(_config, _domain); + _resteasyInbound.start(); + + RESTEasyBindingModel config = new V1RESTEasyBindingModel(RESTEasyNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config.setServiceName(_proxyConsumerService1.getServiceName()); + config.setName("proxy-test"); + config.setInterfaces("org.switchyard.component.resteasy.HelloResource"); + config.setAddress("http://unreachablehost"); + + // Service consumer or Reference binding + _resteasyProxyOutbound1 = new OutboundHandler(config, null); + _resteasyProxyOutbound1.start(); + _domain.registerService(_proxyConsumerService1.getServiceName(), new HelloRESTEasyInterface(), _resteasyProxyOutbound1); + + ProxyModel proxy = new V1ProxyModel(RESTEasyNamespace.DEFAULT.uri()); + proxy.setHost(host); + proxy.setPort("" + PROXYPORT); + config.setAddress("http://" + host + ":" + port); + config.setProxyConfig(proxy); + config.setServiceName(_proxyConsumerService2.getServiceName()); + + // Service consumer or Reference binding + _resteasyProxyOutbound2 = new OutboundHandler(config, null); + _resteasyProxyOutbound2.start(); + _domain.registerService(_proxyConsumerService2.getServiceName(), new HelloRESTEasyInterface(), _resteasyProxyOutbound2); + + proxy.setUser(PROXY_USER); + proxy.setPassword(PROXY_PWD); + config.setProxyConfig(proxy); + config.setServiceName(_proxyConsumerService3.getServiceName()); + + // Service consumer or Reference binding + _resteasyProxyOutbound3 = new OutboundHandler(config, null); + _resteasyProxyOutbound3.start(); + _domain.registerService(_proxyConsumerService3.getServiceName(), new HelloRESTEasyInterface(), _resteasyProxyOutbound3); + + } + + @After + public void tearDown() throws Exception { + _resteasyInbound.stop(); + _resteasyProxyOutbound1.stop(); + _resteasyProxyOutbound2.stop(); + _resteasyProxyOutbound3.stop(); + _proxyServer.stop(); + } + + @Test + public void unknownHost() throws Exception { + try { + Message responseMsg = _proxyConsumerService1.operation(METHOD_NAME).sendInOut(INPUT); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("org.apache.http.NoHttpResponseException: unreachablehost") + || baos.toString().contains("UnknownHostException: unreachablehost")); + } + } + + @Test + public void authenticationMissing() throws Exception { + try { + Message responseMsg = _proxyConsumerService2.operation(METHOD_NAME).sendInOut(INPUT); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("Error status 407 null returned")); + // Newer version returns correct string e.g. WildFly's RESTEasy + // Assert.assertTrue(baos.toString().contains("Error status 407 Proxy Authentication Required returned")); + } + } + + @Ignore // Can be tested offline. + @Test + public void allIsWell() throws Exception { + Message responseMsg = _proxyConsumerService3.operation(METHOD_NAME).sendInOut(INPUT); + String response = responseMsg.getContent(String.class); + } + + private static class HelloRESTEasyInterface extends BaseService { + private static Set _operations = new HashSet(1); + static { + _operations.add(new InOutOperation(METHOD_NAME, STRING_QNAME, STRING_QNAME)); + } + public HelloRESTEasyInterface() { + super(_operations); + } + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/RESTEasyGatewayTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/RESTEasyGatewayTest.java new file mode 100644 index 000000000..be707e9b0 --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/RESTEasyGatewayTest.java @@ -0,0 +1,190 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; + +import com.sun.net.httpserver.HttpContext; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +/** + * Contains tests for RESTEasy Gateway. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyGatewayTest { + + private static final QName STRING_QNAME = new QName("java:java.lang.String"); + private static final QName RESPONSE_QNAME = new QName("javax.ws.rs.core.Response"); + private static ModelPuller _puller; + private ServiceDomain _domain; + private final HTTPMixIn _httpMixIn = new HTTPMixIn(); + + private Invoker _consumerService; + private Invoker _consumerService2; + + private RESTEasyBindingModel _config; + private RESTEasyBindingModel _configRef; + private InboundHandler _restInbound; + private OutboundHandler _restOutbound; + private OutboundHandler _restOutbound2; + private final MockHandler mockService = new MockHandler().forwardInToOut(); + + private final static int PORT = 6080; + + @Before + public void setUp() throws Exception { + System.setProperty("org.switchyard.component.resteasy.standalone.port", PORT + ""); + _httpMixIn.initialize(); + _domain = new ServiceDomainManager().createDomain(); + _consumerService = new Invoker(_domain, QName.valueOf("{urn:resteasy:test:1.1}SampleRESTEasyConsumerService")); + _consumerService2 = new Invoker(_domain, QName.valueOf("{urn:resteasy:test:1.1}TimeoutConsumerService")); + + _puller = new ModelPuller(); + CompositeModel composite = _puller.pull("/HelloSwitchYard.xml", getClass()); + composite.assertModelValid(); + + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (RESTEasyBindingModel)compositeService.getBindings().get(0); + + // Massive hack for Test Runner. Register both a service and a reference binding. + + _domain.registerService(_config.getServiceName(), new HelloRESTEasyInterface(), mockService); + _domain.registerServiceReference(_config.getServiceName(), new HelloRESTEasyInterface()); + _restInbound = new InboundHandler(_config, _domain); + + CompositeReferenceModel compositeReference = composite.getReferences().get(0); + _configRef = (RESTEasyBindingModel)compositeReference.getBindings().get(0); + + _restOutbound = new OutboundHandler(_configRef, null); + // Massive hack for Test Runner. Register both a service and a reference binding. + _domain.registerService(_configRef.getServiceName(), new HelloRESTEasyInterface(), _restOutbound); + _domain.registerServiceReference(_configRef.getServiceName(), new HelloRESTEasyInterface()); + + _configRef = (RESTEasyBindingModel)composite.getReferences().get(1).getBindings().get(0); + _restOutbound2 = new OutboundHandler(_configRef, null); + // Massive hack for Test Runner. Register both a service and a reference binding. + _domain.registerService(_configRef.getServiceName(), new HelloRESTEasyInterface(), _restOutbound2); + _domain.registerServiceReference(_configRef.getServiceName(), new HelloRESTEasyInterface()); + + _restInbound.start(); + _restOutbound.start(); + _restOutbound2.start(); + } + + @After + public void tearDown() throws Exception { + _restInbound.stop(); + _restOutbound.stop(); + _restOutbound2.stop(); + } + + private String getBaseURL() { + return "http://localhost:" + PORT; + } + + @Test + public void restGatewayServiceTest() throws Exception { + _httpMixIn.setContentType("text/plain"); + String baseURL = getBaseURL(); + String response = _httpMixIn.sendString(baseURL + "/greeters/magesh", "", HTTPMixIn.HTTP_PUT); + Assert.assertEquals(1, mockService.getMessages().size()); + Assert.assertEquals("magesh", response); + response = _httpMixIn.sendString(baseURL + "/greeters/keith", "", HTTPMixIn.HTTP_GET); + Assert.assertEquals(2, mockService.getMessages().size()); + Assert.assertEquals("keith", response); + response = _httpMixIn.sendString(baseURL + "/greeters/magesh", "keith", HTTPMixIn.HTTP_POST); + Assert.assertEquals(3, mockService.getMessages().size()); + Assert.assertEquals("keith", response); + response = _httpMixIn.sendString(baseURL + "/greeters/response", "", HTTPMixIn.HTTP_GET); + Assert.assertEquals(4, mockService.getMessages().size()); + } + + @Test + public void restGatewayReferenceTest() throws Exception { + Message responseMsg = _consumerService.operation("addGreeter").sendInOut("magesh"); + Assert.assertEquals("magesh", responseMsg.getContent(String.class)); + responseMsg = _consumerService.operation("greeterInfo").sendInOut("keith"); + Assert.assertEquals("keith", responseMsg.getContent(String.class)); + + // This cannot be tested by design of SwitchYard, as it does not allow multiple parameters + /*responseMsg = _consumerService.operation("sayHello").sendInOut("keith"); + Assert.assertEquals("keith", responseMsg.getContent(String.class));*/ + } + + @Test + public void restGatewayReferenceTimeout() throws Exception { + HttpServer httpServer = HttpServer.create(new InetSocketAddress(8090), 10); + httpServer.setExecutor(null); // creates a default executor + httpServer.start(); + HttpContext httpContext = httpServer.createContext("/forever", new HttpHandler() { + @Override + public void handle(HttpExchange exchange) { + try { + Thread.sleep(10000); + } catch (InterruptedException ie) { + //Ignore + }}}); + try { + Message responseMsg = _consumerService2.operation("addGreeter").sendInOut("magesh"); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("SocketTimeoutException: Read timed out")); + } + httpServer.stop(0); + } + + private static class HelloRESTEasyInterface extends BaseService { + private static Set _operations = new HashSet(3); + static { + _operations.add(new InOutOperation("addGreeter", STRING_QNAME, STRING_QNAME)); + _operations.add(new InOutOperation("greeterInfo", STRING_QNAME, STRING_QNAME)); + _operations.add(new InOutOperation("sayHello", STRING_QNAME, STRING_QNAME)); + _operations.add(new InOutOperation("testResponse", STRING_QNAME, RESPONSE_QNAME)); + } + public HelloRESTEasyInterface() { + super(_operations); + } + } +} + diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapperTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapperTest.java new file mode 100644 index 000000000..3c6ca74d3 --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/composer/RESTEasyContextMapperTest.java @@ -0,0 +1,75 @@ +package org.switchyard.component.resteasy.composer; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Context; +import org.switchyard.internal.DefaultContext; + +/** + * + * Test for SWITCHYARD-1990 to determine whether we are succesfully mapping non-Strings + * from the Context to Strings in the binding data. + * + * @author tcunning + */ +public class RESTEasyContextMapperTest { + + @Before + public void setUp() throws Exception { + } + + /* + * Test for SWITCHYARD-1990 to determine whether we are succesfully mapping non-Strings + * from the Context to Strings in the binding data. + */ + @Test + public void mapToTest() throws Exception { + RESTEasyContextMapper rcm = new RESTEasyContextMapper(); + RESTEasyBindingData rbd = new RESTEasyBindingData(); + + Context context = new DefaultContext(); + context.setProperty("one", Integer.valueOf(1)); + + rcm.mapTo(context, rbd); + Iterator>> entries = rbd.getHeaders().entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry> entry = entries.next(); + List values = entry.getValue(); + Assert.assertTrue(values.size() == 1); + Assert.assertTrue(entry.getKey().equals("one")); + Assert.assertTrue(values.get(0).equals("1")); + } + + RESTEasyBindingData rbd2 = new RESTEasyBindingData(); + context.removeProperties(); + List list = new ArrayList(); + list.add(Integer.valueOf(1)); + list.add(Integer.valueOf(2)); + list.add(Integer.valueOf(3)); + context.setProperty("numbers", list); + rcm.mapTo(context, rbd2); + entries = rbd2.getHeaders().entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry> entry = entries.next(); + List values = entry.getValue(); + Assert.assertTrue(values.size() == 3); + Assert.assertTrue(entry.getKey().equals("numbers")); + for (String value : values) { + Assert.assertTrue(values.get(0).equals("1") || values.get(1).equals("2") || + values.get(1).equals("3")); + } + } + } + + @After + public void tearDown() throws Exception { + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/config/model/RESTEasyConfigModelTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/config/model/RESTEasyConfigModelTest.java new file mode 100644 index 000000000..9d91677c8 --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/config/model/RESTEasyConfigModelTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.config.model; + +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; + +/** + * Test of rest binding model. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyConfigModelTest { + + private static final String REST_BINDING = "rest-binding.xml"; + private static final String REST_BINDING_REFERENCE = "rest-binding-reference.xml"; + private static final String REST_BINDING_INVALID = "rest-binding-invalid.xml"; + private static final String REST_BINDING_AUTH = "rest-binding-auth.xml"; + private static final String REST_BINDING_PROXY = "rest-binding-proxy.xml"; + private static final String REST_BINDING_CONTEXT_PARAMS = "rest-binding-context-params.xml"; + + @Test + public void testReadConfigBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + RESTEasyBindingModel model = puller.pull(REST_BINDING, getClass()); + Assert.assertTrue(model.isModelValid()); + model = puller.pull(REST_BINDING_INVALID, getClass()); + Assert.assertFalse(model.isModelValid()); + } + + @Test + public void testReadReferenceBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + RESTEasyBindingModel model = puller.pull(REST_BINDING_REFERENCE, getClass()); + Assert.assertTrue(model.isModelValid()); + Assert.assertEquals(new Integer(5000), model.getTimeout()); + } + + @Test + public void authBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + RESTEasyBindingModel binding = puller.pull(REST_BINDING_AUTH, getClass()); + binding.assertModelValid(); + NtlmAuthModel authConfig = binding.getNtlmAuthConfig(); + Assert.assertEquals("user", authConfig.getUser()); + Assert.assertEquals("password", authConfig.getPassword()); + Assert.assertEquals("domain", authConfig.getDomain()); + } + + @Test + public void proxyConfigBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + RESTEasyBindingModel model = puller.pull(REST_BINDING_PROXY, getClass()); + model.assertModelValid(); + ProxyModel proxyConfig = model.getProxyConfig(); + Assert.assertNotNull(proxyConfig); + Assert.assertEquals("host", proxyConfig.getHost()); + Assert.assertEquals("8090", proxyConfig.getPort()); + Assert.assertEquals("Beal", proxyConfig.getUser()); + Assert.assertEquals("conjecture", proxyConfig.getPassword()); + } + + @Test + public void testReadConfigBindingWithContextParams() throws Exception { + ModelPuller puller = new ModelPuller(); + RESTEasyBindingModel model = puller.pull(REST_BINDING_CONTEXT_PARAMS, getClass()); + Assert.assertTrue(model.isModelValid()); + + List contextParams = model.getContextParamsConfig().getContextParams(); + Assert.assertEquals(2, contextParams.size()); + + Assert.assertEquals("resteasy.providers", contextParams.get(0).getName()); + Assert.assertEquals("org.switchyard.quickstarts.rest.binding.TestResourceExceptionMapper", contextParams.get(0).getValue()); + + Assert.assertEquals("resteasy.use.builtin.providers", contextParams.get(1).getName()); + Assert.assertEquals("true", contextParams.get(1).getValue()); + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/ContextParamResource.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/ContextParamResource.java new file mode 100644 index 000000000..11a90f92c --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/ContextParamResource.java @@ -0,0 +1,36 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.context; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Path("/context-params") +public interface ContextParamResource { + + @POST + @Consumes(MediaType.TEXT_PLAIN) + @Produces(MediaType.TEXT_PLAIN) + Response create(String payload); + + @PUT + @Consumes(SyTxtMessageBodyRW.MEDIA_TYPE) + @Produces(SyTxtMessageBodyRW.MEDIA_TYPE) + Response createWithOwnMediaType(String payload); +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/RESTEasyContextParamsTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/RESTEasyContextParamsTest.java new file mode 100644 index 000000000..30d98443a --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/RESTEasyContextParamsTest.java @@ -0,0 +1,164 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.context; + +import javax.ws.rs.core.MediaType; +import javax.xml.namespace.QName; +import java.util.HashSet; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.HandlerException; +import org.switchyard.ServiceDomain; +import org.switchyard.component.resteasy.InboundHandler; +import org.switchyard.component.resteasy.OutboundHandler; +import org.switchyard.component.resteasy.config.model.RESTEasyBindingModel; +import org.switchyard.component.resteasy.resource.ResourcePublisherFactory; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.InvocationFaultException; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; + +/** + * Contains tests for RESTEasy context parameters. + */ +public class RESTEasyContextParamsTest { + + private static final QName STRING_QNAME = new QName("java:java.lang.String"); + private static final QName RESPONSE_QNAME = new QName("java:javax.ws.rs.core.Response"); + private static final String PAYLOAD = "payload"; + private static final String APP_ERROR = "App Error"; + private static final String OP_CREATE = "create"; + private static final String OP_CREATE_WITH_OWN_MEDIA_TYPE = "createWithOwnMediaType"; + + private static ModelPuller _puller; + + private ServiceDomain _domain; + private HTTPMixIn _httpMixIn = new HTTPMixIn(); + + private Invoker _noBuiltinsConsumerService; + private Invoker _consumerService; + + private RESTEasyBindingModel _config; + private RESTEasyBindingModel _configRef; + + private InboundHandler _restInbound; + private OutboundHandler _noBuiltinsRestOutbound; + private OutboundHandler _restOutbound; + + private final MockHandler _mockService = new MockHandler().replyWithFault(APP_ERROR); + + private final static int PORT = 6080; + + @Before + public void setUp() throws Exception { + System.setProperty("org.switchyard.component.resteasy.standalone.port", PORT + ""); + + _httpMixIn.initialize(); + _domain = new ServiceDomainManager().createDomain(); + _noBuiltinsConsumerService = new Invoker(_domain, QName.valueOf("{urn:resteasy:test:1.1}ContextParamNoBuiltinsTestReference")); + _consumerService = new Invoker(_domain, QName.valueOf("{urn:resteasy:test:1.1}ContextParamTestReference")); + + _puller = new ModelPuller(); + CompositeModel composite = _puller.pull("/ContextParamsSwitchYard.xml", getClass()); + composite.assertModelValid(); + + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (RESTEasyBindingModel) compositeService.getBindings().get(0); + + // Massive hack for Test Runner. Register both a service and a reference binding. + _domain.registerService(_config.getServiceName(), new RESTEasyContextParamsInterface(), _mockService); + _domain.registerServiceReference(_config.getServiceName(), new RESTEasyContextParamsInterface()); + _restInbound = new InboundHandler(_config, _domain); + + CompositeReferenceModel compositeReference = composite.getReferences().get(0); + _configRef = (RESTEasyBindingModel) compositeReference.getBindings().get(0); + + _noBuiltinsRestOutbound = new OutboundHandler(_configRef, null); + // Massive hack for Test Runner. Register both a service and a reference binding. + _domain.registerService(_configRef.getServiceName(), new RESTEasyContextParamsInterface(), _noBuiltinsRestOutbound); + _domain.registerServiceReference(_configRef.getServiceName(), new RESTEasyContextParamsInterface()); + + compositeReference = composite.getReferences().get(1); + _configRef = (RESTEasyBindingModel) compositeReference.getBindings().get(0); + _restOutbound = new OutboundHandler(_configRef, null); + // Massive hack for Test Runner. Register both a service and a reference binding. + _domain.registerService(_configRef.getServiceName(), new RESTEasyContextParamsInterface(), _restOutbound); + _domain.registerServiceReference(_configRef.getServiceName(), new RESTEasyContextParamsInterface()); + + _restInbound.start(); + _noBuiltinsRestOutbound.start(); + _restOutbound.start(); + } + + @After + public void tearDown() throws Exception { + _restInbound.stop(); + _noBuiltinsRestOutbound.stop(); + _restOutbound.stop(); + } + + @Test + public void exceptionMapperProviderServiceTest() throws Exception { + _httpMixIn.setContentType(MediaType.TEXT_PLAIN); + String contextPath = "/cp/api"; + if (ResourcePublisherFactory.ignoreContext()) { + contextPath = ""; + } + String response = _httpMixIn.sendString("http://localhost:" + PORT + contextPath + "/context-params", PAYLOAD, HTTPMixIn.HTTP_POST); + Assert.assertEquals(WebApplicationExceptionMapper.EM_PREFIX + APP_ERROR, response); + } + + @Test + public void restGatewayReferenceNoBuiltinsTest() throws Exception { + String expectedException = ""; + try { + _noBuiltinsConsumerService.operation(OP_CREATE).sendInOut(PAYLOAD); + } catch (InvocationFaultException e) { + expectedException = ((HandlerException) e.getFaultMessage().getContent()).getCause().getCause().getMessage(); + } + Assert.assertEquals("could not find writer for content-type text/plain type: java.lang.String", expectedException); + } + + @Test + public void messageBodyWriterProviderReferenceTest() throws Exception { + _consumerService.operation(OP_CREATE_WITH_OWN_MEDIA_TYPE).sendInOut(PAYLOAD); + Assert.assertTrue(SyTxtMessageBodyRW.isInvoked()); + } + + private static class RESTEasyContextParamsInterface extends BaseService { + + private static Set _operations = new HashSet(1); + + static { + _operations.add(new InOutOperation(OP_CREATE, STRING_QNAME, RESPONSE_QNAME)); + _operations.add(new InOutOperation(OP_CREATE_WITH_OWN_MEDIA_TYPE, STRING_QNAME, RESPONSE_QNAME)); + } + + public RESTEasyContextParamsInterface() { + super(_operations); + } + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/SyTxtMessageBodyRW.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/SyTxtMessageBodyRW.java new file mode 100644 index 000000000..1d9ac412c --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/SyTxtMessageBodyRW.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.context; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import org.jboss.resteasy.plugins.providers.StringTextStar; + +@Provider +@Produces(SyTxtMessageBodyRW.MEDIA_TYPE) +public class SyTxtMessageBodyRW extends StringTextStar { + + public static final String MEDIA_TYPE = "sy/txt"; + + private static boolean invoked = false; + + @Override + public void writeTo(String o, Class type, Type genericType, Annotation[] annotations, + MediaType mediaType, MultivaluedMap httpHeaders, + OutputStream entityStream) throws IOException { + + invoked = true; + super.writeTo(o, type, genericType, annotations, mediaType, httpHeaders, entityStream); + } + + public static boolean isInvoked() { + return invoked; + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/WebApplicationExceptionMapper.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/WebApplicationExceptionMapper.java new file mode 100644 index 000000000..ccd407e9c --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/context/WebApplicationExceptionMapper.java @@ -0,0 +1,35 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.context; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Provider +public class WebApplicationExceptionMapper implements ExceptionMapper { + + public static final String EM_PREFIX = "Handled :"; + + @Override + public Response toResponse(WebApplicationException ex) { + return Response + .status(Response.Status.BAD_REQUEST) + .entity(EM_PREFIX + ex.getCause().getMessage()) + .type(MediaType.TEXT_PLAIN) + .build(); + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/resource/StandaloneResourcePublisherTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/resource/StandaloneResourcePublisherTest.java new file mode 100644 index 000000000..3badecba4 --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/resource/StandaloneResourcePublisherTest.java @@ -0,0 +1,36 @@ +package org.switchyard.component.resteasy.resource; + +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertThat; + +/** + * Test for StandaloneResourcePublisher + * + * @author Luis del Toro + */ +public class StandaloneResourcePublisherTest { + + private static final int TEST_PORT = 9191; + + @Before + public void setUp() { + // make sure that the system property is not set + System.clearProperty(ResourcePublisher.DEFAULT_PORT_PROPERTY); + } + @Test + public void useDefaultPort() { + final int port = new NettyJaxrsServer().getPort(); + assertThat(port, is(equalTo(ResourcePublisher.DEFAULT_PORT))); + } + + @Test + public void useConfiguredPort() { + System.setProperty(ResourcePublisher.DEFAULT_PORT_PROPERTY, Integer.toString(TEST_PORT)); + final int port = new NettyJaxrsServer().getPort(); + assertThat(port, is(equalTo(TEST_PORT))); + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/ClassUtilTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/ClassUtilTest.java new file mode 100644 index 000000000..fadc190bd --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/ClassUtilTest.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.util; + +import java.lang.reflect.Method; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.component.resteasy.InboundHandler; +import org.switchyard.component.resteasy.composer.RESTEasyBindingData; +import org.switchyard.component.resteasy.config.model.RESTEasyNamespace; +import org.switchyard.component.resteasy.config.model.v1.V1RESTEasyBindingModel; +import org.switchyard.component.resteasy.util.support.Item; + +/** + * Tests for ClassUtil. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class ClassUtilTest extends InboundHandler { + + public ClassUtilTest() { + } + + @Test + public void generateClassInstances() throws Exception { + String[] intfs = {"org.switchyard.component.resteasy.util.support.WarehouseResource"}; + Object instance = ClassUtil.generateSingletons(intfs, this).get(0); + Method method = instance.getClass().getMethod("getItem", Integer.class); + Item response = (Item)method.invoke(instance, 1); + Item apple = new Item(1, "Apple"); + Assert.assertTrue(response.equals(apple)); + method = instance.getClass().getMethod("addItem", Item.class); + Item orange = new Item(2, "Orange"); + Assert.assertEquals("[2:Orange]", method.invoke(instance, orange)); + method = instance.getClass().getMethod("updateItem", Item.class); + Item grape = new Item(2, "Grape"); + Assert.assertEquals("[2:Grape]", method.invoke(instance, grape)); + method = instance.getClass().getMethod("removeItem", Integer.class); + //Assert.assertEquals("2", method.invoke(instance, 2)); + method = instance.getClass().getMethod("getItemCount"); + Assert.assertEquals(0, method.invoke(instance)); + method = instance.getClass().getMethod("testVoid"); + method.invoke(instance); + } + + public RESTEasyBindingData invoke(final RESTEasyBindingData restMessageRequest, final boolean oneWay) { + Object input = restMessageRequest.getParameters().length == 0 ? null : restMessageRequest.getParameters()[0]; + String operationName = restMessageRequest.getOperationName(); + if (operationName.equals("getItem")) { + Assert.assertTrue(input instanceof Integer); + Assert.assertTrue((Integer)input == 1); + Assert.assertFalse(oneWay); + return new RESTEasyBindingData(new Item(1, "Apple")); + } else if (operationName.equals("addItem") || operationName.equals("updateItem")) { + Assert.assertTrue(input instanceof Item); + Assert.assertFalse(oneWay); + return new RESTEasyBindingData(((Item)input).toString()); + } else if (operationName.equals("removeItem")) { + Assert.assertTrue(input instanceof Integer); + Assert.assertFalse(oneWay); + return new RESTEasyBindingData("2"); + } else if (operationName.equals("getItemCount")) { + Assert.assertTrue(input == null); + Assert.assertFalse(oneWay); + return new RESTEasyBindingData(0); + } else if (operationName.equals("testVoid")) { + Assert.assertTrue(input == null); + Assert.assertTrue(oneWay); + } + return null; + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/RESTEasyUtilTest.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/RESTEasyUtilTest.java new file mode 100644 index 000000000..8a8d452dc --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/RESTEasyUtilTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.resteasy.util; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.component.resteasy.InboundHandler; + +/** + * Tests for RESTEasyUtil. + */ +public class RESTEasyUtilTest extends InboundHandler { + + private static final String STRING_CLASS_NAME = "java.lang.String"; + private static final String BAD_CLASS_NAME = "bad.Cls"; + + private Map contextParamsWithProviders; + private Map contextParamsWithOnlyBadProviders; + private Map contextParams; + + public RESTEasyUtilTest() { + contextParams = new HashMap(1); + contextParams.put(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS, "false"); + + contextParamsWithProviders = new HashMap(1); + contextParamsWithProviders.put(ResteasyContextParameters.RESTEASY_PROVIDERS, STRING_CLASS_NAME + "," + BAD_CLASS_NAME); + + contextParamsWithOnlyBadProviders = new HashMap(1); + contextParamsWithOnlyBadProviders.put(ResteasyContextParameters.RESTEASY_PROVIDERS, BAD_CLASS_NAME); + } + + @Test + public void testGetProviders() throws Exception { + Assert.assertNull(RESTEasyUtil.getParamValues(null, ResteasyContextParameters.RESTEASY_PROVIDERS)); + Assert.assertNull(RESTEasyUtil.getParamValues(contextParams, ResteasyContextParameters.RESTEASY_PROVIDERS)); + + List providers = RESTEasyUtil.getParamValues(contextParamsWithProviders, ResteasyContextParameters.RESTEASY_PROVIDERS); + Assert.assertEquals(2, providers.size()); + Assert.assertEquals(STRING_CLASS_NAME, providers.get(0)); + Assert.assertEquals(BAD_CLASS_NAME, providers.get(1)); + } + + @Test + public void testGetProviderClasses() throws Exception { + Assert.assertNull(RESTEasyUtil.getProviderClasses(null)); + Assert.assertNull(RESTEasyUtil.getProviderClasses(contextParams)); + Assert.assertNull(RESTEasyUtil.getProviderClasses(contextParamsWithOnlyBadProviders)); + + List> providerClasses = RESTEasyUtil.getProviderClasses(contextParamsWithProviders); + Assert.assertEquals(1, providerClasses.size()); + Assert.assertEquals(String.class, providerClasses.get(0)); + } + +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/support/Item.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/support/Item.java new file mode 100644 index 000000000..d0e2bbcb3 --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/support/Item.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.util.support; + +/** + * Item for WarehouseService. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class Item { + private Integer _itemId; + private String _name; + + public Item(Integer itemId, String name) { + _itemId = itemId; + _name = name; + } + + public Integer getItemId() { + return _itemId; + } + + public void setItemId(Integer itemId) { + _itemId = itemId; + } + + public String getName() { + return _name; + } + + public void setName(String name) { + _name = name; + } + + public String toString() { + return "[" + _itemId + ":" +_name + "]"; + } + + public boolean equals(Item item) { + return (_itemId == item.getItemId()) && (_name.equals(item.getName())); + } +} diff --git a/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/support/WarehouseResource.java b/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/support/WarehouseResource.java new file mode 100644 index 000000000..285c9541e --- /dev/null +++ b/components/resteasy/src/test/java/org/switchyard/component/resteasy/util/support/WarehouseResource.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.resteasy.util.support; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.PUT; + +/** + * REST interface for WarehouseService. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +@Path("/warehouse") +@Consumes({"application/xml","application/json"}) +public interface WarehouseResource { + + @GET + @Path("{itemId}") + @Produces({"application/xml"}) + public Item getItem(@PathParam("itemId") Integer itemId); + + @PUT + @Path("/") + @Consumes({"application/xml"}) + public String addItem(Item item) throws Exception; + + @POST + @Path("/") + @Consumes({"application/xml"}) + public String updateItem(Item item) throws Exception; + + @DELETE + @Path("{itemId}") + public String removeItem(@PathParam("itemId") Integer itemId) throws Exception; + + @GET + @Path("/count/") + public Integer getItemCount(); + + public void testVoid(); + + @GET + @Path("/error/") + public void getError(); +} diff --git a/components/resteasy/src/test/resources/ContextParamsSwitchYard.xml b/components/resteasy/src/test/resources/ContextParamsSwitchYard.xml new file mode 100644 index 000000000..ac34382cd --- /dev/null +++ b/components/resteasy/src/test/resources/ContextParamsSwitchYard.xml @@ -0,0 +1,50 @@ + + + + + + + org.switchyard.component.resteasy.context.ContextParamResource + cp/api + + + + + + + + + org.switchyard.component.resteasy.context.ContextParamResource + http://localhost:6080 + + + + + + + + + org.switchyard.component.resteasy.context.ContextParamResource + http://localhost:6080 + + + + + + + diff --git a/components/resteasy/src/test/resources/HelloSwitchYard.xml b/components/resteasy/src/test/resources/HelloSwitchYard.xml new file mode 100644 index 000000000..7a15e5943 --- /dev/null +++ b/components/resteasy/src/test/resources/HelloSwitchYard.xml @@ -0,0 +1,45 @@ + + + + + + + + org.switchyard.component.resteasy.HelloResource + http://localhost:6090/greeters + + + + + + + org.switchyard.component.resteasy.HelloResource + http://localhost:6080 + 1300 + + + + + + org.switchyard.component.resteasy.HelloResource + http://localhost:8090/forever + 1300 + + + + diff --git a/components/resteasy/src/test/resources/log4j.xml b/components/resteasy/src/test/resources/log4j.xml new file mode 100644 index 000000000..8eeac24e2 --- /dev/null +++ b/components/resteasy/src/test/resources/log4j.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-auth.xml b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-auth.xml new file mode 100644 index 000000000..f2122203b --- /dev/null +++ b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-auth.xml @@ -0,0 +1,9 @@ + + org.switchyard.quickstarts.rest.binding.OrderResource,org.switchyard.quickstarts.rest.binding.TestResource + http://localhost:8080/ + + user + password + domain + + diff --git a/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-context-params.xml b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-context-params.xml new file mode 100644 index 000000000..291ce0388 --- /dev/null +++ b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-context-params.xml @@ -0,0 +1,8 @@ + + org.switchyard.quickstarts.rest.binding.OrderResource,org.switchyard.quickstarts.rest.binding.TestResource + rest-binding + + + + + diff --git a/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-invalid.xml b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-invalid.xml new file mode 100644 index 000000000..7902c53e2 --- /dev/null +++ b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-invalid.xml @@ -0,0 +1,6 @@ + + org.switchyard.quickstarts.rest.binding.OrderResource,org.switchyard.quickstarts.rest.binding.TestResource + http://localhost:8080 + rest-binding + + diff --git a/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-proxy.xml b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-proxy.xml new file mode 100644 index 000000000..0eabe4fb9 --- /dev/null +++ b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-proxy.xml @@ -0,0 +1,10 @@ + + org.switchyard.quickstarts.rest.binding.OrderResource,org.switchyard.quickstarts.rest.binding.TestResource + http://localhost:8080/ + + host + 8090 + Beal + conjecture + + diff --git a/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-reference.xml b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-reference.xml new file mode 100644 index 000000000..89e1d2b51 --- /dev/null +++ b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding-reference.xml @@ -0,0 +1,5 @@ + + org.switchyard.quickstarts.rest.binding.OrderResource,org.switchyard.quickstarts.rest.binding.TestResource + http://localhost:8080/ + 5000 + diff --git a/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding.xml b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding.xml new file mode 100644 index 000000000..16009ec38 --- /dev/null +++ b/components/resteasy/src/test/resources/org/switchyard/component/resteasy/config/model/rest-binding.xml @@ -0,0 +1,4 @@ + + org.switchyard.quickstarts.rest.binding.OrderResource,org.switchyard.quickstarts.rest.binding.TestResource + rest-binding + diff --git a/components/rules/pom.xml b/components/rules/pom.xml new file mode 100644 index 000000000..b78995b79 --- /dev/null +++ b/components/rules/pom.xml @@ -0,0 +1,80 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-rules + bundle + SwitchYard: Rules Component + http://switchyard.org + + + org.switchyard.component.rules.* + + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-extensions-java + + + org.switchyard.components + switchyard-component-common-knowledge + + + + org.kie + kie-api + + + org.kie + kie-internal + + + diff --git a/components/rules/src/main/java/org/switchyard/component/rules/RulesConstants.java b/components/rules/src/main/java/org/switchyard/component/rules/RulesConstants.java new file mode 100644 index 000000000..bcf0f9ba0 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/RulesConstants.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules; + +import javax.xml.namespace.QName; + +/** + * Rules constants. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class RulesConstants { + + /** urn:switchyard-component-rules:rules:1.0 . */ + public static final String RULES_NAMESPACE = "urn:switchyard-component-rules:rules:1.0"; + + /** + * sessionId is not used anymore. + * @deprecated + */ + @Deprecated + public static final String SESSION_ID = "sessionId"; + /** + * {urn:switchyard-component-rules:rules:1.0}sessionId is not used anymore. + * @deprecated + */ + @Deprecated + public static final String SESSION_ID_PROPERTY = new QName(RULES_NAMESPACE, SESSION_ID).toString(); + + /** continue . */ + public static final String CONTINUE = "continue"; + /** {urn:switchyard-component-rules:rules:1.0}continue . */ + public static final String CONTINUE_PROPERTY = new QName(RULES_NAMESPACE, CONTINUE).toString(); + + /** dispose . */ + public static final String DISPOSE = "dispose"; + /** {urn:switchyard-component-rules:rules:1.0}dispose . */ + public static final String DISPOSE_PROPERTY = new QName(RULES_NAMESPACE, DISPOSE).toString(); + + private RulesConstants() {} + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/RulesLogger.java b/components/rules/src/main/java/org/switchyard/component/rules/RulesLogger.java new file mode 100644 index 000000000..3dfb89f0a --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/RulesLogger.java @@ -0,0 +1,19 @@ +package org.switchyard.component.rules; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 38400-38799 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface RulesLogger { + /** + * A root logger with the category of the package name. + */ + RulesLogger ROOT_LOGGER = Logger.getMessageLogger(RulesLogger.class, RulesLogger.class.getPackage().getName()); + +} + diff --git a/components/rules/src/main/java/org/switchyard/component/rules/RulesMessages.java b/components/rules/src/main/java/org/switchyard/component/rules/RulesMessages.java new file mode 100644 index 000000000..4ae540406 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/RulesMessages.java @@ -0,0 +1,46 @@ +package org.switchyard.component.rules; + +import java.io.IOException; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +/** + *

+ * This file is using the subset 38800-39199 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface RulesMessages { + /** + * The default messages. + */ + RulesMessages MESSAGES = Messages.getBundle(RulesMessages.class); + + /** + * rulesInterfaceGetNameIsAClass@RulesOnlyAllowedOnInterfaces method definition. + * @param rulesInterfaceName rulesInterfaceName + * @return IOException + */ + @Message(id = 38800, value = "%s is a class. @Rules only allowed on interfaces.") + IOException rulesInterfaceGetNameIsAClassRulesOnlyAllowedOnInterfaces(String rulesInterfaceName); + + /** + * unknownEntryPoint method definition. + * @param entryPoint the entryPoint + * @return HandlerException + */ + @Message(id = 38801, value = "Unknown entry point: %s; please check your rules source.") + HandlerException unknownEntryPoint(String entryPoint); + + /** + * unsupportedOperationType method definition. + * @param operationType the operationType + * @return HandlerException + */ + @Message(id = 38802, value = "Unsupported operation type: %s") + HandlerException unsupportedOperationType(String operationType); + +} + diff --git a/components/rules/src/main/java/org/switchyard/component/rules/annotation/Execute.java b/components/rules/src/main/java/org/switchyard/component/rules/annotation/Execute.java new file mode 100644 index 000000000..5cf8d0fb0 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/annotation/Execute.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; + +/** + * Execute. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(METHOD) +@Retention(RUNTIME) +@Documented +public @interface Execute { + + /** Globals. */ + public Global[] globals() default {}; + + /** Inputs. */ + public Input[] inputs() default {}; + + /** Outputs. */ + public Output[] outputs() default {}; + + /** Faults. */ + public Fault[] faults() default {}; + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/annotation/FireAllRules.java b/components/rules/src/main/java/org/switchyard/component/rules/annotation/FireAllRules.java new file mode 100644 index 000000000..8dd9b224f --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/annotation/FireAllRules.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; + +/** + * FireAllRules. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(METHOD) +@Retention(RUNTIME) +@Documented +public @interface FireAllRules { + + /** Globals. */ + public Global[] globals() default {}; + + /** Inputs. */ + public Input[] inputs() default {}; + + /** Outputs. */ + public Output[] outputs() default {}; + + /** Faults. */ + public Fault[] faults() default {}; + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/annotation/FireUntilHalt.java b/components/rules/src/main/java/org/switchyard/component/rules/annotation/FireUntilHalt.java new file mode 100644 index 000000000..c8cc601b4 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/annotation/FireUntilHalt.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; + +/** + * FireUntilHalt. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(METHOD) +@Retention(RUNTIME) +@Documented +public @interface FireUntilHalt { + + /** EventId. */ + public String eventId() default ""; + + /** Globals. */ + public Global[] globals() default {}; + + /** Inputs. */ + public Input[] inputs() default {}; + + /** Outputs. */ + public Output[] outputs() default {}; + + /** Faults. */ + public Fault[] faults() default {}; + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/annotation/Insert.java b/components/rules/src/main/java/org/switchyard/component/rules/annotation/Insert.java new file mode 100644 index 000000000..4739e87f4 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/annotation/Insert.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.annotation; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; + +/** + * Insert. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(METHOD) +@Retention(RUNTIME) +@Documented +public @interface Insert { + + /** Globals. */ + public Global[] globals() default {}; + + /** Inputs. */ + public Input[] inputs() default {}; + + /** Outputs. */ + public Output[] outputs() default {}; + + /** Faults. */ + public Fault[] faults() default {}; + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/annotation/Rules.java b/components/rules/src/main/java/org/switchyard/component/rules/annotation/Rules.java new file mode 100644 index 000000000..90e286db8 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/annotation/Rules.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import org.switchyard.component.common.knowledge.annotation.Channel; +import org.switchyard.component.common.knowledge.annotation.Listener; +import org.switchyard.component.common.knowledge.annotation.Logger; +import org.switchyard.component.common.knowledge.annotation.Manifest; +import org.switchyard.component.common.knowledge.annotation.Property; + +/** + * Rules. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Rules { + + /** Namespace. */ + public String namespace() default ""; + + /** Name. */ + public String name() default ""; + + /** Interface class. */ + public Class value() default UndefinedRulesInterface.class; + + /** Channels. */ + public Channel[] channels() default {}; + + /** Listeners. */ + public Listener[] listeners() default {}; + + /** Loggers. */ + public Logger[] loggers() default {}; + + /** Manifest. */ + public Manifest[] manifest() default {}; + + /** Properties. */ + public Property[] properties() default {}; + + /** Undefined interface class. */ + public static interface UndefinedRulesInterface {}; + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesComponentImplementationModel.java b/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesComponentImplementationModel.java new file mode 100644 index 000000000..7443cf74d --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesComponentImplementationModel.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model; + +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; + +/** + * RulesComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface RulesComponentImplementationModel extends KnowledgeComponentImplementationModel { + + /** + * The "rules" implementation type. + */ + public static final String RULES = "rules"; + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesNamespace.java b/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesNamespace.java new file mode 100644 index 000000000..5269baa99 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesNamespace.java @@ -0,0 +1,112 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model; + +import org.switchyard.component.common.knowledge.config.model.KnowledgeNamespace; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Rules config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum RulesNamespace implements KnowledgeNamespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new RulesNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + RulesNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the RulesNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the RulesNamespace + */ + public static RulesNamespace fromUri(String uri) { + return Util.fromUri(RulesNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(RulesNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-rules:config", version); + } + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesSwitchYardScanner.java b/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesSwitchYardScanner.java new file mode 100644 index 000000000..1567c16f7 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/config/model/RulesSwitchYardScanner.java @@ -0,0 +1,212 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.List; + +import org.switchyard.common.lang.Strings; +import org.switchyard.common.type.classpath.ClasspathScanner; +import org.switchyard.common.type.classpath.IsAnnotationPresentFilter; +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Output; +import org.switchyard.component.common.knowledge.config.model.KnowledgeSwitchYardScanner; +import org.switchyard.component.common.knowledge.config.model.OperationModel; +import org.switchyard.component.common.knowledge.config.model.OperationsModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1OperationsModel; +import org.switchyard.component.rules.RulesMessages; +import org.switchyard.component.rules.annotation.Execute; +import org.switchyard.component.rules.annotation.FireAllRules; +import org.switchyard.component.rules.annotation.FireUntilHalt; +import org.switchyard.component.rules.annotation.Insert; +import org.switchyard.component.rules.annotation.Rules; +import org.switchyard.component.rules.config.model.v1.V1RulesComponentImplementationModel; +import org.switchyard.component.rules.config.model.v1.V1RulesOperationModel; +import org.switchyard.component.rules.operation.RulesOperationType; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.v1.V1ComponentModel; +import org.switchyard.config.model.composite.v1.V1ComponentServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeModel; +import org.switchyard.config.model.composite.v1.V1InterfaceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.metadata.ServiceOperation; + +/** + * RulesSwitchYardScanner. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RulesSwitchYardScanner extends KnowledgeSwitchYardScanner { + + private static final IsAnnotationPresentFilter EXECUTE_FILTER = new IsAnnotationPresentFilter(Execute.class); + private static final IsAnnotationPresentFilter INSERT_FILTER = new IsAnnotationPresentFilter(Insert.class); + private static final IsAnnotationPresentFilter FIRE_ALL_RULES_FILTER = new IsAnnotationPresentFilter(FireAllRules.class); + private static final IsAnnotationPresentFilter FIRE_UNTIL_HALT_FILTER = new IsAnnotationPresentFilter(FireUntilHalt.class); + + private final IsAnnotationPresentFilter _rulesFilter = new IsAnnotationPresentFilter(Rules.class); + + /** + * {@inheritDoc} + */ + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + SwitchYardNamespace switchyardNamespace = input.getSwitchyardNamespace(); + SwitchYardModel switchyardModel = new V1SwitchYardModel(switchyardNamespace.uri()); + CompositeModel compositeModel = new V1CompositeModel(); + compositeModel.setName(input.getCompositeName()); + ClasspathScanner rulesScanner = new ClasspathScanner(_rulesFilter); + for (URL url : input.getURLs()) { + rulesScanner.scan(url); + } + List> rulesClasses = _rulesFilter.getMatchedTypes(); + for (Class rulesClass : rulesClasses) { + compositeModel.addComponent(scan(rulesClass, switchyardNamespace)); + } + if (!compositeModel.getModelChildren().isEmpty()) { + switchyardModel.setComposite(compositeModel); + } + return new ScannerOutput().setModel(switchyardModel); + } + + /** + * Scans a class using the default switchyard namespace. + * @param rulesClass the class + * @return the component model + * @throws IOException oops + */ + public ComponentModel scan(Class rulesClass) throws IOException { + return scan(rulesClass, null); + } + + /** + * Scans a class using the specified switchyard namespace. + * @param rulesClass the class + * @param switchyardNamespace the switchyard namespace + * @return the component model + * @throws IOException oops + */ + public ComponentModel scan(Class rulesClass, SwitchYardNamespace switchyardNamespace) throws IOException { + if (switchyardNamespace == null) { + switchyardNamespace = SwitchYardNamespace.DEFAULT; + } + Rules rules = rulesClass.getAnnotation(Rules.class); + Class rulesInterface = rules.value(); + if (Rules.UndefinedRulesInterface.class.equals(rulesInterface)) { + rulesInterface = rulesClass; + } + if (!rulesInterface.isInterface()) { + throw RulesMessages.MESSAGES.rulesInterfaceGetNameIsAClassRulesOnlyAllowedOnInterfaces(rulesInterface.getName()); + } + String rulesName = Strings.trimToNull(rules.name()); + if (rulesName == null) { + rulesName = rulesInterface.getSimpleName(); + } + ComponentModel componentModel = new V1ComponentModel(); + componentModel.setName(rulesName); + RulesNamespace rulesNamespace = RulesNamespace.fromUri(rules.namespace()); + if (rulesNamespace == null) { + rulesNamespace = RulesNamespace.DEFAULT; + for (RulesNamespace value : RulesNamespace.values()) { + if (value.versionMatches(switchyardNamespace)) { + rulesNamespace = value; + break; + } + } + } + RulesComponentImplementationModel componentImplementationModel = new V1RulesComponentImplementationModel(rulesNamespace.uri()); + OperationsModel operationsModel = new V1OperationsModel(rulesNamespace.uri()); + JavaService javaService = JavaService.fromClass(rulesInterface); + for (Method method : rulesClass.getDeclaredMethods()) { + RulesOperationType operationType = null; + String eventId = null; + Global[] globalMappingAnnotations = null; + Input[] inputMappingAnnotations = null; + Output[] outputMappingAnnotations = null; + Fault[] faultMappingAnnotations = null; + if (EXECUTE_FILTER.matches(method)) { + operationType = RulesOperationType.EXECUTE; + Execute executeAnnotation = method.getAnnotation(Execute.class); + globalMappingAnnotations = executeAnnotation.globals(); + inputMappingAnnotations = executeAnnotation.inputs(); + outputMappingAnnotations = executeAnnotation.outputs(); + faultMappingAnnotations = executeAnnotation.faults(); + } else if (INSERT_FILTER.matches(method)) { + operationType = RulesOperationType.INSERT; + Insert insertAnnotation = method.getAnnotation(Insert.class); + globalMappingAnnotations = insertAnnotation.globals(); + inputMappingAnnotations = insertAnnotation.inputs(); + outputMappingAnnotations = insertAnnotation.outputs(); + faultMappingAnnotations = insertAnnotation.faults(); + } else if (FIRE_ALL_RULES_FILTER.matches(method)) { + operationType = RulesOperationType.FIRE_ALL_RULES; + FireAllRules fireAllRulesAnnotation = method.getAnnotation(FireAllRules.class); + globalMappingAnnotations = fireAllRulesAnnotation.globals(); + inputMappingAnnotations = fireAllRulesAnnotation.inputs(); + outputMappingAnnotations = fireAllRulesAnnotation.outputs(); + faultMappingAnnotations = fireAllRulesAnnotation.faults(); + } else if (FIRE_UNTIL_HALT_FILTER.matches(method)) { + operationType = RulesOperationType.FIRE_UNTIL_HALT; + FireUntilHalt fireUntilHaltAnnotation = method.getAnnotation(FireUntilHalt.class); + eventId = Strings.trimToNull(fireUntilHaltAnnotation.eventId()); + globalMappingAnnotations = fireUntilHaltAnnotation.globals(); + inputMappingAnnotations = fireUntilHaltAnnotation.inputs(); + outputMappingAnnotations = fireUntilHaltAnnotation.outputs(); + faultMappingAnnotations = fireUntilHaltAnnotation.faults(); + } + if (operationType != null) { + ServiceOperation serviceOperation = javaService.getOperation(method.getName()); + if (serviceOperation != null) { + OperationModel operationModel = new V1RulesOperationModel(rulesNamespace.uri()); + operationModel.setEventId(eventId); + operationModel.setName(serviceOperation.getName()); + operationModel.setType(operationType); + operationModel.setGlobals(toGlobalsModel(globalMappingAnnotations, rulesNamespace)); + operationModel.setInputs(toInputsModel(inputMappingAnnotations, rulesNamespace)); + operationModel.setOutputs(toOutputsModel(outputMappingAnnotations, rulesNamespace)); + operationModel.setFaults(toFaultsModel(faultMappingAnnotations, rulesNamespace)); + operationsModel.addOperation(operationModel); + } + } + } + if (!operationsModel.getOperations().isEmpty()) { + componentImplementationModel.setOperations(operationsModel); + } + componentImplementationModel.setChannels(toChannelsModel(rules.channels(), rulesNamespace, componentModel, switchyardNamespace)); + componentImplementationModel.setListeners(toListenersModel(rules.listeners(), rulesNamespace)); + componentImplementationModel.setLoggers(toLoggersModel(rules.loggers(), rulesNamespace)); + componentImplementationModel.setManifest(toManifestModel(rules.manifest(), rulesNamespace)); + componentImplementationModel.setProperties(toPropertiesModel(rules.properties(), rulesNamespace)); + componentModel.setImplementation(componentImplementationModel); + ComponentServiceModel componentServiceModel = new V1ComponentServiceModel(switchyardNamespace.uri()); + InterfaceModel interfaceModel = new V1InterfaceModel(InterfaceModel.JAVA); + interfaceModel.setInterface(rulesInterface.getName()); + componentServiceModel.setInterface(interfaceModel); + componentServiceModel.setName(rulesName); + componentModel.addService(componentServiceModel); + return componentModel; + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesComponentImplementationModel.java b/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesComponentImplementationModel.java new file mode 100644 index 000000000..182e0e343 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesComponentImplementationModel.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model.v1; + +import org.switchyard.component.common.knowledge.config.model.KnowledgeComponentImplementationModel; +import org.switchyard.component.common.knowledge.config.model.v1.V1KnowledgeComponentImplementationModel; +import org.switchyard.component.rules.config.model.RulesComponentImplementationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A "rules" implementation of a KnowledgeComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1RulesComponentImplementationModel extends V1KnowledgeComponentImplementationModel implements RulesComponentImplementationModel { + + /** + * Default constructor for application use. + * @param namespace namespace + */ + public V1RulesComponentImplementationModel(String namespace) { + super(RULES, namespace); + } + + /** + * Constructor for Marshaller use (ie: V1RulesMarshaller). + * + * @param config the Configuration + * @param desc the Descriptor + */ + public V1RulesComponentImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPersistent() { + // unsupported in rules (see bpm) + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setPersistent(boolean persistent) { + // unsupported in rules (see bpm) + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getProcessId() { + // unsupported in rules (see bpm) + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeComponentImplementationModel setProcessId(String processId) { + // unsupported in rules (see bpm) + return this; + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesMarshaller.java b/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesMarshaller.java new file mode 100644 index 000000000..5b0fd742d --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesMarshaller.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model.v1; + +import static org.switchyard.component.common.knowledge.config.model.OperationModel.OPERATION; + +import org.switchyard.component.common.knowledge.config.model.v1.V1KnowledgeMarshaller; +import org.switchyard.component.rules.config.model.RulesComponentImplementationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * A CompositeMarshaller which can also create knowledge models. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1RulesMarshaller extends V1KnowledgeMarshaller { + + /** + * The complete local name ("implementation.rules"). + */ + private static final String IMPLEMENTATION_RULES = ComponentImplementationModel.IMPLEMENTATION + "." + RulesComponentImplementationModel.RULES; + + /** + * Required constructor called via reflection. + * + * @param desc the Descriptor + */ + public V1RulesMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1CompositeMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (IMPLEMENTATION_RULES.equals(name)) { + return new V1RulesComponentImplementationModel(config, desc); + } else if (OPERATION.equals(name)) { + return new V1RulesOperationModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesOperationModel.java b/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesOperationModel.java new file mode 100644 index 000000000..b92cc7e37 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/config/model/v1/V1RulesOperationModel.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model.v1; + +import org.switchyard.component.common.knowledge.config.model.v1.V1OperationModel; +import org.switchyard.component.common.knowledge.operation.KnowledgeOperationType; +import org.switchyard.component.rules.operation.RulesOperationType; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version RulesOperationModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1RulesOperationModel extends V1OperationModel { + + /** + * Creates a new V1RulesOperationModel. + * @param namespace namespace + */ + public V1RulesOperationModel(String namespace) { + super(namespace); + } + + /** + * Creates a new V1RulesOperationModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1RulesOperationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeOperationType getType() { + String type = getModelAttribute("type"); + return type != null ? RulesOperationType.valueOf(type) : null; + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/config/model/v2/V2RulesMarshaller.java b/components/rules/src/main/java/org/switchyard/component/rules/config/model/v2/V2RulesMarshaller.java new file mode 100644 index 000000000..ffa9f0075 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/config/model/v2/V2RulesMarshaller.java @@ -0,0 +1,67 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model.v2; + +import static org.switchyard.component.common.knowledge.config.model.OperationModel.OPERATION; + +import org.switchyard.component.common.knowledge.config.model.v2.V2KnowledgeMarshaller; +import org.switchyard.component.rules.config.model.RulesComponentImplementationModel; +import org.switchyard.component.rules.config.model.v1.V1RulesComponentImplementationModel; +import org.switchyard.component.rules.config.model.v1.V1RulesOperationModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * A CompositeMarshaller which can also create knowledge models. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2RulesMarshaller extends V2KnowledgeMarshaller { + + /** + * The complete local name ("implementation.rules"). + */ + private static final String IMPLEMENTATION_RULES = ComponentImplementationModel.IMPLEMENTATION + "." + RulesComponentImplementationModel.RULES; + + /** + * Required constructor called via reflection. + * + * @param desc the Descriptor + */ + public V2RulesMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads in the Configuration, looking for various knowledge models. + * If not found, it falls back to the super class (V1CompositeMarshaller). + * + * @param config the Configuration + * @return the Model + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (IMPLEMENTATION_RULES.equals(name)) { + return new V1RulesComponentImplementationModel(config, desc); + } else if (OPERATION.equals(name)) { + return new V1RulesOperationModel(config, desc); + } + return super.read(config); + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/deploy/RulesActivator.java b/components/rules/src/main/java/org/switchyard/component/rules/deploy/RulesActivator.java new file mode 100644 index 000000000..0cade19ab --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/deploy/RulesActivator.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.component.rules.config.model.RulesComponentImplementationModel; +import org.switchyard.component.rules.exchange.RulesExchangeHandler; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; + +/** + * Activator for the Rules component. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RulesActivator extends BaseActivator { + + /** + * Rules component activator type name. + */ + public static final String RULES_TYPE = "rules"; + + /** + * Constructs a new Activator of type "rules". + */ + public RulesActivator() { + super(RULES_TYPE); + } + + /** + * {@inheritDoc} + */ + @Override + public ServiceHandler activateService(QName name, ComponentModel config) { + return new RulesExchangeHandler((RulesComponentImplementationModel)config.getImplementation(), getServiceDomain(), name); + } + + /** + * {@inheritDoc} + */ + @Override + public void deactivateService(QName name, ServiceHandler handler) { + // no-op + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/deploy/RulesComponent.java b/components/rules/src/main/java/org/switchyard/component/rules/deploy/RulesComponent.java new file mode 100644 index 000000000..a3d6e42ab --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/deploy/RulesComponent.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.deploy; + +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * An implementation of Rules component. + * + * @author Magesh Kumar B © 2012 Red Hat Inc. + */ +public class RulesComponent extends BaseComponent { + + /** + * Default constructor. + */ + public RulesComponent() { + super(RulesActivator.RULES_TYPE); + setName("RulesComponent"); + } + + /** + * {@inheritDoc} + */ + @Override + public Activator createActivator(ServiceDomain domain) { + RulesActivator activator = new RulesActivator(); + activator.setServiceDomain(domain); + return activator; + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/exchange/RulesExchangeHandler.java b/components/rules/src/main/java/org/switchyard/component/rules/exchange/RulesExchangeHandler.java new file mode 100644 index 000000000..55c78929d --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/exchange/RulesExchangeHandler.java @@ -0,0 +1,402 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.exchange; + +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.getInputList; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.getInputOnlyList; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.getInputOutputMap; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.getListMap; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.setFaults; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.setGlobals; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.setOutputs; +import static org.switchyard.component.common.knowledge.operation.KnowledgeOperations.toVariable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.namespace.QName; + +import org.kie.api.KieServices; +import org.kie.api.command.BatchExecutionCommand; +import org.kie.api.command.Command; +import org.kie.api.command.KieCommands; +import org.kie.api.runtime.ExecutionResults; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.kie.api.runtime.rule.EntryPoint; +import org.kie.internal.runtime.manager.Disposable; +import org.kie.internal.runtime.manager.DisposeListener; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.KnowledgeConstants; +import org.switchyard.component.common.knowledge.exchange.KnowledgeExchangeHandler; +import org.switchyard.component.common.knowledge.operation.KnowledgeOperation; +import org.switchyard.component.common.knowledge.operation.KnowledgeOperations; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeEngine; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManager; +import org.switchyard.component.rules.RulesConstants; +import org.switchyard.component.rules.RulesMessages; +import org.switchyard.component.rules.config.model.RulesComponentImplementationModel; +import org.switchyard.component.rules.operation.RulesOperationType; + +/** + * A "rules" implementation of a KnowledgeExchangeHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RulesExchangeHandler extends KnowledgeExchangeHandler { + + private static final AtomicInteger FIRE_UNTIL_HALT_COUNT = new AtomicInteger(); + private static final KnowledgeOperation DEFAULT_OPERATION = new KnowledgeOperation(RulesOperationType.EXECUTE); + + private KnowledgeRuntimeManager _perRequestRuntimeManager = null; + private KnowledgeRuntimeManager _singletonRuntimeManager = null; + private Thread _fireUntilHaltThread = null; + + /** + * Constructs a new RulesExchangeHandler with the specified model, service domain, and service name. + * @param model the specified model + * @param serviceDomain the specified service domain + * @param serviceName the specified service name + */ + public RulesExchangeHandler(RulesComponentImplementationModel model, ServiceDomain serviceDomain, QName serviceName) { + super(model, serviceDomain, serviceName); + } + + /** + * {@inheritDoc} + */ + @Override + protected void doStart() { + super.doStart(); + _perRequestRuntimeManager = newPerRequestRuntimeManager(); + } + + /** + * {@inheritDoc} + */ + @Override + protected void doStop() { + try { + _perRequestRuntimeManager.close(); + } finally { + try { + disposeSingletonRuntimeEngine(); + } finally { + super.doStop(); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public KnowledgeOperation getDefaultOperation() { + return DEFAULT_OPERATION; + } + + /** + * {@inheritDoc} + */ + @Override + public void handleOperation(Exchange exchange, KnowledgeOperation operation) throws HandlerException { + //Long sessionIdentifier = null; + Message inputMessage = exchange.getMessage(); + ExchangePattern exchangePattern = exchange.getContract().getProviderOperation().getExchangePattern(); + Map expressionVariables = new HashMap(); + RulesOperationType operationType = (RulesOperationType)operation.getType(); + switch (operationType) { + case EXECUTE: { + KnowledgeRuntimeEngine runtime = getPerRequestRuntimeEngine(); + //sessionIdentifier = runtime.getSessionIdentifier(); + setGlobals(inputMessage, operation, runtime, false); + try { + KieSession session = runtime.getKieSession(); + if (ExchangePattern.IN_ONLY.equals(exchangePattern)) { + List facts = getInputList(inputMessage, operation, runtime); + for (Object fact : facts) { + session.insert(fact); + } + session.fireAllRules(); + } else if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + KieCommands cmds = KieServices.Factory.get().getCommands(); + List> batch = new ArrayList>(); + Map inouts = getInputOutputMap(inputMessage, operation, runtime); + for (Entry inout : inouts.entrySet()) { + batch.add(cmds.newInsert(inout.getValue(), inout.getKey())); + } + List facts = getInputOnlyList(inputMessage, operation, runtime); + batch.add(cmds.newInsertElements(facts)); + batch.add(cmds.newFireAllRules()); + BatchExecutionCommand exec = cmds.newBatchExecution(batch, KnowledgeConstants.RESULT); + ExecutionResults results = session.execute(exec); + for (String id : inouts.keySet()) { + expressionVariables.put(id, results.getValue(id)); + } + expressionVariables.putAll(getGlobalVariables(runtime)); + } + } finally { + disposePerRequestRuntimeEngine(runtime); + } + break; + } + case INSERT: + case FIRE_ALL_RULES: { + KnowledgeRuntimeEngine runtime = getSingletonRuntimeEngine(); + if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + synchronized (this) { + fireAllRules(inputMessage, operation); + expressionVariables.putAll(getGlobalVariables(runtime)); + } + } else { + if (KnowledgeOperations.containsGlobals(inputMessage, operation, runtime)) { + synchronized (this) { + fireAllRules(inputMessage, operation); + } + } else { + fireAllRules(inputMessage, operation); + } + + } + + if (isDispose(exchange, inputMessage)) { + disposeSingletonRuntimeEngine(); + } + + break; + } + case FIRE_UNTIL_HALT: { + KnowledgeRuntimeEngine runtime = getSingletonRuntimeEngine(); + if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + synchronized (this) { + fireUntilHalt(inputMessage, exchange, operation); + expressionVariables.putAll(getGlobalVariables(runtime)); + } + } else { + if (KnowledgeOperations.containsGlobals(inputMessage, operation, runtime)) { + synchronized (this) { + fireUntilHalt(inputMessage, exchange, operation); + } + } else { + fireUntilHalt(inputMessage, exchange, operation); + } + + } + + if (isDispose(exchange, inputMessage)) { + disposeSingletonRuntimeEngine(); + } + break; + } + default: { + throw RulesMessages.MESSAGES.unsupportedOperationType(operationType.toString()); + } + } + if (ExchangePattern.IN_OUT.equals(exchangePattern)) { + Message outputMessage = exchange.createMessage(); + /* + Context outputContext = exchange.getContext(outputMessage); + if (sessionIdentifier != null) { + outputContext.setProperty(RulesConstants.SESSION_ID_PROPERTY, sessionIdentifier); + } + */ + setFaults(outputMessage, operation, expressionVariables); + if (outputMessage.getContent() != null) { + exchange.sendFault(outputMessage); + } else { + setOutputs(outputMessage, operation, expressionVariables); + exchange.send(outputMessage); + } + + } + + } + + private KnowledgeRuntimeEngine getPerRequestRuntimeEngine() { + return (KnowledgeRuntimeEngine)_perRequestRuntimeManager.getRuntimeEngine(); + } + + private void disposePerRequestRuntimeEngine(KnowledgeRuntimeEngine perRequestRuntimeEngine) { + _perRequestRuntimeManager.disposeRuntimeEngine(perRequestRuntimeEngine); + } + + private synchronized KnowledgeRuntimeEngine getSingletonRuntimeEngine() { + if (_singletonRuntimeManager == null) { + _singletonRuntimeManager = newSingletonRuntimeManager(); + } + return (KnowledgeRuntimeEngine)_singletonRuntimeManager.getRuntimeEngine(); + } + + private synchronized void disposeSingletonRuntimeEngine() { + if (_singletonRuntimeManager != null) { + try { + _singletonRuntimeManager.disposeRuntimeEngine(_singletonRuntimeManager.getRuntimeEngine()); + } finally { + try { + _singletonRuntimeManager.close(); + } finally { + _singletonRuntimeManager = null; + } + } + } + } + + /* + private boolean isContinue(Exchange exchange, Message message) { + return isBoolean(exchange, message, RulesConstants.CONTINUE_PROPERTY); + } + */ + + private boolean isDispose(Exchange exchange, Message message) { + return isBoolean(exchange, message, RulesConstants.DISPOSE_PROPERTY); + } + + private final class FireUntilHalt implements Runnable, DisposeListener { + + private final RulesExchangeHandler _handler; + private final KnowledgeRuntimeEngine _runtime; + private final ClassLoader _loader; + + private FireUntilHalt(RulesExchangeHandler handler, KnowledgeRuntimeEngine runtime, ClassLoader loader) { + _handler = handler; + _runtime = runtime; + _loader = loader; + } + + @Override + public void run() { + ClassLoader originalLoader = Classes.setTCCL(_loader); + try { + _runtime.getKieSession().fireUntilHalt(); + } finally { + try { + _handler.disposeSingletonRuntimeEngine(); + } finally { + Classes.setTCCL(originalLoader); + } + } + } + + @Override + public void onDispose(RuntimeEngine runtime) { + _handler._fireUntilHaltThread = null; + } + + private Thread startThread() { + Thread thread = new Thread(this); + String name = new StringBuilder() + .append(_handler.getClass().getSimpleName()) + .append(':') + .append(getClass().getSimpleName()) + .append(':') + .append(FIRE_UNTIL_HALT_COUNT.incrementAndGet()) + .toString(); + thread.setName(name); + thread.setDaemon(true); + thread.start(); + return thread; + } + + } + + + private void fireUntilHalt(Message inputMessage, Exchange exchange, + KnowledgeOperation operation) throws HandlerException { + KnowledgeRuntimeEngine runtime = getSingletonRuntimeEngine(); + // sessionIdentifier = runtime.getSessionIdentifier(); + setGlobals(inputMessage, operation, runtime, true); + KieSession session = runtime.getKieSession(); + if (_fireUntilHaltThread == null + && runtime.getWrapped() instanceof Disposable) { + ClassLoader fireUntilHaltLoader = Classes.getTCCL(); + if (fireUntilHaltLoader == null) { + fireUntilHaltLoader = getLoader(); + } + FireUntilHalt fireUntilHalt = new FireUntilHalt(this, + runtime, fireUntilHaltLoader); + ((Disposable) runtime.getWrapped()) + .addDisposeListener(fireUntilHalt); + _fireUntilHaltThread = fireUntilHalt.startThread(); + } + final String undefinedVariable = toVariable(exchange); + Map> inputMap = getListMap( + inputMessage, + operation.getInputExpressionMappings(), true, + undefinedVariable); + if (inputMap.size() > 0) { + for (Entry> inputEntry : inputMap + .entrySet()) { + String key = inputEntry.getKey(); + if (undefinedVariable.equals(key)) { + String eventId = Strings.trimToNull(operation + .getEventId()); + if (eventId != null) { + key = eventId; + } + } + List facts = inputEntry.getValue(); + if (undefinedVariable.equals(key)) { + for (Object fact : facts) { + session.insert(fact); + } + } else { + EntryPoint entryPoint = session + .getEntryPoint(key); + if (entryPoint != null) { + for (Object fact : facts) { + entryPoint.insert(fact); + } + } else { + throw RulesMessages.MESSAGES + .unknownEntryPoint(key); + } + } + } + } else { + List facts = getInputList(inputMessage, + operation, runtime); + for (Object fact : facts) { + session.insert(fact); + } + } + } + + private int fireAllRules(Message inputMessage, KnowledgeOperation operation) { + KnowledgeRuntimeEngine runtime = getSingletonRuntimeEngine(); + RulesOperationType operationType = (RulesOperationType) operation + .getType(); + // sessionIdentifier = runtime.getSessionIdentifier(); + setGlobals(inputMessage, operation, runtime, true); + KieSession session = runtime.getKieSession(); + List facts = getInputList(inputMessage, operation, runtime); + for (Object fact : facts) { + session.insert(fact); + } + if (RulesOperationType.FIRE_ALL_RULES.equals(operationType)) { + return session.fireAllRules(); + } + return 0; + } + +} diff --git a/components/rules/src/main/java/org/switchyard/component/rules/operation/RulesOperationType.java b/components/rules/src/main/java/org/switchyard/component/rules/operation/RulesOperationType.java new file mode 100644 index 000000000..b7fbd9d62 --- /dev/null +++ b/components/rules/src/main/java/org/switchyard/component/rules/operation/RulesOperationType.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.operation; + +import org.switchyard.component.common.knowledge.operation.KnowledgeOperationType; + +/** + * Represents rules operation types. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum RulesOperationType implements KnowledgeOperationType { + + /** The execute type. */ + EXECUTE, + /** The insert type. */ + INSERT, + /** The fire all rules type. */ + FIRE_ALL_RULES, + /** The fire until halt type. */ + FIRE_UNTIL_HALT; + +} diff --git a/components/rules/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/rules/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..a55e5daea --- /dev/null +++ b/components/rules/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.rules.deploy.RulesComponent diff --git a/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v1/rules_1_0.xsd b/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v1/rules_1_0.xsd new file mode 100644 index 000000000..99368705c --- /dev/null +++ b/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v1/rules_1_0.xsd @@ -0,0 +1,277 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v1/rules_1_1.xsd b/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v1/rules_1_1.xsd new file mode 100644 index 000000000..4f78dcb7c --- /dev/null +++ b/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v1/rules_1_1.xsd @@ -0,0 +1,293 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v2/rules_2_0.xsd b/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v2/rules_2_0.xsd new file mode 100644 index 000000000..e07054b1e --- /dev/null +++ b/components/rules/src/main/resources/org/switchyard/component/rules/config/model/v2/rules_2_0.xsd @@ -0,0 +1,355 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/rules/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/rules/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..8e5f642fb --- /dev/null +++ b/components/rules/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +rules_1_0.section=urn:switchyard-component-rules:config +rules_1_0.version=1.0 +rules_1_0.namespace=urn:switchyard-component-rules:config:1.0 +rules_1_0.schema=rules_1_0.xsd +rules_1_0.location=/org/switchyard/component/rules/config/model/v1/ +rules_1_0.marshaller=org.switchyard.component.rules.config.model.v1.V1RulesMarshaller + +rules_1_1.section=urn:switchyard-component-rules:config +rules_1_1.version=1.1 +rules_1_1.namespace=urn:switchyard-component-rules:config:1.1 +rules_1_1.schema=rules_1_1.xsd +rules_1_1.location=/org/switchyard/component/rules/config/model/v1/ +rules_1_1.marshaller=org.switchyard.component.rules.config.model.v1.V1RulesMarshaller + +rules_2_0.section=urn:switchyard-component-rules:config +rules_2_0.version=2.0 +rules_2_0.namespace=urn:switchyard-component-rules:config:2.0 +rules_2_0.schema=rules_2_0.xsd +rules_2_0.location=/org/switchyard/component/rules/config/model/v2/ +rules_2_0.marshaller=org.switchyard.component.rules.config.model.v2.V2RulesMarshaller diff --git a/components/rules/src/test/java/org/switchyard/component/rules/config/model/DoStuff.java b/components/rules/src/test/java/org/switchyard/component/rules/config/model/DoStuff.java new file mode 100644 index 000000000..ceaf51fc1 --- /dev/null +++ b/components/rules/src/test/java/org/switchyard/component/rules/config/model/DoStuff.java @@ -0,0 +1,7 @@ +package org.switchyard.component.rules.config.model; + +public interface DoStuff { + + public void process(Object stuff); + +} diff --git a/components/rules/src/test/java/org/switchyard/component/rules/config/model/DoStuffRules.java b/components/rules/src/test/java/org/switchyard/component/rules/config/model/DoStuffRules.java new file mode 100644 index 000000000..0118bfe81 --- /dev/null +++ b/components/rules/src/test/java/org/switchyard/component/rules/config/model/DoStuffRules.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model; + +import org.kie.api.event.rule.DebugRuleRuntimeEventListener; +import org.switchyard.component.common.knowledge.LoggerType; +import org.switchyard.component.common.knowledge.annotation.Channel; +import org.switchyard.component.common.knowledge.annotation.Fault; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Listener; +import org.switchyard.component.common.knowledge.annotation.Logger; +import org.switchyard.component.common.knowledge.annotation.Manifest; +import org.switchyard.component.common.knowledge.annotation.Output; +import org.switchyard.component.common.knowledge.annotation.Property; +import org.switchyard.component.common.knowledge.annotation.Resource; +import org.switchyard.component.common.knowledge.annotation.ResourceDetail; +import org.switchyard.component.rules.annotation.FireUntilHalt; +import org.switchyard.component.rules.annotation.Rules; + +/** + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Rules( + channels=@Channel(name="theName", operation="theOperation", reference="theReference", value=RulesModelTests.TestChannel.class), + listeners=@Listener(DebugRuleRuntimeEventListener.class), + loggers=@Logger(interval=2000, log="theLog", type=LoggerType.CONSOLE), + manifest=@Manifest( + //container=@Container(baseName="theBase", scan=true, scanInterval=1000, releaseId="theGroupId:theArtifactId:theVersion", sessionName="theSession"), + resources={ + @Resource(location="foo.drl", type="DRL"), + @Resource(location="bar.dsl", type="DSL"), + @Resource(location="foobar.xls", type="DTABLE", + detail=@ResourceDetail(inputType="XLS", worksheetName="MySheet")) // SWITCHYARD-1662, usingExternalTypes=true)) + }), + properties=@Property(name="foo", value="bar") +) +public interface DoStuffRules extends DoStuff { + + @Override + @FireUntilHalt( + eventId="theEventId", + globals=@Global(from="context['foobar']", to="globalVar"), + inputs=@Input(from="message.content.nested", to="inputVar"), + outputs=@Output(from="outputVar", to="message.content"), + faults=@Fault(from="faultVar", to="message.content") + ) + public void process(Object stuff); + +} diff --git a/components/rules/src/test/java/org/switchyard/component/rules/config/model/RulesModelTests.java b/components/rules/src/test/java/org/switchyard/component/rules/config/model/RulesModelTests.java new file mode 100644 index 000000000..a56624cc7 --- /dev/null +++ b/components/rules/src/test/java/org/switchyard/component/rules/config/model/RulesModelTests.java @@ -0,0 +1,330 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.config.model; + +import java.io.File; +import java.io.StringReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.kie.api.builder.ReleaseId; +import org.kie.api.event.rule.DebugRuleRuntimeEventListener; +import org.kie.api.runtime.Channel; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.io.resource.ResourceDetail; +import org.switchyard.common.io.resource.ResourceType; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.knowledge.LoggerType; +import org.switchyard.component.common.knowledge.config.manifest.ContainerManifest; +import org.switchyard.component.common.knowledge.config.model.ChannelModel; +import org.switchyard.component.common.knowledge.config.model.ContainerModel; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassModel; +import org.switchyard.component.common.knowledge.config.model.ExtraJaxbClassesModel; +import org.switchyard.component.common.knowledge.config.model.FaultModel; +import org.switchyard.component.common.knowledge.config.model.GlobalModel; +import org.switchyard.component.common.knowledge.config.model.InputModel; +import org.switchyard.component.common.knowledge.config.model.ListenerModel; +import org.switchyard.component.common.knowledge.config.model.LoggerModel; +import org.switchyard.component.common.knowledge.config.model.ManifestModel; +import org.switchyard.component.common.knowledge.config.model.OperationModel; +import org.switchyard.component.common.knowledge.config.model.OutputModel; +import org.switchyard.component.common.knowledge.config.model.RemoteJmsModel; +import org.switchyard.component.common.knowledge.config.model.RemoteModel; +import org.switchyard.component.common.knowledge.config.model.RemoteRestModel; +import org.switchyard.component.rules.operation.RulesOperationType; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.resource.ResourceModel; +import org.switchyard.config.model.resource.ResourcesModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Tests Rules models. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RulesModelTests { + + private static final String CONTAINER_XML = "/org/switchyard/component/rules/config/model/RulesModelTests-Container.xml"; + private static final String RESOURCES_XML = "/org/switchyard/component/rules/config/model/RulesModelTests-Resources.xml"; + private static final String REMOTEJMS_XML = "/org/switchyard/component/rules/config/model/RulesModelTests-RemoteJms.xml"; + private static final String REMOTEREST_XML = "/org/switchyard/component/rules/config/model/RulesModelTests-RemoteRest.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @After + public void after() throws Exception { + _puller = null; + } + + @Test + public void testReadContainer() throws Exception { + doTestRead(CONTAINER_XML); + } + + @Test + public void testReadResources() throws Exception { + doTestRead(RESOURCES_XML); + } + + @Test + public void testReadRemoteJms() throws Exception { + doTestRead(REMOTEJMS_XML); + } + + @Test + public void testReadRemoteRest() throws Exception { + doTestRead(REMOTEREST_XML); + } + + private void doTestRead(String xml) throws Exception { + ClassLoader loader = getClass().getClassLoader(); + doTestModel(_puller.pull(xml, loader), xml, loader); + } + + private void doTestModel(SwitchYardModel switchyard, String xml, ClassLoader loader) throws Exception { + CompositeModel composite = switchyard.getComposite(); + ComponentModel component = null; + for (ComponentModel c : composite.getComponents()) { + if (DoStuffRules.class.getSimpleName().equals(c.getName())) { + component = c; + break; + } + } + ComponentImplementationModel implementation = component.getImplementation(); + Assert.assertTrue(implementation instanceof RulesComponentImplementationModel); + RulesComponentImplementationModel rules = (RulesComponentImplementationModel)implementation; + Assert.assertEquals("rules", rules.getType()); + OperationModel operation = rules.getOperations().getOperations().get(0); + Assert.assertEquals("theEventId", operation.getEventId()); + Assert.assertEquals("process", operation.getName()); + Assert.assertEquals(RulesOperationType.FIRE_UNTIL_HALT, operation.getType()); + GlobalModel globalModel = operation.getGlobals().getGlobals().get(0); + Assert.assertEquals("context['foobar']", globalModel.getFrom()); + Assert.assertEquals("globalVar", globalModel.getTo()); + InputModel inputModel = operation.getInputs().getInputs().get(0); + Assert.assertEquals("message.content.nested", inputModel.getFrom()); + Assert.assertEquals("inputVar", inputModel.getTo()); + OutputModel outputModel = operation.getOutputs().getOutputs().get(0); + Assert.assertEquals("outputVar", outputModel.getFrom()); + Assert.assertEquals("message.content", outputModel.getTo()); + FaultModel faultModel = operation.getFaults().getFaults().get(0); + Assert.assertEquals("faultVar", faultModel.getFrom()); + Assert.assertEquals("message.content", faultModel.getTo()); + ChannelModel channel = rules.getChannels().getChannels().get(0); + Assert.assertEquals(TestChannel.class, channel.getClazz(loader)); + Assert.assertEquals("theName", channel.getName()); + Assert.assertEquals("theOperation", channel.getOperation()); + Assert.assertEquals("theReference", channel.getReference()); + ListenerModel listener = rules.getListeners().getListeners().get(0); + Assert.assertEquals(DebugRuleRuntimeEventListener.class, listener.getClazz(loader)); + LoggerModel logger = rules.getLoggers().getLoggers().get(0); + Assert.assertEquals(Integer.valueOf(2000), logger.getInterval()); + Assert.assertEquals("theLog", logger.getLog()); + Assert.assertEquals(LoggerType.CONSOLE, logger.getType()); + ManifestModel manifest = rules.getManifest(); + ContainerModel container = manifest.getContainer(); + ResourcesModel resources = manifest.getResources(); + RemoteModel remote = manifest.getRemote(); + if (CONTAINER_XML.equals(xml)) { + ReleaseId rid = ContainerManifest.toReleaseId(container.getReleaseId()); + Assert.assertEquals("theGroupId", rid.getGroupId()); + Assert.assertEquals("theArtifactId", rid.getArtifactId()); + Assert.assertEquals("theVersion", rid.getVersion()); + Assert.assertEquals("theBase", container.getBaseName()); + Assert.assertEquals("theSession", container.getSessionName()); + Assert.assertTrue(container.isScan()); + Assert.assertEquals(Long.valueOf(1000), container.getScanInterval()); + Assert.assertNull(resources); + } else if (RESOURCES_XML.equals(xml)) { + Assert.assertNull(container); + ResourceModel drlResource = resources.getResources().get(0); + Assert.assertEquals("foo.drl", drlResource.getLocation()); + Assert.assertEquals(ResourceType.valueOf("DRL"), drlResource.getType()); + ResourceModel dslResource = resources.getResources().get(1); + Assert.assertEquals("bar.dsl", dslResource.getLocation()); + Assert.assertEquals(ResourceType.valueOf("DSL"), dslResource.getType()); + ResourceModel dtableResource = resources.getResources().get(2); + Assert.assertEquals("foobar.xls", dtableResource.getLocation()); + Assert.assertEquals(ResourceType.valueOf("DTABLE"), dtableResource.getType()); + ResourceDetail dtableDetail = dtableResource.getDetail(); + Assert.assertEquals("XLS", dtableDetail.getInputType()); + Assert.assertEquals("MySheet", dtableDetail.getWorksheetName()); + /* SWITCHYARD-1662 + Assert.assertEquals(true, dtableDetail.isUsingExternalTypes()); + */ + } else if (REMOTEJMS_XML.equals(xml) || REMOTEREST_XML.equals(xml)) { + Assert.assertNull(container); + Assert.assertNull(resources); + Assert.assertEquals("groupId:artifactId:0.0.1", remote.getDeploymentId()); + Assert.assertEquals("kermit", remote.getUserName()); + Assert.assertEquals("the-frog-1", remote.getPassword()); + Assert.assertEquals(5, remote.getTimeout().intValue()); + ExtraJaxbClassesModel extraJaxbClasses = remote.getExtraJaxbClasses(); + Assert.assertNotNull(extraJaxbClasses); + List extraJaxbClassList = extraJaxbClasses.getExtraJaxbClasses(); + Assert.assertEquals(2, extraJaxbClassList.size()); + Assert.assertEquals(Object.class, extraJaxbClassList.get(0).getClazz(loader)); + Assert.assertEquals(String.class, extraJaxbClassList.get(1).getClazz(loader)); + if (REMOTEJMS_XML.equals(xml)) { + RemoteJmsModel remoteJms = (RemoteJmsModel)remote; + Assert.assertEquals("remotehost", remoteJms.getHostName()); + Assert.assertEquals(4447, remoteJms.getRemotingPort().intValue()); + Assert.assertEquals(5455, remoteJms.getMessagingPort().intValue()); + Assert.assertEquals(true, remoteJms.isUseSsl()); + Assert.assertEquals("ksp", remoteJms.getKeystorePassword()); + Assert.assertEquals("/ksl", remoteJms.getKeystoreLocation()); + Assert.assertEquals("tsp", remoteJms.getTruststorePassword()); + Assert.assertEquals("/tsl", remoteJms.getTruststoreLocation()); + } else if (REMOTEREST_XML.equals(xml)) { + RemoteRestModel remoteRest = (RemoteRestModel)remote; + Assert.assertEquals("http://localhost:8080/kie-wb/", remoteRest.getUrl()); + } + } else { + Assert.fail("couldn't find container, resources, remoteJms, or remoteRest"); + } + PropertyModel property = rules.getProperties().getProperties().get(0); + Assert.assertEquals("foo", property.getName()); + Assert.assertEquals("bar", property.getValue()); + } + + @Test + public void testWriteContainer() throws Exception { + doTestWrite(CONTAINER_XML); + } + + @Test + public void testWriteResources() throws Exception { + doTestWrite(RESOURCES_XML); + } + + @Test + public void testWriteRemoteJms() throws Exception { + doTestWrite(REMOTEJMS_XML); + } + + @Test + public void testWriteRemoteRest() throws Exception { + doTestWrite(REMOTEREST_XML); + } + + private void doTestWrite(String xml) throws Exception { + String old_xml = new StringPuller().pull(xml, getClass()); + SwitchYardModel switchyard = _puller.pull(new StringReader(old_xml)); + String new_xml = switchyard.toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testValidateContainer() throws Exception { + doTestValidate(CONTAINER_XML); + } + + @Test + public void testValidateResources() throws Exception { + doTestValidate(RESOURCES_XML); + } + + @Test + public void testValidateRemoteJms() throws Exception { + doTestValidate(REMOTEJMS_XML); + } + + @Test + public void testValidateRemoteRest() throws Exception { + doTestValidate(REMOTEREST_XML); + } + + private void doTestValidate(String xml) throws Exception { + SwitchYardModel switchyard = _puller.pull(xml, getClass()); + switchyard.assertModelValid(); + } + + @Test + @Ignore + public void testScanContainer() throws Exception { + doTestScan(CONTAINER_XML); + } + + @Test + public void testScanResources() throws Exception { + doTestScan(RESOURCES_XML); + } + + @Test + @Ignore + public void testScanRemoteJms() throws Exception { + doTestScan(REMOTEJMS_XML); + } + + @Test + @Ignore + public void testScanRemoteRest() throws Exception { + doTestScan(REMOTEREST_XML); + } + + private void doTestScan(String xml) throws Exception { + ClassLoader loader = getClass().getClassLoader(); + Scanner scanner = new RulesSwitchYardScanner(); + ScannerInput input = new ScannerInput().setCompositeName(getClass().getSimpleName()); + List urls = new ArrayList(); + String resPath = getClass().getName().replaceAll("\\.", "/") + ".class"; + String urlPath = Classes.getResource(resPath).getPath(); + File file = new File(urlPath.substring(0, urlPath.length() - resPath.length())); + urls.add(file.toURI().toURL()); + input.setURLs(urls); + ScannerOutput output = scanner.scan(input); + SwitchYardModel model = output.getModel(); + CompositeModel composite = model.getComposite(); + Assert.assertEquals(getClass().getSimpleName(), composite.getName()); + doTestModel(model, xml, loader); + } + + @Test + public void testScanEmpty() throws Exception { + Scanner scanner = new RulesSwitchYardScanner(); + ScannerInput input = new ScannerInput(); + ScannerOutput output = scanner.scan(input); + Assert.assertNull("Composite element should not be created if no components were found.", output.getModel().getComposite()); + } + + public static final class TestChannel implements Channel { + @Override + public void send(Object object) { + System.out.println(object); + } + } + +} diff --git a/components/rules/src/test/java/org/switchyard/component/rules/service/Cheese.java b/components/rules/src/test/java/org/switchyard/component/rules/service/Cheese.java new file mode 100644 index 000000000..c4f9011db --- /dev/null +++ b/components/rules/src/test/java/org/switchyard/component/rules/service/Cheese.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.service; + +/** + * Copied from org.drools.decisiontable.Cheese drools test. + */ +public class Cheese { + + private final String _type; + private int _price; + + public Cheese(String type) { + this(type, 0); + } + + public Cheese(String type, int price) { + _type = type; + _price = price; + } + + public String getType() { + return _type; + } + + public int getPrice() { + return _price; + } + + public void setPrice(int price) { + _price = price; + } + +} diff --git a/components/rules/src/test/java/org/switchyard/component/rules/service/Person.java b/components/rules/src/test/java/org/switchyard/component/rules/service/Person.java new file mode 100644 index 000000000..5044d280c --- /dev/null +++ b/components/rules/src/test/java/org/switchyard/component/rules/service/Person.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.service; + +/** + * Copied from org.drools.decisiontable.Person drools test. + */ +public class Person { + + private final String _name; + private final String _likes; + private final int _age; + + public Person() { + this(""); + } + + public Person(String name) { + this(name, ""); + } + + public Person(String name, String likes) { + this(name, likes, 0); + } + + public Person(String name, String likes, int age) { + _name = name; + _likes = likes; + _age = age; + } + + public String getName() { + return _name; + } + + public String getLikes() { + return _likes; + } + + public int getAge() { + return _age; + } + +} diff --git a/components/rules/src/test/java/org/switchyard/component/rules/service/RulesServiceTests.java b/components/rules/src/test/java/org/switchyard/component/rules/service/RulesServiceTests.java new file mode 100644 index 000000000..241c92c45 --- /dev/null +++ b/components/rules/src/test/java/org/switchyard/component/rules/service/RulesServiceTests.java @@ -0,0 +1,164 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.service; + +import java.util.ArrayList; +import java.util.List; + +import javax.activation.DataSource; +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.knowledge.annotation.Global; +import org.switchyard.component.common.knowledge.annotation.Input; +import org.switchyard.component.common.knowledge.annotation.Manifest; +import org.switchyard.component.common.knowledge.annotation.Resource; +import org.switchyard.component.common.knowledge.annotation.ResourceDetail; +import org.switchyard.component.rules.annotation.Execute; +import org.switchyard.component.rules.annotation.FireAllRules; +import org.switchyard.component.rules.annotation.Insert; +import org.switchyard.component.rules.annotation.Rules; +import org.switchyard.component.rules.config.model.RulesComponentImplementationModel; +import org.switchyard.component.rules.config.model.RulesSwitchYardScanner; +import org.switchyard.component.rules.exchange.RulesExchangeHandler; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.test.Invoker; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.TestDataSource; + +/** + * Tests the Rules implementation. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class RulesServiceTests { + + private static final String ACCESS_ATTACHMENT_DRL = "org/switchyard/component/rules/service/RulesServiceTests-AccessAttachment.drl"; + private static final String DECISION_TABLE_XLS = "org/switchyard/component/rules/service/RulesServiceTests-DecisionTable.xls"; + private static final String DECLARE_FACTS_DRL = "org/switchyard/component/rules/service/RulesServiceTests-DeclareFacts.drl"; + + private ServiceDomain serviceDomain; + + @Rules(manifest=@Manifest(resources=@Resource(location=ACCESS_ATTACHMENT_DRL, type="DRL"))) + public interface AccessAttachment { + @Execute(inputs={ + @Input(from="message.attachmentMap['someAttach']"), + @Input(from="message.content") + }) + public Object process(Object content); + } + + @Test + public void testAccessAttachment() throws Exception { + final Holder holder = new Holder(); + RulesComponentImplementationModel rci_model = (RulesComponentImplementationModel)new RulesSwitchYardScanner().scan(AccessAttachment.class).getImplementation(); + QName serviceName = new QName("AccessAttachment"); + RulesExchangeHandler handler = new RulesExchangeHandler(rci_model, serviceDomain, serviceName); + Service service = serviceDomain.registerService(serviceName, JavaService.fromClass(AccessAttachment.class), handler); + serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler()); + handler.start(); + DataSource attachment = new TestDataSource("someAttach", "text/plain", "someAttachData"); + new Invoker(serviceDomain, serviceName).operation("process").attachment(attachment.getName(), attachment).sendInOnly(holder); + handler.stop(); + Assert.assertEquals("someAttachData", holder.getValue()); + } + + @Rules(manifest=@Manifest(resources=@Resource(location=DECISION_TABLE_XLS, type="DTABLE"))) + public interface DecisionTable { + @Insert(globals=@Global(from="context['list']", to="list"), inputs=@Input(from="message.content")) + public Object insert(Object content); + @FireAllRules + public Object fireAllRules(); + } + + @Test + public void testDecisionTable() throws Exception { + RulesComponentImplementationModel rci_model = (RulesComponentImplementationModel)new RulesSwitchYardScanner().scan(DecisionTable.class).getImplementation(); + QName serviceName = new QName("DecisionTable"); + RulesExchangeHandler handler = new RulesExchangeHandler(rci_model, serviceDomain, serviceName); + Service service = serviceDomain.registerService(serviceName, JavaService.fromClass(DecisionTable.class), handler); + serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler()); + handler.start(); + List list = new ArrayList(); + Invoker invoker = new Invoker(serviceDomain, serviceName); + invoker.operation("insert").property("list", list).sendInOnly(new Cheese("stilton", 42)); + invoker.operation("insert").sendInOnly(new Person("michael", "stilton", 42)); + invoker.operation("fireAllRules").sendInOnly(null); + Assert.assertEquals(1, list.size()); + Assert.assertEquals("Old man stilton", list.get(0)); + handler.stop(); + } + + @Rules(manifest=@Manifest(resources=@Resource(location=DECISION_TABLE_XLS, type="DTABLE", + detail=@ResourceDetail(inputType="XLS", worksheetName="Tables_2")))) + public interface NamedWorksheet { + @Insert(globals=@Global(from="context['list']", to="list"), inputs=@Input(from="message.content")) + public Object insert(Object content); + @FireAllRules + public Object fireAllRules(); + } + + @Test + public void testNamedWorksheet() throws Exception { + RulesComponentImplementationModel rci_model = (RulesComponentImplementationModel)new RulesSwitchYardScanner().scan(NamedWorksheet.class).getImplementation(); + QName serviceName = new QName("NamedWorksheet"); + RulesExchangeHandler handler = new RulesExchangeHandler(rci_model, serviceDomain, serviceName); + Service service = serviceDomain.registerService(serviceName, JavaService.fromClass(NamedWorksheet.class), handler); + serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler()); + handler.start(); + List list = new ArrayList(); + Invoker invoker = new Invoker(serviceDomain, serviceName); + invoker.operation("insert").property("list", list).sendInOnly(new Cheese("cheddar", 42)); + invoker.operation("insert").sendInOnly(new Person("michael", "stilton", 25)); + invoker.operation("fireAllRules").sendInOnly(null); + Assert.assertEquals(1, list.size()); + Assert.assertEquals("Young man cheddar", list.get(0)); + handler.stop(); + } + + @Rules(manifest=@Manifest(resources=@Resource(location=DECLARE_FACTS_DRL, type="DRL"))) + public interface DeclareFacts { + @Execute(inputs={ + @Input(from="message.content") + }) + public Object process(Object content); + } + + @Test + public void testDeclareFacts() throws Exception { + final Holder holder = new Holder(); + RulesComponentImplementationModel rci_model = (RulesComponentImplementationModel)new RulesSwitchYardScanner().scan(DeclareFacts.class).getImplementation(); + QName serviceName = new QName("DeclareFacts"); + RulesExchangeHandler handler = new RulesExchangeHandler(rci_model, serviceDomain, serviceName); + Service service = serviceDomain.registerService(serviceName, JavaService.fromClass(DeclareFacts.class), handler); + serviceDomain.registerServiceReference(service.getName(), service.getInterface(), service.getProviderHandler()); + handler.start(); + new Invoker(serviceDomain, serviceName).operation("process").sendInOnly(holder); + handler.stop(); + Assert.assertEquals("handled", holder.getValue()); + } + + public static final class Holder { + private String _value; + public String getValue() { return _value; } + public void setValue(String value) { _value = value; } + public String toString() { return _value; } + } + +} diff --git a/components/rules/src/test/java/org/switchyard/component/rules/session/RulesSessionTests.java b/components/rules/src/test/java/org/switchyard/component/rules/session/RulesSessionTests.java new file mode 100644 index 000000000..8ef961909 --- /dev/null +++ b/components/rules/src/test/java/org/switchyard/component/rules/session/RulesSessionTests.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.session; + +import javax.xml.namespace.QName; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.manager.RuntimeEngine; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManager; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerFactory; +import org.switchyard.component.common.knowledge.runtime.KnowledgeRuntimeManagerType; +import org.switchyard.component.rules.config.model.RulesComponentImplementationModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.ServiceDomainManager; + +/** + * Tests Rules sessions. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class RulesSessionTests { + + private static final String GOOD_RESOURCES = "/org/switchyard/component/rules/session/RulesSessionTests-GoodResources.xml"; + private static final String BAD_RESOURCES = "/org/switchyard/component/rules/session/RulesSessionTests-BadResources.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @After + public void after() throws Exception { + _puller = null; + } + + @Test + public void testGoodResources() throws Exception { + Throwable t = doTestResources(GOOD_RESOURCES); + //t.printStackTrace(); + Assert.assertNull(t); + } + + @Test + public void testBadResources() throws Exception { + Throwable t = doTestResources(BAD_RESOURCES); + //t.printStackTrace(); + Assert.assertNotNull(t); + } + + private Throwable doTestResources(String xml) { + try { + ClassLoader loader = getClass().getClassLoader(); + SwitchYardModel switchyardModel = _puller.pull(xml, loader); + RulesComponentImplementationModel implementationModel = (RulesComponentImplementationModel)switchyardModel.getComposite().getComponents().get(0).getImplementation(); + ServiceDomain serviceDomain = new ServiceDomainManager().createDomain(); + QName serviceName = new QName("test"); + KnowledgeRuntimeManagerFactory runtimeManagerFactory = new KnowledgeRuntimeManagerFactory(loader, serviceDomain, serviceName, implementationModel); + KnowledgeRuntimeManager runtimeManager = runtimeManagerFactory.newRuntimeManager(KnowledgeRuntimeManagerType.SINGLETON); + RuntimeEngine runtimeEngine = runtimeManager.getRuntimeEngine(); + KieSession session = runtimeEngine.getKieSession(); + session.insert(this); + session.fireAllRules(); + runtimeManager.disposeRuntimeEngine(runtimeEngine); + runtimeManager.close(); + return null; + } catch (Throwable t) { + return t; + } + } + +} diff --git a/components/rules/src/test/resources/log4j.properties b/components/rules/src/test/resources/log4j.properties new file mode 100644 index 000000000..462e515a9 --- /dev/null +++ b/components/rules/src/test/resources/log4j.properties @@ -0,0 +1,15 @@ +# The logging properties used during tests +log4j.rootLogger=INFO, file, stdout +log4j.logger.org.switchyard.component.rules=INFO + +# Console appender +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.file=org.apache.log4j.FileAppender +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n +log4j.appender.file.file=target/rules-tests.log +log4j.appender.file.append=true diff --git a/components/rules/src/test/resources/log4j.xml b/components/rules/src/test/resources/log4j.xml new file mode 100644 index 000000000..fbca7fd5f --- /dev/null +++ b/components/rules/src/test/resources/log4j.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-Container.xml b/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-Container.xml new file mode 100644 index 000000000..77a6a80c5 --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-Container.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-RemoteJms.xml b/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-RemoteJms.xml new file mode 100644 index 000000000..d123c192c --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-RemoteJms.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + java.lang.Object + java.lang.String + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-RemoteRest.xml b/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-RemoteRest.xml new file mode 100644 index 000000000..91534003a --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-RemoteRest.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + java.lang.Object + java.lang.String + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-Resources.xml b/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-Resources.xml new file mode 100644 index 000000000..0b57e1cbf --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/config/model/RulesModelTests-Resources.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-AccessAttachment.drl b/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-AccessAttachment.drl new file mode 100644 index 000000000..b2a7266ba --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-AccessAttachment.drl @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.service; + +import javax.activation.DataSource; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.rules.service.RulesServiceTests.Holder; + +rule "AccessAttachment" + when + $attachment : DataSource() + $holder : Holder() + then + $holder.setValue(new StringPuller().pull($attachment.getInputStream())); +end diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-DecisionTable.xls b/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-DecisionTable.xls new file mode 100644 index 000000000..31d03363e Binary files /dev/null and b/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-DecisionTable.xls differ diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-DeclareFacts.drl b/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-DeclareFacts.drl new file mode 100644 index 000000000..29e745399 --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/service/RulesServiceTests-DeclareFacts.drl @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.service; + +import org.switchyard.component.rules.service.RulesServiceTests.Holder; + +declare Bucket + holder : Holder +end + +rule "MatchOnHolder" + when + $holder : Holder() + then + insertLogical(new Bucket($holder)); +end + +rule "MatchOnBucket" + when + $bucket : Bucket() + then + $bucket.getHolder().setValue("handled"); +end diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-BadResources.xml b/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-BadResources.xml new file mode 100644 index 000000000..968d2c388 --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-BadResources.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-BadRules.drl b/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-BadRules.drl new file mode 100644 index 000000000..6bd9a6c67 --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-BadRules.drl @@ -0,0 +1,24 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.session; + +import org.switchyard.component.rules.session.RulesSessionTests; + +rule "Bad Rule" + when + // Purposely add an extra 's' to cause DRL failure. + $rst : RulesSessionTestss() + then + System.out.println($rst); +end diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-GoodResources.xml b/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-GoodResources.xml new file mode 100644 index 000000000..681369cc5 --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-GoodResources.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-GoodRules.drl b/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-GoodRules.drl new file mode 100644 index 000000000..522c6ab4d --- /dev/null +++ b/components/rules/src/test/resources/org/switchyard/component/rules/session/RulesSessionTests-GoodRules.drl @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.rules.session; + +import org.switchyard.component.rules.session.RulesSessionTests; + +rule "Good Rule" + when + $rst : RulesSessionTests() + then + System.out.println($rst); +end diff --git a/components/sca/pom.xml b/components/sca/pom.xml new file mode 100644 index 000000000..5eb58eba4 --- /dev/null +++ b/components/sca/pom.xml @@ -0,0 +1,135 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-sca + bundle + SwitchYard: SCA Component + http://switchyard.org + + + org.switchyard.component.sca.* + + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.switchyard.components + switchyard-component-common + + + org.switchyard + switchyard-remote + + + org.switchyard + switchyard-serial + + + org.infinispan + infinispan-core + + + org.jboss.spec.javax.servlet + jboss-servlet-api_3.0_spec + + + org.jboss.jbossts + jbosstxbridge + + + org.jboss.jbossts.jta + narayana-jta + + + org.jboss.jbossts.xts + jbossxts + + + org.osgi + org.osgi.core + provided + + + org.osgi + org.osgi.compendium + provided + + + org.switchyard + switchyard-runtime + test-jar + test + + + org.mockito + mockito-all + test + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + attach-artifacts + package + + attach-artifact + + + + + target/classes/sca.properties + properties + sca + + + target/classes/infinispan-switchyard.xml + xml + infinispan-switchyard + + + + + + + + + diff --git a/components/sca/src/main/java/org/switchyard/component/sca/NOPEndpointPublisher.java b/components/sca/src/main/java/org/switchyard/component/sca/NOPEndpointPublisher.java new file mode 100644 index 000000000..f508d950c --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/NOPEndpointPublisher.java @@ -0,0 +1,67 @@ +package org.switchyard.component.sca; + +import javax.xml.namespace.QName; + +import org.switchyard.ServiceDomain; + +/** + * This is a dummy implementation of RemoteEndpointPublisher that exists solely to satisfy + * the publisher service requirement in unit tests. The SY JBoss AS extension has a real + * implementation of this contract. + */ +public class NOPEndpointPublisher implements RemoteEndpointPublisher { + + @Override + public void init(String context) { + // TODO Auto-generated method stub + + } + + @Override + public void start() throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public void stop() throws Exception { + // TODO Auto-generated method stub + + } + + @Override + public void addService(QName serviceName, ServiceDomain domain) { + // TODO Auto-generated method stub + + } + + @Override + public void removeService(QName serviceName, ServiceDomain domain) { + // TODO Auto-generated method stub + + } + + @Override + public ServiceDomain getDomain(QName serviceName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getAddress() { + // TODO Auto-generated method stub + return null; + } + + @Override + public RemoteEndpointPublisher setDisableRemoteTransaction( + boolean _bridgeRemoteTransaction) { + return this; + } + + @Override + public boolean isDisableRemoteTransaction() { + return false; + } + +} diff --git a/components/sca/src/main/java/org/switchyard/component/sca/OsgiRemoteEndpointPublisher.java b/components/sca/src/main/java/org/switchyard/component/sca/OsgiRemoteEndpointPublisher.java new file mode 100644 index 000000000..9596e0913 --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/OsgiRemoteEndpointPublisher.java @@ -0,0 +1,146 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.sca; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.osgi.service.http.HttpService; +import org.switchyard.ServiceDomain; + +/** + * Instance of SCA RemoteEndpointPublisher which integrates SwitchYardRemotingServlet + * with the OSGi HTTP Service. + */ +public class OsgiRemoteEndpointPublisher implements RemoteEndpointPublisher { + + private HttpService _httpService; + private boolean _started; + private String _contextName; + private String _address; + private int _port; + private Map _services = new ConcurrentHashMap(); + private boolean _disableRemoteTransaction = false; + + private static Logger _log = Logger.getLogger(OsgiRemoteEndpointPublisher.class); + + /** + * Used by blueprint to set the HttpService reference. + * @param httpService the OSGi HTTP service + */ + public void setHttpService(HttpService httpService) { + _httpService = httpService; + } + + @Override + public void init(String context) { + _contextName = context; + } + + @Override + public synchronized void start() throws Exception { + // If the remote listener is already started, just return. + if (_started) { + return; + } + + if (_address == null || _address.trim().length() == 0) { + _address = createEndpointURL(); + } + + SwitchYardRemotingServlet servlet = new SwitchYardRemotingServlet(); + servlet.setEndpointPublisher(this); + _httpService.registerServlet("/" + _contextName, servlet, null, null); + _started = true; + } + + @Override + public synchronized void stop() throws Exception { + _started = false; + } + + @Override + public void addService(QName serviceName, ServiceDomain domain) { + _services.put(serviceName, domain); + } + + @Override + public void removeService(QName serviceName, ServiceDomain domain) { + _services.remove(serviceName); + } + + @Override + public ServiceDomain getDomain(QName serviceName) { + return _services.get(serviceName); + } + + @Override + public String getAddress() { + return _address; + } + + @Override + public RemoteEndpointPublisher setDisableRemoteTransaction(boolean disable) { + _disableRemoteTransaction = disable; + return this; + } + + @Override + public boolean isDisableRemoteTransaction() { + return _disableRemoteTransaction; + } + + /** + * Set the endpoint URL for the remote listener. Setting the endpoint + * address URL overrides any value set for port. + * @param address endpoint URL address + */ + public void setAddress(String address) { + _address = address; + } + + /** + * Returns the port for the remote endpoint listener. + * @return HTTP port for the remote endpoint listener + */ + public int getPort() { + return _port; + } + + /** + * Sets the port for the remote endpoint listener. + * @param port HTTP port for the remote endpoint listener + */ + public void setPort(int port) { + _port = port; + } + + private String createEndpointURL() { + String host; + try { + host = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException hostEx) { + _log.debug("Unable to determine host IP for remote endpoint URL", hostEx); + host = "localhost"; + } + + return "http://" + host + ":" + _port + "/" + _contextName; + } + +} diff --git a/components/sca/src/main/java/org/switchyard/component/sca/RemoteEndpointPublisher.java b/components/sca/src/main/java/org/switchyard/component/sca/RemoteEndpointPublisher.java new file mode 100644 index 000000000..45f4ccbc8 --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/RemoteEndpointPublisher.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.sca; + +import javax.xml.namespace.QName; + +import org.switchyard.ServiceDomain; + +/** + * Interface for allowing SwitchYard to publish an HTTP endpoint for remote service invocations. + * Based on HTTP gateway endpoint contract. A single HTTP endpoint is used for all remote service + * bindings in an instance, so the endpoint has internal dispatch logic to get a given request + * to the correct service. + */ +public interface RemoteEndpointPublisher { + + /** + * Publish a remote HTTP endpoint. + * @param context The web context root where the resource need to be published + */ + void init(String context); + + /** + * Start the endpoint. Multiple calls to start() should be safe and be considered a NOP by + * implementations. + * @throws Exception failed to start + */ + void start() throws Exception; + + /** + * Stop the endpoint. + * @throws Exception failed to stop + */ + void stop() throws Exception; + + /** + * Register a service with the endpoint. This allows the endpoint to dispatch inbound + * requests to a registered service. + * @param serviceName the name of the service + * @param domain the domain in which it's registered + */ + void addService(QName serviceName, ServiceDomain domain); + + /** + * Remove a service endpoint. + * @param serviceName the service name + * @param domain the domain in which it's registered + */ + void removeService(QName serviceName, ServiceDomain domain); + + /** + * Get the service domain for a given registered service. + * @param serviceName name of the service + * @return service domain + */ + ServiceDomain getDomain(QName serviceName); + + /** + * The endpoint URL for this remote endpoint. + * @return endpoint URL as a string + */ + String getAddress(); + + /** + * Set if remote transaction bridging should be disabled. + * @param _disableRemoteTransaction true if it disables remote transaction + * @return this RemoteEndpointPublisher instance (useful for method chaining) + */ + RemoteEndpointPublisher setDisableRemoteTransaction(boolean _disableRemoteTransaction); + + /** + * Get if remote transaction bridging should be disabled. + * @return true if it disables remote transaction + */ + boolean isDisableRemoteTransaction(); +} diff --git a/components/sca/src/main/java/org/switchyard/component/sca/SCAEndpoint.java b/components/sca/src/main/java/org/switchyard/component/sca/SCAEndpoint.java new file mode 100644 index 000000000..6d53b4c6b --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/SCAEndpoint.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.sca; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.config.model.composite.SCABindingModel; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.remote.RemoteEndpoint; +import org.switchyard.remote.RemoteRegistry; + +/** + * Represents a service endpoint binding using . + */ +public class SCAEndpoint extends BaseServiceHandler { + + private RemoteEndpointPublisher _endpointPublisher; + private ServiceDomain _domain; + private RemoteRegistry _registry; + private RemoteEndpoint _endpoint; + private SCABindingModel _bindingModel; + + /** + * Create a new handler for binding.sca service endpoints. + * @param bindingModel The configuration model. + * @param domain service domain used for the service + * @param endpointPublisher endpoint publisher + * @param registry remote registry + */ + public SCAEndpoint(SCABindingModel bindingModel, + ServiceDomain domain, + RemoteEndpointPublisher endpointPublisher, + RemoteRegistry registry) { + super(domain); + _bindingModel = bindingModel; + _endpointPublisher = endpointPublisher; + _domain = domain; + _registry = registry; + } + + @Override + protected void doStart() { + QName serviceName = _bindingModel.getService().getQName(); + _endpointPublisher.addService(serviceName, _domain); + List services = _domain.getServices(serviceName); + if (services.isEmpty()) { + throw SCAMessages.MESSAGES.failedToResolveServiceInDomain(serviceName.toString()); + } + + if (_bindingModel.isClustered()) { + // The registry can be null in test environments or if the cache is misconfigured + if (_registry != null) { + _endpoint = RemoteEndpoint.fromService(services.get(0)); + _endpoint.setEndpoint(_endpointPublisher.getAddress()); + _registry.addEndpoint(_endpoint); + } else { + SCALogger.ROOT_LOGGER.cannotEnableClusteredSCABindingFor(serviceName.toString()); + } + } + } + + @Override + protected void doStop() { + if (_bindingModel.isClustered() && _registry != null) { + _registry.removeEndpoint(_endpoint); + } + _endpointPublisher.removeService(_bindingModel.getService().getQName(), _domain); + } + + /** + * Get the EndpointPublisher instance used by this endpoint. + * @return endpoint publisher + */ + public RemoteEndpointPublisher getEndpointPublisher() { + return _endpointPublisher; + } +} diff --git a/components/sca/src/main/java/org/switchyard/component/sca/SCAInvoker.java b/components/sca/src/main/java/org/switchyard/component/sca/SCAInvoker.java new file mode 100644 index 000000000..e83195024 --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/SCAInvoker.java @@ -0,0 +1,332 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.sca; + +import javax.transaction.Transaction; +import javax.xml.namespace.QName; + +import org.jboss.jbossts.txbridge.outbound.OutboundBridge; +import org.jboss.jbossts.txbridge.outbound.OutboundBridgeManager; +import org.jboss.logging.Logger; +import org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationContextType; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceReference; +import org.switchyard.SwitchYardException; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.config.model.composite.SCABindingModel; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.deploy.internal.Deployment; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.RemoteRegistry; +import org.switchyard.remote.cluster.ClusteredInvoker; +import org.switchyard.remote.cluster.LoadBalanceStrategy; +import org.switchyard.remote.cluster.RandomStrategy; +import org.switchyard.remote.cluster.RoundRobinStrategy; +import org.switchyard.remote.http.HttpInvokerLabel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +import com.arjuna.mw.wst11.TransactionManagerFactory; +import com.arjuna.mwlabs.wst11.at.context.TxContextImple; + +/** + * Handles outbound communication to an SCA service endpoint. + */ +public class SCAInvoker extends BaseServiceHandler { + + private static Logger _log = Logger.getLogger(SCAInvoker.class); + + private final String _bindingName; + private final String _referenceName; + private final String _targetService; + private final String _targetNamespace; + private final boolean _clustered; + private ClusteredInvoker _invoker; + private boolean _preferLocal; + private boolean _disableRemoteTransaction = false; + private TransactionContextSerializer _txSerializer = new TransactionContextSerializer(); + + /** + * Create a new SCAInvoker for invoking local endpoints. + * @param config binding configuration model + */ + public SCAInvoker(SCABindingModel config) { + _bindingName = config.getName(); + _referenceName = config.getReference().getName(); + _targetService = config.getTarget(); + _targetNamespace = config.getTargetNamespace(); + _clustered = config.isClustered(); + _preferLocal = config.isPreferLocal(); + } + + /** + * Create a new SCAInvoker capable of invoking remote service endpoints. + * @param config binding configuration model + * @param registry registry of remote services + */ + public SCAInvoker(SCABindingModel config, RemoteRegistry registry) { + this(config); + if (config.isLoadBalanced()) { + LoadBalanceStrategy loadBalancer = createLoadBalancer(config.getLoadBalance()); + _invoker = new ClusteredInvoker(registry, loadBalancer); + } else { + _invoker = new ClusteredInvoker(registry); + } + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // identify ourselves + exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + + if (getState() != State.STARTED) { + throw SCAMessages.MESSAGES.referenceBindingNotStarted(_referenceName, _bindingName); + } + try { + // Figure out the QName for the service were invoking + QName serviceName = getTargetServiceName(exchange); + // Get a handle for the reference and use a copy of the exchange to invoke it + ServiceReference ref = exchange.getProvider().getDomain().getServiceReference(serviceName); + + if (_clustered) { + // check to see if local is preferred and available + if (_preferLocal && ref != null) { + invokeLocal(exchange, ref); + } else { + invokeRemote(exchange, serviceName); + } + } else { + if (ref == null) { + throw SCAMessages.MESSAGES.serviceReferenceNotFoundInDomain(serviceName.toString(), exchange.getProvider().getDomain().getName().toString()); + } + invokeLocal(exchange, ref); + } + } catch (SwitchYardException syEx) { + throw new HandlerException(syEx.getMessage()); + } + } + + /** + * Set if remote transaction bridging should be disabled. + * @param disable true if it disables remote transaction + * @return this SCAInvoker instance (useful for method chaining) + */ + public SCAInvoker setDisableRemoteTransaction(boolean disable) { + _disableRemoteTransaction = disable; + return this; + } + + // This method exists for test purposes and should not be used at runtime. Initialization + // of the invoker instance occurs in the constructor for SCAInvoker. + void setInvoker(ClusteredInvoker invoker) { + _invoker = invoker; + } + + private void invokeLocal(Exchange exchange, ServiceReference targetRef) throws HandlerException { + SynchronousInOutHandler replyHandler = new SynchronousInOutHandler(); + Exchange ex = targetRef.createExchange(exchange.getContract().getProviderOperation().getName(), replyHandler); + + // Can't send same message twice, so make a copy + Message invokeMsg = exchange.getMessage().copy(); + exchange.getContext().mergeInto(invokeMsg.getContext()); + + // Since this invocation may cross application boundaries, we need to set the TCCL + // based on the target service's application class loader + ClassLoader origCL = null; + try { + ClassLoader targetCL = (ClassLoader) + targetRef.getDomain().getProperty(Deployment.CLASSLOADER_PROPERTY); + origCL = Classes.setTCCL(targetCL); + ex.send(invokeMsg); + } finally { + if (origCL != null) { + Classes.setTCCL(origCL); + } + } + + if (ExchangePattern.IN_OUT.equals(ex.getPattern())) { + replyHandler.waitForOut(); + if (ex.getMessage() != null) { + Message replyMsg = ex.getMessage().copy(); + ex.getContext().mergeInto(replyMsg.getContext()); + if (ExchangeState.FAULT.equals(ex.getState())) { + exchange.sendFault(replyMsg); + } else { + exchange.send(replyMsg); + } + } + } else if (ExchangeState.FAULT.equals(ex.getState())) { + // Even though this is in-only, we need to report a runtime fault on send + throw createHandlerException(ex.getMessage()); + } + } + + private void invokeRemote(Exchange exchange, QName serviceName) throws HandlerException { + + RemoteMessage request = new RemoteMessage() + .setDomain(exchange.getProvider().getDomain().getName()) + .setService(serviceName) + .setOperation(exchange.getContract().getConsumerOperation().getName()) + .setContent(exchange.getMessage().getContent()); + exchange.getContext().mergeInto(request.getContext()); + boolean transactionPropagated = bridgeOutgoingTransaction(request); + + try { + RemoteMessage reply = _invoker.invoke(request); + if (transactionPropagated) { + bridgeIncomingTransaction(); + } + if (reply == null) { + return; + } + + if (ExchangePattern.IN_OUT.equals(exchange.getPattern())) { + Message msg = exchange.createMessage(); + msg.setContent(reply.getContent()); + Context replyCtx = reply.getContext(); + if (replyCtx != null) { + replyCtx.mergeInto(exchange.getContext()); + } + if (reply.isFault()) { + exchange.sendFault(msg); + } else { + exchange.send(msg); + } + } else { + // still need to account for runtime exceptions on in-only + if (reply.isFault()) { + throw createHandlerException(reply.getContent()); + } + } + } catch (java.io.IOException ioEx) { + ioEx.printStackTrace(); + exchange.sendFault(exchange.createMessage().setContent(ioEx)); + } + } + + private QName getTargetServiceName(Exchange exchange) { + // Figure out the QName for the service were invoking + QName service = exchange.getProvider().getName(); + String targetName = _targetService != null ? _targetService : service.getLocalPart(); + String targetNS = _targetNamespace != null ? _targetNamespace : service.getNamespaceURI(); + return new QName(targetNS, targetName); + } + + private boolean bridgeOutgoingTransaction(RemoteMessage request) throws HandlerException { + if (_disableRemoteTransaction) { + return false; + } + + Transaction currentTransaction = null; + try { + currentTransaction = com.arjuna.ats.jta.TransactionManager.transactionManager().getTransaction(); + } catch (Throwable t) { + if (_log.isDebugEnabled()) { + _log.debug(t); + } + } + if (currentTransaction == null) { + return false; + } + + try { + // create/resume subordinate WS-AT transaction + OutboundBridge txOutboundBridge = OutboundBridgeManager.getOutboundBridge(); + if (txOutboundBridge == null) { + return false; + } + txOutboundBridge.start(); + + // embed WS-AT transaction context into request header + final com.arjuna.mw.wst11.TransactionManager wsatManager = TransactionManagerFactory.transactionManager(); + CoordinationContextType coordinationContext = null; + if (wsatManager != null) { + final TxContextImple txContext = (TxContextImple)wsatManager.currentTransaction(); + if (txContext != null) { + coordinationContext = txContext.context().getCoordinationContext(); + } + } + + if (coordinationContext != null) { + String txContextString = _txSerializer.serialise(coordinationContext); + if (_log.isDebugEnabled()) { + _log.debug("Embedding transaction context into request header: " + txContextString); + } + request.getContext() + .setProperty(TransactionContextSerializer.HEADER_TXCONTEXT, txContextString) + .addLabels(BehaviorLabel.TRANSIENT.label(), HttpInvokerLabel.HEADER.label()); + } + return true; + } catch (final Throwable th) { + throw createHandlerException(th); + } + } + + private void bridgeIncomingTransaction() throws HandlerException { + // disassociate subordinate WS-AT transaction + OutboundBridge txOutboundBridge = OutboundBridgeManager.getOutboundBridge(); + if (txOutboundBridge != null) { + try { + txOutboundBridge.stop(); + } catch (Exception e) { + throw createHandlerException(e); + } + } + } + + private HandlerException createHandlerException(Message message) { + return createHandlerException(message == null ? null : message.getContent()); + } + + private HandlerException createHandlerException(Object content) { + HandlerException ex; + if (content == null) { + ex = SCAMessages.MESSAGES.runtimeFaultOccurredWithoutExceptionDetails(); + } else if (content instanceof HandlerException) { + ex = (HandlerException)content; + } else if (content instanceof Throwable) { + ex = new HandlerException((Throwable)content); + } else { + ex = new HandlerException(content.toString()); + } + return ex; + } + + + LoadBalanceStrategy createLoadBalancer(String strategy) { + if (RoundRobinStrategy.class.getSimpleName().equals(strategy)) { + return new RoundRobinStrategy(); + } else if (RandomStrategy.class.getSimpleName().equals(strategy)) { + return new RandomStrategy(); + } else { + try { + Class strategyClass = Class.forName(strategy); + if (!LoadBalanceStrategy.class.isAssignableFrom(strategyClass)) { + throw SCAMessages.MESSAGES.loadBalanceClassDoesNotImplementLoadBalanceStrategy(strategy); + } + return (LoadBalanceStrategy)strategyClass.newInstance(); + } catch (Exception ex) { + throw SCAMessages.MESSAGES.unableToInstantiateStrategyClass(strategy, ex); + } + } + } +} diff --git a/components/sca/src/main/java/org/switchyard/component/sca/SCALogger.java b/components/sca/src/main/java/org/switchyard/component/sca/SCALogger.java new file mode 100644 index 000000000..7760b7ce3 --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/SCALogger.java @@ -0,0 +1,77 @@ +package org.switchyard.component.sca; + +import org.jboss.logging.Cause; +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 39200-39599 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface SCALogger { + /** + * A root logger with the category of the package name. + */ + SCALogger ROOT_LOGGER = Logger.getMessageLogger(SCALogger.class, SCALogger.class.getPackage().getName()); + + /** + * unableToResolveCacheContainer method definition. + * @param cacheName the cacheName + */ + @LogMessage(level = Level.INFO) + @Message(id = 39200, value = "Unable to resolve cache-container %s. clustering for will not be available for services and references.") + void unableToResolveCacheContainer(String cacheName); + + /** + * failedToStartRemoteEndpointListenerForSCAEndpoints method definition. + * @param ex the ex + */ + @LogMessage(level = Level.WARN) + @Message(id = 39201, value = "Failed to start remote endpoint listener for SCA endpoints.") + void failedToStartRemoteEndpointListenerForSCAEndpoints(@Cause Exception ex); + + /** + * failedToInitializeRemoteEndpointPublisher method definition. + * @param ex the ex + */ + @LogMessage(level = Level.WARN) + @Message(id = 39202, value = "Failed to initialize remote endpoint publisher") + void failedToInitializeRemoteEndpointPublisher(@Cause Exception ex); + + /** + * failedToDestroyRemoteEndpointPublisher method definition. + * @param ex the ex + */ + @LogMessage(level = Level.WARN) + @Message(id = 39203, value = "Failed to destroy remote endpoint publisher") + void failedToDestroyRemoteEndpointPublisher(@Cause Exception ex); + + /** + * cannotEnableClusteredSCABindingFor method definition. + * @param serviceName the serviceName + */ + @LogMessage(level = Level.WARN) + @Message(id = 39204, value = "Cannot enable clustered SCA binding for %s. No distributed cache is avaialble.") + void cannotEnableClusteredSCABindingFor(String serviceName); + + /** + * noEndpointPublisherRegistered method definition. + */ + @LogMessage(level = Level.WARN) + @Message(id = 39205, value = "No endpoint publisher service registered. Defaulting to NO-OP publisher.") + void noEndpointPublisherRegistered(); + + /** + * ignoringReceivedTransactionContext method definition. + */ + @LogMessage(level = Level.WARN) + @Message(id = 39206, value = "Transaction context was received through remote SCA invocation, but remote transaction bridging is disabled on this node. Ignoring.") + void ignoringReceivedTransactionContext(); + +} + diff --git a/components/sca/src/main/java/org/switchyard/component/sca/SCAMessages.java b/components/sca/src/main/java/org/switchyard/component/sca/SCAMessages.java new file mode 100644 index 000000000..9d22327d7 --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/SCAMessages.java @@ -0,0 +1,95 @@ +package org.switchyard.component.sca; + +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; +/** + *

+ * This file is using the subset 39600-39999 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface SCAMessages { + /** + * The default messages. + */ + SCAMessages MESSAGES = Messages.getBundle(SCAMessages.class); + + /** + * invalidSCABindingForReferenceTargetServiceOrNamespaceMustBeSpecified method definition. + * @return IllegalArgumentException + */ + @Message(id = 39600, value = "Invalid SCA binding for reference - target service or namespace must be specified") + IllegalArgumentException invalidSCABindingForReferenceTargetServiceOrNamespaceMustBeSpecified(); + + /** + * failedToResolveServiceInDomain method definition. + * @param serviceName the serviceName + * @return SwitchYardException + */ + @Message(id = 39601, value = "Failed to resolve service in domain %s") + SwitchYardException failedToResolveServiceInDomain(String serviceName); + + /** + * referenceBindingNotStarted method definition. + * @param referenceName referenceName + * @param bindingName bindingName + * @return HandlerException + */ + @Message(id = 39602, value = "Reference binding \"%s/%s\" is not started.") + HandlerException referenceBindingNotStarted(String referenceName, String bindingName); + + /** + * serviceReferenceNotFoundInDomain method definition. + * @param serviceName the serviceName + * @param exchangeProviderDomainName exchangeProviderDomainName + * @return HandlerException + */ + @Message(id = 39604, value = "Service reference %s not found in domain %s") + HandlerException serviceReferenceNotFoundInDomain(String serviceName, String exchangeProviderDomainName); + + /** + * loadBalanceClassDoesNotImplementLoadBalanceStrategy method definition. + * @param strategy the strategy + * @return SwitchYardException + */ + @Message(id = 39605, value = "Load balance class does not implement LoadBalanceStrategy: %s") + SwitchYardException loadBalanceClassDoesNotImplementLoadBalanceStrategy(String strategy); + + /** + * unableToInstantiateStrategyClass method definition. + * @param strategy the strategy + * @param ex the ex + * @return SwitchYardException + */ + @Message(id = 39606, value = "Unable to instantiate strategy class: %s") + SwitchYardException unableToInstantiateStrategyClass(String strategy, @Cause Exception ex); + + /** + * requiredHeaderIsMissingOrEmpty method definition. + * @param serviceHeader serviceHeader + * @return SwitchYardException + */ + @Message(id = 39607, value = "Required '%s' header is missing or empty") + SwitchYardException requiredHeaderIsMissingOrEmpty(String serviceHeader); + + /** + * unableToFindServiceDomainForService method definition. + * @param service the service + * @return SwitchYardException + */ + @Message(id = 39608, value = "Unable to find ServiceDomain for service: %s. Verify the service name and namespace are registered in the runtime.") + SwitchYardException unableToFindServiceDomainForService(String service); + + /** + * runtimeFaultOccurredWithoutExceptionDetails method definition. + * @return HandlerException + */ + @Message(id = 39609, value = "Runtime fault occurred without exception details!") + HandlerException runtimeFaultOccurredWithoutExceptionDetails(); +} + diff --git a/components/sca/src/main/java/org/switchyard/component/sca/SwitchYardRemotingServlet.java b/components/sca/src/main/java/org/switchyard/component/sca/SwitchYardRemotingServlet.java new file mode 100644 index 000000000..5905c2a32 --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/SwitchYardRemotingServlet.java @@ -0,0 +1,240 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.sca; + +import java.io.IOException; +import java.io.OutputStream; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.jboss.jbossts.txbridge.inbound.InboundBridge; +import org.jboss.jbossts.txbridge.inbound.InboundBridgeManager; +import org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationContextType; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangeState; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.SwitchYardException; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.deploy.internal.Deployment; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; + +import com.arjuna.mw.wst.TxContext; +import com.arjuna.mw.wst11.TransactionManagerFactory; +import com.arjuna.mwlabs.wst11.at.context.TxContextImple; + +/** + * HTTP servlet which handles inbound remote communication for remote service endpoints. + */ +public class SwitchYardRemotingServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + private static Logger _log = Logger.getLogger(SwitchYardRemotingServlet.class); + + private Serializer _serializer = SerializerFactory.create(FormatType.JSON, null, true); + private TransactionContextSerializer _txSerializer = new TransactionContextSerializer(); + private RemoteEndpointPublisher _endpointPublisher; + + /** + * {@inheritDoc} + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ClassLoader setTCCL = null; + boolean transactionPropagated = false; + + try { + // Grab the right service domain based on the service header + ServiceDomain domain = findDomain(request); + // Set our TCCL to the domain's deployment loader + ClassLoader loader = (ClassLoader) domain.getProperty(Deployment.CLASSLOADER_PROPERTY); + setTCCL = Classes.setTCCL(loader); + + transactionPropagated = bridgeIncomingTransaction(request); + + RemoteMessage msg = _serializer.deserialize(request.getInputStream(), RemoteMessage.class); + if (_log.isDebugEnabled()) { + _log.debug("Remote servlet received request for service " + msg.getService()); + } + + ServiceReference service = domain.getServiceReference(msg.getService()); + SynchronousInOutHandler replyHandler = new SynchronousInOutHandler(); + Exchange ex = msg.getOperation() == null + ? service.createExchange(replyHandler) + : service.createExchange(msg.getOperation(), replyHandler); + Message m = ex.createMessage(); + if (msg.getContext() != null) { + m.getContext().setProperties(msg.getContext().getProperties()); + } + m.setContent(msg.getContent()); + + if (_log.isDebugEnabled()) { + _log.debug("Invoking service " + msg.getService()); + } + ex.send(m); + + // handle reply or fault + RemoteMessage reply = null; + if (ExchangePattern.IN_OUT.equals(ex.getPattern())) { + replyHandler.waitForOut(); + reply = createReplyMessage(ex); + } else if (ExchangeState.FAULT.equals(ex.getState())) { + // Even though this is in-only, we need to report a runtime fault on send + reply = createReplyMessage(ex); + } + if (transactionPropagated) { + bridgeOutgoingTransaction(); + transactionPropagated = false; + } + + // If there's a reply, send it back + if (reply != null) { + OutputStream out = response.getOutputStream(); + if (_log.isDebugEnabled()) { + _log.debug("Writing reply message to HTTP response stream " + msg.getService()); + } + _serializer.serialize(reply, RemoteMessage.class, out); + out.flush(); + } else { + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (_log.isDebugEnabled()) { + _log.debug("No content to return for invocation of " + msg.getService()); + } + } + } catch (SwitchYardException syEx) { + if (_log.isDebugEnabled()) { + _log.debug("Failed to process remote invocation", syEx); + } + + RemoteMessage reply = new RemoteMessage(); + reply.setFault(true); + reply.setContent(syEx); + _serializer.serialize(reply, RemoteMessage.class, response.getOutputStream()); + response.getOutputStream().flush(); + } finally { + if (transactionPropagated) { + bridgeOutgoingTransaction(); + } + + if (setTCCL != null) { + Classes.setTCCL(setTCCL); + } + } + } + + private boolean bridgeIncomingTransaction(HttpServletRequest request) { + try { + // extract WS-AT transaction context from response header and resume it + String txContextHeader = request.getHeader(TransactionContextSerializer.HEADER_TXCONTEXT); + if (txContextHeader == null) { + return false; + } else { + if (_log.isDebugEnabled()) { + _log.debug("Transaction context is found in request message: " + txContextHeader); + } + + if (_endpointPublisher.isDisableRemoteTransaction()) { + SCALogger.ROOT_LOGGER.ignoringReceivedTransactionContext(); + return false; + } + + ClassLoader origCl = Thread.currentThread().getContextClassLoader(); + CoordinationContextType cc = null; + try { + Thread.currentThread().setContextClassLoader(SwitchYardRemotingServlet.class.getClassLoader()); + cc = _txSerializer.deserialise(txContextHeader); + } finally { + Thread.currentThread().setContextClassLoader(origCl); + } + final TxContext txContext = new TxContextImple(cc); + TransactionManagerFactory.transactionManager().resume(txContext); + + // create or resume subordinate JTA transaction + InboundBridge txInboundBridge = InboundBridgeManager.getInboundBridge(); + txInboundBridge.start(); + return true; + } + } catch (Throwable t) { + throw new SwitchYardException(t); + } + } + + private void bridgeOutgoingTransaction() { + try { + // disassociate subordinate JTA transaction + InboundBridge txInboundBridge = InboundBridgeManager.getInboundBridge(); + txInboundBridge.stop(); + + // disassociate WS-AT transaction + final com.arjuna.mw.wst11.TransactionManager wsatManager = TransactionManagerFactory.transactionManager(); + if (wsatManager != null) { + wsatManager.suspend(); + } + } catch (final Throwable th) { + throw new SwitchYardException(th); + } + } + + private ServiceDomain findDomain(HttpServletRequest request) throws SwitchYardException { + ServiceDomain domain = null; + String service = request.getHeader(HttpInvoker.SERVICE_HEADER); + + if (service == null || service.trim().length() == 0) { + throw SCAMessages.MESSAGES.requiredHeaderIsMissingOrEmpty(HttpInvoker.SERVICE_HEADER); + } + + domain = _endpointPublisher.getDomain(QName.valueOf(service)); + if (domain == null) { + throw SCAMessages.MESSAGES.unableToFindServiceDomainForService(service); + } + return domain; + } + + /** + * Set the endpoint publisher used by this servlet to locate the service domain for a service. + * @param endpointPublisher endpoint publisher + */ + public void setEndpointPublisher(RemoteEndpointPublisher endpointPublisher) { + _endpointPublisher = endpointPublisher; + } + + RemoteMessage createReplyMessage(Exchange exchange) { + RemoteMessage reply = new RemoteMessage(); + reply.setDomain(exchange.getProvider().getDomain().getName()) + .setOperation(exchange.getContract().getConsumerOperation().getName()) + .setService(exchange.getConsumer().getName()); + exchange.getContext().mergeInto(reply.getContext()); + + if (exchange.getMessage() != null) { + reply.setContent(exchange.getMessage().getContent()); + } + if (exchange.getState().equals(ExchangeState.FAULT)) { + reply.setFault(true); + } + return reply; + } + +} diff --git a/components/sca/src/main/java/org/switchyard/component/sca/TransactionContextSerializer.java b/components/sca/src/main/java/org/switchyard/component/sca/TransactionContextSerializer.java new file mode 100644 index 000000000..34dade4b0 --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/TransactionContextSerializer.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.sca; + +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.Name; +import javax.xml.soap.SOAPEnvelope; +import javax.xml.soap.SOAPHeader; +import javax.xml.soap.SOAPHeaderElement; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationContextType; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +import com.arjuna.mw.wst11.common.CoordinationContextHelper; +import com.arjuna.webservices11.wscoor.CoordinationConstants; + +/** + * Serialize/Deserialize the transaction context to be propagated via remote invocation. + */ +public class TransactionContextSerializer { + + /** + * HTTP header used to communicate the transaction context to be propagated. + */ + public static final String HEADER_TXCONTEXT = "switchyard-transaction-context"; + + /** + * Serialize the transaction context as a XML String. + * @param cc CoordinationContextType + * @return String representation of XML transaction context + * @throws Exception if it fails to serialise + */ + public String serialise(CoordinationContextType cc) throws Exception { + SOAPEnvelope soapenv = MessageFactory.newInstance().createMessage().getSOAPPart().getEnvelope(); + SOAPHeader header = soapenv.getHeader(); + if (header == null) { + header = soapenv.addHeader(); + } + final Name name = soapenv.createName(CoordinationConstants.WSCOOR_ELEMENT_COORDINATION_CONTEXT, CoordinationConstants.WSCOOR_PREFIX, CoordinationConstants.WSCOOR_NAMESPACE); + final SOAPHeaderElement root = header.addHeaderElement(name); + root.addNamespaceDeclaration(CoordinationConstants.WSCOOR_PREFIX, CoordinationConstants.WSCOOR_NAMESPACE); + + /* + * TODO Is it possible to craft plain DOM element but not to create whole SOAPMessage? + * following code hits an NPE in the CoordinationContextHelper.serialise() when it invokes + * getPrefix().equals("xmlns") against the attribute generated by JAXB marshaller. + * + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + Document doc = factory.newDocumentBuilder().newDocument(); + Element root = doc.createElement(CoordinationConstants.WSCOOR_PREFIX + ":" + CoordinationConstants.WSCOOR_ELEMENT_COORDINATION_CONTEXT); + root.setAttribute("xmlns:" + CoordinationConstants.WSCOOR_PREFIX, CoordinationConstants.WSCOOR_NAMESPACE); + */ + + CoordinationContextHelper.serialise(cc, root); + StringWriter sw = new StringWriter(); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.transform(new DOMSource(root), new StreamResult(sw)); + return sw.toString(); + } + + /** + * Deserialize the transaction context from a XML String. + * @param header XML String to be parsed + * @return CoordinationContextType + * @throws Exception if it fails to deserialise + */ + public CoordinationContextType deserialise(String header) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(header))); + return CoordinationContextHelper.deserialise(doc.getDocumentElement()); + } +} diff --git a/components/sca/src/main/java/org/switchyard/component/sca/deploy/SCAActivator.java b/components/sca/src/main/java/org/switchyard/component/sca/deploy/SCAActivator.java new file mode 100644 index 000000000..5860ba832 --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/deploy/SCAActivator.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.sca.deploy; + +import javax.xml.namespace.QName; + +import org.infinispan.Cache; +import org.switchyard.component.sca.RemoteEndpointPublisher; +import org.switchyard.component.sca.SCAEndpoint; +import org.switchyard.component.sca.SCAInvoker; +import org.switchyard.component.sca.SCALogger; +import org.switchyard.component.sca.SCAMessages; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.SCABindingModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; +import org.switchyard.remote.RemoteRegistry; +import org.switchyard.remote.infinispan.InfinispanRegistry; + +/** + * Activator for remote endpoints. + * + */ +public class SCAActivator extends BaseActivator { + + static final String[] TYPES = new String[] {"sca"}; + + private RemoteRegistry _registry; + private RemoteEndpointPublisher _endpointPublisher; + private boolean _disableRemoteTransaction = false; + + /** + * Create a new RemoteActivator. + * @param cache Infinispan cache + */ + public SCAActivator(Cache cache) { + super(TYPES); + // Configure a registry client to use the specified cache + if (cache != null) { + _registry = new InfinispanRegistry(cache); + } + } + + @Override + public ServiceHandler activateBinding(QName name, BindingModel config) { + _endpointPublisher.setDisableRemoteTransaction(_disableRemoteTransaction); + + // Signal the remote endpoint publisher to start. Multiple calls to start are harmless. + try { + // Note that stop() occurs as part of the SCAComponent lifecycle. + _endpointPublisher.start(); + } catch (Exception ex) { + SCALogger.ROOT_LOGGER.failedToStartRemoteEndpointListenerForSCAEndpoints(ex); + } + + SCABindingModel scab = (SCABindingModel)config; + if (scab.isServiceBinding()) { + return new SCAEndpoint(scab, super.getServiceDomain(), _endpointPublisher, _registry); + } else { + if ((scab.getTarget() == null) && (scab.getTargetNamespace() == null)) { + throw SCAMessages.MESSAGES.invalidSCABindingForReferenceTargetServiceOrNamespaceMustBeSpecified(); + } + return new SCAInvoker(scab, _registry) + .setDisableRemoteTransaction(_disableRemoteTransaction); + } + } + + @Override + public void deactivateBinding(QName name, ServiceHandler handler) { + // Nothing to do here + } + + /** + * Set the endpoint publisher used by this activator. + * @param endpointPublisher endpoint publisher + */ + public void setEndpointPublisher(RemoteEndpointPublisher endpointPublisher) { + _endpointPublisher = endpointPublisher; + } + + /** + * Get the endpoint publisher used by this activator. + * @return endpoint publisher + */ + public RemoteEndpointPublisher getEndpointPublisher() { + return _endpointPublisher; + } + + /** + * Set disalbe remote transaction. + * @param disable if true, disable remote transaction + */ + public void setDisableRemoteTransaction(boolean disable) { + _disableRemoteTransaction = disable; + } +} diff --git a/components/sca/src/main/java/org/switchyard/component/sca/deploy/SCAComponent.java b/components/sca/src/main/java/org/switchyard/component/sca/deploy/SCAComponent.java new file mode 100644 index 000000000..a6de1625d --- /dev/null +++ b/components/sca/src/main/java/org/switchyard/component/sca/deploy/SCAComponent.java @@ -0,0 +1,177 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.sca.deploy; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import javax.naming.InitialContext; + +import org.infinispan.Cache; +import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; +import org.infinispan.configuration.parsing.ParserRegistry; +import org.infinispan.manager.DefaultCacheManager; +import org.infinispan.manager.EmbeddedCacheManager; +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.component.sca.NOPEndpointPublisher; +import org.switchyard.component.sca.RemoteEndpointPublisher; +import org.switchyard.component.sca.SCALogger; +import org.switchyard.config.Configuration; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * The "remote" component used in SwitchYard for providing and consuming clustered endpoints. + */ +public class SCAComponent extends BaseComponent { + + private static final String CONTEXT_PATH = "switchyard-remote"; + private static final String CACHE_CONTAINER_ROOT = "java:jboss/infinispan/container/"; + private static final String CACHE_NAME_PROPERTY = "cache-name"; + private static final String CACHE_CONFIG_PROPERTY = "cache-config"; + private static final String JGROUPS_CONFIG_PROPERTY = "jgroups-config"; + private static final String DISABLE_REMOTE_TRANSACTION_PROPERTY = "disable-remote-transaction"; + + private Logger _log = Logger.getLogger(SCAComponent.class); + private RemoteEndpointPublisher _endpointPublisher; + private String _cacheName; + private Cache _cache; + private boolean _disableRemoteTransaction = false; + + /** + * Default constructor. + */ + public SCAComponent() { + super(SCAActivator.TYPES); + setName("RemoteComponent"); + try { + initEndpointPublisher(); + } catch (Exception ex) { + SCALogger.ROOT_LOGGER.failedToInitializeRemoteEndpointPublisher(ex); + } + } + + @Override + public void init(Configuration environment) { + super.init(environment); + + // Determine the cache name + _cacheName = "cluster"; + Configuration cacheNameConfig = environment.getFirstChild(CACHE_NAME_PROPERTY); + if (cacheNameConfig != null) { + _cacheName = cacheNameConfig.getValue(); + } + + // If a cache config is specified in the component configuration, then we + // are managing the creation of the cache. If not, then we look up a + // cache manager and try to resolve the cache. + Configuration cacheFileConfig = environment.getFirstChild(CACHE_CONFIG_PROPERTY); + if (cacheFileConfig != null && cacheFileConfig.getValue() != null) { + Configuration jgroupsConfig = environment.getFirstChild(JGROUPS_CONFIG_PROPERTY); + createCache(cacheFileConfig.getValue(), _cacheName, jgroupsConfig != null ? jgroupsConfig.getValue() : null); + } + + Configuration bridgeRemoteTxConfig = environment.getFirstChild(DISABLE_REMOTE_TRANSACTION_PROPERTY); + if (bridgeRemoteTxConfig != null) { + _disableRemoteTransaction = Boolean.parseBoolean(bridgeRemoteTxConfig.getValue()); + } + } + + @Override + public Activator createActivator(ServiceDomain domain) { + if (_cache == null) { + lookupCache(_cacheName); + if (_cache == null) { + SCALogger.ROOT_LOGGER.unableToResolveCacheContainer(_cacheName); + } + } + + SCAActivator activator = new SCAActivator(_cache); + activator.setServiceDomain(domain); + activator.setEndpointPublisher(_endpointPublisher); + activator.setDisableRemoteTransaction(_disableRemoteTransaction); + return activator; + } + + @Override + public synchronized void destroy() { + try { + _endpointPublisher.stop(); + } catch (Exception ex) { + SCALogger.ROOT_LOGGER.failedToDestroyRemoteEndpointPublisher(ex); + } + } + + private void initEndpointPublisher() { + _endpointPublisher = ProviderRegistry.getProvider(RemoteEndpointPublisher.class); + // if we couldn't find a provider, default to NOP implementation + if (_endpointPublisher == null) { + _endpointPublisher = new NOPEndpointPublisher(); + SCALogger.ROOT_LOGGER.noEndpointPublisherRegistered(); + } + _endpointPublisher.init(CONTEXT_PATH); + } + + private void createCache(String cacheConfig, String cacheName, String jgroupsConfig) { + ClassLoader origCl = Thread.currentThread().getContextClassLoader(); + try { + InputStream configStream = null; + try { + File f = new File(cacheConfig); + if (f.exists() && f.isFile()) { + configStream = new FileInputStream(f); + } else { + configStream = SCAActivator.class.getClassLoader().getResourceAsStream(cacheConfig); + } + + ClassLoader cacheClassLoader = DefaultCacheManager.class.getClassLoader(); + Thread.currentThread().setContextClassLoader(cacheClassLoader); + ConfigurationBuilderHolder holder = new ParserRegistry(cacheClassLoader).parse(configStream); + if (jgroupsConfig != null) { + holder.getGlobalConfigurationBuilder() + .transport() + .defaultTransport() + .addProperty("configurationFile", jgroupsConfig); + } + _cache = new DefaultCacheManager(holder, true).getCache(cacheName); + } finally { + if (configStream != null) { + try { + configStream.close(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + } catch (Exception ex) { + _log.debug("Failed to create cache for distributed registry", ex); + } finally { + Thread.currentThread().setContextClassLoader(origCl); + } + } + + private void lookupCache(String cacheName) { + // Attempt to resolve the cache container to use for the distributed registry through JNDI + try { + EmbeddedCacheManager cm = (EmbeddedCacheManager) + new InitialContext().lookup(CACHE_CONTAINER_ROOT + cacheName); + _cache = cm.getCache(); + } catch (Exception ex) { + _log.debug("Failed to lookup cache container for distributed registry", ex); + } + } +} diff --git a/components/sca/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/sca/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..f4c7515ba --- /dev/null +++ b/components/sca/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.sca.deploy.SCAComponent diff --git a/components/sca/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/components/sca/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 000000000..1ef31bef9 --- /dev/null +++ b/components/sca/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/components/sca/src/main/resources/infinispan-switchyard.xml b/components/sca/src/main/resources/infinispan-switchyard.xml new file mode 100644 index 000000000..2f095585c --- /dev/null +++ b/components/sca/src/main/resources/infinispan-switchyard.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/sca/src/main/resources/sca.properties b/components/sca/src/main/resources/sca.properties new file mode 100644 index 000000000..c94c97544 --- /dev/null +++ b/components/sca/src/main/resources/sca.properties @@ -0,0 +1,23 @@ +### +### This file contains properties used to configure the SCA binding on Karaf. +### + +# Name of the cache to use for the distributed registry +cache-name = switchyard + +# Name of the configuration file used to configure Infinispan +cache-config = ${karaf.base}/etc/infinispan-switchyard.xml + +# Name of the JGroups configuration file which is used by Infinispan +# jgroups-udp.xml in the infinispan jar is used by default. Uncomment +# this and place the file when you need to change JGroups settings. +# jgroups-config = ${karaf.base}/etc/jgroups-udp-switchyard.xml + +# Disable remote transaction bridging (which is not available on karaf) +disable-remote-transaction = true + +# Optional settings to override the generated URL for the remote endpoint +# used for clustering communication with this instance. If you have a +# clustered setup over multiple hosts, you will need to set this to the +# correct host+port for each instance. +#endpoint-url = http://localhost:8181/switchyard-remote diff --git a/components/sca/src/test/java/org/switchyard/component/sca/SCAInvokerTest.java b/components/sca/src/test/java/org/switchyard/component/sca/SCAInvokerTest.java new file mode 100644 index 000000000..c16bc4579 --- /dev/null +++ b/components/sca/src/test/java/org/switchyard/component/sca/SCAInvokerTest.java @@ -0,0 +1,375 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.sca; + +import java.io.IOException; +import java.util.LinkedList; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.MockExchange; +import org.switchyard.Service; +import org.switchyard.ServiceReference; +import org.switchyard.SwitchYardException; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.config.model.composite.v1.V1SCABindingModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.remote.RemoteEndpoint; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.RemoteRegistry; +import org.switchyard.remote.cluster.ClusteredInvoker; +import org.switchyard.remote.cluster.LoadBalanceStrategy; +import org.switchyard.remote.cluster.RandomStrategy; +import org.switchyard.remote.cluster.RoundRobinStrategy; +import org.switchyard.test.MockHandler; + +public class SCAInvokerTest { + + private MockDomain _domain; + private MockHandler _provider; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + _provider = new MockHandler(); + } + + @Test + public void localInvocationSameName() throws Exception { + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "testBinding"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + SCAInvoker invoker = new SCAInvoker(config); + invoker.start(); + + final QName TEST_SERVICE = new QName("urn:test", "SCAInvokerTest"); + ServiceReference reference = _domain.createInOnlyService(TEST_SERVICE, _provider); + MockExchange ex = new MockExchange(); + Message msg = ex.createMessage().setContent("TEST"); + ex.setMessage(msg); + ex.consumer(reference, new InOnlyOperation("Test")); + ex.provider(_domain.getServices().get(0), new InOnlyOperation("Test")); + invoker.handleMessage(ex); + + Assert.assertTrue(_provider.getMessages().size() == 1); + Assert.assertEquals(msg.getContent(), _provider.getMessages().poll().getMessage().getContent()); + } + + @Test + public void localInvocationTarget() throws Exception { + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "testBinding"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + config.setTarget("ServiceB"); + SCAInvoker invoker = new SCAInvoker(config); + invoker.start(); + + // Serivce A is for app 1, Service B is for app 2 + final QName SERVICE_A = new QName("urn:test", "ServiceA"); + final QName SERVICE_B = new QName("urn:test", "ServiceB"); + ServiceReference referenceA = _domain.registerServiceReference(SERVICE_A, new InOnlyService()); + _domain.registerServiceReference(SERVICE_B, new InOnlyService()); + Service serviceA = _domain.registerService(SERVICE_A, new InOnlyService(), new MockHandler()); + _domain.registerService(SERVICE_B, new InOnlyService(), _provider); + + MockExchange ex = new MockExchange(); + Message msg = ex.createMessage().setContent("TEST"); + ex.setMessage(msg); + ex.consumer(referenceA, new InOnlyOperation(null)); + ex.provider(serviceA, new InOnlyOperation(null)); + invoker.handleMessage(ex); + + Assert.assertTrue(_provider.getMessages().size() == 1); + Assert.assertEquals(msg.getContent(), _provider.getMessages().poll().getMessage().getContent()); + } + + @Test + public void crossDomain() throws Exception { + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "testBinding"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + config.setTargetNamespace("urn:testb"); + SCAInvoker invoker = new SCAInvoker(config); + invoker.start(); + + // service names with different namespace + final QName SERVICE_A = new QName("urn:testa", "Service"); + final QName SERVICE_B = new QName("urn:testb", "Service"); + + // two domains + MockDomain domain1 = _domain; + MockDomain domain2 = new MockDomain(domain1.getServiceRegistry()); + + ServiceReference referenceA = domain1.registerServiceReference(SERVICE_A, new InOnlyService()); + Service serviceA = domain1.registerService(SERVICE_A, new InOnlyService(), new MockHandler()); + domain2.registerServiceReference(SERVICE_B, new InOnlyService()); + domain2.registerService(SERVICE_B, new InOnlyService(), _provider); + + MockExchange ex = new MockExchange(); + Message msg = ex.createMessage().setContent("TEST"); + ex.setMessage(msg); + ex.consumer(referenceA, new InOnlyOperation(null)); + ex.provider(serviceA, new InOnlyOperation(null)); + invoker.handleMessage(ex); + + Assert.assertTrue(_provider.getMessages().size() == 1); + Assert.assertEquals(msg.getContent(), _provider.getMessages().poll().getMessage().getContent()); + } + + @Test + public void localInvocationWithInvalidServiceReference() throws Exception { + boolean fail = false; + + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "testBinding"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + config.setTarget("Blah"); + SCAInvoker invoker = new SCAInvoker(config); + invoker.start(); + + // Create one valid but unregistered reference + final QName SERVICE_A = new QName("urn:test", "ServiceA"); + ServiceReference referenceA = _domain.registerServiceReference(SERVICE_A, new InOnlyService()); + + Service serviceA = _domain.registerService(SERVICE_A, new InOnlyService(), null); + _domain.registerService(SERVICE_A, new InOnlyService(), _provider); + + MockExchange ex = new MockExchange(); + Message msg = ex.createMessage().setContent("TEST"); + ex.setMessage(msg); + ex.consumer(referenceA, new InOnlyOperation(null)); + ex.provider(serviceA, new InOnlyOperation(null)); + + // Should throw a Handler exception + try { + invoker.handleMessage(ex); + } catch (HandlerException e) { + String message = e.getMessage(); + Assert.assertTrue(message.contains("SWITCHYARD039604")); + fail = true; + } + + Assert.assertTrue(fail); + } + + @Test + public void localInvocationTargetNamespace() throws Exception { + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "testBinding"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + config.setTargetNamespace("urn:app2"); + SCAInvoker invoker = new SCAInvoker(config); + invoker.start(); + + // urn:app1 is for app 1, urn:app2 is for app 2 + final QName SERVICE_A = new QName("urn:app1", "ServiceA"); + final QName SERVICE_B = new QName("urn:app2", "ServiceA"); + ServiceReference referenceA = _domain.registerServiceReference(SERVICE_A, new InOnlyService()); + _domain.registerServiceReference(SERVICE_B, new InOnlyService()); + Service serviceA = _domain.registerService(SERVICE_A, new InOnlyService(), new MockHandler()); + _domain.registerService(SERVICE_B, new InOnlyService(), _provider); + + MockExchange ex = new MockExchange(); + Message msg = ex.createMessage().setContent("TEST"); + ex.setMessage(msg); + ex.consumer(referenceA, new InOnlyOperation(null)); + ex.provider(serviceA, new InOnlyOperation(null)); + invoker.handleMessage(ex); + + Assert.assertTrue(_provider.getMessages().size() == 1); + Assert.assertEquals(msg.getContent(), _provider.getMessages().poll().getMessage().getContent()); + } + + @Test + public void createOOTBLoadBalancers() throws Exception { + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "testBinding"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + SCAInvoker invoker = new SCAInvoker(config); + invoker.start(); + + LoadBalanceStrategy roundRobin = invoker.createLoadBalancer("RoundRobinStrategy"); + Assert.assertTrue(roundRobin instanceof RoundRobinStrategy); + LoadBalanceStrategy random = invoker.createLoadBalancer("RandomStrategy"); + Assert.assertTrue(random instanceof RandomStrategy); + } + + @Test + public void contextPropertiesCopied() throws Exception { + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "testBinding"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + SCAInvoker invoker = new SCAInvoker(config); + invoker.start(); + + final QName TEST_SERVICE = new QName("urn:test", "SCAInvokerTest"); + ServiceReference reference = _domain.createInOnlyService(TEST_SERVICE, _provider); + MockExchange ex = new MockExchange(); + Message msg = ex.createMessage().setContent("TEST"); + ex.setMessage(msg); + ex.getMessage().getContext().setProperty("message-prop", "abc"); + ex.consumer(reference, new InOnlyOperation("Test")); + ex.provider(_domain.getServices().get(0), new InOnlyOperation("Test")); + invoker.handleMessage(ex); + + Assert.assertTrue(_provider.getMessages().size() == 1); + Exchange receivedEx = _provider.getMessages().poll(); + Assert.assertEquals("abc", receivedEx.getMessage().getContext().getPropertyValue("message-prop")); + } + + @Test + public void createCustomLoadBalancers() throws Exception { + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "testBinding"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + SCAInvoker invoker = new SCAInvoker(config); + invoker.start(); + + LoadBalanceStrategy lb = invoker.createLoadBalancer("org.switchyard.component.sca.MyLoadBalancer"); + Assert.assertTrue(lb instanceof MyLoadBalancer); + + // try to create a bogus load balancer + try { + invoker.createLoadBalancer("org.foo.Bar"); + Assert.fail("Should not be able to create a bogus load balance strategy"); + } catch (SwitchYardException ex) { + // expected + } + } + + @Test + public void verifyRemoteMessageCreation() throws Exception { + // Create a binding config with clustering enabled + V1SCABindingModel config = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()) { + @Override + public String getName() { + return "verifyRemoteMessageCreation"; + } + @Override + public boolean isClustered() { + return true; + } + @Override + public String getTarget() { + return "test-target"; + } + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + }; + }; + + // Mock the invoker so that we don't need an actual remote endpoint + final LinkedList msgs = new LinkedList(); + ClusteredInvoker clInovker = new ClusteredInvoker(null) { + @Override + public RemoteMessage invoke(RemoteMessage request) throws IOException { + msgs.push(request); + return null; + } + }; + + SCAInvoker scaInvoker = new SCAInvoker(config); + scaInvoker.setInvoker(clInovker); + scaInvoker.start(); + + // Verify that exchange is mapped to remote message correctly + Exchange mockEx = Mockito.mock(Exchange.class, Mockito.RETURNS_DEEP_STUBS); + Mockito.when(mockEx.getContract().getConsumerOperation().getName()).thenReturn("test-operation"); + Mockito.when(mockEx.getProvider().getDomain().getName()).thenReturn(new QName("test-domain")); + Mockito.when(mockEx.getMessage().getContent()).thenReturn("test-content"); + scaInvoker.handleMessage(mockEx); + + RemoteMessage remoteMsg = msgs.pop(); + Assert.assertEquals(new QName("test-domain"), remoteMsg.getDomain()); + Assert.assertEquals("test-operation", remoteMsg.getOperation()); + Assert.assertEquals("test-content", remoteMsg.getContent()); + } +} + +class MyLoadBalancer implements LoadBalanceStrategy { + + @Override + public RemoteEndpoint selectEndpoint(QName serviceName) { + return null; + } + + @Override + public RemoteRegistry getRegistry() { + return null; + } + + @Override + public void setRegistry(RemoteRegistry registry) { + } +} diff --git a/components/sca/src/test/java/org/switchyard/component/sca/SwitchYardRemotingServletTest.java b/components/sca/src/test/java/org/switchyard/component/sca/SwitchYardRemotingServletTest.java new file mode 100644 index 000000000..01c5eaa95 --- /dev/null +++ b/components/sca/src/test/java/org/switchyard/component/sca/SwitchYardRemotingServletTest.java @@ -0,0 +1,135 @@ +package org.switchyard.component.sca; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.concurrent.TimeUnit; + +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Exchange; +import org.switchyard.MockDomain; +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.internal.Deployment; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; +import org.switchyard.test.MockHandler; + +public class SwitchYardRemotingServletTest { + + private final QName TEST_SERVICE = new QName("RemotingTest"); + + private Serializer serializer = SerializerFactory.create(FormatType.JSON, null, true); + private SwitchYardRemotingServlet servlet; + private HttpServletRequest request; + private HttpServletResponse response; + private ServiceDomain domain; + private InputStream input; + + @Before + public void setUp() throws Exception { + domain = new MockDomain(); + domain.setProperty(Deployment.CLASSLOADER_PROPERTY, this.getClass().getClassLoader()); + RemoteEndpointPublisher rep = mock(RemoteEndpointPublisher.class); + when(rep.getDomain(TEST_SERVICE)).thenReturn(domain); + servlet = new SwitchYardRemotingServlet(); + servlet.setEndpointPublisher(rep); + request = mock(HttpServletRequest.class); + ServletInputStream sis = new ServletInputStream() { + public int read() throws IOException { + return input.read(); + } + public int read(byte[] b, int off, int len) throws IOException { + return input.read(b, off, len); + } + }; + when(request.getInputStream()).thenReturn(sis); + when(request.getHeader(HttpInvoker.SERVICE_HEADER)).thenReturn(TEST_SERVICE.toString()); + response = mock(HttpServletResponse.class); + } + + @Test + public void missingServiceName() { + try { + when(request.getHeader(HttpInvoker.SERVICE_HEADER)).thenReturn(null); + servlet.doPost(request, response); + Assert.fail("Expected failure due to missing service name on message"); + } catch (Exception ex) { + // success + } + } + + @Test + public void noOperationName() throws Exception { + domain.registerServiceReference(TEST_SERVICE, new InOnlyService()); + domain.registerService(TEST_SERVICE, new InOnlyService(), new MockHandler()); + RemoteMessage msg = new RemoteMessage() + .setService(TEST_SERVICE); + setRequestMessage(msg); + servlet.doPost(request, response); + } + + @Test + public void noOperationNameMultipleOperations() throws Exception { + MockHandler handler = new MockHandler(); + domain.registerServiceReference(TEST_SERVICE, JavaService.fromClass(MyInterface.class)); + domain.registerService(TEST_SERVICE, JavaService.fromClass(MyInterface.class), handler); + + RemoteMessage msg = new RemoteMessage() + .setService(TEST_SERVICE); + setRequestMessage(msg); + + try { + servlet.doPost(request, response); + Assert.fail("No operation was supplied with multiple service operations - this should fail!"); + } catch (Exception ex) { + // expected + } + } + + @Test + public void operationNameMultipleOperations() throws Exception { + MockHandler handler = new MockHandler(); + domain.registerServiceReference(TEST_SERVICE, JavaService.fromClass(MyInterface.class)); + domain.registerService(TEST_SERVICE, JavaService.fromClass(MyInterface.class), handler); + + RemoteMessage msg = new RemoteMessage() + .setService(TEST_SERVICE) + .setOperation("bar"); + setRequestMessage(msg); + servlet.doPost(request, response); + + Exchange ex = handler.getMessages().poll(300, TimeUnit.MILLISECONDS); + Assert.assertNotNull(ex); + Assert.assertEquals("bar", ex.getContract().getConsumerOperation().getName()); + } + + private void setRequestMessage(RemoteMessage message) throws Exception { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + serializer.serialize(message, RemoteMessage.class, bos); + bos.flush(); + input = new ByteArrayInputStream(bos.toByteArray()); + } + +} + +interface MyInterface { + void foo(String arg); + void bar(String arg); +} diff --git a/components/sca/src/test/java/org/switchyard/component/sca/deploy/SCAActivatorTest.java b/components/sca/src/test/java/org/switchyard/component/sca/deploy/SCAActivatorTest.java new file mode 100644 index 000000000..4847075be --- /dev/null +++ b/components/sca/src/test/java/org/switchyard/component/sca/deploy/SCAActivatorTest.java @@ -0,0 +1,40 @@ +package org.switchyard.component.sca.deploy; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.component.sca.NOPEndpointPublisher; +import org.switchyard.config.model.composite.SCABindingModel; +import org.switchyard.config.model.composite.v1.V1SCABindingModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; + +public class SCAActivatorTest { + private SCAActivator activator; + + @Before + public void setUp() throws Exception { + activator = new SCAActivator(null); + } + + @Test + public void testBindingActivationWithNullTargetAndNamespace() throws Exception { + activator.setEndpointPublisher(new NOPEndpointPublisher()); + + SCABindingModel scab = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()); + scab.setClustered(true) + .setLoadBalance("RoundRobin") + .setTarget(null) + .setTargetNamespace(null); + + try { + activator.activateBinding(new QName("urn:test","one"), scab); + + Assert.fail("No IllegalArgumentException has been thrown"); + } catch (IllegalArgumentException e) { + String message = e.getMessage(); + Assert.assertTrue(message.contains("SWITCHYARD039600")); + } + } +} diff --git a/components/sca/src/test/resources/META-INF/beans.xml b/components/sca/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/sca/src/test/resources/TestConfig.xml b/components/sca/src/test/resources/TestConfig.xml new file mode 100644 index 000000000..97af6c24d --- /dev/null +++ b/components/sca/src/test/resources/TestConfig.xml @@ -0,0 +1,19 @@ + + + + stuff + metal + + \ No newline at end of file diff --git a/components/soap/README b/components/soap/README new file mode 100644 index 000000000..163c1ca46 --- /dev/null +++ b/components/soap/README @@ -0,0 +1,39 @@ +SOAP Component for SwitchYard +============================= +A barebone implementation that provides the following features: + +a) Allows SwitchYard services to be exposed as a WebService. +b) Allows SwitchYard services to invoke externally/internally hosted WebServices. +c) Uses pure JAX-WS Dispatch and Provider APIs. + +Test +----- +Includes these usecases: + +1. Invoke a oneway WebService +2. Invoke a request-response WebService +3. Invoke the request-response WebService with improper data +4. Invoke the request-response WebService to test InboundHandler's multi-threading capability + +|-----------------------------------------------------------------| +| SOAPGateway | +| |-----------------------------| |-----------------------------| | +| | Outbound | | Inbound | | +| | |------------| |----------| | | |----------| |------------| | | +| | | Decomposer | | Composer | | | | Composer | | Decomposer | | | +| | |------------| |----------| | | |----------| |------------| | | +| |-----------------------------| |-----------------------------| | +|-----------------------------------------------------------------| + +SwitchYard Request --> Outbound --> Decomposer --> WebService +WebService Response --> Outbound --> Composer --> SwitchYard Service + +WebService Client Request --> Inbound --> Composer --> SwitchYard Service +SwitchYard Response --> Inbound --> Decomposer --> WebService Client + +Features to be added +-------------------- +Deployment support on other Containers like JBossWeb/JBossWS +WS-Security (SOAP Header processing, HTTP Header/Properties processing) +Throttling on Outbound side + diff --git a/components/soap/pom.xml b/components/soap/pom.xml new file mode 100644 index 000000000..bdca9614c --- /dev/null +++ b/components/soap/pom.xml @@ -0,0 +1,181 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-component-soap + SwitchYard: SOAP Component + bundle + + + org.switchyard.component.soap.* + + + org.switchyard.security.jboss.credential.extractor;resolution:=optional;${switchyard.osgi.import.switchyard.version}, + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;${switchyard.osgi.import.switchyard.version}, + !org.apache.cxf.ws.addressing.impl, + org.apache.cxf.*;version="[2.7,3.1)", + * + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-security + + + org.switchyard + switchyard-security-jboss + + + org.switchyard + switchyard-transform + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard.components + switchyard-component-common + + + org.jboss.spec.javax.servlet + jboss-servlet-api_2.5_spec + + + javax.mail + mail + + + wsdl4j + wsdl4j + + + + org.apache.cxf + cxf-api + + + org.apache.cxf + cxf-rt-core + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-frontend-jaxws + + + org.apache.cxf + cxf-rt-bindings-coloc + + + org.apache.cxf + cxf-rt-bindings-object + + + org.apache.cxf + cxf-rt-bindings-soap + + + org.apache.cxf + cxf-rt-bindings-xml + + + org.apache.cxf + cxf-rt-databinding-jaxb + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.cxf + cxf-rt-transports-local + + + org.apache.cxf + cxf-rt-ws-addr + + + org.apache.ws.xmlschema + xmlschema-core + + + org.littleshoot + littleproxy + test + + + org.apache.cxf + cxf-rt-transports-http-jetty + + + org.apache.httpcomponents + httpclient + + + junit + junit + + + org.osgi + org.osgi.core + provided + + + org.osgi + org.osgi.compendium + provided + + + diff --git a/components/soap/src/main/java/org/switchyard/component/soap/AddressingInterceptor.java b/components/soap/src/main/java/org/switchyard/component/soap/AddressingInterceptor.java new file mode 100644 index 000000000..6a998d787 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/AddressingInterceptor.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import javax.xml.ws.handler.MessageContext.Scope; + +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.jaxws.context.WrappedMessageContext; +import org.apache.cxf.jaxws.interceptors.WebFaultOutInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.ws.addressing.AddressingProperties; +import org.apache.cxf.ws.addressing.AttributedURIType; +import org.apache.cxf.ws.addressing.ContextUtils; +import org.apache.cxf.ws.addressing.EndpointReferenceType; +import org.apache.cxf.ws.addressing.RelatesToType; +import org.apache.cxf.ws.addressing.soap.MAPCodec; +import org.switchyard.Context; +import org.switchyard.component.soap.util.SOAPUtil; + +/** + * Outbound Addressing handler. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class AddressingInterceptor extends AbstractSoapInterceptor { + + /** + * Default Constructor. + */ + public AddressingInterceptor() { + super(Phase.PRE_PROTOCOL); + addAfter(WebFaultOutInterceptor.class.getName()); + addBefore(MAPCodec.class.getName()); + } + + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(SoapMessage message) throws Fault { + if (ContextUtils.isOutbound(message)) { + AddressingProperties maps = ContextUtils.retrieveMAPs(message, false, true, false); + WrappedMessageContext soapContext = new WrappedMessageContext(message, Scope.APPLICATION); + if (soapContext.containsKey(SOAPUtil.SWITCHYARD_CONTEXT)) { + Context context = (Context)soapContext.get(SOAPUtil.SWITCHYARD_CONTEXT); + + String property = (String)context.getPropertyValue(SOAPUtil.WSA_ACTION_STR); + AttributedURIType uri = null; + EndpointReferenceType ref = null; + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + maps.setAction(uri); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_FROM_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + ref = new EndpointReferenceType(); + ref.setAddress(uri); + maps.setFrom(ref); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_TO_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + ref = new EndpointReferenceType(); + ref.setAddress(uri); + maps.setTo(ref); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_FAULTTO_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + ref = new EndpointReferenceType(); + ref.setAddress(uri); + maps.setFaultTo(ref); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_REPLYTO_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + ref = new EndpointReferenceType(); + ref.setAddress(uri); + maps.setReplyTo(ref); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_RELATESTO_STR); + if (property != null) { + RelatesToType relatesTo = new RelatesToType(); + relatesTo.setValue(property); + maps.setRelatesTo(relatesTo); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_MESSAGEID_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + maps.setMessageID(uri); + } + } + } + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/DefaultSOAP11ExceptionTransformer.java b/components/soap/src/main/java/org/switchyard/component/soap/DefaultSOAP11ExceptionTransformer.java new file mode 100644 index 000000000..6f5bc6a9d --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/DefaultSOAP11ExceptionTransformer.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import java.lang.reflect.InvocationTargetException; + +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPMessage; + +import org.switchyard.component.soap.util.SOAPUtil; +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; + +/** + * Default {@link Exception} to SOAP 1.1 fault transformer. + * + * @param From type. + * @param To type. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + * @author tom.fennelly@gmail.com + */ +@Scannable(false) +public class DefaultSOAP11ExceptionTransformer extends BaseTransformer { + + @Override + public QName getFrom() { + return toMessageType(Exception.class); + } + + @Override + public QName getTo() { + return SOAPUtil.SOAP11_FAULT_MESSAGE_TYPE; + } + + @Override + public SOAPMessage transform(Exception from) { + try { + Throwable cause = from.getCause(); + if (cause instanceof InvocationTargetException) { + return SOAPUtil.generateSOAP11Fault(cause.getCause()); + } else { + return SOAPUtil.generateSOAP11Fault(from); + } + } catch (SOAPException e1) { + // TODO: We're in a fault on a fault type situation now... should generateFault be throwing exceptions?? + throw SOAPMessages.MESSAGES.unexpectedSOAPExceptionWhenGeneratingASOAP11FaultMessage(from); + } + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/DefaultSOAP12ExceptionTransformer.java b/components/soap/src/main/java/org/switchyard/component/soap/DefaultSOAP12ExceptionTransformer.java new file mode 100644 index 000000000..52fe5ef84 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/DefaultSOAP12ExceptionTransformer.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import java.lang.reflect.InvocationTargetException; + +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPMessage; + +import org.switchyard.component.soap.util.SOAPUtil; +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; + +/** + * Default {@link Exception} to SOAP 1.2 fault transformer. + * + * @param From type. + * @param To type. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +@Scannable(false) +public class DefaultSOAP12ExceptionTransformer extends BaseTransformer { + + @Override + public QName getFrom() { + return toMessageType(Exception.class); + } + + @Override + public QName getTo() { + return SOAPUtil.SOAP12_FAULT_MESSAGE_TYPE; + } + + @Override + public SOAPMessage transform(Exception from) { + try { + Throwable cause = from.getCause(); + if (cause instanceof InvocationTargetException) { + return SOAPUtil.generateSOAP12Fault(cause.getCause()); + } else { + return SOAPUtil.generateSOAP12Fault(from); + } + } catch (SOAPException e1) { + // TODO: We're in a fault on a fault type situation now... should generateFault be throwing exceptions?? + throw SOAPMessages.MESSAGES.unexpectedSOAPExceptionWhenGeneratingASOAP12FaultMessage(from); + } + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/Feature.java b/components/soap/src/main/java/org/switchyard/component/soap/Feature.java new file mode 100644 index 000000000..ffcea715a --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/Feature.java @@ -0,0 +1,125 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import javax.xml.ws.soap.AddressingFeature; +import javax.xml.ws.soap.MTOMFeature; + +import org.switchyard.component.soap.config.model.SOAPBindingModel; + +/** + * Feature booleans. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class Feature { + + private Boolean _addressingEnabled = false; + private Boolean _addressingRequired = false; + private Boolean _mtomEnabled = false; + + /** + * Check if addressing feature is enabled. + * + * @return true if addressing is enabled, false otherwise + */ + public Boolean isAddressingEnabled() { + return _addressingEnabled; + } + + /** + * Set if addressing is enabled. + * + * @param enabled true if addressing is enabled, false otherwise + */ + public void setAddressingEnabled(Boolean enabled) { + _addressingEnabled = enabled; + } + + /** + * Check if addressing feature is required. + * + * @return true if addressing is required, false otherwise + */ + public Boolean isAddressingRequired() { + return _addressingRequired; + } + + /** + * Set if addressing is required. + * + * @param required true if addressing is required, false otherwise + */ + public void setAddressingRequired(Boolean required) { + _addressingRequired = required; + } + + /** + * Check if MTOM feature is enabled. + * + * @return true if MTOM is enabled, false otherwise + */ + public Boolean isMtomEnabled() { + return _mtomEnabled; + } + + /** + * Set if MTOM is enabled. + * + * @param enabled true if addressing is enabled, false otherwise + */ + public void setMtomEnabled(Boolean enabled) { + _mtomEnabled = enabled; + } + + /** + * Create Addressing feature. + * + * @return the Addressing feature + */ + public AddressingFeature getAddressing() { + return new AddressingFeature(_addressingEnabled, _addressingRequired); + } + + /** + * Create MTOM feature from config. + * + * @param config the soap config + * @return the MTOM feature + */ + public MTOMFeature getMtom(SOAPBindingModel config) { + if (config.getMtomConfig() == null) { + return new MTOMFeature(_mtomEnabled); + } + MTOMFeature mtom = null; + if (config.getMtomConfig().getThreshold() != null) { + mtom = new MTOMFeature(true, config.getMtomConfig().getThreshold()); + } else if (config.getMtomConfig().isEnabled() != null) { + mtom = new MTOMFeature(config.getMtomConfig().isEnabled()); + } else { + mtom = new MTOMFeature(_mtomEnabled); + } + return mtom; + } + + /** + * Returns a String representation of this class. + * + * @return the String representation + */ + public String toString() { + return "[AddressingEnabled:" + _addressingEnabled + ", AddressingRequired:" +_addressingRequired + ", MtomEnabled:" + _mtomEnabled + "]"; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/InboundHandler.java b/components/soap/src/main/java/org/switchyard/component/soap/InboundHandler.java new file mode 100644 index 000000000..561dc5899 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/InboundHandler.java @@ -0,0 +1,453 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.wsdl.BindingOperation; +import javax.wsdl.Definition; +import javax.wsdl.Fault; +import javax.wsdl.Operation; +import javax.wsdl.Part; +import javax.wsdl.Port; +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPMessage; +import javax.xml.ws.WebServiceContext; +import javax.xml.ws.handler.MessageContext; +import javax.xml.ws.soap.MTOMFeature; +import javax.xml.ws.soap.SOAPFaultException; + +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.component.common.DeliveryException; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.soap.composer.SOAPBindingData; +import org.switchyard.component.soap.composer.SOAPComposition; +import org.switchyard.component.soap.composer.SOAPMessageComposer; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.endpoint.EndpointPublisherFactory; +import org.switchyard.component.soap.util.SOAPUtil; +import org.switchyard.component.soap.util.WSDLUtil; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.security.context.SecurityContext; +import org.switchyard.security.context.SecurityContextManager; +import org.switchyard.security.credential.Credential; +import org.w3c.dom.Node; + +/** + * Handles SOAP requests to invoke a SwitchYard service. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class InboundHandler extends BaseServiceHandler { + + private static final Logger LOGGER = Logger.getLogger(InboundHandler.class); + private static final long DEFAULT_TIMEOUT = 15000; + private static final String MESSAGE_NAME = "org.switchyard.soap.messageName"; + + private final SOAPBindingModel _config; + private final String _gatewayName; + private MessageComposer _messageComposer; + private SecurityContextManager _securityContextManager; + private ServiceDomain _domain; + private ServiceReference _service; + private long _waitTimeout = DEFAULT_TIMEOUT; // default of 15 seconds + private Endpoint _endpoint; + private Port _wsdlPort; + private String _bindingId; + private Boolean _documentStyle = false; + private Boolean _unwrapped = false; + private String _targetNamespace; + private Feature _feature = new Feature(); + private Map _operationsMap = new HashMap(); + private Map _faultsMap = new HashMap(); + + private static final ThreadLocal> CREDENTIALS = new ThreadLocal>(); + + /** + * Gets the thread-local credentials set. + * @return the thread-local credentials set + */ + public static Set getCredentials() { + return getCredentials(false); + } + + private static Set getCredentials(boolean unset) { + Set credentials = CREDENTIALS.get(); + if (credentials == null) { + credentials = new LinkedHashSet(); + if (!unset) { + CREDENTIALS.set(credentials); + } + } + if (unset) { + CREDENTIALS.set(null); + } + return credentials; + } + + /** + * Unsets the thread-local credentials. + */ + public static void unsetCredentials() { + CREDENTIALS.set(null); + } + + /** + * Constructor. + * @param config the configuration settings + * @param domain the service domain + */ + public InboundHandler(final SOAPBindingModel config, ServiceDomain domain) { + super(domain); + _config = config; + _gatewayName = config.getName(); + _domain = domain; + _securityContextManager = new SecurityContextManager(_domain); + } + + /** + * Start lifecycle. + * @throws WebServicePublishException If unable to publish the endpoint + */ + @Override + protected void doStart() throws WebServicePublishException { + try { + _service = _domain.getServiceReference(_config.getServiceName()); + PortName portName = _config.getPort(); + Definition definition = WSDLUtil.readWSDL(_config.getWsdl()); + _targetNamespace = definition.getTargetNamespace(); + javax.wsdl.Service wsdlService = WSDLUtil.getService(definition, portName); + _wsdlPort = WSDLUtil.getPort(wsdlService, portName); + // Update the portName + portName.setServiceQName(wsdlService.getQName()); + portName.setName(_wsdlPort.getName()); + + String style = WSDLUtil.getStyle(_wsdlPort); + _documentStyle = style.equals(WSDLUtil.DOCUMENT) ? true : false; + _unwrapped = _config.isUnwrapped(); + _feature = WSDLUtil.getFeature(definition, _wsdlPort, _documentStyle); + + if (_feature.isAddressingEnabled()) { + @SuppressWarnings("unchecked") + List bindingOperations = _wsdlPort.getBinding().getBindingOperations(); + for (BindingOperation bindingOp : bindingOperations) { + String inputAction = WSDLUtil.getInputAction(_wsdlPort, new QName(_targetNamespace, bindingOp.getOperation().getName()), _documentStyle); + _operationsMap.put(inputAction, bindingOp.getOperation()); + for (Fault fault : (Collection)bindingOp.getOperation().getFaults().values()) { + String faultAction = WSDLUtil.getFaultAction(fault, _wsdlPort, new QName(_targetNamespace, bindingOp.getOperation().getName())); + _faultsMap.put(fault.getName(), faultAction); + } + } + } + + // Config feature setting overrides WSDL + MTOMFeature mtom = _feature.getMtom(_config); + _bindingId = WSDLUtil.getBindingId(_wsdlPort, mtom.isEnabled()); + + _endpoint = EndpointPublisherFactory.getEndpointPublisher().publish(_domain, _config, + _bindingId, + this, + _feature.getAddressing(), + mtom); + + // Create and configure the SOAP message composer + _messageComposer = SOAPComposition.getMessageComposer(_config); + ((SOAPMessageComposer)_messageComposer).setDocumentStyle(_documentStyle); + ((SOAPMessageComposer)_messageComposer).setWsdlPort(_wsdlPort); + ((SOAPMessageComposer)_messageComposer).setMtomEnabled(mtom.isEnabled()); + ((SOAPMessageComposer)_messageComposer).setUnwrapped(_unwrapped); + if (_config.getMtomConfig() != null) { + ((SOAPMessageComposer)_messageComposer).setXopExpand(_config.getMtomConfig().isXopExpand()); + } + } catch (WSDLException e) { + throw new WebServicePublishException(e); + } + } + + /** + * Stop lifecycle. + */ + @Override + protected void doStop() { + if (_endpoint != null) { + _endpoint.stop(); + } + SOAPLogger.ROOT_LOGGER.webService(_config.getPort().toString()); + } + + @Override + public void handleFault(Exchange exchange) { + // TODO: Why is this class an ExchangeHandler? See SOAPActivator + throw SOAPMessages.MESSAGES.unexpected(); + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // TODO: Why is this class an ExchangeHandler? See SOAPActivator + throw SOAPMessages.MESSAGES.unexpected(); + } + + /** + * The delegate method called by the Webservice implementation. + * @param soapMessage the SOAP request + * @return the SOAP response + */ + public SOAPMessage invoke(final SOAPMessage soapMessage) { + return invoke(soapMessage, null); + } + + /** + * The delegate method called by the Webservice implementation. + * @param soapMessage the SOAP request + * @param wsContext the web service context + * @return the SOAP response + */ + public SOAPMessage invoke(final SOAPMessage soapMessage, final WebServiceContext wsContext) { + String operationName = null; + Operation operation; + Boolean oneWay = false; + QName firstBodyElement = null; + MessageContext msgContext = null; + + // Collect and unset any thread-local credentials + Set credentials = getCredentials(true); + + if (wsContext != null) { + // Caching the message context + msgContext = wsContext.getMessageContext(); + } + + if ((soapMessage == null) || (soapMessage.getSOAPPart() == null)) { + return handleException(oneWay, + SOAPMessages.MESSAGES.noSuchOperation(_wsdlPort.getName().toString())); + } + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Inbound <-- Request:[" + _service.getName() + "][" + SOAPUtil.soapMessageToString(soapMessage) + "]"); + } + try { + String action = SOAPUtil.getAddressingAction(soapMessage); + if (_feature.isAddressingEnabled() && (action != null)) { + // Get the operation using the action + operation = _operationsMap.get(action); + if (operation == null) { + return handleException(oneWay, + SOAPMessages.MESSAGES.couldNotFindOperation(action) + ); + } + } else { + firstBodyElement = SOAPUtil.getFirstBodyElement(soapMessage); + operation = WSDLUtil.getOperationByElement(_wsdlPort, firstBodyElement, _documentStyle); + } + if (operation != null) { + operationName = operation.getName(); + oneWay = WSDLUtil.isOneWay(operation); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Received SOAP message targeted at Webservice operation '" + operationName + "' on port '" + _wsdlPort.getName() + "'."); + } + } + } catch (SOAPException e) { + LOGGER.error(e); + return null; + } + + if (operation == null) { + return handleException(oneWay, + SOAPMessages.MESSAGES.operationNotAvailableTarget(firstBodyElement.toString(), _service.getName() + "'.")); + } + + try { + SynchronousInOutHandler inOutHandler = new SynchronousInOutHandler(); + Exchange exchange = _service.createExchange(operationName, inOutHandler); + + // identify ourselves + exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _gatewayName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + + SOAPBindingData soapBindingData = new SOAPBindingData(soapMessage, wsContext); + + // add any thread-local and/or binding-extracted credentials + SecurityContext securityContext = _securityContextManager.getContext(exchange); + securityContext.getCredentials().addAll(credentials); + securityContext.getCredentials().addAll(soapBindingData.extractCredentials()); + _securityContextManager.setContext(exchange, securityContext); + + @SuppressWarnings("unchecked") + Map> httpHeaders = + (Map>) wsContext.getMessageContext() + .get(MessageContext.HTTP_REQUEST_HEADERS); + soapBindingData.setHttpHeaders(httpHeaders); + + Message message; + try { + message = _messageComposer.compose(soapBindingData, exchange); + } catch (Exception e) { + throw e instanceof SOAPException ? (SOAPException)e : new SOAPException(e); + } + + // Do not perfom this check if the message has been unwrapped + if (!_unwrapped) { + assertComposedMessageOK(message, operation); + } + + exchange.getContext(message).setProperty(MESSAGE_NAME, operation.getInput().getMessage().getQName().getLocalPart()); + + if (oneWay) { + exchange.send(message); + if (exchange.getState().equals(ExchangeState.FAULT)) { + return composeResponse(exchange, msgContext, operation, true); + } else { + return null; + } + } else { + exchange.send(message); + try { + exchange = inOutHandler.waitForOut(_waitTimeout); + } catch (DeliveryException e) { + return handleException(oneWay, + SOAPMessages.MESSAGES.timedOut(String.valueOf(_waitTimeout), + _service.getName().toString())); + } + + if (SOAPUtil.getFactory(_bindingId) == null) { + throw SOAPMessages.MESSAGES.failedToInstantiateSOAPMessageFactory(); + } + if (msgContext != null) { + msgContext.put(SOAPUtil.SWITCHYARD_CONTEXT, exchange.getContext()); + } + return composeResponse(exchange, msgContext, operation, false); + } + } catch (SOAPException se) { + if (msgContext != null) { + msgContext.put(MessageContext.HTTP_RESPONSE_CODE, SOAPUtil.DEFAULT_FAULT_RESONSE_CODE); + } + return handleException(oneWay, se); + } + } + + private SOAPMessage composeResponse(Exchange exchange, MessageContext msgContext, Operation operation, Boolean oneWay) throws SOAPException { + SOAPBindingData bindingData = new SOAPBindingData(SOAPUtil.createMessage(_bindingId)); + SOAPMessage soapResponse; + try { + soapResponse = _messageComposer.decompose(exchange, bindingData).getSOAPMessage(); + if ((msgContext != null) && (bindingData.getStatus() != null)) { + msgContext.put(MessageContext.HTTP_RESPONSE_CODE, bindingData.getStatus()); + } + if (msgContext != null) { + @SuppressWarnings("unchecked") + Map> httpHeaders = + (Map>) msgContext.get(MessageContext.HTTP_RESPONSE_HEADERS); + if (httpHeaders == null) { + msgContext.put(MessageContext.HTTP_RESPONSE_HEADERS, bindingData.getHttpHeaders()); + } else { + httpHeaders.putAll(bindingData.getHttpHeaders()); + } + } + } catch (SOAPException soapEx) { + throw soapEx; + } catch (Exception ex) { + // The map will contain the exception name only if WS-A is enabled, so no need to check if WS-A is enabled + String faultAction = _faultsMap.get(ex.getClass().getSimpleName()); + if ((faultAction != null) && (msgContext != null)) { + msgContext.put(SOAPUtil.WSA_ACTION_STR, faultAction); + } + throw new SOAPFaultException(SOAPUtil.createFault(ex, _bindingId, WSDLUtil.getFaultQName(operation, ex.getClass().getSimpleName()))); + } + if (exchange.getState() == ExchangeState.FAULT && soapResponse.getSOAPBody().getFault() == null) { + return handleException(oneWay, + SOAPMessages.MESSAGES.invalidResponseConstruction(_messageComposer.getClass().getName())); + } + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Inbound --> Response:[" + _service.getName() + "][" + SOAPUtil.soapMessageToString(soapResponse) + "]"); + } + return soapResponse; + } + + private void assertComposedMessageOK(Message soapMessage, Operation operation) throws SOAPException { + Node inputMessage = soapMessage.getContent(Node.class); + + String actualNS = inputMessage.getNamespaceURI(); + String actualLN = inputMessage.getLocalName(); + @SuppressWarnings("unchecked") + List parts = operation.getInput().getMessage().getOrderedParts(null); + + if (parts.isEmpty()) { + throw SOAPMessages.MESSAGES.invalidInputSOAPPayloadForServiceOperation(operation.getName(), _service.getName().toString(), actualLN); + } + + QName expectedPayloadType = null; + + if (_documentStyle) { + if (parts.get(0).getElementName() != null) { + expectedPayloadType = parts.get(0).getElementName(); + } else if (parts.get(0).getTypeName() != null) { + expectedPayloadType = parts.get(0).getTypeName(); + } + } else { + // RPC + expectedPayloadType = new QName(_targetNamespace, operation.getName()); + } + + String expectedNS = null; + String expectedLN = null; + + if (expectedPayloadType != null) { + expectedNS = expectedPayloadType.getNamespaceURI(); + expectedLN = expectedPayloadType.getLocalPart(); + + } + if (!_documentStyle) { + expectedLN = operation.getName(); + } + + if (expectedNS != null && !expectedNS.equals(actualNS)) { + throw SOAPMessages.MESSAGES.invalidInputSOAPPayloadNamespaceForServiceOperation(operation.getName(), _service.getName().toString(), expectedNS, actualNS); + } else if (expectedLN != null && !expectedLN.equals(actualLN)) { + throw SOAPMessages.MESSAGES.invalidInputSOAPPayloadLocalNamePartForServiceOperation(operation.getName(), _service.getName().toString(), expectedLN, actualLN); + } + } + + private SOAPMessage handleException(Boolean oneWay, SOAPException se) { + if (oneWay) { + LOGGER.error(se); + } else { + try { + return SOAPUtil.generateFault(se, _bindingId); + } catch (SOAPException e) { + LOGGER.error(e); + } + } + return null; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/OutboundHandler.java b/components/soap/src/main/java/org/switchyard/component/soap/OutboundHandler.java new file mode 100644 index 000000000..b4ff48cd2 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/OutboundHandler.java @@ -0,0 +1,357 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPMessage; +import javax.xml.ws.BindingProvider; +import javax.xml.ws.Dispatch; +import javax.xml.ws.Service; +import javax.xml.ws.WebServiceException; +import javax.xml.ws.handler.MessageContext; +import javax.xml.ws.soap.MTOMFeature; +import javax.xml.ws.soap.SOAPFaultException; + +import org.apache.cxf.configuration.security.AuthorizationPolicy; +import org.apache.cxf.configuration.security.ProxyAuthorizationPolicy; +import org.apache.cxf.endpoint.Client; +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.jaxws.DispatchImpl; +import org.apache.cxf.transport.http.HTTPConduit; +import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; +import org.apache.cxf.transports.http.configuration.ProxyServerType; +import org.jboss.logging.Logger; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.soap.composer.SOAPBindingData; +import org.switchyard.component.soap.composer.SOAPComposition; +import org.switchyard.component.soap.composer.SOAPFaultInfo; +import org.switchyard.component.soap.composer.SOAPMessageComposer; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.endpoint.EndpointPublisherFactory; +import org.switchyard.component.soap.util.SOAPUtil; +import org.switchyard.component.soap.util.WSDLUtil; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * Handles invoking external Webservice endpoints. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class OutboundHandler extends BaseServiceHandler { + + private static final Logger LOGGER = Logger.getLogger(OutboundHandler.class); + + private static final String NO_RESPONSE = "No response returned."; + + private final SOAPBindingModel _config; + private final String _bindingName; + private final String _referenceName; + private MessageComposer _messageComposer; + private Dispatch _dispatcher; + private Port _wsdlPort; + private String _bindingId; + private Boolean _documentStyle; + private Feature _feature = new Feature(); + + /** + * Constructor. + * @param config the configuration settings + */ + public OutboundHandler(final SOAPBindingModel config) { + _config = config; + _bindingName = config.getName(); + _referenceName = config.getReference().getName(); + } + + /** + * Start lifecycle. + * @throws WebServiceConsumeException If unable to load the WSDL + */ + @Override + protected void doStart() throws WebServiceConsumeException { + if (_dispatcher == null) { + try { + Definition definition = WSDLUtil.readWSDL(_config.getWsdl()); + PortName portName = _config.getPort(); + javax.wsdl.Service wsdlService = WSDLUtil.getService(definition, portName); + _wsdlPort = WSDLUtil.getPort(wsdlService, portName); + // Update the portName + portName.setServiceQName(wsdlService.getQName()); + portName.setName(_wsdlPort.getName()); + + String style = WSDLUtil.getStyle(_wsdlPort); + _documentStyle = style.equals(WSDLUtil.DOCUMENT) ? true : false; + _feature = WSDLUtil.getFeature(definition, _wsdlPort, _documentStyle); + + // Config feature setting overrides WSDL + MTOMFeature mtom = _feature.getMtom(_config); + _bindingId = WSDLUtil.getBindingId(_wsdlPort, mtom.isEnabled()); + + _messageComposer = SOAPComposition.getMessageComposer(_config); + ((SOAPMessageComposer)_messageComposer).setDocumentStyle(_documentStyle); + ((SOAPMessageComposer)_messageComposer).setWsdlPort(_wsdlPort); + ((SOAPMessageComposer)_messageComposer).setMtomEnabled(mtom.isEnabled()); + if (_config.getMtomConfig() != null) { + ((SOAPMessageComposer)_messageComposer).setXopExpand(_config.getMtomConfig().isXopExpand()); + } + + URL wsdlUrl = WSDLUtil.getURL(_config.getWsdl()); + SOAPLogger.ROOT_LOGGER.creatingDispatchWithWSDL(wsdlUrl.toString()); + + Service service = Service.create(wsdlUrl, portName.getServiceQName()); + + _dispatcher = service.createDispatch(portName.getPortQName(), + SOAPMessage.class, + Service.Mode.MESSAGE, + _feature.getAddressing(), + mtom); + + // this does not return a proper qualified Fault element and has no Detail so deferring for now + // _dispatcher.getRequestContext().put("jaxws.response.throwExceptionIfSOAPFault", Boolean.FALSE); + + Client client = ((DispatchImpl)_dispatcher).getClient(); + if (_feature.isAddressingEnabled()) { + // Add handler to process WS-A headers + Interceptor addressingInterceptor = EndpointPublisherFactory.getEndpointPublisher().createAddressingInterceptor(); + client.getOutInterceptors().add(addressingInterceptor); + client.getOutFaultInterceptors().add(addressingInterceptor); + } else { + // Defaulting to use soapAction property in request header + _dispatcher.getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE); + } + + if (_config.getEndpointAddress() != null) { + _dispatcher.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, _config.getEndpointAddress()); + } + + Integer timeout = _config.getTimeout(); + HTTPConduit conduit = (HTTPConduit)client.getConduit(); + // Proxy authentication + if (_config.getProxyConfig() != null) { + HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); + httpClientPolicy.setProxyServerType(ProxyServerType.fromValue(_config.getProxyConfig().getType())); + httpClientPolicy.setProxyServer(_config.getProxyConfig().getHost()); + if (_config.getProxyConfig().getPort() != null) { + httpClientPolicy.setProxyServerPort(Integer.valueOf(_config.getProxyConfig().getPort()).intValue()); + } + conduit.setClient(httpClientPolicy); + if (_config.getProxyConfig().getUser() != null) { + ProxyAuthorizationPolicy policy = new ProxyAuthorizationPolicy(); + policy.setUserName(_config.getProxyConfig().getUser()); + policy.setPassword(_config.getProxyConfig().getPassword()); + conduit.setProxyAuthorization(policy); + } + } + if (_config.hasAuthentication()) { + AuthorizationPolicy policy = new AuthorizationPolicy(); + // Set authentication + if (_config.isBasicAuth()) { + policy.setUserName(_config.getBasicAuthConfig().getUser()); + policy.setPassword(_config.getBasicAuthConfig().getPassword()); + policy.setAuthorizationType("Basic"); + } else { + policy.setUserName(_config.getNtlmAuthConfig().getDomain() + "\\" + _config.getNtlmAuthConfig().getUser()); + policy.setPassword(_config.getNtlmAuthConfig().getPassword()); + HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); + if (timeout != null) { + httpClientPolicy.setConnectionTimeout(timeout); + } else { + httpClientPolicy.setConnectionTimeout(36000); + } + httpClientPolicy.setAllowChunking(false); + conduit.setClient(httpClientPolicy); + } + conduit.setAuthorization(policy); + } + if (timeout != null) { + if (conduit.getClient() != null) { + conduit.getClient().setConnectionTimeout(timeout); + conduit.getClient().setReceiveTimeout(timeout); + } else { + HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); + httpClientPolicy.setConnectionTimeout(timeout); + httpClientPolicy.setReceiveTimeout(timeout); + conduit.setClient(httpClientPolicy); + } + } + + } catch (MalformedURLException e) { + throw new WebServiceConsumeException(e); + } catch (WSDLException wsdle) { + throw new WebServiceConsumeException(wsdle); + } + } + } + + /** + * Stop lifecycle. + */ + public void stop() { + } + + /** + * The handler method that invokes the actual Webservice when the + * component is used as a WS consumer. + * @param exchange the Exchange + * @throws HandlerException handler exception + */ + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + // identify ourselves + exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + + try { + if (getState() != State.STARTED) { + throw SOAPMessages.MESSAGES.referenceBindingNotStarted(_referenceName, _bindingName); + } + if (SOAPUtil.getFactory(_bindingId) == null) { + throw SOAPMessages.MESSAGES.failedToInstantiateSOAPMessageFactory(); + } + + SOAPBindingData request; + Boolean oneWay = false; + String action = null; + try { + request = _messageComposer.decompose(exchange, new SOAPBindingData(SOAPUtil.createMessage(_bindingId))); + + QName firstBodyElement = SOAPUtil.getFirstBodyElement(request.getSOAPMessage()); + action = WSDLUtil.getSoapAction(_wsdlPort, firstBodyElement, _documentStyle); + oneWay = WSDLUtil.isOneWay(_wsdlPort, firstBodyElement, _documentStyle); + + if (_feature.isAddressingEnabled()) { + Context context = exchange.getContext(); + _dispatcher.getRequestContext().put(SOAPUtil.SWITCHYARD_CONTEXT, context); + // It is a one way if a replyto address is set + String toAddress = SOAPUtil.getToAddress(exchange.getContext()); + if (toAddress != null) { + _dispatcher.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, toAddress); + } + } + } catch (Exception e) { + throw e instanceof SOAPException ? (SOAPException)e : new SOAPException(e); + } + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Outbound ---> Request:[" + _referenceName + "][" + SOAPUtil.soapMessageToString(request.getSOAPMessage()) + "]" + (oneWay ? " oneWay " : "")); + } + SOAPMessage response = invokeService(request, oneWay, action); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Outbound <--- Response:[" + _referenceName + "][" + SOAPUtil.soapMessageToString(response) + "]"); + } + if (response != null) { + // This property vanishes once message composer processes this message + // so caching it here + Boolean hasFault = response.getSOAPBody().hasFault(); + Message message; + try { + SOAPBindingData bindingData = new SOAPBindingData(response); + if (hasFault) { + SOAPFaultInfo faultInfo = new SOAPFaultInfo(); + faultInfo.copyFaultInfo(response); + bindingData.setSOAPFaultInfo(faultInfo); + } + Integer status = (Integer)_dispatcher.getResponseContext().get(MessageContext.HTTP_RESPONSE_CODE); + if (status != null) { + bindingData.setStatus(status); + } + @SuppressWarnings("unchecked") + Map> httpHeaders = + (Map>) _dispatcher.getResponseContext().get(MessageContext.HTTP_RESPONSE_HEADERS); + if (httpHeaders != null) { + bindingData.setHttpHeaders(httpHeaders); + } + + message = _messageComposer.compose(bindingData, exchange); + } catch (Exception e) { + throw e instanceof SOAPException ? (SOAPException)e : new SOAPException(e); + } + if (hasFault) { + exchange.sendFault(message); + } else { + exchange.send(message); + } + } + + } catch (SOAPException se) { + throw SOAPMessages.MESSAGES.unexpectedExceptionHandlingSOAPMessage(se); + } + } + + /** + * Invoke Webservice via Dispatch API + * @param soapMessage the SOAP request + * @param oneWay if it is request only operation + * @param action the SOAP Action + * @return the SOAP response + * @throws SOAPException If a Dispatch could not be created based on the SOAP message. + */ + private SOAPMessage invokeService(final SOAPBindingData bindingData, final Boolean oneWay, final String action) throws SOAPException { + + SOAPMessage soapMessage = bindingData.getSOAPMessage(); + SOAPMessage response = null; + try { + @SuppressWarnings("unchecked") + Map> httpHeaders = + (Map>) _dispatcher.getRequestContext().get(MessageContext.HTTP_REQUEST_HEADERS); + if (httpHeaders == null) { + httpHeaders = new HashMap>(); + _dispatcher.getRequestContext() + .put(MessageContext.HTTP_REQUEST_HEADERS, httpHeaders); + } + httpHeaders.putAll(bindingData.getHttpHeaders()); + + if (!_feature.isAddressingEnabled() && (action != null)) { + _dispatcher.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, "\"" + action + "\""); + } + + if (oneWay) { + _dispatcher.invokeOneWay(soapMessage); + //return empty response + } else { + response = _dispatcher.invoke(soapMessage); + } + } catch (SOAPFaultException sfex) { + response = SOAPUtil.generateFault(sfex, _bindingId); + } catch (WebServiceException wsex) { + if (wsex.getMessage().equals(NO_RESPONSE) && _feature.isAddressingEnabled()) { + // Ignore it + SOAPLogger.ROOT_LOGGER.sentAMessageWithReplyToToARequestResponseWebserviceSoNoResponseReturned(); + } else { + throw new SOAPException(wsex); + } + } catch (Exception ex) { + throw SOAPMessages.MESSAGES.cannotProcessSOAPRequest(ex); + } + + return response; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/PortName.java b/components/soap/src/main/java/org/switchyard/component/soap/PortName.java new file mode 100644 index 000000000..8b565e394 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/PortName.java @@ -0,0 +1,202 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import java.io.Serializable; +import javax.xml.namespace.QName; + +/** + * Represents the SOAPGateway's wsPort parameter. The value of a PortName contains a Service QName and Port name. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class PortName implements Serializable { + private static final long serialVersionUID = -1904811344687200683L; + + private QName _serviceQName = new QName(""); + private String _name; + + /** + * Default Constructor. + */ + public PortName() { + } + + /** + * Construct the PortName from a string. + * + * The string can be in the form "{namespaceURI}serviceName:portName", with the "{namespaceURI}" and "serviceName:" part being optional. + * If the PortName need to represent only a service name then the string could be just "serviceName:" + * + * @param portName a port name String. + */ + public PortName(final String portName) { + if (portName != null) { + int idx = portName.lastIndexOf(":"); + _name = portName.substring(idx + 1, portName.length()); + if (idx > 0) { + String serviceStr = portName.substring(0, idx); + _serviceQName = QName.valueOf(serviceStr); + } + } + } + + /** + * Construct the PortName given a Service QName and Port name. + * + * @param serviceQName The Service QName. + * @param name a port name. + */ + public PortName(final QName serviceQName, final String name) { + if (serviceQName != null) { + _serviceQName = serviceQName; + } + _name = name; + } + + /** + * Construct the PortName given a namespace URI, Service name and Port name. + * + * @param namespace a namespace URI. + * @param serviceName the Service QName. + * @param name the port name. + */ + public PortName(final String namespace, final String serviceName, final String name) { + _serviceQName = new QName(namespace, serviceName); + _name = name; + } + + /** + * Get the Port as a QName. + * + * @return the Port QName. + */ + public QName getPortQName() { + return new QName(getNamespaceURI(), _name); + } + + /** + * Get the Port's Service QName. + * + * @return the Service QName. + */ + public QName getServiceQName() { + return _serviceQName; + } + + /** + * Set the Port's Service QName. + * + * @param serviceQName a Service QName. + */ + public void setServiceQName(final QName serviceQName) { + _serviceQName = serviceQName; + } + + /** + * Get the Port's Service name. + * + * @return the Service name. + */ + public String getServiceName() { + return _serviceQName.getLocalPart(); + } + + /** + * Set the Port's Service name. + * + * @param serviceName a Service name. + */ + public void setServiceName(final String serviceName) { + String namespaceURI = _serviceQName.getNamespaceURI(); + _serviceQName = new QName(namespaceURI, serviceName); + } + + /** + * Get the Port's Service namespace URI. + * + * @return the namespace URI. + */ + public String getNamespaceURI() { + return _serviceQName.getNamespaceURI(); + } + + /** + * Set the Port's Service namespace URI. + * + * @param namespaceURI a namespaceURI String. + */ + public void setNamespaceURI(final String namespaceURI) { + String serviceName = _serviceQName.getLocalPart(); + _serviceQName = new QName(namespaceURI, serviceName); + } + + /** + * Get the Port's name. + * + * @return the Port name String. + */ + public String getName() { + return _name; + } + + /** + * Set the Port name. + * + * @param name a Port name. + */ + public void setName(final String name) { + _name = name; + } + + /** + * Test this PortName for equality with another Object. + * + * @param objectToTest the Object to test with this PortName. + * @return true if equal else false. + */ + public final boolean equals(Object objectToTest) { + if ((objectToTest == null) || (!(objectToTest instanceof PortName))) { + return false; + } + + PortName portName = (PortName) objectToTest; + + return (this._name.equals(portName._name)) && (this._serviceQName.equals(portName._serviceQName)); + } + + /** + * Generate the hashcode for this PortName. + * + * @return The hashcode. + */ + public final int hashCode() { + return _serviceQName.hashCode() ^ _name.hashCode(); + } + + /** + * Retruns a String representation of PortName in the form "{namespaceURI}serviceName:portName". + * If the serviceQName is null then returns only the portName. + * + * @return A PortName string. + */ + public String toString() { + if (_serviceQName != null) { + return _serviceQName + ":" + _name; + } else { + return _name; + } + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/SOAPLogger.java b/components/soap/src/main/java/org/switchyard/component/soap/SOAPLogger.java new file mode 100644 index 000000000..ba51d9650 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/SOAPLogger.java @@ -0,0 +1,134 @@ +package org.switchyard.component.soap; + +import javax.xml.soap.SOAPException; +import org.jboss.logging.Cause; +import org.jboss.logging.Logger; +import org.jboss.logging.Logger.Level; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 35000-35399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface SOAPLogger { + /** + * A root logger with the category of the package name. + */ + SOAPLogger ROOT_LOGGER = Logger.getMessageLogger(SOAPLogger.class, SOAPLogger.class.getPackage().getName()); + + /** + * credentialsAreIgnoredForServletRequest! method definition. + */ + @LogMessage(level = Level.WARN) + @Message(id = 35000, value = "Credentials are ignored for ServletRequest!") + void credentialsAreIgnoredForServletRequest(); + + /** + * addressingEnabledRequired method definition. + * @param isEnabled isEnabled + * @param isRequired isRequired + */ + @LogMessage(level = Level.INFO) + @Message(id = 35001, value = "Addressing [enabled = %s, required = %s]") + void addressingEnabledRequired(String isEnabled, String isRequired); + + /** + * mTOMEnabledThreshold method definition. + * @param isEnabled isEnabled + * @param threshold threshold + */ + @LogMessage(level = Level.INFO) + @Message(id = 35002, value = "MTOM [enabled = %s, threshold = %s]") + void mTOMEnabledThreshold(String isEnabled, String threshold); + + /** + * publishingWebServiceAt method definition. + * @param publishUrl the publishUrl + */ + @LogMessage(level = Level.INFO) + @Message(id = 35003, value = "Publishing WebService at %s") + void publishingWebServiceAt(String publishUrl); + + /** + * stoppingWebServiceAt method definition. + * @param publishUrl publishUrl + */ + @LogMessage(level = Level.INFO) + @Message(id = 35004, value = "Stopping WebService at %s") + void stoppingWebServiceAt(String publishUrl); + + /** + * webService method definition. + * @param port port + */ + @LogMessage(level = Level.INFO) + @Message(id = 35010, value = "WebService %s stopped.") + void webService(String port); + + /** + * creatingDispatchWithWSDL method definition. + * @param wsdlUrl the wsdlUrl + */ + @LogMessage(level = Level.INFO) + @Message(id = 35014, value = "Creating dispatch with WSDL %s") + void creatingDispatchWithWSDL(String wsdlUrl); + + /** + * sentAMessageWithReplyToToARequestResponseWebserviceSoNoResponseReturned method definition. + */ + @LogMessage(level = Level.WARN) + @Message(id = 35015, value = "Sent a message with ReplyTo to a Request_Response Webservice, so no response returned!") + void sentAMessageWithReplyToToARequestResponseWebserviceSoNoResponseReturned(); + + /** + * couldNotParseSOAPMessage method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 35016, value = "Could not parse SOAP Message") + void couldNotParseSOAPMessage(@Cause Exception e); + + /** + * couldNotParseMessageString method definition. + * @param e the e + */ + @LogMessage(level = Level.ERROR) + @Message(id = 35018, value = "Could not parse Message String") + void couldNotParseMessageString(@Cause Exception e); + + /** + * couldNotInstantiateSOAP11MessageFactory method definition. + * @param soape the soape + */ + @LogMessage(level = Level.ERROR) + @Message(id = 35019, value = "Could not instantiate SOAP 1.1 Message Factory") + void couldNotInstantiateSOAP11MessageFactory(@Cause SOAPException soape); + + /** + * couldNotInstantiateSOAP12MessageFactory method definition. + * @param soape the soape + */ + @LogMessage(level = Level.ERROR) + @Message(id = 35020, value = "Could not instantiate SOAP 1.2 Message Factory") + void couldNotInstantiateSOAP12MessageFactory(@Cause SOAPException soape); + + /** + * noEndpointPublisherRegistered method definition. + */ + @LogMessage(level = Level.WARN) + @Message(id = 35021, value = "No endpoint publisher service registered. Using default publisher.") + void noEndpointPublisherRegistered(); + + /** + * endpointPublisherRegistered method definition. + * @param type the publisher type + */ + @LogMessage(level = Level.DEBUG) + @Message(id = 35022, value = "Endpoint publisher service loaded: %s.") + void endpointPublisherRegistered(String type); +} + diff --git a/components/soap/src/main/java/org/switchyard/component/soap/SOAPMessages.java b/components/soap/src/main/java/org/switchyard/component/soap/SOAPMessages.java new file mode 100644 index 000000000..db69fe290 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/SOAPMessages.java @@ -0,0 +1,344 @@ +package org.switchyard.component.soap; + +import javax.xml.soap.SOAPException; +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 35400-35799 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface SOAPMessages { + /** + * The default messages. + */ + SOAPMessages MESSAGES = Messages.getBundle(SOAPMessages.class); + + /** + * missingSOAPBodyFromRequest method definition. + * @return SOAPException + */ + @Message(id = 35401, value = "Missing SOAP body from request") + SOAPException missingSOAPBodyFromRequest(); + + /** + * foundMultipleSOAPElementsInSOAPBody method definition. + * @return SOAPException + */ + @Message(id = 35402, value = "Found multiple SOAPElements in SOAPBody") + SOAPException foundMultipleSOAPElementsInSOAPBody(); + + /** + * couldNotFindSOAPElementInSOAPBody method definition. + * @return SOAPException + */ + @Message(id = 35403, value = "Could not find SOAPElement in SOAPBody") + SOAPException couldNotFindSOAPElementInSOAPBody(); + + /** + * contentIDHeaderMissingForAttachmentPart method definition. + * @return SOAPException + */ + @Message(id = 35404, value = "Content-ID header missing for attachment part") + SOAPException contentIDHeaderMissingForAttachmentPart(); + + /** + * unableToReadWSDL method definition. + * @param wsdlLocation wsdlLocation + * @return String + */ + @Message(id = 35405, value = "Unable to read WSDL at %s") + String unableToReadWSDL(String wsdlLocation); + + /** + * unableToCreateSOAPBodyDueToNullMessageContent method definition. + * @return SOAPException + */ + @Message(id = 35406, value = "Unable to create SOAP Body due to null message content") + SOAPException unableToCreateSOAPBodyDueToNullMessageContent(); + + /** + * unableToParseSOAPMessage method definition. + * @param e the e + * @return SOAPException + */ + @Message(id = 35407, value = "Unable to parse SOAP Message") + SOAPException unableToParseSOAPMessage(@Cause Exception e); + + /** + * failedToMapContextPropertiesToSOAPMessage method definition. + * @param ex the ex + * @return SOAPException + */ + @Message(id = 35408, value = "Failed to map context properties to SOAP message") + SOAPException failedToMapContextPropertiesToSOAPMessage(@Cause Exception ex); + + /** + * not method definition. + * @param interceptors interceptors + * @return IllegalArgumentException + */ + @Message(id = 35409, value = "not %s") + IllegalArgumentException not(String interceptors); + + /** + * unableToReadWSDL method definition. + * @param wsdlLocation wsdlLocation + * @return String + */ + @Message(id = 35410, value = "Unable to resolve WSDL document at %s") + String unableToResolveWSDL(String wsdlLocation); + + /** + * unexpectedSOAPExceptionWhenGeneratingASOAP11FaultMessage method definition. + * @param from the from + * @return IllegalStateException + */ + @Message(id = 35411, value = "Unexpected SOAPException when generating a SOAP 1.1 Fault message.") + IllegalStateException unexpectedSOAPExceptionWhenGeneratingASOAP11FaultMessage(@Cause Exception from); + + /** + * unexpectedSOAPExceptionWhenGeneratingASOAP12FaultMessage method definition. + * @param from the from + * @return IllegalStateException + */ + @Message(id = 35412, value = "Unexpected SOAPException when generating a SOAP 1.2 Fault message.") + IllegalStateException unexpectedSOAPExceptionWhenGeneratingASOAP12FaultMessage(@Cause Exception from); + + /** + * unexpected method definition. + * @return IllegalStateException + */ + @Message(id = 35418, value = "Unexpected") + IllegalStateException unexpected(); + + /** + * invalidInputSOAPPayloadForServiceOperation method definition. + * @param operationName operationName + * @param serviceName serviceName + * @param actualLN the actualLN + * @return SOAPException + */ + @Message(id = 35422, value = "Invalid input SOAP payload for service operation '%s' (service '%s'). No such Part '%s'.") + SOAPException invalidInputSOAPPayloadForServiceOperation(String operationName, String serviceName, String actualLN); + + /** + * invalidInputSOAPPayloadNamespaceForServiceOperation method definition. + * @param operationName operationName + * @param serviceName serviceName + * @param expectedNS the expectedNS + * @param actualNS the actualNS + * @return SOAPException + */ + @Message(id = 35423, value = "Invalid input SOAP payload namespace for service operation '%s' (service '%s'). Port defines operation namespace as '%s'. Actual namespace on input SOAP message '%s'.") + SOAPException invalidInputSOAPPayloadNamespaceForServiceOperation(String operationName, String serviceName, String expectedNS, String actualNS); + + /** + * invalidInputSOAPPayloadLocalNamePartForServiceOperation method definition. + * @param operationName operationName + * @param serviceName serviceName + * @param expectedLN the expectedLN + * @param actualLN the actualLN + * @return SOAPException + */ + @Message(id = 35424, value = "Invalid input SOAP payload localNamePart for service operation '%s' (service '%s'). Port defines operation localNamePart as '%s'. Actual localNamePart on input SOAP message '%s'.") + SOAPException invalidInputSOAPPayloadLocalNamePartForServiceOperation(String operationName, String serviceName, String expectedLN, String actualLN); + + /** + * referenceBindingNotStarted method definition. + * @param referenceName the referenceName + * @param bindingName the bindingName + * @return HandlerException + */ + @Message(id = 35427, value = "Reference binding \"%s/%s\" is not started.") + HandlerException referenceBindingNotStarted(String referenceName, String bindingName); + + /** + * failedToInstantiateSOAPMessageFactory method definition. + * @return SOAPException + */ + @Message(id = 35428, value = "Failed to instantiate SOAP Message Factory") + SOAPException failedToInstantiateSOAPMessageFactory(); + + /** + * unexpectedExceptionHandlingSOAPMessage method definition. + * @param se the se + * @return HandlerException + */ + @Message(id = 35429, value = "Unexpected exception handling SOAP Message") + HandlerException unexpectedExceptionHandlingSOAPMessage(@Cause SOAPException se); + + /** + * cannotProcessSOAPRequest method definition. + * @param ex the ex + * @return SOAPException + */ + @Message(id = 35431, value = "Cannot process SOAP request") + SOAPException cannotProcessSOAPRequest(@Cause Exception ex); + + /** + * noAttachmentFoundWithName method definition. + * @param contentId the contentId + * @return RuntimeException + */ + @Message(id = 35433, value = "No attachment found with name '%s'") + RuntimeException noAttachmentFoundWithName(String contentId); + + /** + * couldNotFindServiceInTheWSDL method definition. + * @param portName the portName + * @param definitionDocumentBaseURI definitionDocumentBaseURI + * @return String + */ + @Message(id = 35436, value = "Could not find service %s in the WSDL %s") + String couldNotFindServiceInTheWSDL(String portName, String definitionDocumentBaseURI); + + /** + * couldNotFindAPortDefinitionWithinService method definition. + * @param wsdlServiceQName wsdlServiceQName + * @return String + */ + @Message(id = 35437, value = "Could not find a port definition within service %s") + String couldNotFindAPortDefinitionWithinService(String wsdlServiceQName); + + /** + * couldNotFindPortInTheService method definition. + * @param portName the portName + * @param wsdlServiceQName wsdlServiceQName + * @return String + */ + @Message(id = 35438, value = "Could not find port %s in the Service %s") + String couldNotFindPortInTheService(String portName, String wsdlServiceQName); + + /** + * incompatibleStyleOfSoapOperationLevelBindingsDetected method definition. + * @return SwitchYardException + */ + @Message(id = 35439, value = "Incompatible style of soap operation level bindings detected") + SwitchYardException incompatibleStyleOfSoapOperationLevelBindingsDetected(); + + /** + * detectedMixingDifferentSoapBindingStyleOnPortTypeAndOperationLevel method definition. + * @return SwitchYardException + */ + @Message(id = 35440, value = "Detected mixing different soap binding style on port type and operation level") + SwitchYardException detectedMixingDifferentSoapBindingStyleOnPortTypeAndOperationLevel(); + + /** + * faultNameNotFoundOnOperation method definition. + * @param faultName the faultName + * @param operationNameLocalPart operationNameLocalPart + * @return IllegalArgumentException + */ + @Message(id = 35441, value = "Fault name %s not found on operation %s") + IllegalArgumentException faultNameNotFoundOnOperation(String faultName, String operationNameLocalPart); + + /** + * policyReferenceURIMissingFor method definition. + * @param portBindingQNametLocalPart portBindingQNametLocalPart + * @return RuntimeException + */ + @Message(id = 35442, value = "Policy reference URI missing for %s") + RuntimeException policyReferenceURIMissingFor(String portBindingQNametLocalPart); + + /** + * invalidWSDLNoOperationsFound method definition. + * @return WebServicePublishException + */ + @Message(id = 35443, value = "Invalid WSDL. No operations found.") + WebServicePublishException invalidWSDLNoOperationsFound(); + + /** + * wSDLOperationNotFoundInService method definition. + * @param name the name + * @param serviceName serviceName + * @return WebServicePublishException + */ + @Message(id = 35444, value = "WSDL Operation %s not found in Service %s") + WebServicePublishException wSDLOperationNotFoundInService(String name, String serviceName); + + /** + * wSDLOperationDoesNotMatchServiceOperation method definition. + * @param name the name + * @param targetServiceOperationName targetServiceOperationName + * @return WebServicePublishException + */ + @Message(id = 35445, value = "WSDL Operation %s does not match Service Operation %s") + WebServicePublishException wSDLOperationDoesNotMatchServiceOperation(String name, String targetServiceOperationName); + + /** + * wSDLOperationDoesNotHaveAnyInputMessageParts method definition. + * @param name the name + * @return WebServicePublishException + */ + @Message(id = 35446, value = "WSDL Operation %s does not have any input Message parts") + WebServicePublishException wSDLOperationDoesNotHaveAnyInputMessageParts(String name); + + /** + * wSDLOperationDoesNotHaveAnyOuputMessageParts method definition. + * @param name the name + * @return WebServicePublishException + */ + @Message(id = 35447, value = "WSDL Operation %s does not have any ouput Message parts") + WebServicePublishException wSDLOperationDoesNotHaveAnyOuputMessageParts(String name); + + /** + * sendFailed method definition. + * @return String + */ + @Message(id = 35448, value = "Send Failed") + String sendFailed(); + + + /** + * noSuchOperation method definition. + * @param operationName operationName + * @return SOAPException + */ + @Message(id = 35449, value = "No such operation: %s->null") + SOAPException noSuchOperation(String operationName); + + + /** + * couldNotFindOperation method definition. + * @param action action + * @return SOAPException + */ + @Message(id = 35450, value = "Could not find any operation associated with WS-A Action '%s'.") + SOAPException couldNotFindOperation(String action); + + /** + * operationNotAvailableTarget method definition. + * @param firstBodyElement firstBodyElement + * @param serviceName serviceName + * @return SOAPException + */ + @Message(id = 35451, value = "Operation for '%s' not available on target Service '%s'.") + SOAPException operationNotAvailableTarget(String firstBodyElement, String serviceName); + + + /** + * operationNotAvailableTarget method definition. + * @param waitTimeout waitTimeout + * @param serviceName serviceName + * @return SOAPException + */ + @Message(id = 35452, value = "Timed out after %s ms waiting on synchronous response from target service '%s'.") + SOAPException timedOut(String waitTimeout, String serviceName); + + /** + * invalidResponseConstruction method definition. + * @param messageComposerName messageComposerName + * @return SOAPException + */ + @Message(id = 35453, value = "Invalid response SOAPMessage construction. The associated SwitchYard Exchange is in a FAULT state, but the SOAPMessage is not a Fault message. The MessageComposer implementation in use (\"%s\") must generate the SOAPMessage instance properly as a Fault message.") + SOAPException invalidResponseConstruction(String messageComposerName); +} + diff --git a/components/soap/src/main/java/org/switchyard/component/soap/WebServiceConsumeException.java b/components/soap/src/main/java/org/switchyard/component/soap/WebServiceConsumeException.java new file mode 100644 index 000000000..ea536eeca --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/WebServiceConsumeException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import org.switchyard.SwitchYardException; + +/** + * Wrapper for WebService consumer exceptions. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class WebServiceConsumeException extends SwitchYardException { + private static final long serialVersionUID = 1L; + + /** + * Public constructor. + * @param message Exception message. + */ + public WebServiceConsumeException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Exception cause. + */ + public WebServiceConsumeException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Public constructor. + * @param cause Exception cause. + */ + public WebServiceConsumeException(final Throwable cause) { + super(cause); + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/WebServicePublishException.java b/components/soap/src/main/java/org/switchyard/component/soap/WebServicePublishException.java new file mode 100644 index 000000000..921d231b7 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/WebServicePublishException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import org.switchyard.SwitchYardException; + +/** + * Wrapper for WebService creation exceptions. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class WebServicePublishException extends SwitchYardException { + private static final long serialVersionUID = 1L; + + /** + * Public constructor. + * @param message Exception message. + */ + public WebServicePublishException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Exception cause. + */ + public WebServicePublishException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Public constructor. + * @param cause Exception cause. + */ + public WebServicePublishException(final Throwable cause) { + super(cause); + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPBindingData.java b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPBindingData.java new file mode 100644 index 000000000..1dc9071d9 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPBindingData.java @@ -0,0 +1,154 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.composer; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.ServletRequest; +import javax.xml.soap.SOAPMessage; +import javax.xml.ws.WebServiceContext; +import javax.xml.ws.handler.MessageContext; + +import org.switchyard.component.common.composer.SecurityBindingData; +import org.switchyard.component.soap.SOAPLogger; +import org.switchyard.security.SecurityServices; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.extractor.SOAPMessageCredentialExtractor; +import org.switchyard.security.credential.extractor.WebServiceContextCredentialExtractor; + +/** + * SOAP binding data. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + * @author Magesh Kumar B © 2013 Red Hat Inc. + */ +public class SOAPBindingData implements SecurityBindingData { + + private final SOAPMessage _soapMessage; + private final WebServiceContext _webServiceContext; + private SOAPFaultInfo _soapFaultInfo; + private Integer _status; + private Map> _httpHeaders = new HashMap>(); + + /** + * Constructs a new SOAP binding data with the specified SOAP message. + * @param soapMessage the specified SOAP message. + */ + public SOAPBindingData(SOAPMessage soapMessage) { + this(soapMessage, null); + } + + /** + * Constructs a new SOAP binding data with the specified SOAP message and web service context. + * @param soapMessage the specified SOAP message + * @param webServiceContext the specified web service context + */ + public SOAPBindingData(SOAPMessage soapMessage, WebServiceContext webServiceContext) { + _soapMessage = soapMessage; + _webServiceContext = webServiceContext; + } + + /** + * Gets the SOAP message. + * @return the SOAP message + */ + public SOAPMessage getSOAPMessage() { + return _soapMessage; + } + + /** + * Gets the SOAPFault information. + * @return the SOAPFaultInfo object + */ + public SOAPFaultInfo getSOAPFaultInfo() { + return _soapFaultInfo; + } + + /** + * Sets the SOAPFault information. + * @param faultInfo the SOAPFaultInfo object + */ + public void setSOAPFaultInfo(SOAPFaultInfo faultInfo) { + _soapFaultInfo = faultInfo; + } + + /** + * Gets the web service context. + * @return the web service context + */ + public WebServiceContext getWebServiceContext() { + return _webServiceContext; + } + + /** + * Get the HTTP response status. + * @return HTTP response status + */ + public Integer getStatus() { + return _status; + } + + /** + * Set the HTTP response status. + * @param status the response status + */ + public void setStatus(Integer status) { + _status = status; + } + + /** + * Get the HTTP headers. + * @return HTTP headers + */ + public Map> getHttpHeaders() { + return _httpHeaders; + } + + /** + * Set the HTTP headers. + * @param httpHeaders HTTP headers + */ + public void setHttpHeaders(Map> httpHeaders) { + _httpHeaders = httpHeaders; + } + + /** + * {@inheritDoc} + */ + @Override + public Set extractCredentials() { + Set credentials = new HashSet(); + credentials.addAll(new SOAPMessageCredentialExtractor().extract(getSOAPMessage())); + credentials.addAll(new WebServiceContextCredentialExtractor().extract(getWebServiceContext())); + try { + credentials.addAll(SecurityServices.getServletRequestCredentialExtractor().extract(getServletRequest())); + } catch (UnsupportedOperationException uoe) { + // Ignore. This can happen with JBossWS http transport + SOAPLogger.ROOT_LOGGER.credentialsAreIgnoredForServletRequest(); + } + return credentials; + } + + private ServletRequest getServletRequest() { + if (_webServiceContext != null) { + return (ServletRequest)_webServiceContext.getMessageContext().get(MessageContext.SERVLET_REQUEST); + } + return null; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPComposition.java b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPComposition.java new file mode 100644 index 000000000..76999bbfc --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPComposition.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.composer; + +import org.switchyard.component.common.composer.Composition; +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.config.model.SOAPContextMapperModel; +import org.switchyard.component.soap.config.model.SOAPMessageComposerModel; + +/** + * Utility class for SOAP-specific Composition. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class SOAPComposition { + + /** The soap_fault_info property name. */ + public static final String SOAP_FAULT_INFO = "soap_fault_info"; + + /** + * Uses the {@link Composition} class to create a SOAP-specific MessageComposer. + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer() { + return Composition.getMessageComposer(SOAPBindingData.class); + } + + /** + * Uses the {@link Composition} class to create a SOAP-specific MessageComposer. + * @param sbm a SOAPBindingModel to get configuration details from + * @return the MessageComposer + */ + public static MessageComposer getMessageComposer(SOAPBindingModel sbm) { + SOAPContextMapperModel scmm = sbm != null ? sbm.getSOAPContextMapper() : null; + SOAPMessageComposerModel mcm = sbm != null ? sbm.getSOAPMessageComposer() : null; + MessageComposer mc = Composition.getMessageComposer(SOAPBindingData.class, scmm, mcm); + ContextMapper cm = mc.getContextMapper(); + if (cm instanceof SOAPContextMapper && scmm != null) { + ((SOAPContextMapper)cm).setSOAPHeadersType(scmm.getSOAPHeadersType()); + } + return mc; + } + + private SOAPComposition() {} + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPContextMapper.java b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPContextMapper.java new file mode 100644 index 000000000..210fb2b51 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPContextMapper.java @@ -0,0 +1,198 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.composer; + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPHeader; +import javax.xml.soap.SOAPHeaderElement; +import javax.xml.soap.SOAPMessage; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.common.composer.BaseRegexContextMapper; +import org.switchyard.component.common.label.ComponentLabel; +import org.switchyard.component.common.label.EndpointLabel; +import org.switchyard.config.Configuration; +import org.switchyard.config.ConfigurationPuller; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * SOAPContextMapper. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class SOAPContextMapper extends BaseRegexContextMapper { + + /** + * The HTTP responce code. + */ + public static final String HTTP_RESPONSE_STATUS = "http_response_status"; + /** + * Headers to be excluded. + */ + public static final List HTTP_HEADERS_EXCLUDED = Arrays.asList(new String[]{"content-type", "content-length"}); + private static final String[] SOAP_HEADER_LABELS = new String[]{ComponentLabel.SOAP.label(), EndpointLabel.SOAP.label()}; + private static final String[] SOAP_MIME_LABELS = new String[]{ComponentLabel.SOAP.label(), EndpointLabel.HTTP.label()}; + + private SOAPHeadersType _soapHeadersType = null; + + /** + * Gets the SOAPHeadersType. + * @return the SOAPHeadersType + */ + public SOAPHeadersType getSOAPHeadersType() { + return _soapHeadersType; + } + + /** + * Sets the SOAPHeadersType. + * @param soapHeadersType the SOAPHeadersType + * @return this instance (useful for chaining) + */ + public SOAPContextMapper setSOAPHeadersType(SOAPHeadersType soapHeadersType) { + _soapHeadersType = soapHeadersType; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public void mapFrom(SOAPBindingData source, Context context) throws Exception { + SOAPMessage soapMessage = source.getSOAPMessage(); + if (soapMessage.getSOAPBody().hasFault() && (source.getSOAPFaultInfo() != null)) { + context.setProperty(SOAPComposition.SOAP_FAULT_INFO, source.getSOAPFaultInfo(), Scope.EXCHANGE).addLabels(SOAP_HEADER_LABELS); + } + if (source.getStatus() != null) { + context.setProperty(HTTP_RESPONSE_STATUS, source.getStatus()).addLabels(SOAP_MIME_LABELS); + } + for (String key : source.getHttpHeaders().keySet()) { + if (matches(key)) { + List values = source.getHttpHeaders().get(key); + if (values != null) { + context.setProperty(key, values).addLabels(SOAP_MIME_LABELS); + } + } + } + + @SuppressWarnings("unchecked") + Iterator soapHeaders = soapMessage.getSOAPHeader().examineAllHeaderElements(); + while (soapHeaders.hasNext()) { + SOAPHeaderElement soapHeader = soapHeaders.next(); + QName qname = soapHeader.getElementQName(); + if (matches(qname)) { + final Object value; + switch (_soapHeadersType != null ? _soapHeadersType : SOAPHeadersType.VALUE) { + case CONFIG: + value = new ConfigurationPuller().pull(soapHeader); + break; + case DOM: + value = soapHeader; + break; + case VALUE: + value = soapHeader.getValue(); + break; + case XML: + value = new ConfigurationPuller().pull(soapHeader).toString(); + break; + default: + value = null; + } + if (value != null) { + String name = qname.toString(); + context.setProperty(name, value).addLabels(SOAP_HEADER_LABELS); + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mapTo(Context context, SOAPBindingData target) throws Exception { + SOAPMessage soapMessage = target.getSOAPMessage(); + SOAPHeader soapHeader = soapMessage.getSOAPHeader(); + for (Property property : context.getProperties()) { + Object value = property.getValue(); + if (value != null) { + String name = property.getName(); + QName qname = XMLHelper.createQName(name); + boolean qualifiedForSoapHeader = Strings.trimToNull(qname.getNamespaceURI()) != null; + if (qualifiedForSoapHeader && matches(qname)) { + if (value instanceof Node) { + Node domNode = soapHeader.getOwnerDocument().importNode((Node)value, true); + soapHeader.appendChild(domNode); + } else if (value instanceof Configuration) { + Element configElement = new ElementPuller().pull(new StringReader(value.toString())); + Node configNode = soapHeader.getOwnerDocument().importNode(configElement, true); + soapHeader.appendChild(configNode); + } else { + String v = value.toString(); + if (SOAPHeadersType.XML.equals(_soapHeadersType)) { + try { + Element xmlElement = new ElementPuller().pull(new StringReader(v)); + Node xmlNode = soapHeader.getOwnerDocument().importNode(xmlElement, true); + soapHeader.appendChild(xmlNode); + } catch (Throwable t) { + soapHeader.addChildElement(qname).setValue(v); + } + } else { + soapHeader.addChildElement(qname).setValue(v); + } + } + } else if (matches(name) || property.hasLabel(EndpointLabel.HTTP.label())) { + if (HTTP_RESPONSE_STATUS.equalsIgnoreCase(name)) { + if (value instanceof String) { + target.setStatus(Integer.parseInt((String) value)); + } else if (value instanceof Integer) { + target.setStatus((Integer) value); + } + } else if (HTTP_HEADERS_EXCLUDED.contains(name.toLowerCase())) { + // Excluding HTTP headers which should not be set manually + continue; + } else { + if (value instanceof List) { + List stringValues = new ArrayList(); + for (Object v : List.class.cast(value)) { + if (v == null || v instanceof String) { + stringValues.add((String)v); + } + } + if (!stringValues.isEmpty()) { + target.getHttpHeaders().put(name, stringValues); + } + } else if (value instanceof String) { + target.getHttpHeaders().put(name, Collections.singletonList((String)value)); + } + } + } + } + } + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPContextMapperFactory.java b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPContextMapperFactory.java new file mode 100644 index 000000000..a40acf591 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPContextMapperFactory.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.composer; + +import org.switchyard.component.common.composer.ContextMapper; +import org.switchyard.component.common.composer.ContextMapperFactory; + +/** + * SOAPContextMapperFactory. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SOAPContextMapperFactory extends ContextMapperFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return SOAPBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapper newContextMapperDefault() { + return new SOAPContextMapper(); + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPFaultInfo.java b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPFaultInfo.java new file mode 100644 index 000000000..c38400cdc --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPFaultInfo.java @@ -0,0 +1,310 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.composer; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPFault; +import javax.xml.soap.SOAPMessage; + +import org.switchyard.component.soap.util.SOAPUtil; +import org.w3c.dom.Node; + +/** + * Wrapper for SOAPFault details. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class SOAPFaultInfo implements Serializable { + + private static final long serialVersionUID = -2522751288771130086L; + + private String _actor; + private String _code; + private String _prefix; + private QName _codeAsQName; + private String _node; + private List _reasonLocales = new ArrayList(); + private Map _reasonTexts = new HashMap(); + private String _role; + private String _string; + private Locale _stringLocale; + private List _subcodes = new ArrayList(); + private Node _detail; + + /** + * @return the Fault actor + */ + public String getActor() { + return _actor; + } + + /** + * @param actor the Fault actor to set + */ + public void setActor(String actor) { + _actor = actor; + } + + /** + * @return the Fault code + */ + public String getCode() { + return _code; + } + + /** + * @param code the Fault code to set + */ + public void setCode(String code) { + _code = code; + } + + /** + * @return the Fault code prefix + */ + public String getPrefix() { + return _prefix; + } + + /** + * @param prefix the Fault code prefix to set + */ + public void setPrefix(String prefix) { + _prefix = prefix; + } + + /** + * @return the Fault code as a QName + */ + public QName getCodeAsQName() { + return _codeAsQName; + } + + /** + * @param codeAsQName the Fault code QName to set + */ + public void setCodeAsQName(QName codeAsQName) { + _codeAsQName = codeAsQName; + } + + /** + * @return the Fault node + */ + public String getNode() { + return _node; + } + + /** + * @param node the Fault node to set + */ + public void setNode(String node) { + _node = node; + } + + /** + * @return the Fault reasonLocales + */ + public List getReasonLocales() { + return _reasonLocales; + } + + /** + * @param reasonLocales the Fault reasonLocales to set + */ + public void setReasonLocales(List reasonLocales) { + _reasonLocales = reasonLocales; + } + + /** + * @param reasonLocales the Fault reasonLocales to set + */ + public void setReasonLocales(Iterator reasonLocales) { + _reasonLocales = new ArrayList(); + while (reasonLocales.hasNext()) { + _reasonLocales.add(reasonLocales.next()); + } + } + + /** + * Return the Fault reason text for a given Locale if it exists. + * + * @param locale the reasonLocale + * @return the Fault reasonText + */ + public String getReasonText(Locale locale) { + return _reasonTexts.get(locale); + } + + /** + * Return all the Fault reason texts. + * + * @return the Fault reasonTexts + */ + public Iterator getReasonTexts() { + return _reasonTexts.values().iterator(); + } + + /** + * @param reasonTexts the Fault reasonTexts to set + */ + public void setReasonTexts(Map reasonTexts) { + _reasonTexts = reasonTexts; + } + + /** + * @param locale the reasonLocale + * @param reasonText the Fault reasonText to add + */ + public void addReasonText(Locale locale, String reasonText) { + _reasonTexts.put(locale, reasonText); + } + + /** + * @return the Fault role + * @deprecated use {@link #getRole()} instead + */ + @Deprecated + public String geRole() { + return _role; + } + + /** + * @return the Fault role + */ + public String getRole() { + return _role; + } + + /** + * @param role the Fault role to set + */ + public void setRole(String role) { + _role = role; + } + + /** + * @return the Fault string + */ + public String getString() { + return _string; + } + + /** + * @param string the Fault string to set + */ + public void setString(String string) { + _string = string; + } + + /** + * @return the Fault string's Locale + */ + public Locale getStringLocale() { + return _stringLocale; + } + + /** + * @param stringLocale the Fault string Locale to set + */ + public void setStringLocale(Locale stringLocale) { + _stringLocale = stringLocale; + } + + /** + * @return the Fault subcodes + */ + public List getSubcodes() { + return _subcodes; + } + + /** + * @param subcodes the Fault subcodes to set + */ + public void setSubcodes(List subcodes) { + _subcodes = subcodes; + } + + /** + * @param subcodes the Fault subcodes to set + */ + public void setSubcodes(Iterator subcodes) { + _subcodes = new ArrayList(); + while (subcodes.hasNext()) { + _subcodes.add(subcodes.next()); + } + } + + /** + * @return the Fault detail + */ + public Node getDetail() { + return _detail; + } + + /** + * @param detail the Fault detail to set + */ + public void setDetail(Node detail) { + if (detail != null) { + _detail = detail.cloneNode(true); + } + } + + @Override + public String toString() { + return "SOAPFaultInfo [_actor=" + _actor + ", _codeAsQName=" + + _codeAsQName + ", _reasonTexts=" + _reasonTexts + ", _role=" + + _role + ", _string=" + _string + ", _stringLocale=" + + _stringLocale + ", _subcodes=" + _subcodes + + ", _detail=" + _detail + "]"; + } + + /** + * @param soapMessage the soap message to copy fault information from + * @throws SOAPException if any + */ + public void copyFaultInfo(SOAPMessage soapMessage) throws SOAPException { + SOAPFault fault = soapMessage.getSOAPBody().getFault(); + setActor(fault.getFaultActor()); + setCode(fault.getFaultCode()); + setPrefix(fault.getFaultCodeAsName().getPrefix()); + setCodeAsQName(fault.getFaultCodeAsQName()); + setString(fault.getFaultString()); + setStringLocale(fault.getFaultStringLocale()); + if (fault.hasDetail()) { + setDetail(fault.getDetail()); + } + + // SOAP 1.2 specifics + if (SOAPUtil.isSOAP12(soapMessage)) { + setReasonLocales(fault.getFaultReasonLocales()); + Iterator locales = fault.getFaultReasonLocales(); + while (locales.hasNext()) { + Locale locale = locales.next(); + addReasonText(locale, fault.getFaultReasonText(locale)); + } + setRole(fault.getFaultRole()); + setSubcodes(fault.getFaultSubcodes()); + } + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPHeadersType.java b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPHeadersType.java new file mode 100644 index 000000000..a20b1fdb2 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPHeadersType.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.composer; + +/** + * SOAPHeadersType. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public enum SOAPHeadersType { + + /** Store SOAP headers as Configuration objects. */ + CONFIG, + /** Store SOAP headers as Document Object Models. */ + DOM, + /** Store SOAP headers as simple String values. */ + VALUE, + /** Store SOAP headers as XML Strings. */ + XML + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPMessageComposer.java b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPMessageComposer.java new file mode 100644 index 000000000..e7795de82 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPMessageComposer.java @@ -0,0 +1,381 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.composer; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.wsdl.Operation; +import javax.wsdl.Part; +import javax.wsdl.Port; +import javax.xml.soap.AttachmentPart; +import javax.xml.soap.SOAPBody; +import javax.xml.soap.SOAPEnvelope; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPFault; +import javax.xml.soap.SOAPMessage; + +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.ExchangeState; +import org.switchyard.Message; +import org.switchyard.component.common.composer.BaseMessageComposer; +import org.switchyard.component.soap.SOAPMessages; +import org.switchyard.component.soap.util.SOAPUtil; +import org.switchyard.component.soap.util.WSDLUtil; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * The SOAP implementation of MessageComposer simply copies the SOAP body into + * the Message and SOAP headers into the Message's context, and vice-versa. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SOAPMessageComposer extends BaseMessageComposer { + + // Constant suffix used for the reply wrapper when the composer is configured to + // wrap response messages with operation name. + private static final String DOC_LIT_WRAPPED_REPLY_SUFFIX = "Response"; + + private static final String CONTENT_DISPOSITION = "Content-Disposition"; + private static final String CONTENT_ID = "Content-ID"; + private static final String CONTENT_ID_START = "<"; + private static final String CONTENT_DISPOSITION_NAME = "name="; + private static final String CONTENT_DISPOSITION_QUOTE = "\""; + private static final String TEMP_FILE_EXTENSION = ".tmp"; + + private static Logger _log = Logger.getLogger(SOAPMessageComposer.class); + private Port _wsdlPort; + private Boolean _documentStyle = false; + private Boolean _mtomEnabled = false; + private Boolean _xopExpand = false; + private Boolean _unwrapped = false; + + /** + * {@inheritDoc} + */ + @Override + public Message compose(SOAPBindingData source, Exchange exchange) throws Exception { + final SOAPMessage soapMessage = source.getSOAPMessage(); + final Message message = exchange.createMessage(); + getContextMapper().mapFrom(source, exchange.getContext(message)); + + final SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope(); + if (envelope == null) { + return message; + } + + final SOAPBody soapBody = envelope.getBody(); + if (soapBody == null) { + throw SOAPMessages.MESSAGES.missingSOAPBodyFromRequest(); + } + + try { + if (soapBody.hasFault()) { + // peel off the Fault element + SOAPFault fault = soapBody.getFault(); + Node faultNode = fault.getParentNode().removeChild(fault); + message.setContent(faultNode); + return message; + } + + List bodyChildren = getChildElements(soapBody); + if (bodyChildren.size() > 1) { + throw SOAPMessages.MESSAGES.foundMultipleSOAPElementsInSOAPBody(); + } else if (bodyChildren.size() == 0 || bodyChildren.get(0) == null) { + throw SOAPMessages.MESSAGES.couldNotFindSOAPElementInSOAPBody(); + } + + Node bodyNode = bodyChildren.get(0); + if (_documentStyle) { + if (_unwrapped) { + String opName = exchange.getContract().getConsumerOperation().getName(); + // peel off the operation wrapper, if present + if (opName != null && opName.equals(bodyNode.getLocalName())) { + List subChildren = getChildElements(bodyNode); + if (subChildren.size() == 0 || subChildren.size() > 1) { + _log.debug("Unable to unwrap element: " + bodyNode.getLocalName() + + ". A single child element is required."); + } else { + bodyNode = subChildren.get(0); + } + } + } + } + bodyNode = bodyNode.getParentNode().removeChild(bodyNode); + + // SOAP Attachments + Map attachments = new HashMap(); + Iterator aparts = (Iterator) soapMessage.getAttachments(); + while (aparts.hasNext()) { + AttachmentPart apRequest = aparts.next(); + String[] contentId = apRequest.getMimeHeader(CONTENT_ID); + String name = null; + if (_mtomEnabled) { + if (contentId == null) { + throw SOAPMessages.MESSAGES.contentIDHeaderMissingForAttachmentPart(); + } + name = contentId[0]; + } else { + name = apRequest.getDataHandler().getDataSource().getName(); + if ((name == null) || (name.length() == 0)) { + String[] disposition = apRequest.getMimeHeader(CONTENT_DISPOSITION); + name = (contentId != null) ? contentId[0] : null; + if ((name == null) && (disposition != null)) { + int start = disposition[0].indexOf(CONTENT_DISPOSITION_NAME); + String namePart = disposition[0].substring(start + CONTENT_DISPOSITION_NAME.length() + 1); + int end = namePart.indexOf(CONTENT_DISPOSITION_QUOTE); + name = namePart.substring(0, end); + } else if (name == null) { + // TODO: Identify the extension using content-type + name = UUID.randomUUID() + TEMP_FILE_EXTENSION; + } + } + } + if (name.startsWith(CONTENT_ID_START)) { + name = name.substring(1, name.length() - 1); + } + if (_mtomEnabled && _xopExpand) { + // Using a different map because Camel throws java.lang.StackOverflowError + // when we do message.removeAttachment(cid); + attachments.put(name, apRequest.getDataHandler().getDataSource()); + } else { + message.addAttachment(name, apRequest.getDataHandler().getDataSource()); + } + } + if (_mtomEnabled && _xopExpand) { + // Expand xop message by inlining Base64 content + bodyNode = SOAPUtil.expandXop((Element)bodyNode, attachments); + } + message.setContent(bodyNode); + } catch (Exception ex) { + if (ex instanceof SOAPException) { + throw (SOAPException) ex; + } + throw new SOAPException(ex); + } + + return message; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingData decompose(Exchange exchange, SOAPBindingData target) throws Exception { + final SOAPMessage soapMessage = target.getSOAPMessage(); + final Message message = exchange.getMessage(); + final Boolean input = exchange.getPhase() == null; + + if (message != null) { + // check to see if the payload is null or it's a full SOAP Message + if (message.getContent() == null) { + throw SOAPMessages.MESSAGES.unableToCreateSOAPBodyDueToNullMessageContent(); + } + if (message.getContent() instanceof SOAPMessage) { + return new SOAPBindingData((SOAPMessage)message.getContent()); + } + + try { + // convert the message content to a form we can work with + Node messageNode = message.getContent(Node.class); + if (messageNode != null) { + Node messageNodeImport = soapMessage.getSOAPBody().getOwnerDocument().importNode(messageNode, true); + if (exchange.getState() != ExchangeState.FAULT || isSOAPFaultPayload(messageNode)) { + if (_documentStyle) { + String opName = exchange.getContract().getProviderOperation().getName(); + if (_unwrapped) { + String ns = getWrapperNamespace(opName, input); + // Don't wrap if it's already wrapped + if (!messageNodeImport.getLocalName().equals(opName + DOC_LIT_WRAPPED_REPLY_SUFFIX)) { + Element wrapper = messageNodeImport.getOwnerDocument().createElementNS( + ns, opName + DOC_LIT_WRAPPED_REPLY_SUFFIX); + wrapper.appendChild(messageNodeImport); + messageNodeImport = wrapper; + } + } + } + soapMessage.getSOAPBody().appendChild(messageNodeImport); + // SOAP Attachments + for (String name : message.getAttachmentMap().keySet()) { + AttachmentPart apResponse = soapMessage.createAttachmentPart(); + apResponse.setDataHandler(new DataHandler(message.getAttachment(name))); + apResponse.setContentId("<" + name + ">"); + soapMessage.addAttachmentPart(apResponse); + } + } else { + // convert to SOAP Fault since ExchangeState is FAULT but the message is not SOAP Fault + SOAPUtil.addFault(soapMessage).addDetail().appendChild(messageNodeImport); + } + } + } catch (Exception e) { + // Account for exception as payload in case of fault + if (exchange.getState().equals(ExchangeState.FAULT) + && exchange.getMessage().getContent() instanceof Exception) { + // Throw the Exception and let JAX-WS format the fault. + throw exchange.getMessage().getContent(Exception.class); + } + throw SOAPMessages.MESSAGES.unableToParseSOAPMessage(e); + } + } + + try { + getContextMapper().mapTo(exchange.getContext(), target); + } catch (Exception ex) { + throw SOAPMessages.MESSAGES.failedToMapContextPropertiesToSOAPMessage(ex); + } + + return target; + } + + private boolean isSOAPFaultPayload(org.w3c.dom.Node messageNode) { + String rootName = messageNode.getLocalName().toLowerCase(); + + if (rootName.equals("fault")) { + String nsURI = messageNode.getNamespaceURI(); + + if (nsURI.equals(SOAPUtil.SOAP12_URI) || nsURI.equals(SOAPUtil.SOAP11_URI)) { + return true; + } + } + + return false; + } + + // Retrieves the immediate child of the specified parent element + private List getChildElements(Node parent) { + List children = new ArrayList(); + NodeList nodes = parent.getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) { + children.add((Element)nodes.item(i)); + } + } + + return children; + } + + private String getWrapperNamespace(String operationName, boolean input) { + String ns = null; + + if (_wsdlPort != null) { + Operation operation = WSDLUtil.getOperationByName(_wsdlPort, operationName); + if (!_documentStyle) { + ns = input ? operation.getInput().getMessage().getQName().getNamespaceURI() + : operation.getOutput().getMessage().getQName().getNamespaceURI(); + } else { + // Note: WS-I Profile allows only one child under SOAPBody. + Part part = input ? (Part)operation.getInput().getMessage().getParts().values().iterator().next() + : (Part)operation.getOutput().getMessage().getParts().values().iterator().next(); + if (part.getElementName() != null) { + ns = part.getElementName().getNamespaceURI(); + } else if (part.getTypeName() != null) { + ns = part.getTypeName().getNamespaceURI(); + } + } + } + + return ns; + } + + /** + * Get the WSDL Port used by this message composer. + * @return the wsdlPort + */ + public Port getWsdlPort() { + return _wsdlPort; + } + + /** + * Set the WSDL Port used by this message composer. + * @param wsdlPort WSDL port + */ + public void setWsdlPort(Port wsdlPort) { + _wsdlPort = wsdlPort; + } + + /** + * Check if the WSDL used is of 'document' style. + * @return true if 'document' style, false otherwise + */ + public Boolean isDocumentStyle() { + return _documentStyle; + } + + /** + * Set that the WSDL used is of 'document' style. + * @param style true or false + */ + public void setDocumentStyle(Boolean style) { + _documentStyle = style; + } + + /** + * Check if MTOM is enabled. + * @return true if enabled, false otherwise + */ + public Boolean isMtomEnabled() { + return _mtomEnabled; + } + + /** + * Set MTOM enabled/disabled. + * @param enabled true or false + */ + public void setMtomEnabled(Boolean enabled) { + _mtomEnabled = enabled; + } + + /** + * Check if XOP message should expanded. + * @return true if expandable, false otherwise + */ + public Boolean isXopExpand() { + return _xopExpand; + } + + /** + * Set XOP expansion. + * @param expand true or false + */ + public void setXopExpand(Boolean expand) { + _xopExpand = expand; + } + + /** + * Check if composer has set unwrap. + * @return true if expandable, false otherwise + */ + public Boolean isUnwrapped() { + return _unwrapped; + } + + /** + * Set unwrap flag. + * @param unwrapped true or false + */ + public void setUnwrapped(Boolean unwrapped) { + _unwrapped = unwrapped; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPMessageComposerFactory.java b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPMessageComposerFactory.java new file mode 100644 index 000000000..bd24028d0 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/composer/SOAPMessageComposerFactory.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.composer; + +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.composer.MessageComposerFactory; + +/** + * SOAPMessageComposerFactory. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SOAPMessageComposerFactory extends MessageComposerFactory { + + /** + * {@inheritDoc} + */ + @Override + public Class getBindingDataClass() { + return SOAPBindingData.class; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposer newMessageComposerDefault() { + return new SOAPMessageComposer(); + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/BasicAuthModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/BasicAuthModel.java new file mode 100644 index 000000000..27fc9d787 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/BasicAuthModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.config.model.Model; + +/** + * A Basic Authentication Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface BasicAuthModel extends Model { + + /** + * Get user name. + * @return authentication username + */ + public String getUser(); + + /** + * Set user name. + * @param user the user name + * @return this BasicAuthModel + */ + public BasicAuthModel setUser(String user); + + /** + * Get user password. + * @return authentication password + */ + public String getPassword(); + + /** + * Set user password. + * @param password the user password + * @return this BasicAuthModel + */ + public BasicAuthModel setPassword(String password); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/EndpointConfigModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/EndpointConfigModel.java new file mode 100644 index 000000000..f11ee7f32 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/EndpointConfigModel.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.config.model.Model; + +/** + * A EndpointConfig Model. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface EndpointConfigModel extends Model { + + /** + * The endpointConfig XML element. + */ + public static final String ENDPOINT_CONFIG = "endpointConfig"; + + /** + * Gets the configFile. + * @return the configFile + */ + public String getConfigFile(); + + /** + * Sets the configFile. + * @param configFile the configFile + * @return this EndpointConfigModel (useful for chaining) + */ + public EndpointConfigModel setConfigFile(String configFile); + + /** + * Gets the configName. + * @return the configName + */ + public String getConfigName(); + + /** + * Sets the configName. + * @param configName the configName + * @return this EndpointConfigModel (useful for chaining) + */ + public EndpointConfigModel setConfigName(String configName); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/InterceptorModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/InterceptorModel.java new file mode 100644 index 000000000..7fcb8d1d0 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/InterceptorModel.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.config.model.NamedModel; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * A Interceptor Model. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface InterceptorModel extends NamedModel { + + /** + * The interceptor XML element. + */ + public static final String INTERCEPTOR = "interceptor"; + + /** + * Gets the Interceptor class. + * @param loader the ClassLoader to use + * @return the Interceptor class + */ + public Class getClazz(ClassLoader loader); + + /** + * Sets the Interceptor class. + * @param clazz the Interceptor class + * @return this InterceptorModel (useful for chaining) + */ + public InterceptorModel setClazz(Class clazz); + + /** + * Gets the child properties model. + * @return the child properties model + */ + public PropertiesModel getProperties(); + + /** + * Sets the child properties model. + * @param properties the child properties model + * @return this InterceptorModel (useful for chaining) + */ + public InterceptorModel setProperties(PropertiesModel properties); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/InterceptorsModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/InterceptorsModel.java new file mode 100644 index 000000000..ee4d9970f --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/InterceptorsModel.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A Interceptors Model. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface InterceptorsModel extends Model { + + /** The "inInterceptors" name. */ + public static final String IN_INTERCEPTORS = "inInterceptors"; + + /** The "outInterceptors" name. */ + public static final String OUT_INTERCEPTORS = "outInterceptors"; + + /** + * Gets the child interceptor models. + * @return the child interceptor models + */ + public List getInterceptors(); + + /** + * Adds a child interceptor model. + * @param interceptor the child interceptor model + * @return this ChannelsModel (useful for chaining) + */ + public InterceptorsModel addInterceptor(InterceptorModel interceptor); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/MtomModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/MtomModel.java new file mode 100644 index 000000000..68e9b6295 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/MtomModel.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.config.model.Model; + +/** + * A Mtom Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface MtomModel extends Model { + + /** + * Get if MTOM enabled. + * @return true if enabled, false otherwise + */ + public Boolean isEnabled(); + + /** + * Enable or disable MTOM feature. + * @param enabled true to enable, false to diable + * @return this MtomModel (useful for chaining) + */ + public MtomModel setEnabled(Boolean enabled); + + /** + * Gets the threshold value. + * @return the configName + */ + public Integer getThreshold(); + + /** + * Sets the threshold value. + * @param threshold the threshold value to set + * @return this MtomModel (useful for chaining) + */ + public MtomModel setThreshold(Integer threshold); + + /** + * Get if XOP expand enabled. + * @return true if XOP expand enabled, false otherwise + */ + public Boolean isXopExpand(); + + /** + * Enable or disable XOP expand feature. + * @param enabled true to enable, false to diable + * @return this MtomModel (useful for chaining) + */ + public MtomModel setXopExpand(Boolean enabled); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/NtlmAuthModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/NtlmAuthModel.java new file mode 100644 index 000000000..adc82ec7e --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/NtlmAuthModel.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +/** + * A NTLM Authentication Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface NtlmAuthModel extends BasicAuthModel { + + /** + * Get the NTLM domain. + * @return domain name + */ + public String getDomain(); + + /** + * Set the NTLM domain. + * @param domain the domain name + * @return this NTLMAuthModel + */ + public NtlmAuthModel setDomain(String domain); +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/ProxyModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/ProxyModel.java new file mode 100644 index 000000000..c51362ee3 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/ProxyModel.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.config.model.Model; + +/** + * A Proxy Configuration Model. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface ProxyModel extends Model { + + /** + * Get host. + * @return authentication host + */ + public String getHost(); + + /** + * Set host. + * @param host the authentication host + * @return this ProxyModel + */ + public ProxyModel setHost(String host); + + /** + * Get authentication port. + * @return authentication port + */ + public String getPort(); + + /** + * Set authentication port. + * @param port the authentication port + * @return this ProxyModel + */ + public ProxyModel setPort(String port); + + /** + * Get user name. + * @return authentication username + */ + public String getUser(); + + /** + * Set user name. + * @param user the user name + * @return this ProxyModel + */ + public ProxyModel setUser(String user); + + /** + * Get user password. + * @return authentication password + */ + public String getPassword(); + + /** + * Set user password. + * @param password the user password + * @return this ProxyModel + */ + public ProxyModel setPassword(String password); + + /** + * Get proxy type. + * @return proxy type + */ + public String getType(); + + /** + * Set proxy type. Default is HTTP. + * @param type the proxy type + * @return this ProxyModel + */ + public ProxyModel setType(String type); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPBindingModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPBindingModel.java new file mode 100644 index 000000000..78eced558 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPBindingModel.java @@ -0,0 +1,263 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import javax.xml.namespace.QName; + +import org.switchyard.common.net.SocketAddr; +import org.switchyard.component.soap.PortName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.composite.BindingModel; + +/** + * A SOAPBinding Model. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface SOAPBindingModel extends BindingModel { + + /** + * Prefix for SOAP Gateway Configuration. + */ + public static final String SOAP = "soap"; + + /** + * Gets the SOAPContextMapperModel. + * @return the SOAPContextMapperModel + */ + public SOAPContextMapperModel getSOAPContextMapper(); + + /** + * Gets the SOAPMessageComposerModel. + * @return the SOAPMessageComposerModel + */ + public SOAPMessageComposerModel getSOAPMessageComposer(); + + /** + * Gets the global environment configuration. + * @return global environment configuration + */ + public Configuration getEnvironment(); + + /** + * Sets the global environment configuration. + * @param environment the global environment configuration + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setEnvironment(Configuration environment); + + /** + * Returns the WebService Service name. + * @return the serviceName + */ + public QName getServiceName(); + + /** + * Sets the WebService Service name. + * @param serviceName the serviceName to set + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setServiceName(QName serviceName); + + /** + * Returns the WebService WSDL. + * @return the wsdl + */ + public String getWsdl(); + + /** + * Sets the WebService WSDL. + * @param wsdl the wsdl to set + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setWsdl(String wsdl); + + /** + * Returns the WebService port. + * @return the port + */ + public PortName getPort(); + + /** + * Sets the WebService port. + * @param port the port to set + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setPort(PortName port); + + /** + * Returns the IP Socket Address where the WebService will be hosted. + * @return the IP Socket Address + */ + public SocketAddr getSocketAddr(); + + /** + * Sets the IP Socket Address where the WebService will be hosted. + * @param socketAddr the IP Socket Address to set + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setSocketAddr(SocketAddr socketAddr); + + /** + * Gets the extra context path of the WebService. + * @return the contextPath + */ + public String getContextPath(); + + /** + * Sets the extra context path of the WebService. + * @param contextPath the contextPath to set + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setContextPath(String contextPath); + + /** + * Gets the target endpoint address of the WebService. + * @return the endpoint address + */ + public String getEndpointAddress(); + + /** + * Sets the target endpoint address of the WebService. + * This overrides the address set inside the WSDL. + * @param endpointAddress the endpoint address to set + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setEndpointAddress(String endpointAddress); + + /** + * Gets the request's time-out value. + * + * @return the time-out value + */ + public Integer getTimeout(); + + /** + * Sets the request's time-out value. + * + * @param timeout the time-out value + * @return this SOAPBindingModel + */ + public SOAPBindingModel setTimeout(Integer timeout); + + /** + * Gets the basic config. + * @return the basic config + */ + public BasicAuthModel getBasicAuthConfig(); + + /** + * Sets the basic config. + * @param config the basic config + * @return this SOAPBindingModel + */ + public SOAPBindingModel setBasicAuthConfig(BasicAuthModel config); + + /** + * Gets the ntlm config. + * @return the ntlm config + */ + public NtlmAuthModel getNtlmAuthConfig(); + + /** + * Sets the ntlm config. + * @param config the ntlm config + * @return this SOAPBindingModel + */ + public SOAPBindingModel setNtlmAuthConfig(NtlmAuthModel config); + + /** + * Check if Basic authentication is set. + * @return true if Basic, false otherwise + */ + public Boolean isBasicAuth(); + + /** + * Check if authentication is set. + * @return true if set, false otherwise + */ + public Boolean hasAuthentication(); + + /** + * Gets the proxy config. + * @return the proxy config + */ + public ProxyModel getProxyConfig(); + + /** + * Sets the proxy config. + * @param proxyConfig the proxy config + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setProxyConfig(ProxyModel proxyConfig); + + /** + * Gets the mtom config. + * @return the mtom config + */ + public MtomModel getMtomConfig(); + + /** + * Sets the mtom config. + * @param mtomConfig the mtom config + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setMtomConfig(MtomModel mtomConfig); + + /** + * Gets the endpointConfig. + * @return the endpointConfig + */ + public EndpointConfigModel getEndpointConfig(); + + /** + * Sets the endpointConfig. + * @param endpointConfig the endpointConfig + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setEndpointConfig(EndpointConfigModel endpointConfig); + + /** + * Gets the inInterceptors. + * @return the inInterceptors + */ + public InterceptorsModel getInInterceptors(); + + /** + * Sets the inInterceptors. + * @param inInterceptors the inInterceptors + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setInInterceptors(InterceptorsModel inInterceptors); + + /** + * Gets the outInterceptors. + * @return the outInterceptors + */ + public InterceptorsModel getOutInterceptors(); + + /** + * Sets the outInterceptors. + * @param outInterceptors the outInterceptors + * @return this SOAPBindingModel (useful for chaining) + */ + public SOAPBindingModel setOutInterceptors(InterceptorsModel outInterceptors); + + /** + * Indicates whether the composer is in "unwrapped" mode. + * @return true if the composer is in unwrapped mode, false otherwise + */ + public Boolean isUnwrapped(); +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPContextMapperModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPContextMapperModel.java new file mode 100644 index 000000000..eb6441709 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPContextMapperModel.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.component.soap.composer.SOAPHeadersType; +import org.switchyard.config.model.composer.ContextMapperModel; + +/** + * SOAPContextMapperModel. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public interface SOAPContextMapperModel extends ContextMapperModel { + + /** + * Gets the SOAPHeadersType. + * @return the SOAPHeadersType + */ + public SOAPHeadersType getSOAPHeadersType(); + + /** + * Sets the SOAPHeadersType. + * @param soapHeadersType the SOAPHeadersType + * @return this instance (useful for chaining) + */ + public SOAPContextMapperModel setSOAPHeadersType(SOAPHeadersType soapHeadersType); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPMessageComposerModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPMessageComposerModel.java new file mode 100644 index 000000000..df3b13e2b --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPMessageComposerModel.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.config.model.composer.MessageComposerModel; + +/** + * SOAPMessageComposerModel. + */ +public interface SOAPMessageComposerModel extends MessageComposerModel { + + /** + * Indicates whether the composer is in "unwrapped" mode. + * @return true if the composer is in unwrapped mode, false otherwise + */ + Boolean isUnwrapped(); + + /** + * Specifies that the composer should operate in "unwrapped" mode. + * @param unwrapped true to operate in unwrapped mode + * @return this instance (useful for chaining) + */ + SOAPMessageComposerModel setUnwrapped(boolean unwrapped); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPNameValueModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPNameValueModel.java new file mode 100644 index 000000000..9710b7a53 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPNameValueModel.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.config.model.Model; + +/** + * A SOAP Value Model. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public interface SOAPNameValueModel extends Model { + + /** Known XML element names. */ + public enum SOAPName { + /** Known XML element names. */ + + wsdl, wsdlPort, socketAddr, contextPath, endpointAddress, mtom, proxy, user, password, host, port, type, basic, ntlm, domain, timeout; + } + + /** + * Gets the name. + * @return the name + */ + public SOAPName getName(); + + /** + * Gets the value. + * @return the value + */ + public String getValue(); + + /** + * Sets the value. + * @param value the value + * @return this SOAPValueModel (useful for chaining) + */ + public SOAPNameValueModel setValue(String value); + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPNamespace.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPNamespace.java new file mode 100644 index 000000000..cde2740f8 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/SOAPNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A SOAP config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum SOAPNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new SOAPNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + SOAPNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the SOAPNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the SOAPNamespace + */ + public static SOAPNamespace fromUri(String uri) { + return Util.fromUri(SOAPNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(SOAPNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-component-soap:config", version); + } + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1BasicAuthModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1BasicAuthModel.java new file mode 100644 index 000000000..cf858aaca --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1BasicAuthModel.java @@ -0,0 +1,123 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import org.switchyard.component.soap.config.model.BasicAuthModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel.SOAPName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A BasicAuthModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1BasicAuthModel extends BaseModel implements BasicAuthModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + SOAPName.user.name(), + SOAPName.password.name() + }; + + private SOAPNameValueModel _user; + private SOAPNameValueModel _password; + + /** + * Creates a new BasicAuthModel. + * @param namespace namespace + */ + public V1BasicAuthModel(String namespace) { + super(namespace, SOAPName.basic.name()); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new BasicAuthModel. + * @param namespace namespace + * @param name the name of the model + */ + public V1BasicAuthModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new BasicAuthModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1BasicAuthModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * {@inheritDoc} + */ + public String getUser() { + if (_user == null) { + _user = getNameValue(SOAPName.user); + } + return _user != null ? _user.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setUser(String user) { + _user = setNameValue(_user, SOAPName.user, user); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPassword() { + if (_password == null) { + _password = getNameValue(SOAPName.password); + } + return _password != null ? _password.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel setPassword(String password) { + _password = setNameValue(_password, SOAPName.password, password); + return this; + } + + protected SOAPNameValueModel getNameValue(SOAPName name) { + return (SOAPNameValueModel)getFirstChildModel(name.name()); + } + + protected SOAPNameValueModel setNameValue(SOAPNameValueModel model, SOAPName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1SOAPNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1EndpointConfigModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1EndpointConfigModel.java new file mode 100644 index 000000000..4c472df11 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1EndpointConfigModel.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import org.switchyard.component.soap.config.model.EndpointConfigModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version InterceptorModel. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class V1EndpointConfigModel extends BaseModel implements EndpointConfigModel { + + private static final String CONFIG_FILE = "configFile"; + private static final String CONFIG_NAME = "configName"; + + /** + * Creates a new InterceptorModel. + * @param namespace namespace + */ + public V1EndpointConfigModel(String namespace) { + super(namespace, ENDPOINT_CONFIG); + } + + /** + * Creates a new EndpointConfigModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1EndpointConfigModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getConfigFile() { + return getModelAttribute(CONFIG_FILE); + } + + /** + * {@inheritDoc} + */ + @Override + public EndpointConfigModel setConfigFile(String configFile) { + setModelAttribute(CONFIG_FILE, configFile); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getConfigName() { + return getModelAttribute(CONFIG_NAME); + } + + /** + * {@inheritDoc} + */ + @Override + public EndpointConfigModel setConfigName(String configName) { + setModelAttribute(CONFIG_NAME, configName); + return this; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1InterceptorModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1InterceptorModel.java new file mode 100644 index 000000000..52358e6ee --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1InterceptorModel.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import static org.switchyard.config.model.property.PropertiesModel.PROPERTIES; + +import org.switchyard.common.type.Classes; +import org.switchyard.component.soap.config.model.InterceptorModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * The 1st version InterceptorModel. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class V1InterceptorModel extends BaseNamedModel implements InterceptorModel { + + private PropertiesModel _properties; + + /** + * Creates a new InterceptorModel. + * @param namespace namespace + */ + public V1InterceptorModel(String namespace) { + super(namespace, INTERCEPTOR); + setModelChildrenOrder(PROPERTIES); + } + + /** + * Creates a new InterceptorModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1InterceptorModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(PROPERTIES); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getClazz(ClassLoader loader) { + String c = getModelAttribute("class"); + return c != null ? Classes.forName(c, loader) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public InterceptorModel setClazz(Class clazz) { + String c = clazz != null ? clazz.getName() : null; + setModelAttribute("class", c); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public PropertiesModel getProperties() { + if (_properties == null) { + _properties = (PropertiesModel)getFirstChildModel(PROPERTIES); + } + return _properties; + } + + /** + * {@inheritDoc} + */ + @Override + public InterceptorModel setProperties(PropertiesModel properties) { + setChildModel(properties); + _properties = properties; + return this; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1InterceptorsModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1InterceptorsModel.java new file mode 100644 index 000000000..038f643b1 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1InterceptorsModel.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import static org.switchyard.component.soap.config.model.InterceptorModel.INTERCEPTOR; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.component.soap.config.model.InterceptorModel; +import org.switchyard.component.soap.config.model.InterceptorsModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A version 1 InterceptorsModel. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class V1InterceptorsModel extends BaseModel implements InterceptorsModel { + + private List _interceptors = new ArrayList(); + + /** + * Creates a new InterceptorsModel. + * @param namespace namespace + * @param name inInterceptors or outInterceptors + */ + public V1InterceptorsModel(String namespace, String name) { + super(new QName(namespace, name)); + setModelChildrenOrder(INTERCEPTOR); + } + + /** + * Creates a new InterceptorsModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1InterceptorsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration interceptor_config : config.getChildren(INTERCEPTOR)) { + InterceptorModel interceptor = (InterceptorModel)readModel(interceptor_config); + if (interceptor != null) { + _interceptors.add(interceptor); + } + } + setModelChildrenOrder(INTERCEPTOR); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getInterceptors() { + return Collections.unmodifiableList(_interceptors); + } + + /** + * {@inheritDoc} + */ + @Override + public InterceptorsModel addInterceptor(InterceptorModel interceptor) { + addChildModel(interceptor); + _interceptors.add(interceptor); + return this; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1MtomModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1MtomModel.java new file mode 100644 index 000000000..ed5e8f335 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1MtomModel.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import org.switchyard.component.soap.config.model.MtomModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel.SOAPName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version MtomModel. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1MtomModel extends BaseModel implements MtomModel { + + private static final String ENABLED = "enabled"; + private static final String THRESHOLD = "threshold"; + private static final String XOP_EXPAND = "xopExpand"; + + private Boolean _enabled = false; + + /** + * Creates a new MtomModel. + * @param namespace namespace + */ + public V1MtomModel(String namespace) { + super(namespace, SOAPName.mtom.name()); + } + + /** + * Creates a new MtomModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1MtomModel(Configuration config, Descriptor desc) { + super(config, desc); + _enabled = true; + } + + /** + * {@inheritDoc} + */ + @Override + public Boolean isEnabled() { + String enabled = getModelAttribute(ENABLED); + if (enabled != null) { + return Boolean.valueOf(enabled); + } + return _enabled; + } + + /** + * {@inheritDoc} + */ + @Override + public MtomModel setEnabled(Boolean enabled) { + setModelAttribute(ENABLED, String.valueOf(enabled)); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Integer getThreshold() { + String threshold = getModelAttribute(THRESHOLD); + if (threshold != null) { + return Integer.valueOf(threshold); + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public MtomModel setThreshold(Integer threshold) { + setModelAttribute(THRESHOLD, String.valueOf(threshold)); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Boolean isXopExpand() { + String expand = getModelAttribute(XOP_EXPAND); + if (expand != null) { + return Boolean.valueOf(expand); + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public MtomModel setXopExpand(Boolean expand) { + setModelAttribute(XOP_EXPAND, String.valueOf(expand)); + return this; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1NtlmAuthModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1NtlmAuthModel.java new file mode 100644 index 000000000..f3a4231b0 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1NtlmAuthModel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import org.switchyard.component.soap.config.model.NtlmAuthModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel.SOAPName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; + +/** + * A NtlmAuthModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1NtlmAuthModel extends V1BasicAuthModel implements NtlmAuthModel { + + private SOAPNameValueModel _domain; + + /** + * Creates a new NtlmAuthModel. + * @param namespace namespace + */ + public V1NtlmAuthModel(String namespace) { + super(namespace, SOAPName.ntlm.name()); + } + + /** + * Creates a new NtlmAuthModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1NtlmAuthModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + public String getDomain() { + if (_domain == null) { + _domain = getNameValue(SOAPName.domain); + } + return _domain != null ? _domain.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public NtlmAuthModel setDomain(String domain) { + _domain = setNameValue(_domain, SOAPName.domain, domain); + return this; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1ProxyModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1ProxyModel.java new file mode 100644 index 000000000..83673208c --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1ProxyModel.java @@ -0,0 +1,186 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import org.switchyard.component.soap.config.model.ProxyModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel.SOAPName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * A ProxyModel V1 implementation. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1ProxyModel extends BaseModel implements ProxyModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + SOAPName.type.name(), + SOAPName.host.name(), + SOAPName.port.name(), + SOAPName.user.name(), + SOAPName.password.name() + }; + + private static final String DEFAULT_PROXY_TYPE = "HTTP"; + + private SOAPNameValueModel _type; + private SOAPNameValueModel _host; + private SOAPNameValueModel _port; + private SOAPNameValueModel _user; + private SOAPNameValueModel _password; + + /** + * Creates a new ProxyModel. + * @param namespace namespace + */ + public V1ProxyModel(String namespace) { + super(namespace, SOAPName.proxy.name()); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new ProxyModel. + * @param namespace namespace + * @param name the name of the model + */ + public V1ProxyModel(String namespace, String name) { + super(namespace, name); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new ProxyModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ProxyModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + + /** + * {@inheritDoc} + */ + public String getType() { + if (_type == null) { + _type = getNameValue(SOAPName.type); + } + return _type != null ? _type.getValue() : DEFAULT_PROXY_TYPE; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setType(String type) { + _type = setNameValue(_type, SOAPName.type, type); + return this; + } + + /** + * {@inheritDoc} + */ + public String getHost() { + if (_host == null) { + _host = getNameValue(SOAPName.host); + } + return _host != null ? _host.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setHost(String host) { + _host = setNameValue(_host, SOAPName.host, host); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPort() { + if (_port == null) { + _port = getNameValue(SOAPName.port); + } + return _port != null ? _port.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public String getUser() { + if (_user == null) { + _user = getNameValue(SOAPName.user); + } + return _user != null ? _user.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setUser(String user) { + _user = setNameValue(_user, SOAPName.user, user); + return this; + } + + /** + * {@inheritDoc} + */ + public String getPassword() { + if (_password == null) { + _password = getNameValue(SOAPName.password); + } + return _password != null ? _password.getValue() : null; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setPassword(String password) { + _password = setNameValue(_password, SOAPName.password, password); + return this; + } + + /** + * {@inheritDoc} + */ + public ProxyModel setPort(String port) { + _port = setNameValue(_port, SOAPName.port, port); + return this; + } + + protected SOAPNameValueModel getNameValue(SOAPName name) { + return (SOAPNameValueModel)getFirstChildModel(name.name()); + } + + protected SOAPNameValueModel setNameValue(SOAPNameValueModel model, SOAPName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1SOAPNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPBindingModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPBindingModel.java new file mode 100644 index 000000000..f426323eb --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPBindingModel.java @@ -0,0 +1,493 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import static org.switchyard.component.soap.config.model.EndpointConfigModel.ENDPOINT_CONFIG; +import static org.switchyard.component.soap.config.model.InterceptorsModel.IN_INTERCEPTORS; +import static org.switchyard.component.soap.config.model.InterceptorsModel.OUT_INTERCEPTORS; + +import javax.xml.namespace.QName; + +import org.switchyard.common.net.SocketAddr; +import org.switchyard.component.soap.SOAPMessages; +import org.switchyard.component.soap.PortName; +import org.switchyard.component.soap.config.model.EndpointConfigModel; +import org.switchyard.component.soap.config.model.InterceptorsModel; +import org.switchyard.component.soap.config.model.BasicAuthModel; +import org.switchyard.component.soap.config.model.MtomModel; +import org.switchyard.component.soap.config.model.NtlmAuthModel; +import org.switchyard.component.soap.config.model.ProxyModel; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.config.model.SOAPContextMapperModel; +import org.switchyard.component.soap.config.model.SOAPMessageComposerModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel.SOAPName; +import org.switchyard.config.Configuration; +import org.switchyard.config.Configurations; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1BindingModel; + +/** + * The 1st version SOAPBindingModel. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class V1SOAPBindingModel extends V1BindingModel implements SOAPBindingModel { + + private static final String[] MODEL_CHILDREN_ORDER = new String[]{ + SOAPName.wsdl.name(), + SOAPName.wsdlPort.name(), + SOAPName.socketAddr.name(), + SOAPName.contextPath.name(), + SOAPName.endpointAddress.name(), + SOAPName.timeout.name(), + SOAPName.basic.name(), + SOAPName.ntlm.name(), + SOAPName.proxy.name(), + ENDPOINT_CONFIG, + SOAPName.mtom.name(), + IN_INTERCEPTORS, + OUT_INTERCEPTORS + }; + + private Configuration _environment; + private QName _serviceName; + + private SOAPNameValueModel _wsdl; + private PortName _port; + private SocketAddr _socketAddr; + private SOAPNameValueModel _contextPath; + private SOAPNameValueModel _endpointAddress; + private SOAPNameValueModel _timeout; + private BasicAuthModel _basicAuth; + private NtlmAuthModel _ntlmAuth; + private ProxyModel _proxyConfig; + private MtomModel _mtomConfig; + private EndpointConfigModel _endpointConfig; + private InterceptorsModel _inInterceptors; + private InterceptorsModel _outInterceptors; + + /** + * Creates a new SOAPBindingModel. + * @param namespace namespace + */ + public V1SOAPBindingModel(String namespace) { + super(SOAP, namespace); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * Creates a new SOAPBindingModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1SOAPBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(MODEL_CHILDREN_ORDER); + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPContextMapperModel getSOAPContextMapper() { + return (SOAPContextMapperModel)getContextMapper(); + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPMessageComposerModel getSOAPMessageComposer() { + return (SOAPMessageComposerModel)getMessageComposer(); + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration getEnvironment() { + if (_environment == null) { + _environment = Configurations.newConfiguration(); + } + return _environment; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setEnvironment(Configuration environment) { + _environment = environment; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public QName getServiceName() { + if (_serviceName == null) { + _serviceName = isServiceBinding() ? getService().getQName() : getReference().getQName(); + } + return _serviceName; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setServiceName(QName serviceName) { + _serviceName = serviceName; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getWsdl() { + if (_wsdl == null) { + _wsdl = getNameValue(SOAPName.wsdl); + } + return _wsdl != null ? _wsdl.getValue() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setWsdl(String wsdl) { + _wsdl = setNameValue(_wsdl, SOAPName.wsdl, wsdl); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public PortName getPort() { + if (_port == null) { + SOAPNameValueModel wsdlPortModel = getNameValue(SOAPName.wsdlPort); + if (wsdlPortModel != null) { + _port = new PortName(wsdlPortModel.getValue()); + } else { + _port = new PortName(); + } + } + return _port; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setPort(PortName port) { + _port = port; + setNameValue(null, SOAPName.wsdlPort, port != null ? port.getName() : null); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SocketAddr getSocketAddr() { + if (_socketAddr == null) { + SOAPNameValueModel socketAddrModel = getNameValue(SOAPName.socketAddr); + String socketAddrValue = socketAddrModel != null ? socketAddrModel.getValue() : null; + if (socketAddrValue == null) { + Configuration socketAddrEnvConfig = getEnvironment().getFirstChild(SOAPName.socketAddr.name()); + socketAddrValue = socketAddrEnvConfig != null ? socketAddrEnvConfig.getValue() : null; + } + if (socketAddrValue != null) { + _socketAddr = new SocketAddr(socketAddrValue); + } else { + _socketAddr = new SocketAddr(); + } + } + return _socketAddr; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setSocketAddr(SocketAddr socketAddr) { + _socketAddr = socketAddr; + setNameValue(null, SOAPName.socketAddr, socketAddr != null ? socketAddr.toString() : null); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getContextPath() { + if (_contextPath == null) { + _contextPath = getNameValue(SOAPName.contextPath); + } + String contextPath = _contextPath != null ? _contextPath.getValue() : null; + if (contextPath == null) { + Configuration contextPathConfig = getEnvironment().getFirstChild(SOAPName.contextPath.name()); + contextPath = contextPathConfig != null ? contextPathConfig.getValue() : null; + } + return contextPath; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setContextPath(String contextPath) { + _contextPath = setNameValue(_contextPath, SOAPName.contextPath, contextPath); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getEndpointAddress() { + if (_endpointAddress == null) { + _endpointAddress = getNameValue(SOAPName.endpointAddress); + } + return _endpointAddress != null ? _endpointAddress.getValue() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setEndpointAddress(String endpointAddress) { + _endpointAddress = setNameValue(_endpointAddress, SOAPName.endpointAddress, endpointAddress); + return this; + } + + /** + * {@inheritDoc} + */ + public Integer getTimeout() { + if (_timeout == null) { + _timeout = getNameValue(SOAPName.timeout); + } + return _timeout != null ? Integer.valueOf(_timeout.getValue()) : null; + } + + /** + * {@inheritDoc} + */ + public SOAPBindingModel setTimeout(Integer timeout) { + _timeout = setNameValue(_timeout, SOAPName.timeout, String.valueOf(timeout)); + return this; + } + + /** + * {@inheritDoc} + */ + public BasicAuthModel getBasicAuthConfig() { + if (_basicAuth == null) { + _basicAuth = (BasicAuthModel)getFirstChildModel(SOAPName.basic.name()); + } + return _basicAuth; + } + + /** + * {@inheritDoc} + */ + public SOAPBindingModel setBasicAuthConfig(BasicAuthModel config) { + setChildModel(config); + _basicAuth = config; + return this; + } + + /** + * {@inheritDoc} + */ + public NtlmAuthModel getNtlmAuthConfig() { + if (_ntlmAuth == null) { + _ntlmAuth = (NtlmAuthModel)getFirstChildModel(SOAPName.ntlm.name()); + } + return _ntlmAuth; + } + + /** + * {@inheritDoc} + */ + public SOAPBindingModel setNtlmAuthConfig(NtlmAuthModel config) { + setChildModel(config); + _ntlmAuth = config; + return this; + } + + /** + * {@inheritDoc} + */ + public Boolean isBasicAuth() { + return (getBasicAuthConfig() != null) ? true : false; + } + + /** + * {@inheritDoc} + */ + public Boolean hasAuthentication() { + return ((getBasicAuthConfig() != null) || (getNtlmAuthConfig() != null)) ? true : false; + } + + /** + * {@inheritDoc} + */ + @Override + public ProxyModel getProxyConfig() { + if (_proxyConfig == null) { + _proxyConfig = (ProxyModel)getFirstChildModel(SOAPName.proxy.name()); + } + return _proxyConfig; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setProxyConfig(ProxyModel proxyConfig) { + setChildModel(proxyConfig); + _proxyConfig = proxyConfig; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public MtomModel getMtomConfig() { + if (_mtomConfig == null) { + _mtomConfig = (MtomModel)getFirstChildModel(SOAPName.mtom.name()); + } + return _mtomConfig; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setMtomConfig(MtomModel mtomConfig) { + setChildModel(mtomConfig); + _mtomConfig = mtomConfig; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public EndpointConfigModel getEndpointConfig() { + if (_endpointConfig == null) { + _endpointConfig = (EndpointConfigModel)getFirstChildModel(ENDPOINT_CONFIG); + } + return _endpointConfig; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setEndpointConfig(EndpointConfigModel endpointConfig) { + setChildModel(endpointConfig); + _endpointConfig = endpointConfig; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public InterceptorsModel getInInterceptors() { + if (_inInterceptors == null) { + _inInterceptors = (InterceptorsModel)getFirstChildModel(IN_INTERCEPTORS); + } + return _inInterceptors; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setInInterceptors(InterceptorsModel inInterceptors) { + if (inInterceptors != null) { + if (!IN_INTERCEPTORS.equals(inInterceptors.getModelConfiguration().getName())) { + throw SOAPMessages.MESSAGES.not(IN_INTERCEPTORS); + } + } + setChildModel(inInterceptors); + _inInterceptors = inInterceptors; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public InterceptorsModel getOutInterceptors() { + if (_outInterceptors == null) { + _outInterceptors = (InterceptorsModel)getFirstChildModel(OUT_INTERCEPTORS); + } + return _outInterceptors; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPBindingModel setOutInterceptors(InterceptorsModel outInterceptors) { + if (outInterceptors != null) { + if (!OUT_INTERCEPTORS.equals(outInterceptors.getModelConfiguration().getName())) { + throw SOAPMessages.MESSAGES.not(OUT_INTERCEPTORS); + } + } + setChildModel(outInterceptors); + _outInterceptors = outInterceptors; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Boolean isUnwrapped() { + return getSOAPMessageComposer() != null && getSOAPMessageComposer().isUnwrapped(); + } + + private SOAPNameValueModel getNameValue(SOAPName name) { + return (SOAPNameValueModel)getFirstChildModel(name.name()); + } + + private SOAPNameValueModel setNameValue(SOAPNameValueModel model, SOAPName name, String value) { + if (value != null) { + if (model == null) { + model = getNameValue(name); + } + if (model == null) { + model = new V1SOAPNameValueModel(getNamespaceURI(), name); + setChildModel(model); + } + model.setValue(value); + } else { + getModelConfiguration().removeChildren(name.name()); + model = null; + } + return model; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPContextMapperModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPContextMapperModel.java new file mode 100644 index 000000000..a8bc01d70 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPContextMapperModel.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import static org.switchyard.component.soap.composer.SOAPHeadersType.VALUE; + +import org.switchyard.component.soap.composer.SOAPHeadersType; +import org.switchyard.component.soap.config.model.SOAPContextMapperModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composer.v1.V1ContextMapperModel; + +/** + * V1SOAPContextMapperModel. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public class V1SOAPContextMapperModel extends V1ContextMapperModel implements SOAPContextMapperModel { + + /** + * Constructs a new V1SOAPContextMapperModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1SOAPContextMapperModel(String namespace) { + super(namespace); + } + + /** + * Constructs a new V1SOAPContextMapperModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1SOAPContextMapperModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPHeadersType getSOAPHeadersType() { + String sht = getModelAttribute("soapHeadersType"); + return sht != null ? SOAPHeadersType.valueOf(sht) : VALUE; + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPContextMapperModel setSOAPHeadersType(SOAPHeadersType soapHeadersType) { + String sht = soapHeadersType != null ? soapHeadersType.name() : null; + setModelAttribute("soapHeadersType", sht); + return this; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPMarshaller.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPMarshaller.java new file mode 100644 index 000000000..57c46dc5a --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPMarshaller.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.config.model.v1; + +import org.switchyard.component.soap.config.model.EndpointConfigModel; +import org.switchyard.component.soap.config.model.InterceptorModel; +import org.switchyard.component.soap.config.model.InterceptorsModel; +import org.switchyard.component.soap.config.model.SOAPNameValueModel.SOAPName; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.property.v1.V1PropertiesModel; +import org.switchyard.config.model.property.v1.V1PropertyModel; + +/** + * Marshaller for SOAP Gateway configurations. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class V1SOAPMarshaller extends BaseMarshaller { + + /** + * Construct a SOAP Model Marshaller with help of a Descriptor. + * + * @param desc the Descriptor + */ + public V1SOAPMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads a SOAP Model configuration. + * + * @param config the configuration + * @return the SOAP Binding Model + */ + @Override + public Model read(Configuration config) { + Descriptor desc = getDescriptor(); + String name = config.getName(); + if (name.startsWith(BindingModel.BINDING)) { + return new V1SOAPBindingModel(config, desc); + } else if (name.equals(ContextMapperModel.CONTEXT_MAPPER)) { + return new V1SOAPContextMapperModel(config, desc); + } else if (name.equals(MessageComposerModel.MESSAGE_COMPOSER)) { + return new V1SOAPMessageComposerModel(config, desc); + } else if (name.equals(SOAPName.mtom.name())) { + return new V1MtomModel(config, desc); + } else if (name.equals(SOAPName.basic.name())) { + return new V1BasicAuthModel(config, desc); + } else if (name.equals(SOAPName.ntlm.name())) { + return new V1NtlmAuthModel(config, desc); + } else if (name.equals(SOAPName.proxy.name())) { + return new V1ProxyModel(config, desc); + } else if (name.equals(EndpointConfigModel.ENDPOINT_CONFIG)) { + return new V1EndpointConfigModel(config, desc); + } else if (name.equals(InterceptorsModel.IN_INTERCEPTORS) || name.equals(InterceptorsModel.OUT_INTERCEPTORS)) { + return new V1InterceptorsModel(config, desc); + } else if (name.equals(InterceptorModel.INTERCEPTOR)) { + return new V1InterceptorModel(config, desc); + } else if (name.equals(PropertiesModel.PROPERTIES)) { + return new V1PropertiesModel(config, desc); + } else if (name.equals(PropertyModel.PROPERTY)) { + return new V1PropertyModel(config, desc); + } else { + for (SOAPName n : SOAPName.values()) { + if (n.name().equals(name)) { + return new V1SOAPNameValueModel(config, desc); + } + } + } + return null; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPMessageComposerModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPMessageComposerModel.java new file mode 100644 index 000000000..dacaea84d --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPMessageComposerModel.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import org.switchyard.component.soap.config.model.SOAPMessageComposerModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composer.v1.V1MessageComposerModel; + +/** + * V1SOAPMessageComposerModel. + */ +public class V1SOAPMessageComposerModel extends V1MessageComposerModel implements SOAPMessageComposerModel { + + /** + * Constructs a new V1SOAPMessageComposerModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1SOAPMessageComposerModel(String namespace) { + super(namespace); + } + + /** + * Constructs a new V1SOAPMessageComposerModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1SOAPMessageComposerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public Boolean isUnwrapped() { + String unwrap = getModelAttribute("unwrapped"); + return unwrap != null && Boolean.valueOf(unwrap); + } + + @Override + public SOAPMessageComposerModel setUnwrapped(boolean unwrapped) { + setModelAttribute("unwrapped", String.valueOf(unwrapped)); + return this; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPNameValueModel.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPNameValueModel.java new file mode 100644 index 000000000..dd9e094f1 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v1/V1SOAPNameValueModel.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import org.switchyard.component.soap.config.model.SOAPNameValueModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * The 1st version SOAPNameValueModel. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class V1SOAPNameValueModel extends BaseModel implements SOAPNameValueModel { + + /** + * Creates a new V1SOAPNameValueModel. + * @param namespace namespace + * @param name the SOAPName + */ + public V1SOAPNameValueModel(String namespace, SOAPName name) { + super(namespace, name.name()); + } + + /** + * Creates a new V1SOAPNameValueModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1SOAPNameValueModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPName getName() { + return SOAPName.valueOf(getModelConfiguration().getName()); + } + + /** + * {@inheritDoc} + */ + @Override + public String getValue() { + return getModelValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public SOAPNameValueModel setValue(String value) { + setModelValue(value); + return this; + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/config/model/v2/V2SOAPMarshaller.java b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v2/V2SOAPMarshaller.java new file mode 100644 index 000000000..be3e704d8 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/config/model/v2/V2SOAPMarshaller.java @@ -0,0 +1,52 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v2; + +import org.switchyard.component.soap.config.model.v1.V1SOAPMarshaller; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.property.v2.V2PropertiesModel; + +/** + * Marshaller for V2 SOAP Gateway configurations. + */ +public class V2SOAPMarshaller extends V1SOAPMarshaller { + + /** + * Construct a SOAP Model Marshaller with help of a Descriptor. + * + * @param desc the Descriptor + */ + public V2SOAPMarshaller(Descriptor desc) { + super(desc); + } + + /** + * Reads a SOAP Model configuration. + * + * @param config the configuration + * @return the SOAP Binding Model + */ + @Override + public Model read(Configuration config) { + Descriptor desc = getDescriptor(); + String name = config.getName(); + if (name.equals(PropertiesModel.PROPERTIES)) { + return new V2PropertiesModel(config, desc); + } + return super.read(config); + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/deploy/SOAPActivator.java b/components/soap/src/main/java/org/switchyard/component/soap/deploy/SOAPActivator.java new file mode 100644 index 000000000..7baa71ba1 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/deploy/SOAPActivator.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.OutboundHandler; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.ServiceHandler; + + +/** + * SOAP Activator. + */ +public class SOAPActivator extends BaseActivator { + + static final String SOAP_TYPE = "soap"; + private Configuration _environment; + + /** + * Creates a new activator for SOAP endpoints. + */ + public SOAPActivator() { + super(SOAP_TYPE); + } + + @Override + public ServiceHandler activateBinding(QName name, BindingModel config) { + SOAPBindingModel binding = (SOAPBindingModel)config; + binding.setEnvironment(_environment); + + if (binding.isServiceBinding()) { + return new InboundHandler(binding, getServiceDomain()); + } else { + return new OutboundHandler(binding); + } + } + + @Override + public void deactivateBinding(QName name, ServiceHandler handler) { + // Nothing to do here + } + + /** + * Set the Environment configuration for the activator. + * @param config The global environment configuration. + */ + public void setEnvironment(Configuration config) { + _environment = config; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/deploy/SOAPComponent.java b/components/soap/src/main/java/org/switchyard/component/soap/deploy/SOAPComponent.java new file mode 100644 index 000000000..8a275be10 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/deploy/SOAPComponent.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.deploy; + +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * An implementation of SOAP component. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SOAPComponent extends BaseComponent { + + /** + * Default constructor. + */ + public SOAPComponent() { + super(SOAPActivator.SOAP_TYPE); + setName("SOAPComponent"); + } + + /** + * {@inheritDoc} + */ + @Override + public Activator createActivator(ServiceDomain domain) { + SOAPActivator activator = new SOAPActivator(); + activator.setServiceDomain(domain); + activator.setEnvironment(getConfig()); + return activator; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/endpoint/AbstractEndpointPublisher.java b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/AbstractEndpointPublisher.java new file mode 100644 index 000000000..cf575c3ed --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/AbstractEndpointPublisher.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.endpoint; + +import java.net.MalformedURLException; + +import javax.xml.ws.WebServiceFeature; + +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.message.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.AddressingInterceptor; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.util.WSDLUtil; + +/** + * Hanldes configuration of Webservice Endpoints. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public abstract class AbstractEndpointPublisher implements EndpointPublisher { + + private String _ctxRoot; + private String _ctxPath; + private String _wsdlLocation; + + /** + * Returns the context root for this publisher. + * @return The context root + */ + public String getContextRoot() { + return _ctxRoot; + } + + /** + * Returns the context path for this publisher. + * @return The context path + */ + public String getContextPath() { + return _ctxPath; + } + + /** + * Returns the location of the WSDL for this publisher. + * @return The wsdl location + */ + public String getWsdlLocation() { + return _wsdlLocation; + } + + /** + * Initialize paths and location for this publisher. + * @param The SOAP binding configuration + */ + protected void initialize(final SOAPBindingModel config) throws MalformedURLException { + if (config.getContextPath() != null) { + _ctxRoot = config.getContextPath(); + _ctxPath = _ctxRoot + "/" + config.getPort().getServiceName(); + } else { + _ctxRoot = ""; + _ctxPath = config.getPort().getServiceName(); + } + _wsdlLocation = WSDLUtil.getURL(config.getWsdl()).toExternalForm(); + } + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, final SOAPBindingModel config, final String bindingId, final InboundHandler handler) { + return publish(domain, config, bindingId, handler, (WebServiceFeature)null); + } + + @Override + public Interceptor createAddressingInterceptor() { + return new AddressingInterceptor(); + } + +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/endpoint/BaseWebService.java b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/BaseWebService.java new file mode 100644 index 000000000..988e71560 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/BaseWebService.java @@ -0,0 +1,117 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.endpoint; + +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; +import javax.xml.soap.MimeHeaders; +import javax.xml.soap.SOAPMessage; +import javax.xml.ws.BindingType; +import javax.xml.ws.Provider; +import javax.xml.ws.Service.Mode; +import javax.xml.ws.ServiceMode; +import javax.xml.ws.WebServiceContext; +import javax.xml.ws.WebServiceProvider; +import javax.xml.ws.handler.MessageContext; +import javax.xml.ws.soap.SOAPBinding; + +import org.switchyard.common.type.Classes; +import org.switchyard.component.soap.InboundHandler; + +/** + * This is the abstract base class for a SOAP messages. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +@WebServiceProvider +@ServiceMode(Mode.MESSAGE) +@BindingType(SOAPBinding.SOAP12HTTP_BINDING) // Actually accepts both 1.1 and 1.2; needs to be present for ws-security to work. +public class BaseWebService implements Provider { + + private static String ACTION_EQUALS = "action="; + private static String CONTENT_TYPE_L = "Content-type"; + private static String CONTENT_TYPE = "Content-Type"; + + private InboundHandler _serviceConsumer; + private ClassLoader _invocationClassLoader; + + @Resource + private WebServiceContext _wsContext; + + /** + * Contruct a generic Webservice. + */ + public BaseWebService() { + } + + /** + * Sets the service handler. + * @param serviceConsumer the service handler. + */ + public void setConsumer(final InboundHandler serviceConsumer) { + _serviceConsumer = serviceConsumer; + } + + /** + * Sets the Invocation TCCL. + * @param classLoader the classloader to be set. + */ + public void setInvocationClassLoader(final ClassLoader classLoader) { + _invocationClassLoader = classLoader; + } + + /** + * The Webservice implementation method, invokes the service handler. + * @param request the SOAP request + * @return the SOAP response + */ + public SOAPMessage invoke(final SOAPMessage request) { + if (request != null) { + // Workaround for SOAP1.2 SOAPAction. Although HTTP header has the action value it is missing in + // the SOAPMessage's MimeHeader + MimeHeaders mimeHeaders = request.getMimeHeaders(); + String[] mimeContentTypes = mimeHeaders.getHeader(CONTENT_TYPE); + if (mimeContentTypes != null) { + String mimeContentType = mimeContentTypes[0]; + if ((mimeContentType != null) && (mimeContentType.indexOf(ACTION_EQUALS) == -1)) { + Map headers = (Map)_wsContext.getMessageContext().get(MessageContext.HTTP_REQUEST_HEADERS); + List contentTypes = (List)headers.get(CONTENT_TYPE_L); + if ((contentTypes == null) || (contentTypes.size() == 0)) { + contentTypes = (List)headers.get(CONTENT_TYPE); + } + if ((contentTypes != null) && (contentTypes.size() > 0)) { + int idx = contentTypes.get(0).indexOf(ACTION_EQUALS); + if (idx > 0) { + String action = contentTypes.get(0).substring(idx + 7).replace("\"\"","\""); + mimeHeaders.setHeader(CONTENT_TYPE, mimeContentType + "; " + ACTION_EQUALS + action); + } + } + } + } + } + + SOAPMessage response = null; + ClassLoader original = Classes.setTCCL(_invocationClassLoader); + try { + response = _serviceConsumer.invoke(request, _wsContext); + } finally { + Classes.setTCCL(original); + } + return response; + } +} + diff --git a/components/soap/src/main/java/org/switchyard/component/soap/endpoint/CXFJettyEndpoint.java b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/CXFJettyEndpoint.java new file mode 100644 index 000000000..4e172bec9 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/CXFJettyEndpoint.java @@ -0,0 +1,147 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.endpoint; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.ws.WebServiceFeature; +import javax.xml.ws.soap.AddressingFeature; +import javax.xml.ws.soap.MTOMFeature; + +import org.apache.cxf.Bus; +import org.apache.cxf.BusFactory; +import org.apache.cxf.endpoint.Server; +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.interceptor.LoggingInInterceptor; +import org.apache.cxf.interceptor.LoggingOutInterceptor; +import org.apache.cxf.jaxws.JaxWsServerFactoryBean; +import org.apache.cxf.message.Message; +import org.apache.cxf.ws.addressing.WSAddressingFeature; +import org.apache.cxf.ws.addressing.soap.DecoupledFaultHandler; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.SOAPLogger; + +/** + * Wrapper for CXF JAX-WS endpoints. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class CXFJettyEndpoint implements Endpoint { + + private static Bus _bus; + + private JaxWsServerFactoryBean _svrFactory; + private Server _server; + private String _publishUrl; + + static { + _bus = BusFactory.newInstance().createBus(); + try { + _bus.setExtension(new org.apache.cxf.ws.addressing.impl.AddressingFeatureApplier(), WSAddressingFeature.WSAddressingFeatureApplier.class); + } catch (Throwable t) { + // checkstyle + t.fillInStackTrace(); + } + } + + /** + * Construct a JAX-WS endpoint based on SOAP version. + * @param bindingId The SOAP binding version + * @param handler The handler instance that contains the actual invoke method implementation + * @param addressingInterceptor specialized interceptor for mapping addressing information + * @param features A list of WebService features + */ + public CXFJettyEndpoint(final String bindingId, final InboundHandler handler, Interceptor addressingInterceptor, WebServiceFeature... features) { + BaseWebService wsProvider = new BaseWebService(); + wsProvider.setInvocationClassLoader(Classes.getTCCL()); + // Hook the handler + wsProvider.setConsumer(handler); + //_endpoint = Endpoint.create(bindingId, wsProvider); + _svrFactory = new JaxWsServerFactoryBean(); + _svrFactory.setServiceClass(BaseWebService.class); + _svrFactory.setServiceBean(wsProvider); + _svrFactory.setBindingId(bindingId); + Map props = new HashMap(); + List cxfFeatures = new ArrayList(); + Boolean addressingEnabled = false; + + for (WebServiceFeature feature : features) { + cxfFeatures.add(feature); + if ((feature instanceof AddressingFeature) && ((AddressingFeature)feature).isEnabled()) { + addressingEnabled = true; + SOAPLogger.ROOT_LOGGER.addressingEnabledRequired(String.valueOf(((AddressingFeature)feature).isEnabled()), + String.valueOf(((AddressingFeature)feature).isRequired())); + } else if (feature instanceof MTOMFeature) { + props.put("mtom-enabled", ((MTOMFeature)feature).isEnabled()); + SOAPLogger.ROOT_LOGGER.mTOMEnabledThreshold(String.valueOf(((MTOMFeature)feature).isEnabled()), + String.valueOf(((MTOMFeature)feature).getThreshold())); + } + } + ((JaxWsServerFactoryBean)_svrFactory).getJaxWsServiceFactory().setWsFeatures(cxfFeatures); + _svrFactory.setProperties(props); + if (addressingEnabled) { + _svrFactory.getInInterceptors().add(new DecoupledFaultHandler()); + if (addressingInterceptor != null) { + _svrFactory.getOutInterceptors().add(addressingInterceptor); + _svrFactory.getOutFaultInterceptors().add(addressingInterceptor); + } + } + _svrFactory.getInInterceptors().add(new LoggingInInterceptor()); + _svrFactory.getInInterceptors().add(new org.apache.cxf.binding.soap.saaj.SAAJInInterceptor()); + _svrFactory.getInInterceptors().add(new org.apache.cxf.binding.soap.interceptor.SoapActionInInterceptor()); + _svrFactory.getOutInterceptors().add(new LoggingOutInterceptor()); + _svrFactory.getOutInterceptors().add(new org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor()); + } + + /** + * Returns the wrapped JAX-WS endpoint. + * @return The JAX-WS endpoint + */ + public JaxWsServerFactoryBean getEndpoint() { + return _svrFactory; + } + + /** + * Publish the JAX-WS endpoint. + * @param publishUrl The url to publish the endpoint to + */ + public void publish(String publishUrl) { + _publishUrl = publishUrl; + SOAPLogger.ROOT_LOGGER.publishingWebServiceAt(_publishUrl); + _svrFactory.setAddress(publishUrl); + _server = _svrFactory.create(); + _server.start(); + } + + /** + * {@inheritDoc} + */ + public void start() { + } + + /** + * {@inheritDoc} + */ + public void stop() { + SOAPLogger.ROOT_LOGGER.stoppingWebServiceAt(_publishUrl); + _server.stop(); + _server.destroy(); + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/endpoint/CXFJettyEndpointPublisher.java b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/CXFJettyEndpointPublisher.java new file mode 100644 index 000000000..1933ad223 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/CXFJettyEndpointPublisher.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.endpoint; + +import java.net.MalformedURLException; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.ws.WebServiceFeature; +import javax.xml.ws.handler.MessageContext; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.AddressingInterceptor; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.WebServicePublishException; +import org.switchyard.component.soap.config.model.SOAPBindingModel; + +/** + * Handles publishing of Webservice Endpoints on CXF JAX-WS implementations. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class CXFJettyEndpointPublisher extends AbstractEndpointPublisher { + + private static final String HTTP_SCHEME = "http"; + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, final SOAPBindingModel config, final String bindingId, final InboundHandler handler, WebServiceFeature... features) { + CXFJettyEndpoint wsEndpoint = null; + try { + initialize(config); + Map properties = new HashMap(); + properties.put(javax.xml.ws.Endpoint.WSDL_SERVICE, config.getPort().getServiceQName()); + properties.put(javax.xml.ws.Endpoint.WSDL_PORT, config.getPort().getPortQName()); + properties.put(MessageContext.WSDL_DESCRIPTION, getWsdlLocation()); + + String publishUrl = HTTP_SCHEME + "://" + config.getSocketAddr().getHost() + ":" + config.getSocketAddr().getPort() + "/" + getContextPath(); + + wsEndpoint = new CXFJettyEndpoint(bindingId, handler, new AddressingInterceptor(), features); + //wsEndpoint.getEndpoint().setProperties(properties); + wsEndpoint.getEndpoint().setWsdlURL(getWsdlLocation()); + wsEndpoint.getEndpoint().setServiceName(config.getPort().getServiceQName()); + wsEndpoint.publish(publishUrl); + } catch (MalformedURLException e) { + throw new WebServicePublishException(e); + } + return wsEndpoint; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/endpoint/EndpointPublisher.java b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/EndpointPublisher.java new file mode 100644 index 000000000..890fc9111 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/EndpointPublisher.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.endpoint; +import javax.xml.ws.WebServiceFeature; + +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.message.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.config.model.SOAPBindingModel; + +/** + * Interface for allowing SwitchYard to publish and stop Webservice endpoints. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public interface EndpointPublisher { + + /** + * Publish a Webservice Endpoint. + * @param domain The ServiceDomain for the application + * @param config The SOAP binding config + * @param bindingId The SOAP binding version + * @param handler The handler instance that contains the actual invoke method implementation + * @return The published endpoint + */ + Endpoint publish(ServiceDomain domain, SOAPBindingModel config, String bindingId, InboundHandler handler); + + /** + * Publish a Webservice Endpoint. + * @param domain The ServiceDomain for the application + * @param config The SOAP binding config + * @param bindingId The SOAP binding version + * @param handler The handler instance that contains the actual invoke method implementation + * @param features A list of WebServiceFeature to configure on the endpoint. + * @return The published endpoint + */ + Endpoint publish(ServiceDomain domain, SOAPBindingModel config, String bindingId, InboundHandler handler, WebServiceFeature... features); + + /** + * @return a new interceptor used to hook addressing + */ + Interceptor createAddressingInterceptor(); +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/endpoint/EndpointPublisherFactory.java b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/EndpointPublisherFactory.java new file mode 100644 index 000000000..67de8f15f --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/EndpointPublisherFactory.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.endpoint; + +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.component.soap.SOAPLogger; +import org.switchyard.component.soap.WebServicePublishException; + +/** + * Factory for creating Endpoint publishers. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class EndpointPublisherFactory { + + private static EndpointPublisher PUBLISHER; + + static { + try { + PUBLISHER = ProviderRegistry.getProvider(EndpointPublisher.class); + if (PUBLISHER == null) { + SOAPLogger.ROOT_LOGGER.noEndpointPublisherRegistered(); + PUBLISHER = new CXFJettyEndpointPublisher(); + } + SOAPLogger.ROOT_LOGGER.endpointPublisherRegistered(PUBLISHER.getClass().getSimpleName()); + } catch (Exception e) { + throw new WebServicePublishException(e); + } + } + + private EndpointPublisherFactory() { + } + + /** + * Creates an EndpointPublisher based on the environment. + * @return The EndpointPublisher + */ + public static EndpointPublisher getEndpointPublisher() { + return PUBLISHER; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/endpoint/JAXWSEndpoint.java b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/JAXWSEndpoint.java new file mode 100644 index 000000000..696aae203 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/JAXWSEndpoint.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.endpoint; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import javax.xml.ws.WebServiceFeature; + +import org.jboss.logging.Logger; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.SOAPLogger; +import org.switchyard.component.soap.InboundHandler; + +/** + * Wrapper for JAX-WS endpoints. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JAXWSEndpoint implements Endpoint { + + private static final Logger LOGGER = Logger.getLogger(JAXWSEndpoint.class); + + private javax.xml.ws.Endpoint _endpoint; + private String _publishUrl; + + /** + * Construct a JAX-WS endpoint based on SOAP version. + * @param bindingId The SOAP binding version + * @param handler The handler instance that contains the actual invoke method implementation + * @param features A list of WebService features + */ + public JAXWSEndpoint(final String bindingId, final InboundHandler handler, WebServiceFeature... features) { + BaseWebService wsProvider = new BaseWebService(); + wsProvider.setInvocationClassLoader(Classes.getTCCL()); + // Hook the handler + wsProvider.setConsumer(handler); + + try { + _endpoint = javax.xml.ws.Endpoint.create(bindingId, wsProvider, features); + } catch (NoSuchMethodError t) { + _endpoint = javax.xml.ws.Endpoint.create(bindingId, wsProvider); + try { + Method method = _endpoint.getBinding().getClass().getSuperclass().getMethod("addFeature", new Class[]{WebServiceFeature.class}); + for (WebServiceFeature feature : features) { + method.invoke(_endpoint.getBinding(), feature); + } + } catch (NoSuchMethodException nsme) { + // Silent fail + LOGGER.error(nsme); + } catch (IllegalAccessException iae) { + // Silent fail + LOGGER.error(iae); + } catch (InvocationTargetException ite) { + // Silent fail + LOGGER.error(ite); + } + } + } + + /** + * Returns the wrapped JAX-WS endpoint. + * @return The JAX-WS endpoint + */ + public javax.xml.ws.Endpoint getEndpoint() { + return _endpoint; + } + + /** + * Publish the JAX-WS endpoint. + * @param publishUrl The url to publish the endpoint to + */ + public void publish(String publishUrl) { + _publishUrl = publishUrl; + SOAPLogger.ROOT_LOGGER.publishingWebServiceAt(_publishUrl); + _endpoint.publish(_publishUrl); + } + + /** + * {@inheritDoc} + */ + public void start() { + } + + /** + * {@inheritDoc} + */ + public void stop() { + SOAPLogger.ROOT_LOGGER.stoppingWebServiceAt(_publishUrl); + _endpoint.stop(); + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/endpoint/JAXWSEndpointPublisher.java b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/JAXWSEndpointPublisher.java new file mode 100644 index 000000000..9efd4cc51 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/endpoint/JAXWSEndpointPublisher.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.endpoint; + +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.wsdl.WSDLException; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import javax.xml.ws.WebServiceFeature; +import javax.xml.ws.handler.MessageContext; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.WebServicePublishException; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.util.WSDLUtil; + +/** + * Handles publishing of Webservice Endpoints on JAX-WS implementations. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JAXWSEndpointPublisher extends AbstractEndpointPublisher { + + private static final String HTTP_SCHEME = "http"; + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, final SOAPBindingModel config, final String bindingId, final InboundHandler handler, WebServiceFeature... features) { + JAXWSEndpoint wsEndpoint = null; + try { + initialize(config); + List metadata = new ArrayList(); + StreamSource source = WSDLUtil.getStream(config.getWsdl()); + metadata.add(source); + Map properties = new HashMap(); + properties.put(javax.xml.ws.Endpoint.WSDL_SERVICE, config.getPort().getServiceQName()); + properties.put(javax.xml.ws.Endpoint.WSDL_PORT, config.getPort().getPortQName()); + properties.put(MessageContext.WSDL_DESCRIPTION, getWsdlLocation()); + + String publishUrl = HTTP_SCHEME + "://" + config.getSocketAddr().getHost() + ":" + config.getSocketAddr().getPort() + "/" + getContextPath(); + + wsEndpoint = new JAXWSEndpoint(bindingId, handler, features); + wsEndpoint.getEndpoint().setMetadata(metadata); + wsEndpoint.getEndpoint().setProperties(properties); + wsEndpoint.publish(publishUrl); + } catch (MalformedURLException e) { + throw new WebServicePublishException(e); + } catch (WSDLException e) { + throw new WebServicePublishException(e); + } + return wsEndpoint; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/util/SOAPUtil.java b/components/soap/src/main/java/org/switchyard/component/soap/util/SOAPUtil.java new file mode 100644 index 000000000..fcafda1af --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/util/SOAPUtil.java @@ -0,0 +1,645 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.util; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URLDecoder; +import java.util.Iterator; +import java.util.Map; + +import javax.activation.DataSource; +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.soap.Detail; +import javax.xml.soap.DetailEntry; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPBody; +import javax.xml.soap.SOAPConstants; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPEnvelope; +import javax.xml.soap.SOAPFactory; +import javax.xml.soap.SOAPFault; +import javax.xml.soap.SOAPHeaderElement; +import javax.xml.soap.SOAPMessage; +import javax.xml.ws.soap.SOAPBinding; +import javax.xml.ws.soap.SOAPFaultException; + +import org.jboss.logging.Logger; +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.common.codec.Base64; +import org.switchyard.common.xml.XMLHelper; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; +import org.switchyard.component.soap.SOAPLogger; +import org.switchyard.component.soap.SOAPMessages; + +/** + * Contains utility methods to examine/manipulate SOAP Messages. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public final class SOAPUtil { + private static final Logger LOGGER = Logger.getLogger(SOAPUtil.class); + + /** + * SwitchYard Context key. + */ + public static final String SWITCHYARD_CONTEXT = "SWITCHYARD_CONTEXT"; + + /** + * SOAP 1.1 namespace. + */ + public static final String SOAP11_URI = "http://schemas.xmlsoap.org/soap/envelope/"; + + /** + * SOAP 1.2 namespace. + */ + public static final String SOAP12_URI = "http://www.w3.org/2003/05/soap-envelope"; + + /** + * WS-A namespace. + */ + public static final String WSA_URI = "http://www.w3.org/2005/08/addressing"; + + /** + * MTOM XOP namespace. + */ + public static final String MTOM_XOP_URI = "http://www.w3.org/2004/08/xop/include"; + + /** + * SOAP 1.1 Server Fault Qname. + */ + public static final QName SOAP11_SERVER_FAULT_TYPE = new QName(SOAP11_URI, "Server"); + + /** + * SOAP 1.1 Fault QName. + */ + public static final QName SOAP11_FAULT_MESSAGE_TYPE = new QName(SOAP11_URI, "Fault"); + + /** + * SOAP 1.2 Server Fault Qname. + */ + public static final QName SOAP12_RECEIVER_FAULT_TYPE = new QName(SOAP12_URI, "Receiver"); + + /** + * SOAP 1.2 Fault QName. + */ + public static final QName SOAP12_FAULT_MESSAGE_TYPE = new QName(SOAP12_URI, "Fault"); + + /** + * The WS-A Action QName. + */ + public static final QName WSA_ACTION_QNAME = new QName(WSA_URI, "Action"); + + /** + * The WS-A From QName. + */ + public static final QName WSA_FROM_QNAME = new QName(WSA_URI, "From"); + + /** + * The WS-A MessageID QName. + */ + public static final QName WSA_MESSAGEID_QNAME = new QName(WSA_URI, "MessageID"); + + /** + * The WS-A ReplyTo QName. + */ + public static final QName WSA_REPLYTO_QNAME = new QName(WSA_URI, "ReplyTo"); + + /** + * The WS-A FaultTo QName. + */ + public static final QName WSA_FAULTTO_QNAME = new QName(WSA_URI, "FaultTo"); + + /** + * The WS-A RelatesTo QName. + */ + public static final QName WSA_RELATESTO_QNAME = new QName(WSA_URI, "RelatesTo"); + + /** + * The WS-A To QName. + */ + public static final QName WSA_TO_QNAME = new QName(WSA_URI, "To"); + /** + * The MTOM/XOP Include QName. + */ + public static final QName MTOM_XOP_INCLUDE_QNAME = new QName(MTOM_XOP_URI, "Include"); + + /** + * The WS-A Action QName String. + */ + public static final String WSA_ACTION_STR = WSA_ACTION_QNAME.toString(); + + /** + * The WS-A From QName String. + */ + public static final String WSA_FROM_STR = WSA_FROM_QNAME.toString(); + + /** + * The WS-A FaultTo QName String. + */ + public static final String WSA_FAULTTO_STR = WSA_FAULTTO_QNAME.toString(); + + /** + * The WS-A ReplyTo QName String. + */ + public static final String WSA_REPLYTO_STR = WSA_REPLYTO_QNAME.toString(); + + /** + * The WS-A RelatesTo QName String. + */ + public static final String WSA_RELATESTO_STR = WSA_RELATESTO_QNAME.toString(); + + /** + * The WS-A MessageID QName String. + */ + public static final String WSA_MESSAGEID_STR = WSA_MESSAGEID_QNAME.toString(); + + /** + * The WS-A To QName String. + */ + public static final String WSA_TO_STR = WSA_TO_QNAME.toString(); + + /** + * Http status code. + */ + public static final String STATUS = "org.switchyard.http.status"; + + /** + * Default fault response code. + */ + public static final Integer DEFAULT_FAULT_RESONSE_CODE = 500; + + private static final boolean RETURN_STACK_TRACES = false; + private static final String INDENT_FEATURE = "{http://xml.apache.org/xslt}indent-amount"; + private static final String INDENT_AMOUNT = "4"; + private static final String CID_STR = "cid:"; + private static final String HREF_STR = "href"; + + /** SOAP Message Factory holder. */ + private static final MessageFactory SOAP11_MESSAGE_FACTORY; + private static final MessageFactory SOAP12_MESSAGE_FACTORY; + + /** SOAP Factory holder. */ + private static final SOAPFactory SOAP11_FACTORY; + private static final SOAPFactory SOAP12_FACTORY; + + private SOAPUtil() { + } + + /** + * Retrieves the first element name in the SOAP Envelope's body. + * + * @param soapMessage The SOAP message. + * @return The first Element QName. + * @throws SOAPException If the SOAP message is invalid + */ + public static QName getFirstBodyElement(final SOAPMessage soapMessage) throws SOAPException { + QName operationName = null; + SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody(); + + if (body != null) { + Iterator nodes = body.getChildElements(); + Node node = null; + while (nodes.hasNext()) { + node = nodes.next(); + if (node instanceof Element) { + operationName = new QName(node.getNamespaceURI(), node.getLocalName()); + } + } + } + + return operationName; + } + + /** + * Determines if the envelope is SOAP 1.1 or 1.2. + * + * @param soapMessage The SOAPMessage + * @return The true if envelope is SOAP 1.2 + * @throws SOAPException If the envelope could not be read + */ + public static Boolean isSOAP12(SOAPMessage soapMessage) throws SOAPException { + return soapMessage.getSOAPPart().getEnvelope().getNamespaceURI().equals(SOAP12_URI); + } + + /** + * Determines if the envelope has addressing action header. + * + * @param soapMessage The SOAPMessage + * @return The action addressing header + * @throws SOAPException If the envelope could not be read + */ + public static String getAddressingAction(SOAPMessage soapMessage) throws SOAPException { + String action = null; + Iterator headers = soapMessage.getSOAPPart().getEnvelope().getHeader().examineAllHeaderElements(); + while (headers.hasNext()) { + SOAPHeaderElement element = headers.next(); + if (element.getElementQName().equals(WSA_ACTION_QNAME)) { + action = element.getValue(); + break; + } + } + return action; + } + + /** + * Get the WS-A MessageID from the envelope. + * + * @param soapEnvelope The SOAPEnvelope + * @return The message id if found, null otehrwise + * @throws SOAPException If the envelope could not be read + */ + public static String getMessageID(SOAPEnvelope soapEnvelope) throws SOAPException { + NodeList headers = soapEnvelope.getHeader().getElementsByTagNameNS(WSA_ACTION_QNAME.getNamespaceURI(), WSA_ACTION_QNAME.getLocalPart()); + if (headers.getLength() == 1) { + return ((javax.xml.soap.Node)headers.item(0)).getValue(); + } + return null; + } + + /** + * Get the To header if it is set. + * + * @param context The SwitchYard Context + * @return The To address + */ + public static String getToAddress(Context context) { + String address = null; + Property toProp = context.getProperty(WSA_TO_STR); + if (toProp == null) { + toProp = context.getProperty(WSA_TO_STR.toLowerCase()); + } + if (toProp != null) { + Element toEl = (Element)toProp.getValue(); + address = toEl.getFirstChild().getNodeValue(); + } + return address; + } + + /** + * Expand xop inlines. + * + * @param element the element to expand + * @param attachmentMap the attachment Map + * @return the expanded element + * @throws IOException if the xop content could not be expanded + */ + public static Element expandXop(Element element, Map attachmentMap) throws IOException { + if (element != null) { + NodeList children = element.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node node = children.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + QName name = new QName(node.getNamespaceURI(), node.getLocalName()); + if (name.equals(MTOM_XOP_INCLUDE_QNAME)) { + String contentId = XMLHelper.getAttribute((Element)node, "", HREF_STR); + if (contentId.startsWith(CID_STR)) { + contentId = contentId.substring(4); + } + contentId = URLDecoder.decode(contentId, "UTF-8"); + if (attachmentMap.get(contentId) == null) { + throw SOAPMessages.MESSAGES.noAttachmentFoundWithName(contentId); + } + InputStream is = attachmentMap.get(contentId).getInputStream(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + byte[] buff = new byte[128]; + int read; + try { + while ((read = is.read(buff)) != -1) { + os.write(buff, 0, read); + } + } finally { + os.flush(); + os.close(); + is.close(); + } + // Encode attachment and add it here + String imageString = Base64.encode(os.toByteArray()); + Node content = element.getOwnerDocument().createTextNode(imageString); + element.removeChild(node); + element.appendChild(content); + attachmentMap.remove(contentId); + } else { + expandXop((Element)node, attachmentMap); + } + } + } + return element; + } + return null; + } + + /** + * Adds a SOAP 1.1 or 1.2 Fault element to the SOAPBody. + * + * @param soapMessage The SOAPMessage + * @return The SOAPFault that was added + * @throws SOAPException If the fault could not be generated + */ + public static SOAPFault addFault(SOAPMessage soapMessage) throws SOAPException { + if (isSOAP12(soapMessage)) { + return soapMessage.getSOAPBody().addFault(SOAP12_FAULT_MESSAGE_TYPE, + SOAPMessages.MESSAGES.sendFailed()); + } else { + return soapMessage.getSOAPBody().addFault(SOAP11_FAULT_MESSAGE_TYPE, + SOAPMessages.MESSAGES.sendFailed()); + } + } + + /** + * Generates a SOAP 1.1 or 1.2 Fault Message based on binding id and Exception passed. + * + * @param th The Exception + * @param bindingId SOAPBinding type + * @return The SOAP Message containing the Fault + * @throws SOAPException If the message could not be generated + */ + public static SOAPMessage generateFault(final Throwable th, final String bindingId) throws SOAPException { + if (bindingId.equals(SOAPBinding.SOAP12HTTP_BINDING) || bindingId.equals(SOAPBinding.SOAP12HTTP_MTOM_BINDING)) { + return generateSOAP12Fault(th); + } else { + return generateSOAP11Fault(th); + } + } + + /** + * Generates a SOAP 1.1 Fault Message based on the Exception passed. + * + * @param th The Exception. + * @return The SOAP Message containing the Fault. + * @throws SOAPException If the message could not be generated. + */ + public static SOAPMessage generateSOAP11Fault(final Throwable th) throws SOAPException { + SOAPMessage faultMsg = SOAP11_MESSAGE_FACTORY.createMessage(); + return generateFault(th, faultMsg, SOAP11_SERVER_FAULT_TYPE); + } + + /** + * Generates a SOAP 1.2 Fault Message based on the Exception passed. + * + * @param th The Exception. + * @return The SOAP Message containing the Fault. + * @throws SOAPException If the message could not be generated. + */ + public static SOAPMessage generateSOAP12Fault(final Throwable th) throws SOAPException { + final SOAPMessage faultMsg = SOAP12_MESSAGE_FACTORY.createMessage(); + return generateFault(th, faultMsg, SOAP12_RECEIVER_FAULT_TYPE); + } + + private static SOAPMessage generateFault(final Throwable th, final SOAPMessage faultMsg, final QName faultQname) throws SOAPException { + if (LOGGER.isDebugEnabled()) { + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + th.printStackTrace(pw); + pw.flush(); + pw.close(); + LOGGER.debug(sw.toString()); + } + if (th instanceof SOAPFaultException) { + // Copy the Fault from the exception + SOAPFault exFault = ((SOAPFaultException) th).getFault(); + SOAPFault fault = faultMsg.getSOAPBody().addFault(); + fault.setFaultCode(exFault.getFaultCodeAsQName()); + final String faultString = exFault.getFaultString(); + fault.setFaultString(faultString == null ? "" : faultString); + if (SOAP11_SERVER_FAULT_TYPE.equals(faultQname)) { + if (exFault.getFaultActor() != null) { + fault.setFaultActor(exFault.getFaultActor()); + } + } else { + if (exFault.getFaultNode() != null) { + fault.setFaultNode(exFault.getFaultNode()); + } + if (exFault.getFaultRole() != null) { + fault.setFaultRole(exFault.getFaultRole()); + } + } + if (exFault.hasDetail()) { + Detail exDetail = exFault.getDetail(); + Detail detail = fault.addDetail(); + for (Iterator entries = exDetail.getDetailEntries(); entries.hasNext();) { + Node entry = entries.next(); + Node entryImport = detail.getOwnerDocument().importNode(entry, true); + detail.appendChild(entryImport); + } + } + if (!SOAP11_SERVER_FAULT_TYPE.equals(faultQname) && exFault.getFaultSubcodes() != null) { + Iterator faultSubcodes = exFault.getFaultSubcodes(); + while (faultSubcodes.hasNext()) { + fault.appendFaultSubcode(faultSubcodes.next()); + } + } + } else { + if (RETURN_STACK_TRACES) { + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + th.printStackTrace(pw); + pw.flush(); + pw.close(); + faultMsg.getSOAPBody().addFault(faultQname, sw.toString()); + } else { + String message = th.getMessage(); + if (message == null) { + message = th.toString(); + } + faultMsg.getSOAPBody().addFault(faultQname, message); + } + } + return faultMsg; + } + + /** + * Generates a SOAP 1.1 or 1.2 Fault based on binding id and Exception passed. + * + * @param th The Exception + * @param bindingId SOAPBinding type + * @param detail Fault detail QName + * @return The SOAP Fault + * @throws SOAPException If the Fault could not be generated + */ + public static SOAPFault createFault(final Throwable th, final String bindingId, final QName detail) throws SOAPException { + SOAPFault fault = null; + if (bindingId.equals(SOAPBinding.SOAP12HTTP_BINDING) || bindingId.equals(SOAPBinding.SOAP12HTTP_MTOM_BINDING)) { + fault = createSOAP12Fault(th); + } else { + fault = createSOAP11Fault(th); + } + if (detail != null) { + fault.addDetail().addDetailEntry(detail); + } + return fault; + } + + private static SOAPFault createSOAP11Fault(final Throwable th) throws SOAPException { + return createFault(th, SOAP11_FACTORY, SOAP11_SERVER_FAULT_TYPE); + } + + private static SOAPFault createSOAP12Fault(final Throwable th) throws SOAPException { + return createFault(th, SOAP12_FACTORY, SOAP12_RECEIVER_FAULT_TYPE); + } + + private static SOAPFault createFault(final Throwable th, SOAPFactory factory, final QName faultQname) throws SOAPException { + if (LOGGER.isDebugEnabled()) { + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + th.printStackTrace(pw); + pw.flush(); + pw.close(); + LOGGER.debug(sw.toString()); + } + String message = th.getMessage(); + if (message == null) { + message = th.toString(); + } + SOAPFault fault = factory.createFault(message, faultQname); + return fault; + } + + /** + * Create a new document based on a SOAP Message. + * @param soapRes the SOAP Message + * @return the new document + * @throws ParserConfigurationException for errors during creation + * @throws IOException if the source could not be read + * @throws SAXException if any parser error occurs + */ + public static Document parseAsDom(final String soapRes) throws ParserConfigurationException, IOException, SAXException { + // Note: Using DOM approach rather than Event based because, comments are not handled properly. + // An END_DOCUMENT event is sent when a comment is encountered and that leads to: + // org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. + return XMLHelper.getDocumentFromString(soapRes); + } + + /** + * Generate String representation of SOAP message from javax.xml.soap.SOAPMessage. + * @param msg SOAPMessage to parse + * @return String representation of SOAP message + */ + public static String soapMessageToString(SOAPMessage msg) { + String str = null; + if (msg != null) { + try { + str = XMLHelper.toPretty(msg.getSOAPPart().getDocumentElement()); + } catch (Exception e) { + SOAPLogger.ROOT_LOGGER.couldNotParseSOAPMessage(e); + } + } + return str; + } + + /** + * Pretty print a Document element. + * @param element the Document element to print + * @param out PrintStream to print to. + */ + public static void prettyPrint(Element element, PrintStream out) { + try { + out.println(XMLHelper.toPretty(element)); + } catch (Exception e) { + SOAPLogger.ROOT_LOGGER.couldNotParseSOAPMessage(e); + } + } + + /** + * Pretty print a SOAP message. + * @param msg SOAPMessage to print + * @param out PrintStream to print to. + */ + public static void prettyPrint(SOAPMessage msg, PrintStream out) { + prettyPrint(msg.getSOAPPart().getDocumentElement(), out); + } + + /** + * Pretty print a SOAP message. + * @param msg SOAPMessage to print + * @param out PrintStream to print to. + */ + public static void prettyPrint(String msg, PrintStream out) { + try { + prettyPrint(XMLHelper.getDocumentFromString(msg).getDocumentElement(), out); + } catch (Exception e) { + SOAPLogger.ROOT_LOGGER.couldNotParseMessageString(e); + } + } + + /** + * Creates a SOAP Message of version 1.1 or 1.2 based on binding id. The binding Id + * can be one of javax.xml.ws.soap.SOAPBinding ids. + * + * @param bindingId SOAPBinding type + * @return javax.xml.soap.SOAPMessage + * @throws SOAPException If the message could not be generated. + */ + public static SOAPMessage createMessage(String bindingId) throws SOAPException { + SOAPMessage message = null; + if (bindingId.equals(SOAPBinding.SOAP12HTTP_BINDING) || bindingId.equals(SOAPBinding.SOAP12HTTP_MTOM_BINDING)) { + message = SOAP12_MESSAGE_FACTORY.createMessage(); + } else { + message = SOAP11_MESSAGE_FACTORY.createMessage(); + } + return message; + } + + /** + * Returns the SOAP Message factory of version 1.1 or 1.2 based on binding id. The binding Id + * can be one of javax.xml.ws.soap.SOAPBinding ids. + * + * @param bindingId SOAPBinding type + * @return javax.xml.soap.MessageFactory + */ + public static MessageFactory getFactory(String bindingId) { + MessageFactory factory = null; + if (bindingId.equals(SOAPBinding.SOAP12HTTP_BINDING) || bindingId.equals(SOAPBinding.SOAP12HTTP_MTOM_BINDING)) { + factory = SOAP12_MESSAGE_FACTORY; + } else { + factory = SOAP11_MESSAGE_FACTORY; + } + return factory; + } + + static { + MessageFactory soapMessageFactory = null; + SOAPFactory soapFactory = null; + try { + soapMessageFactory = MessageFactory.newInstance(); + soapFactory = SOAPFactory.newInstance(); + } catch (final SOAPException soape) { + SOAPLogger.ROOT_LOGGER.couldNotInstantiateSOAP11MessageFactory(soape); + } + SOAP11_MESSAGE_FACTORY = soapMessageFactory; + SOAP11_FACTORY = soapFactory; + + soapMessageFactory = null; + soapFactory = null; + try { + soapMessageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + soapFactory = SOAPFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + } catch (final SOAPException soape) { + SOAPLogger.ROOT_LOGGER.couldNotInstantiateSOAP12MessageFactory(soape); + } + SOAP12_MESSAGE_FACTORY = soapMessageFactory; + SOAP12_FACTORY = soapFactory; + } +} diff --git a/components/soap/src/main/java/org/switchyard/component/soap/util/WSDLUtil.java b/components/soap/src/main/java/org/switchyard/component/soap/util/WSDLUtil.java new file mode 100644 index 000000000..99d451d31 --- /dev/null +++ b/components/soap/src/main/java/org/switchyard/component/soap/util/WSDLUtil.java @@ -0,0 +1,939 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap.util; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +import javax.wsdl.BindingOperation; +import javax.wsdl.Definition; +import javax.wsdl.Fault; +import javax.wsdl.Import; +import javax.wsdl.Message; +import javax.wsdl.Operation; +import javax.wsdl.OperationType; +import javax.wsdl.Part; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.Types; +import javax.wsdl.WSDLException; +import javax.wsdl.extensions.ExtensibilityElement; +import javax.wsdl.extensions.UnknownExtensibilityElement; +import javax.wsdl.extensions.schema.Schema; +import javax.wsdl.extensions.schema.SchemaImport; +import javax.wsdl.extensions.soap.SOAPAddress; +import javax.wsdl.extensions.soap.SOAPBinding; +import javax.wsdl.extensions.soap.SOAPOperation; +import javax.wsdl.extensions.soap12.SOAP12Address; +import javax.wsdl.extensions.soap12.SOAP12Binding; +import javax.wsdl.extensions.soap12.SOAP12Operation; +import javax.wsdl.factory.WSDLFactory; +import javax.wsdl.xml.WSDLReader; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.transform.stream.StreamSource; + +import org.jboss.logging.Logger; +import org.switchyard.ExchangePattern; +import org.switchyard.common.type.Classes; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.soap.SOAPMessages; +import org.switchyard.component.soap.Feature; +import org.switchyard.component.soap.PortName; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/** + * Contains utility methods to examine/manipulate WSDLs. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public final class WSDLUtil { + + private static final Logger LOGGER = Logger.getLogger(WSDLUtil.class); + + /** + * WSDL SOAP 1.1 QName namespace. + */ + public static final String WSDL_SOAP11_URI = "http://schemas.xmlsoap.org/wsdl/soap/"; + + /** + * WSDL SOAP 1.2 QName namespace. + */ + public static final String WSDL_SOAP12_URI = "http://schemas.xmlsoap.org/wsdl/soap12/"; + + /** + * Document style. + */ + public static final String DOCUMENT = "document"; + + private static final String SCHEME_URN = "urn:"; + private static final String STR_ACTION = "Action"; + private static final String STR_COLON = ":"; + private static final String STR_SLASH = "/"; + private static final String STR_FAULT = "Fault"; + private static final String REQUEST_SUFFIX = "Request"; + private static final String RESPONSE_SUFFIX = "Response"; + private static final String ATTR_ID = "Id"; + private static final String ATTR_REQUIRED = "required"; + private static final String ATTR_URI = "URI"; + private static final String ATTR_EXP_CT = "expectedContentTypes"; + private static final String ATTR_LOCATION = "location"; + private static final String ELE_ADDRESSING = "Addressing"; + private static final String ELE_ALL = "All"; + private static final String ELE_EXACTLYONE = "ExactlyOne"; + private static final String ELE_MTOM = "MTOM"; + private static final String WSA_METADATA_URI = "http://www.w3.org/2007/05/addressing/metadata"; + private static final String WSA_WSDL_URI = "http://www.w3.org/2006/05/addressing/wsdl"; + private static final String POLICY_URI = "http://www.w3.org/ns/ws-policy"; + private static final String WS_MTOM_URI = "http://www.w3.org/2007/08/soap12-mtom-policy"; + private static final String WSDL_XMIME_URI = "http://www.w3.org/2005/05/xmlmime"; + private static final String SECURITY_UTILITY_URI = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"; + // No support for WSDL2.0 yet, as CXF doesn't have it. + // http://cxf.apache.org/project-status.html - GSoC project just started + // private static final String WSDL20_URI = "http://www.w3.org/2006/01/wsdl"; + private static final String WSDL11_URI = "http://schemas.xmlsoap.org/wsdl/"; + private static final QName USING_WSA_QNAME = new QName(WSA_WSDL_URI, "UsingAddressing"); + private static final QName POLICY_QNAME = new QName(POLICY_URI, "Policy"); + private static final QName POLICY_REFERENCE_QNAME = new QName(POLICY_URI, "PolicyReference"); + private static final QName POLICY_EXACTLYONE_QNAME = new QName(POLICY_URI, ELE_EXACTLYONE); + private static final QName POLICY_ALL_QNAME = new QName(POLICY_URI, ELE_ALL); + private static final QName WSA_QNAME = new QName(WSA_METADATA_URI, ELE_ADDRESSING); + private static final QName WSDL_ACTION_QNAME = new QName(WSA_WSDL_URI, STR_ACTION); + private static final QName WSDL_MTOM_QNAME = new QName(WS_MTOM_URI, ELE_MTOM); + private static final QName MTOM_EXPT_QNAME = new QName(WSDL_XMIME_URI, ATTR_EXP_CT); + + private WSDLUtil() { + } + + /** + * Read the WSDL document and create a WSDL Definition. + * + * @param wsdlLocation location pointing to a WSDL XML definition. + * @return the Definition. + * @throws WSDLException If unable to read the WSDL + */ + public static Definition readWSDL(final String wsdlLocation) throws WSDLException { + InputStream inputStream = null; + try { + URL url = getURL(wsdlLocation); + inputStream = url.openStream(); + InputSource source = new InputSource(inputStream); + source.setSystemId(url.toString()); + Document wsdlDoc = XMLHelper.getDocument(source); + WSDLFactory wsdlFactory = WSDLFactory.newInstance(); + WSDLReader reader = wsdlFactory.newWSDLReader(); + reader.setFeature("javax.wsdl.verbose", false); + return reader.readWSDL(url.toString(), wsdlDoc); + } catch (Exception e) { + throw new WSDLException(WSDLException.OTHER_ERROR, + SOAPMessages.MESSAGES.unableToReadWSDL(wsdlLocation), e); + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException ioe) { + LOGGER.error(ioe); + } + } + } + } + + /** + * Read the WSDL document accessible via the specified + * URI into a StreamSource. + * + * @param wsdlURI a URI (can be a filename or URL) pointing to a + * WSDL XML definition. + * @return the StreamSource. + * @throws WSDLException If unable to read the WSDL + */ + public static StreamSource getStream(final String wsdlURI) throws WSDLException { + try { + URL url = getURL(wsdlURI); + InputStream inputStream = url.openStream(); + StreamSource inputSource = new StreamSource(inputStream); + inputSource.setSystemId(url.toString()); + return inputSource; + } catch (Exception e) { + throw new WSDLException(WSDLException.OTHER_ERROR, + SOAPMessages.MESSAGES.unableToResolveWSDL(wsdlURI.toString()), e); + + } + } + + /** + * Convert a path/uri to a URL. + * + * @param path a path or URI. + * @return the URL. + * @throws MalformedURLException If the url path is not valid + */ + public static URL getURL(final String path) throws MalformedURLException { + if (path.startsWith("http://") || path.startsWith("https://") || path.startsWith("file://")) { + return new URL(null, path); + } else { + URL url; + try { + url = Classes.getResource(path, WSDLUtil.class); + } catch (IOException ioe) { + url = null; + } + if (url == null) { + File localFile = new File(path); + url = localFile.toURI().toURL(); + } + return url; + } + } + + /** + * Get the Service from the WSDL given a PortName. + * If the PortName.getServiceQName() is empty (QName("")) then this method returns the first found Service. + * + * @param wsdlLocation location pointing to a WSDL XML definition. + * @param portName the PortName. + * @return the Service. + * @throws WSDLException If the Service could not be retrieved. + */ + public static Service getService(final String wsdlLocation, final PortName portName) throws WSDLException { + Definition definition = readWSDL(wsdlLocation); + return getService(definition, portName); + } + + /** + * Get the Service from the WSDL Definition given a PortName. + * If the PortName.getServiceQName() is empty (QName("")) then this method returns the first found Service. + * + * @param definition the WSDL XML definition. + * @param portName the PortName. + * @return the Service. + * @throws WSDLException If the Service could not be retrieved. + */ + public static Service getService(final Definition definition, final PortName portName) throws WSDLException { + Service service = null; + if (portName.getServiceQName().equals(new QName(""))) { + service = (Service) definition.getAllServices().values().iterator().next(); + portName.setServiceQName(service.getQName()); + } else { + String namespace = portName.getNamespaceURI(); + Boolean namespaceSet = false; + if (namespace.equals(XMLConstants.NULL_NS_URI)) { + namespace = definition.getTargetNamespace(); + } else { + namespaceSet = true; + } + QName serviceQName = new QName(namespace, portName.getServiceName()); + Iterator services = definition.getAllServices().values().iterator(); +outer: while (services.hasNext()) { + Service wsdlService = services.next(); + if (wsdlService.getQName().equals(serviceQName)) { + service = wsdlService; + break; + } else if (!namespaceSet) { + Iterator importedNamespaces = definition.getImports().keySet().iterator(); + while (importedNamespaces.hasNext()) { + QName qName = new QName(importedNamespaces.next(), portName.getServiceName()); + if (wsdlService.getQName().equals(qName)) { + service = wsdlService; + break outer; + } + } + } + } + } + if (service == null) { + throw new WSDLException(SOAPMessages.MESSAGES.couldNotFindServiceInTheWSDL(portName.toString(), definition.getDocumentBaseURI()), null); + } + return service; + } + + /** + * Get the Port from the Service given a port name string. If the PortName.getName() is null then this method returns the first found Port. + * + * @param wsdlService the Service to be queried for. + * @param portName the PortName. + * @return the Webservice Port. + * @throws WSDLException If the Port could not be found. + */ + public static Port getPort(final Service wsdlService, final PortName portName) throws WSDLException { + String name = portName.getName(); + Port port = null; + if ((name == null) || (name.length() == 0)) { + try { + port = (Port) wsdlService.getPorts().values().iterator().next(); + } catch (NoSuchElementException nsee) { + throw new WSDLException(SOAPMessages.MESSAGES.couldNotFindAPortDefinitionWithinService(wsdlService.getQName().toString()), null); + } + } else { + Iterator ports = wsdlService.getPorts().values().iterator(); + while (ports.hasNext()) { + Port wsdlPort = ports.next(); + if (wsdlPort.getName().equals(name)) { + port = wsdlPort; + break; + } + } + } + if (port == null) { + throw new WSDLException(SOAPMessages.MESSAGES.couldNotFindPortInTheService(portName.toString(), wsdlService.getQName().toString()), null); + } + return port; + } + + /** + * Get the style for the port binding. + * @param port The WSDL port. + * @return The style, can be 'document' or 'rpc'. + */ + @SuppressWarnings("unchecked") + public static String getStyle(Port port) { + String portStyle = null; + String bindingStyle = null; + for (ExtensibilityElement element : (List) port.getBinding().getExtensibilityElements()) { + if ((element instanceof SOAPBinding) && (((SOAPBinding)element).getStyle() != null)) { + bindingStyle = ((SOAPBinding) element).getStyle(); + } else if ((element instanceof SOAP12Binding) && (((SOAP12Binding)element).getStyle() != null)) { + bindingStyle = ((SOAP12Binding) element).getStyle(); + } + if (bindingStyle != null) { + portStyle = bindingStyle.toLowerCase(); + } + } + + String operationStyle = null; + String currentOperationStyle = null; + for (BindingOperation operation : (List) port.getBinding().getBindingOperations()) { + for (ExtensibilityElement element : (List) operation.getExtensibilityElements()) { + if (element instanceof SOAPOperation) { + currentOperationStyle = ((SOAPOperation) element).getStyle(); + } else if (element instanceof SOAP12Operation) { + currentOperationStyle = ((SOAP12Operation) element).getStyle(); + } + if (currentOperationStyle != null) { + if (operationStyle != null && !currentOperationStyle.equals(operationStyle)) { + throw SOAPMessages.MESSAGES.incompatibleStyleOfSoapOperationLevelBindingsDetected(); + } + operationStyle = currentOperationStyle; + } + } + } + + if (operationStyle != null && portStyle != null) { + if (!portStyle.equals(operationStyle)) { + throw SOAPMessages.MESSAGES.detectedMixingDifferentSoapBindingStyleOnPortTypeAndOperationLevel(); + } + return portStyle; + } else if (portStyle != null) { + return portStyle; + } else if (operationStyle != null) { + return operationStyle; + } + return DOCUMENT; //default + } + + /** + * Get the SOAP {@link Operation} instance for the specified message element. + * + * @param port The WSDL port. + * @param elementName The SOAP Body element QName. + * @param documentStyle true if it is 'document', false if 'rpc'. + * @return The Operation instance, or null if the operation was not found on the port. + */ + public static Operation getOperationByElement(Port port, QName elementName, Boolean documentStyle) { + List operations = port.getBinding().getPortType().getOperations(); + + for (Operation operation : operations) { + if (!documentStyle && (elementName.getLocalPart().equals(operation.getName()))) { + return operation; + } else { + // Note: WS-I Profile allows only one child under SOAPBody. + Part part = (Part)operation.getInput().getMessage().getParts().values().iterator().next(); + if ((part.getElementName() != null) && elementName.equals(part.getElementName()) + || (part.getTypeName() != null) && elementName.equals(part.getTypeName())) { + return operation; + } else if (elementName.getLocalPart().equals(operation.getName())) { + return operation; + } + } + } + return null; + } + + /** + * Get the {@link Operation} instance for the specified SOAP operation name. + * @param port The WSDL port. + * @param operationName The SOAP Body element name. + * @return The Operation instance, or null if the operation was not found on the port. + */ + public static Operation getOperationByName(Port port, String operationName) { + Operation operation = null; + List operationList = port.getBinding().getPortType().getOperations(); + + for (Operation op : operationList) { + if (op.getName().equals(operationName)) { + operation = op; + break; + } + } + return operation; + } + + /** + * Get the SOAP Binding Id for the specified {@link Port}. + * + * @param port The WSDL port. + * @param mtomEnabled MTOM feature boolean + * @return The SOAPBinding Id found on the port. + */ + public static String getBindingId(Port port, Boolean mtomEnabled) { + String bindingId = null; + List extElements = port.getExtensibilityElements(); + for (ExtensibilityElement extElement : extElements) { + if (extElement instanceof SOAP12Address) { + if (mtomEnabled) { + bindingId = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_MTOM_BINDING; + } else { + bindingId = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING; + } + break; + } else { + if (mtomEnabled) { + bindingId = javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_MTOM_BINDING; + } else { + bindingId = javax.xml.ws.soap.SOAPBinding.SOAP11HTTP_BINDING; + } + break; + } + } + return bindingId; + } + + /** + * Get the SOAP Binding Id for the specified {@link Port}. + * + * @param port The WSDL port. + * @return The endpoint address. + */ + public static String getEndpointAddress(Port port) { + String address = null; + List extElements = port.getExtensibilityElements(); + for (ExtensibilityElement extElement : extElements) { + if (extElement instanceof SOAPAddress) { + address = ((SOAPAddress)extElement).getLocationURI(); + break; + } else if (extElement instanceof SOAP12Address) { + address = ((SOAP12Address)extElement).getLocationURI(); + break; + } + } + return address; + } + + /** + * Check if we are invoking a @Oneway annotated method. + * + * @param port The WSDL service port. + * @param elementName The SOAP Body element QName. + * @param documentStyle true if it is 'document', false if 'rpc'. + * @return True if there is no response to be expected. + */ + public static boolean isOneWay(final Port port, final QName elementName, Boolean documentStyle) { + // Overloaded methods not supported + // Encrypted messages will be treated as request-response as it cannot be decrypted + Operation operation = getOperationByElement(port, elementName, documentStyle); + return isOneWay(operation); + } + + /** + * Check if we are invoking a @Oneway annotated method. + * + * @param operation The WSDL Operation. + * @return True if there is no response to be expected. + */ + public static boolean isOneWay(final Operation operation) { + boolean isOneWay = false; + if (operation != null) { + isOneWay = operation.getStyle().equals(OperationType.ONE_WAY); + } + return isOneWay; + } + + /** + * Get the SOAP {@link BindingOperation} instance for the specified SOAP operation name. + * @param port The WSDL port. + * @param elementName The SOAP Body element QName. + * @param documentStyle true if it is 'document', false if 'rpc'. + * @return The BindingOperation instance, or null if the operation was not found on the port. + */ + public static BindingOperation getBindingOperation(Port port, QName elementName, Boolean documentStyle) { + Operation operation = getOperationByElement(port, elementName, documentStyle); + if (operation != null) { + List bindingOperations = port.getBinding().getBindingOperations(); + for (BindingOperation bindingOperation : bindingOperations) { + if (bindingOperation.getName().equals(operation.getName())) { + return bindingOperation; + } + } + } + return null; + } + + /** + * Get the soapAction value for a given operation. + * + * @param port The WSDL service port. + * @param elementName The SOAP Body element QName. + * @param documentStyle true if it is 'document', false if 'rpc'. + * @return the soapAction value if it exists. + */ + public static String getSoapAction(final Port port, final QName elementName, Boolean documentStyle) { + // Overloaded methods not supported + BindingOperation operation = getBindingOperation(port, elementName, documentStyle); + return getSoapAction(operation); + } + + /** + * Get the soapAction value for a given operation. + * + * @param operation The WSDL BindingOperation. + * @return the soapAction value if it exists. + */ + public static String getSoapAction(final BindingOperation operation) { + String soapActionUri = ""; + if (operation != null) { + List extElements = operation.getExtensibilityElements(); + for (ExtensibilityElement extElement : extElements) { + if (extElement instanceof SOAPOperation) { + soapActionUri = ((SOAPOperation) extElement).getSoapActionURI(); + break; + } else if (extElement instanceof SOAP12Operation) { + SOAP12Operation soapOperation = ((SOAP12Operation) extElement); + Boolean soapActionRequired = soapOperation.getSoapActionRequired(); + if ((soapActionRequired == null) || soapActionRequired) { + soapActionUri = soapOperation.getSoapActionURI(); + } + break; + } + } + } + return soapActionUri; + } + + /** + * Get the input action value for a given operation. + * + * @param port The WSDL service port. + * @param operationName The SOAP Operation element QName. + * @param documentStyle true if it is 'document', false if 'rpc'. + * @return the input action value. + */ + public static String getInputAction(final Port port, final QName operationName, Boolean documentStyle) { + // Overloaded methods not supported + Operation operation = getOperationByElement(port, operationName, documentStyle); + String action = null; + String targetNamespace = operationName.getNamespaceURI(); + for (QName attribute : (Set)operation.getInput().getExtensionAttributes().keySet()) { + if (attribute.equals(WSDL_ACTION_QNAME)) { + Object value = operation.getInput().getExtensionAttribute(WSDL_ACTION_QNAME); + if (value != null) { + action = ((QName)value).getLocalPart(); + break; + } + } + } + + if (action == null) { + // http://www.w3.org/TR/2006/WD-ws-addr-wsdl-20060216/#defactionwsdl11 + // [target namespace][delimiter][port type name][delimiter][input name] + String delimiter = targetNamespace.startsWith(SCHEME_URN) ? STR_COLON : STR_SLASH; + String namespace = targetNamespace.endsWith(delimiter) ? targetNamespace.substring(0, targetNamespace.length()-2) : targetNamespace; + if (operation.getInput().getName() != null) { + action = namespace + delimiter + port.getBinding().getPortType().getQName().getLocalPart() + delimiter + operation.getInput().getName(); + } else { + action = namespace + delimiter + port.getBinding().getPortType().getQName().getLocalPart() + delimiter + operation.getName() + REQUEST_SUFFIX; + } + } + + return action; + } + + /** + * Get the output action value for a given operation. + * + * @param port The WSDL service port. + * @param operationName The SOAP Operation element QName. + * @param documentStyle true if it is 'document', false if 'rpc'. + * @return the output action value. + */ + public static String getOutputAction(final Port port, final QName operationName, Boolean documentStyle) { + // Overloaded methods not supported + Operation operation = getOperationByElement(port, operationName, documentStyle); + String action = null; + String targetNamespace = operationName.getNamespaceURI(); + + for (QName attribute : (Set)operation.getOutput().getExtensionAttributes().keySet()) { + if (attribute.equals(WSDL_ACTION_QNAME)) { + Object value = operation.getOutput().getExtensionAttribute(WSDL_ACTION_QNAME); + if (value != null) { + action = ((QName)value).getLocalPart(); + break; + } + } + } + + if (action == null) { + // http://www.w3.org/TR/2006/WD-ws-addr-wsdl-20060216/#defactionwsdl11 + // [target namespace][delimiter][port type name][delimiter][output name] + String delimiter = targetNamespace.startsWith(SCHEME_URN) ? STR_COLON : STR_SLASH; + String namespace = targetNamespace.endsWith(delimiter) ? targetNamespace.substring(0, targetNamespace.length()-2) : targetNamespace; + if (operation.getOutput().getName() != null) { + action = namespace + delimiter + port.getBinding().getPortType().getQName().getLocalPart() + delimiter + operation.getOutput().getName(); + } else { + action = namespace + delimiter + port.getBinding().getPortType().getQName().getLocalPart() + delimiter + operation.getName() + RESPONSE_SUFFIX; + } + } + + return action; + } + + /** + * Get the fault action value for a given operation. + * + * @param port The WSDL service port. + * @param operationName The SOAP Operation element QName. + * @param faultName The fault name. + * @param documentStyle true if it is 'document', false if 'rpc'. + * @return the fault action value. + */ + public static String getFaultAction(final Port port, final QName operationName, String faultName, Boolean documentStyle) { + // Overloaded methods not supported + Operation operation = getOperationByElement(port, operationName, documentStyle); + + if (operation.getFault(faultName) == null) { + throw SOAPMessages.MESSAGES.faultNameNotFoundOnOperation(faultName, operationName.getLocalPart()); + } + return getFaultAction(operation.getFault(faultName), port, operationName); + + } + + /** + * Get the fault action value for a given operation. + * + * @param fault The WSDL Fault. + * @param port The WSDL service port. + * @param operationName The SOAP Operation element QName. + * @return the fault action value. + */ + public static String getFaultAction(final Fault fault, final Port port, final QName operationName) { + String action = null; + String targetNamespace = operationName.getNamespaceURI(); + Object value = fault.getExtensionAttribute(WSDL_ACTION_QNAME); + if (value != null) { + action = ((QName)value).getLocalPart(); + } + + if (action == null) { + // http://www.w3.org/TR/2006/WD-ws-addr-wsdl-20060216/#defactionwsdl11 + // [target namespace][delimiter][port type name][delimiter][operation name][delimiter]Fault[delimiter][fault name] + String delimiter = targetNamespace.startsWith(SCHEME_URN) ? STR_COLON : STR_SLASH; + String namespace = targetNamespace.endsWith(delimiter) ? targetNamespace.substring(0, targetNamespace.length()-2) : targetNamespace; + action = namespace + delimiter + port.getBinding().getPortType().getQName().getLocalPart() + delimiter + + operationName.getLocalPart() + delimiter + STR_FAULT + delimiter + fault.getName(); + } + + return action; + } + + /** + * Get the fault QName. + * + * @param operation The WSDL operation. + * @param faultName the name of the Fault + * @return the fault QName or null. + */ + public static QName getFaultQName(final Operation operation, final String faultName) { + Fault fault = operation.getFault(faultName); + QName qName = null; + if (fault != null) { + qName = fault.getMessage().getQName(); + } + return qName; + } + + /** + * Get enabled features. + * + * @param definition The WSDL definition. + * @param port The WSDL service port. + * @param documentStyle true if it is 'document', false if 'rpc'. + * @return the feature booleans. + */ + public static Feature getFeature(final Definition definition, final Port port, Boolean documentStyle) { + Feature feature = new Feature(); + Boolean addressing = false; + Boolean mtom = false; + List extensibilityElements = getExtensibilityElements(definition); + if (documentStyle) { + // Check if any element uses xmime:expectedContentTypes + for (ExtensibilityElement element : extensibilityElements) { + if (element instanceof Schema) { + mtom = setMtomEnabled((Schema)element); + if (mtom) { + feature.setMtomEnabled(true); + break; + } + } + } + } else { + // Check if any part uses xmime:expectedContentTypes + for (Message message : ((Map)definition.getMessages()).values()) { + for (Part part : (List)message.getOrderedParts(null)) { + if (part.getExtensionAttribute(MTOM_EXPT_QNAME) != null) { + feature.setMtomEnabled(true); + } + } + } + } + +outer: for (ExtensibilityElement element : (List)port.getBinding().getExtensibilityElements()) { + if (element instanceof UnknownExtensibilityElement) { + String attrValue = null; + Element domElement = ((UnknownExtensibilityElement)element).getElement(); + if (element.getElementType().equals(USING_WSA_QNAME)) { + feature.setAddressingEnabled(true); + setAddressingRequired(feature, domElement); + break; + } else if (element.getElementType().equals(POLICY_REFERENCE_QNAME)) { + String uri = XMLHelper.getAttribute(domElement, WSDL11_URI, ATTR_URI); + /*if (uri == null) { + uri = XMLHelper.getAttribute(domElement, WSDL20_URI, ATTR_URI); + }*/ + if (uri == null) { + throw SOAPMessages.MESSAGES.policyReferenceURIMissingFor(port.getBinding().getQName().getLocalPart()); + } + uri = uri.substring(1); + for (ExtensibilityElement defElement : extensibilityElements) { + if (defElement.getElementType().equals(POLICY_QNAME)) { + Element defDomElement = ((UnknownExtensibilityElement)defElement).getElement(); + attrValue = XMLHelper.getAttribute(defDomElement, SECURITY_UTILITY_URI, ATTR_ID); + if ((attrValue != null) + && attrValue.equals(uri)) { + // Addressing + if (!addressing) { + addressing = setAddressingEnabled(feature, defDomElement); + } + // MTOM + if (!mtom) { + mtom = setMtomEnabled(feature, defDomElement); + } + if (addressing && mtom) { + break outer; + } + } + } + } + } + } + } + return feature; + } + + private static List getExtensibilityElements(Definition definition) { + List elements = new ArrayList(); + Types types = definition.getTypes(); + if (types != null) { + elements.addAll(definition.getExtensibilityElements()); + elements.addAll(types.getExtensibilityElements()); + } + Iterator> wsdlImports = definition.getImports().values().iterator(); + while (wsdlImports.hasNext()) { + List imports = wsdlImports.next(); + int size = imports.size(); + for (int i = 0; i < size; i++) { + elements.addAll(getExtensibilityElements(imports.get(i).getDefinition())); + } + } + return elements; + } + + private static Boolean setAddressingEnabled(Feature feature, Element defDomElement) { + Element child = XMLHelper.getFirstChildElementByName(defDomElement, ELE_ADDRESSING); + if (child != null) { + feature.setAddressingEnabled(true); + setAddressingRequired(feature, child); + return true; + } else { + child = XMLHelper.getFirstChildElementByName(defDomElement, ELE_EXACTLYONE); + if (child != null) { + child = XMLHelper.getFirstChildElementByName(child, ELE_ALL); + while (child != null) { + Element addressingEle = XMLHelper.getFirstChildElementByName(child, ELE_ADDRESSING); + if (addressingEle != null) { + feature.setAddressingEnabled(true); + setAddressingRequired(feature, addressingEle); + return true; + } + child = XMLHelper.getNextSiblingElementByName(child, ELE_ALL); + } + } + } + return false; + } + + private static void setAddressingRequired(Feature feature, Element element) { + String attrValue = XMLHelper.getAttribute(element, WSDL11_URI, ATTR_REQUIRED); + /*if (attrValue == null) { + attrValue = XMLHelper.getAttribute(element, WSDL20_URI, ATTR_REQUIRED); + }*/ + if (attrValue != null) { + feature.setAddressingRequired(Boolean.valueOf(attrValue)); + } + } + + private static Boolean setMtomEnabled(Feature feature, Element defDomElement) { + Element child = XMLHelper.getFirstChildElementByName(defDomElement, ELE_MTOM); + if (child != null) { + feature.setMtomEnabled(true); + return true; + } else { + child = XMLHelper.getFirstChildElementByName(defDomElement, ELE_EXACTLYONE); + if (child != null) { + child = XMLHelper.getFirstChildElementByName(child, ELE_ALL); + while (child != null) { + Element addressingEle = XMLHelper.getFirstChildElementByName(child, ELE_MTOM); + if (addressingEle != null) { + feature.setMtomEnabled(true); + return true; + } + child = XMLHelper.getNextSiblingElementByName(child, ELE_ALL); + } + } + } + return false; + } + + // Caution: recursive + private static Boolean setMtomEnabled(Schema schema) { + if (schema != null) { + if (hasExpectedContentTypes(schema.getElement())) { + return true; + } + for (List c : ((Map>)schema.getImports()).values()) { + for (SchemaImport simport : c) { + if (setMtomEnabled(simport.getReferencedSchema())) { + return true; + } + } + } + } + return false; + } + + // Caution: recursive + private static Boolean hasExpectedContentTypes(Element element) { + if (element != null) { + if (XMLHelper.hasAttribute(element, WSDL_XMIME_URI, ATTR_EXP_CT)) { + return true; + } + NodeList children = element.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node node = children.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (hasExpectedContentTypes((Element)node)) { + return true; + } + } + } + } + return false; + } + + /** + * Given a Port construct the Exchange Contracts for all Operations. + * + * @param port The WSDL service port. + * @param service The SwitchYard service. + * @return A Map of exchange contracts. + * @throws WebServicePublishException If the WSDL does not match the Service operations. + + public static Map getContracts(final Port port, final org.switchyard.ServiceReference service) throws WebServicePublishException { + Map contracts = new HashMap(); + List operations = port.getBinding().getPortType().getOperations(); + if ((operations == null) || operations.isEmpty()) { + throw SOAPMessages.MESSAGES.invalidWSDLNoOperationsFound(); + } + for (Operation operation : operations) { + String name = operation.getName(); + ServiceOperation targetServiceOperation = service.getInterface().getOperation(name); + if (targetServiceOperation == null) { + throw SOAPMessages.MESSAGES.wSDLOperationNotFoundInService(name, service.getName()); + } + ExchangePattern wsdlExchangePattern = getExchangePattern(operation); + if (targetServiceOperation.getExchangePattern() != wsdlExchangePattern) { + throw SOAPMessages.MESSAGES.wSDLOperationDoesNotMatchServiceOperation(name, targetServiceOperation.getName()); + } + BaseExchangeContract exchangeContract = new BaseExchangeContract(targetServiceOperation); + BaseInvocationContract soapMetaData = exchangeContract.getInvokerInvocationMetaData(); + List parts = operation.getInput().getMessage().getOrderedParts(null); + if (parts.isEmpty()) { + throw SOAPMessages.MESSAGES.wSDLOperationDoesNotHaveAnyInputMessageParts(name); + } + // Only one Part (one child of the soap:body) allowed per WS-I Basic Profile similar to Document/Literal wrapped + QName inputMessageQName = parts.get(0).getElementName(); + soapMetaData.setInputType(inputMessageQName); + soapMetaData.setFaultType(SOAP_FAULT_MESSAGE_TYPE); + + if (!isOneWay(operation)) { + parts = operation.getOutput().getMessage().getOrderedParts(null); + if (parts.isEmpty()) { + throw SOAPMessages.MESSAGES.wSDLOperationDoesNotHaveAnyOuputMessageParts(name); + } + // Only one Part (one child of the soap:body) allowed per WS-I Basic Profile similar to Document/Literal wrapped + QName outputMessageQName = parts.get(0).getElementName(); + soapMetaData.setOutputType(outputMessageQName); + } + contracts.put(name, exchangeContract); + } + return contracts; + } + */ + + /** + * Get the exchange pattern for the specified WS Operation. + * + * @param operation The operation to check for. + * @return The Exchange Pattern. + */ + public static ExchangePattern getExchangePattern(final Operation operation) { + if (operation.getStyle().equals(OperationType.ONE_WAY)) { + return ExchangePattern.IN_ONLY; + } else { + return ExchangePattern.IN_OUT; + } + } +} diff --git a/components/soap/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory b/components/soap/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory new file mode 100644 index 000000000..6361d1cfa --- /dev/null +++ b/components/soap/src/main/resources/META-INF/services/org.switchyard.component.common.composer.ContextMapperFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.soap.composer.SOAPContextMapperFactory diff --git a/components/soap/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory b/components/soap/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory new file mode 100644 index 000000000..9eab31b10 --- /dev/null +++ b/components/soap/src/main/resources/META-INF/services/org.switchyard.component.common.composer.MessageComposerFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.soap.composer.SOAPMessageComposerFactory diff --git a/components/soap/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/components/soap/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..1d55b0436 --- /dev/null +++ b/components/soap/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.component.soap.deploy.SOAPComponent diff --git a/components/soap/src/main/resources/META-INF/switchyard/transforms.xml b/components/soap/src/main/resources/META-INF/switchyard/transforms.xml new file mode 100644 index 000000000..81c73c2a8 --- /dev/null +++ b/components/soap/src/main/resources/META-INF/switchyard/transforms.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + diff --git a/components/soap/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/components/soap/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 000000000..6edafe3ad --- /dev/null +++ b/components/soap/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/components/soap/src/main/resources/OSGI-INF/blueprint/transformers.xml b/components/soap/src/main/resources/OSGI-INF/blueprint/transformers.xml new file mode 100644 index 000000000..d7c903944 --- /dev/null +++ b/components/soap/src/main/resources/OSGI-INF/blueprint/transformers.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v1/soap_1_0.xsd b/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v1/soap_1_0.xsd new file mode 100644 index 000000000..2b59db7f2 --- /dev/null +++ b/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v1/soap_1_0.xsd @@ -0,0 +1,263 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + A WSDL file name that can be found in classpath else can be a file://, http:// or https:// URL location. + + + + + Specify the WSDL port to be used. The string can be in the form {namespaceURI}serviceName:portName", with the "{namespaceURI}" and "serviceName:" part being optional. + + + + + + + Specify the IP Socket Address to be used. The string can be in the form "hostName/ipAddress:portNumber", with the "hostName/ipAddress:" or ":portNumber" part being optional. Applicable only for service bindings. + + + + + The context path used in the HTTP URL where the endpoint will be hosted. Applicable only for service bindings. + + + + + The JBossWS @EndpointConfig to add + + + + + + + The endpoint address override. Applicable only for reference bindings. + + + + + + + + + Http proxy settings. + + + + + + + Mtom feature override. By default this feature is enabled. Use this to disable or change threshold value. + + + + + The Apache CXF @InInterceptors to add + + + + + The Apache CXF @OutInterceptors to add + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Type. Default is HTTP. Allowed values are HTTP and SOCKS + + + + + Proxy Host. + + + + + Proxy Port. + + + + + Proxy user name. + + + + + Proxy password. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v1/soap_1_1.xsd b/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v1/soap_1_1.xsd new file mode 100644 index 000000000..3da02ec48 --- /dev/null +++ b/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v1/soap_1_1.xsd @@ -0,0 +1,268 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + A WSDL file name that can be found in classpath else can be a file://, http:// or https:// URL location. + + + + + Specify the WSDL port to be used. The string can be in the form {namespaceURI}serviceName:portName", with the "{namespaceURI}" and "serviceName:" part being optional. + + + + + + + Specify the IP Socket Address to be used. The string can be in the form "hostName/ipAddress:portNumber", with the "hostName/ipAddress:" or ":portNumber" part being optional. Applicable only for service bindings. + + + + + The context path used in the HTTP URL where the endpoint will be hosted. Applicable only for service bindings. + + + + + The JBossWS @EndpointConfig to add + + + + + + + The endpoint address override. Applicable only for reference bindings. + + + + + The request's time-out value in milliseconds. + + + + + + + + + Http proxy settings. + + + + + + + Mtom feature override. By default this feature is enabled. Use this to disable or change threshold value. + + + + + The Apache CXF @InInterceptors to add + + + + + The Apache CXF @OutInterceptors to add + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Type. Default is HTTP. Allowed values are HTTP and SOCKS + + + + + Proxy Host. + + + + + Proxy Port. + + + + + Proxy user name. + + + + + Proxy password. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v2/soap_2_0.xsd b/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v2/soap_2_0.xsd new file mode 100644 index 000000000..d05440e7f --- /dev/null +++ b/components/soap/src/main/resources/org/switchyard/component/soap/config/model/v2/soap_2_0.xsd @@ -0,0 +1,269 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Specify the ContextMapper to be used. + + + + + Specify the MessageComposer to be used. + + + + + A WSDL file name that can be found in classpath else can be a file://, http:// or https:// URL location. + + + + + Specify the WSDL port to be used. The string can be in the form {namespaceURI}serviceName:portName", with the "{namespaceURI}" and "serviceName:" part being optional. + + + + + + + Specify the IP Socket Address to be used. The string can be in the form "hostName/ipAddress:portNumber", with the "hostName/ipAddress:" or ":portNumber" part being optional. Applicable only for service bindings. + + + + + The context path used in the HTTP URL where the endpoint will be hosted. Applicable only for service bindings. + + + + + The JBossWS @EndpointConfig to add + + + + + + + The endpoint address override. Applicable only for reference bindings. + + + + + The request's time-out value in milliseconds. + + + + + + + + + Http proxy settings. + + + + + + + Mtom feature override. By default this feature is enabled. Use this to disable or change threshold value. + + + + + The Apache CXF @InInterceptors to add + + + + + The Apache CXF @OutInterceptors to add + + + + + + + + + + + + + + User name. + + + + + Password. + + + + + + + + + + + + + The NTLM Domain. + + + + + + + + + + + + + Proxy Type. Default is HTTP. Allowed values are HTTP and SOCKS + + + + + Proxy Host. + + + + + Proxy Port. + + + + + Proxy user name. + + + + + Proxy password. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/main/resources/org/switchyard/component/soap/endpoint/jaxws-handlers.xml b/components/soap/src/main/resources/org/switchyard/component/soap/endpoint/jaxws-handlers.xml new file mode 100644 index 000000000..631248fc7 --- /dev/null +++ b/components/soap/src/main/resources/org/switchyard/component/soap/endpoint/jaxws-handlers.xml @@ -0,0 +1,8 @@ + + + + + org.switchyard.component.soap.InboundResponseHandler + + + diff --git a/components/soap/src/main/resources/org/switchyard/config/model/descriptor.properties b/components/soap/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..6b1e5f8bc --- /dev/null +++ b/components/soap/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +soap_1_0.section=urn:switchyard-component-soap:config +soap_1_0.version=1.0 +soap_1_0.namespace=urn:switchyard-component-soap:config:1.0 +soap_1_0.schema=soap_1_0.xsd +soap_1_0.location=/org/switchyard/component/soap/config/model/v1/ +soap_1_0.marshaller=org.switchyard.component.soap.config.model.v1.V1SOAPMarshaller + +soap_1_1.section=urn:switchyard-component-soap:config +soap_1_1.version=1.1 +soap_1_1.namespace=urn:switchyard-component-soap:config:1.1 +soap_1_1.schema=soap_1_1.xsd +soap_1_1.location=/org/switchyard/component/soap/config/model/v1/ +soap_1_1.marshaller=org.switchyard.component.soap.config.model.v1.V1SOAPMarshaller + +soap_2_0.section=urn:switchyard-component-soap:config +soap_2_0.version=2.0 +soap_2_0.namespace=urn:switchyard-component-soap:config:2.0 +soap_2_0.schema=soap_2_0.xsd +soap_2_0.location=/org/switchyard/component/soap/config/model/v2/ +soap_2_0.marshaller=org.switchyard.component.soap.config.model.v2.V2SOAPMarshaller diff --git a/components/soap/src/test/java/org/switchyard/component/soap/AuthenticationTest.java b/components/soap/src/test/java/org/switchyard/component/soap/AuthenticationTest.java new file mode 100644 index 000000000..aaff49f63 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/AuthenticationTest.java @@ -0,0 +1,167 @@ +/* + * Copyright Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.URL; +import java.util.HashSet; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.common.net.SocketAddr; +import org.switchyard.component.soap.config.model.NtlmAuthModel; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.config.model.SOAPNamespace; +import org.switchyard.component.soap.config.model.v1.V1NtlmAuthModel; +import org.switchyard.component.soap.config.model.v1.V1SOAPBindingModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.SwitchYardRunner; + +/** + * Contains tests for Http authentication support on SOAPGateway. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class AuthenticationTest { + + private static final String METHOD_NAME = "sayHello"; + + private static final String input = "" + + " Magesh" + + ""; + private static final String output = "" + + " Hello Magesh! The soapAction received is " + + ""; + + private ServiceDomain _domain; + + @org.switchyard.test.ServiceOperation("auth-required") + private Invoker _authConsumerService1; + @org.switchyard.test.ServiceOperation("all-is-well") + private Invoker _authConsumerService2; + + private SOAPBindingModel _config; + private InboundHandler _soapInbound; + + private static ModelPuller _puller; + + + @Before + public void setUp() throws Exception { + String host = System.getProperty("org.switchyard.test.soap.host", "localhost"); + String port = System.getProperty("org.switchyard.test.soap.port", "8080"); + + _puller = new ModelPuller(); + + // Provide a switchyard service + CompositeModel composite = _puller.pull("/HelloSwitchYard.xml", getClass()); + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (SOAPBindingModel)compositeService.getBindings().get(0); + _config.setSocketAddr(new SocketAddr(host, Integer.parseInt(port))); + _domain.registerService(_config.getServiceName(), new HelloWebServiceInterface(), new SOAPProvider()); + _domain.registerServiceReference(_config.getServiceName(), new HelloWebServiceInterface()); + + // Service exposed as WS + _soapInbound = new InboundHandler(_config, _domain); + _soapInbound.start(); + + URL serviceURL = new URL("http://" + host + ":" + port + "/HelloWebService"); + + SOAPBindingModel config = new V1SOAPBindingModel(SOAPNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config.setWsdl(serviceURL.toExternalForm() + "?wsdl"); + config.setServiceName(_authConsumerService1.getServiceName()); + config.setName("auth-test"); + config.setEndpointAddress("http://192.168.169.4/index.htm"); + + // Service consumer or Reference binding + OutboundHandler soapProxyOutbound1 = new OutboundHandler(config); + soapProxyOutbound1.start(); + _domain.registerService(_authConsumerService1.getServiceName(), new HelloWebServiceInterface(), soapProxyOutbound1); + + NtlmAuthModel auth = new V1NtlmAuthModel(SOAPNamespace.DEFAULT.uri()); + auth.setUser("SwitchYard"); + auth.setPassword("JBoss123!"); + auth.setDomain("JBOSS"); + config.setNtlmAuthConfig(auth); + config.setServiceName(_authConsumerService2.getServiceName()); + + // Service consumer or Reference binding + OutboundHandler soapProxyOutbound2 = new OutboundHandler(config); + soapProxyOutbound2.start(); + _domain.registerService(_authConsumerService2.getServiceName(), new HelloWebServiceInterface(), soapProxyOutbound2); + } + + @After + public void tearDown() throws Exception { + _soapInbound.stop(); + } + + @Ignore // This can be tested only offline. + @Test + public void authenticationMissing() throws Exception { + try { + Message responseMsg = _authConsumerService1.operation(METHOD_NAME).sendInOut(input); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("401: Unauthorized")); + } + } + + @Ignore // This can be tested only offline. + @Test + public void allIsWell() throws Exception { + try { + Message responseMsg = _authConsumerService2.operation(METHOD_NAME).sendInOut(input); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + // Because the local server is not setup with a SOAP Endpoint or to allow POST method. + // If we get to this point then we are good. + Assert.assertTrue(baos.toString().contains("405: Method Not Allowed")); + } + } + + private static class HelloWebServiceInterface extends BaseService { + private static Set _operations = new HashSet(1); + static { + _operations.add(new InOutOperation(METHOD_NAME)); + } + public HelloWebServiceInterface() { + super(_operations); + } + } +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/DoclitSOAPProvider.java b/components/soap/src/test/java/org/switchyard/component/soap/DoclitSOAPProvider.java new file mode 100644 index 000000000..2735e8df6 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/DoclitSOAPProvider.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.soap.util.SOAPUtil; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * A mock up WebService provider. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class DoclitSOAPProvider extends BaseHandler { + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + if (exchange.getContract().getProviderOperation().getExchangePattern().equals(ExchangePattern.IN_OUT)) { + String response = null; + Message message = exchange.createMessage(); + + Node request = exchange.getMessage().getContent(Node.class); + Element orderId = XMLHelper.getFirstChildElementByName(request, "orderId"); + + if(orderId != null && orderId.getFirstChild().getNodeValue().equals("PO-19838-XYZ")){ + + response = "" + + "" + + "" + + "PO-19838-XYZ" + + "true" + + "Order Accepted" + + "" + + "" + + ""; + + }else{ + response = "" + + " soap:Server.AppError" + + " Invalid soap request" + + " " + + " The soap request does not look like what we have expected" + + " 9999" + + " " + + ""; + } + + setContent(message, response); + exchange.send(message); + } + } + + private void setContent(Message message, String response) { + try { + Document responseDom = SOAPUtil.parseAsDom(response); + message.setContent(responseDom.getDocumentElement()); + } catch (Exception e) { + // Generate fault + } + } +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/HttpProxyTest.java b/components/soap/src/test/java/org/switchyard/component/soap/HttpProxyTest.java new file mode 100644 index 000000000..ee8e9163b --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/HttpProxyTest.java @@ -0,0 +1,206 @@ +/* + * Copyright Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.URL; +import java.util.HashSet; +import java.util.Set; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.littleshoot.proxy.DefaultHttpProxyServer; +import org.littleshoot.proxy.HttpProxyServer; +import org.littleshoot.proxy.ProxyAuthorizationHandler; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.common.net.SocketAddr; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.soap.config.model.ProxyModel; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.config.model.SOAPNamespace; +import org.switchyard.component.soap.config.model.v1.V1ProxyModel; +import org.switchyard.component.soap.config.model.v1.V1SOAPBindingModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.SwitchYardRunner; +import org.w3c.dom.Node; + +/** + * Contains tests for Http proxy support on SOAPGateway. Thanks to alessio.soldano@jboss.com! + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class HttpProxyTest { + + private static final int PROXYPORT = 9090; + private static final String PROXY_USER = "foo"; + private static final String PROXY_PWD = "bar"; + private static final String METHOD_NAME = "sayHello"; + + private static final String input = "" + + " Magesh" + + ""; + private static final String output = "" + + " Hello Magesh! The soapAction received is " + + ""; + + private ServiceDomain _domain; + + @org.switchyard.test.ServiceOperation("unknown-host") + private Invoker _proxyConsumerService1; + @org.switchyard.test.ServiceOperation("proxy-auth-required") + private Invoker _proxyConsumerService2; + @org.switchyard.test.ServiceOperation("all-is-well") + private Invoker _proxyConsumerService3; + + private SOAPBindingModel _config; + private InboundHandler _soapInbound; + + private static ModelPuller _puller; + private HttpProxyServer _proxyServer; + + + @Before + public void setUp() throws Exception { + String host = System.getProperty("org.switchyard.test.soap.host", "localhost"); + String port = System.getProperty("org.switchyard.test.soap.port", "8080"); + _proxyServer = new DefaultHttpProxyServer(PROXYPORT); + ProxyAuthorizationHandler authorizationHandler = new ProxyAuthorizationHandler() { + @Override + public boolean authenticate(String user, String pwd) { + return (PROXY_USER.equals(user) && PROXY_PWD.equals(pwd)); + } + }; + _proxyServer.addProxyAuthenticationHandler(authorizationHandler); + _proxyServer.start(); + + _puller = new ModelPuller(); + + // Provide a switchyard service + CompositeModel composite = _puller.pull("/HelloSwitchYard.xml", getClass()); + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (SOAPBindingModel)compositeService.getBindings().get(0); + _config.setSocketAddr(new SocketAddr(host, Integer.parseInt(port))); + _domain.registerService(_config.getServiceName(), new HelloWebServiceInterface(), new SOAPProvider()); + _domain.registerServiceReference(_config.getServiceName(), new HelloWebServiceInterface()); + + // Service exposed as WS + _soapInbound = new InboundHandler(_config, _domain); + _soapInbound.start(); + + URL serviceURL = new URL("http://" + host + ":" + port + "/HelloWebService"); + + SOAPBindingModel config = new V1SOAPBindingModel(SOAPNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config.setWsdl(serviceURL.toExternalForm() + "?wsdl"); + config.setServiceName(_proxyConsumerService1.getServiceName()); + config.setName("proxy-test"); + config.setEndpointAddress("http://unreachablehost/HelloWebService"); + + // Service consumer or Reference binding + OutboundHandler soapProxyOutbound1 = new OutboundHandler(config); + soapProxyOutbound1.start(); + _domain.registerService(_proxyConsumerService1.getServiceName(), new HelloWebServiceInterface(), soapProxyOutbound1); + + ProxyModel proxy = new V1ProxyModel(SOAPNamespace.DEFAULT.uri()); + proxy.setHost(host); + proxy.setPort("" + PROXYPORT); + config.setProxyConfig(proxy); + config.setEndpointAddress(serviceURL.toExternalForm()); + config.setServiceName(_proxyConsumerService2.getServiceName()); + + // Service consumer or Reference binding + OutboundHandler soapProxyOutbound2 = new OutboundHandler(config); + soapProxyOutbound2.start(); + _domain.registerService(_proxyConsumerService2.getServiceName(), new HelloWebServiceInterface(), soapProxyOutbound2); + + proxy.setUser(PROXY_USER); + proxy.setPassword(PROXY_PWD); + config.setProxyConfig(proxy); + config.setServiceName(_proxyConsumerService3.getServiceName()); + + // Service consumer or Reference binding + OutboundHandler soapProxyOutbound3 = new OutboundHandler(config); + soapProxyOutbound3.start(); + _domain.registerService(_proxyConsumerService3.getServiceName(), new HelloWebServiceInterface(), soapProxyOutbound3); + + XMLUnit.setIgnoreWhitespace(true); + } + + @After + public void tearDown() throws Exception { + _soapInbound.stop(); + _proxyServer.stop(); + } + + @Ignore // Can be tested offline + @Test + public void unknownHost() throws Exception { + try { + Message responseMsg = _proxyConsumerService1.operation(METHOD_NAME).sendInOut(input); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("UnknownHostException: unreachablehost")); + } + } + + @Test + public void authenticationMissing() throws Exception { + try { + Message responseMsg = _proxyConsumerService2.operation(METHOD_NAME).sendInOut(input); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("407: Proxy Authentication Required")); + } + } + + @Test + public void allIsWell() throws Exception { + Message responseMsg = _proxyConsumerService3.operation(METHOD_NAME).sendInOut(input); + String response = XMLHelper.toString(responseMsg.getContent(Node.class)); + XMLAssert.assertXMLEqual(output, response); + } + + private static class HelloWebServiceInterface extends BaseService { + private static Set _operations = new HashSet(1); + static { + _operations.add(new InOutOperation(METHOD_NAME)); + } + public HelloWebServiceInterface() { + super(_operations); + } + } +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/RPCLiteralTest.java b/components/soap/src/test/java/org/switchyard/component/soap/RPCLiteralTest.java new file mode 100644 index 000000000..54010a6be --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/RPCLiteralTest.java @@ -0,0 +1,151 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap; + +import java.io.StringWriter; +import java.net.URL; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.common.net.SocketAddr; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.config.model.SOAPNamespace; +import org.switchyard.component.soap.config.model.v1.V1SOAPBindingModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestKit; +import org.w3c.dom.Node; + +/** + * Tests for rpc literal. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class RPCLiteralTest { + + private SwitchYardTestKit _testKit; + + private ServiceDomain _domain = new ServiceDomainManager().createDomain(); + private SOAPBindingModel _config; + private static URL _serviceURL; + private InboundHandler _soapInbound; + private OutboundHandler _soapOutbound; + + @org.switchyard.test.ServiceOperation("webservice-consumer") + private Invoker consumerService; + + private static ModelPuller _puller; + + @Before + public void setUp() throws Exception { + + // Provide a switchyard service + RPClitSOAPProvider provider = new RPClitSOAPProvider(); + + String host = System.getProperty("org.switchyard.test.soap.host", "localhost"); + String port = System.getProperty("org.switchyard.test.soap.port", "48080"); + + _puller = new ModelPuller(); + CompositeModel composite = _puller.pull("/RPClitSwitchyard.xml", getClass()); + + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (SOAPBindingModel)compositeService.getBindings().get(0); + + _domain.registerService(_config.getServiceName(), new OrderServiceInterface(), provider); + _domain.registerServiceReference(_config.getServiceName(), new OrderServiceInterface()); + + _config.setSocketAddr(new SocketAddr(host, Integer.parseInt(port))); + + _soapInbound = new InboundHandler(_config, _domain); + + _soapInbound.start(); + + _serviceURL = new URL("http://" + host + ":" + port + "/OrderServiceRPC"); + + // A WS Consumer as Service + SOAPBindingModel config2 = new V1SOAPBindingModel(SOAPNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config2.setWsdl(_serviceURL.toExternalForm() + "?wsdl"); + config2.setServiceName(consumerService.getServiceName()); + config2.setName("testGateway"); + _soapOutbound = new OutboundHandler(config2); + _soapOutbound.start(); + _domain.registerService(consumerService.getServiceName(), new OrderServiceInterface(), _soapOutbound); + + XMLUnit.setIgnoreWhitespace(true); + } + + @After + public void tearDown() throws Exception { + // NOOP + } + + @Test + public void sendMessage() throws Exception { + + DOMSource domSource = new DOMSource(_testKit.readResourceDocument("/rpclit_request.xml")); + Message responseMsg = consumerService.operation("submitPhantomOrder").sendInOut(toString(domSource.getNode())); + String response = toString(responseMsg.getContent(Node.class)); + _testKit.compareXMLToResource(response, "/rpclit_response.xml"); + + } + + private static class OrderServiceInterface extends BaseService { + private static Set _operations = new HashSet(2); + static { + _operations.add(new InOutOperation("submitPhantomOrder")); + } + public OrderServiceInterface() { + super(_operations); + } + } + + private String toString(Node node) throws Exception + { + TransformerFactory transFactory = TransformerFactory.newInstance(); + Transformer transformer = transFactory.newTransformer(); + StringWriter sw = new StringWriter(); + DOMSource source = new DOMSource(node); + StreamResult result = new StreamResult(sw); + transformer.transform(source, result); + return sw.toString(); + } + +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/RPClitSOAPProvider.java b/components/soap/src/test/java/org/switchyard/component/soap/RPClitSOAPProvider.java new file mode 100644 index 000000000..3dd9ea570 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/RPClitSOAPProvider.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.soap.util.SOAPUtil; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * A mock up WebService provider. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RPClitSOAPProvider extends BaseHandler { + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + if (exchange.getContract().getProviderOperation().getExchangePattern().equals(ExchangePattern.IN_OUT)) { + String response = null; + Message message = exchange.createMessage(); + Node request = exchange.getMessage().getContent(Node.class); + Element orderId = XMLHelper.getFirstChildElementByName(request, "orderId"); + + if (orderId != null && orderId.getFirstChild().getNodeValue().equals("PO-121212-XYZ")) { + response = "" + + "" + + "" + + "PO-121212-XYZ" + + "true" + + "Order Accepted" + + "" + + "" + + ""; + } else { + response = "" + + " soap:Server.AppError" + + " Invalid soap request" + + " " + + " The soap request does not look like what we have expected" + + " 9999" + + " " + + ""; + } + + setContent(message, response); + exchange.send(message); + } + } + + private void setContent(Message message, String response) { + try { + Document responseDom = SOAPUtil.parseAsDom(response); + message.setContent(responseDom.getDocumentElement()); + } catch (Exception e) { + // Generate fault + } + } +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/SOAPContextMapperTest.java b/components/soap/src/test/java/org/switchyard/component/soap/SOAPContextMapperTest.java new file mode 100644 index 000000000..34307ced5 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/SOAPContextMapperTest.java @@ -0,0 +1,170 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap; + +import java.io.StringReader; + +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPMessage; +import javax.xml.ws.soap.SOAPBinding; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.Context; +import org.switchyard.Scope; +import org.switchyard.component.soap.composer.SOAPBindingData; +import org.switchyard.component.soap.composer.SOAPContextMapper; +import org.switchyard.component.soap.composer.SOAPHeadersType; +import org.switchyard.component.soap.util.SOAPUtil; +import org.switchyard.config.Configuration; +import org.switchyard.config.ConfigurationPuller; +import org.switchyard.internal.CompositeContext; +import org.switchyard.internal.DefaultContext; +import org.w3c.dom.Element; + +/** + * SOAPContextMapperTest. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public class SOAPContextMapperTest { + + private static final QName FIRST_NAME = new QName("urn:names:1.0", "first"); + private static final QName LAST_NAME = new QName("urn:names:1.0", "last"); + + private SOAPMessage newSourceMessage() throws Exception { + SOAPMessage source = SOAPUtil.createMessage(SOAPBinding.SOAP11HTTP_BINDING); + source.getSOAPHeader().addChildElement(FIRST_NAME).setValue("John"); + source.getSOAPHeader().addChildElement(LAST_NAME).setValue("Doe"); + return source; + } + + private Context newSourceContext() { + CompositeContext source = newContext(); + source.setProperty(FIRST_NAME.toString(), "John"); + source.setProperty(LAST_NAME.toString(), "Doe"); + return source; + } + + private SOAPMessage newTargetMessage() throws Exception { + SOAPMessage target = SOAPUtil.createMessage(SOAPBinding.SOAP11HTTP_BINDING); + return target; + } + + private CompositeContext newContext() { + CompositeContext source = new CompositeContext(); + source.setContext(Scope.MESSAGE, new DefaultContext(Scope.MESSAGE)); + source.setContext(Scope.EXCHANGE, new DefaultContext()); + return source; + } + + private Object getPropertyValue(Context context, QName qname) { + Object o = context.getProperty(qname.toString(), Scope.MESSAGE).getValue(); + return o; + } + + private Element getChildElement(SOAPMessage message, QName qname) throws Exception { + return (Element)message.getSOAPHeader().getChildElements(qname).next(); + } + + private Configuration newConfiguration(String xml) throws Exception { + return new ConfigurationPuller().pull(new StringReader(xml)); + } + + private String toString(Element element) throws Exception { + return new ConfigurationPuller().pull(element).toString(); + } + + @Test + public void testDefaultContextMapping() throws Exception { + testStringContextMapping(null); + } + + @Test + public void testValueContextMapping() throws Exception { + testStringContextMapping(SOAPHeadersType.VALUE); + } + + private void testStringContextMapping(SOAPHeadersType soapHeadersType) throws Exception { + SOAPContextMapper mapper = new SOAPContextMapper(); + mapper.setSOAPHeadersType(soapHeadersType); + // test mapFrom + SOAPMessage sourceMessage = newSourceMessage(); + Context targetContext = newContext(); + mapper.mapFrom(new SOAPBindingData(sourceMessage), targetContext); + Assert.assertEquals("John", getPropertyValue(targetContext, FIRST_NAME)); + Assert.assertEquals("Doe", getPropertyValue(targetContext, LAST_NAME)); + // test mapTo + Context sourceContext = newSourceContext(); + SOAPMessage targetMessage = newTargetMessage(); + mapper.mapTo(sourceContext, new SOAPBindingData(targetMessage)); + Assert.assertEquals("John", getChildElement(targetMessage, FIRST_NAME).getTextContent()); + Assert.assertEquals("Doe", getChildElement(targetMessage, LAST_NAME).getTextContent()); + } + + @Test + public void testXmlContextMapping() throws Exception { + SOAPContextMapper mapper = new SOAPContextMapper(); + mapper.setSOAPHeadersType(SOAPHeadersType.XML); + // test mapFrom + SOAPMessage sourceMessage = newSourceMessage(); + Context targetContext = newContext(); + mapper.mapFrom(new SOAPBindingData(sourceMessage), targetContext); + Assert.assertEquals("John", getPropertyValue(targetContext, FIRST_NAME)); + Assert.assertEquals("Doe", getPropertyValue(targetContext, LAST_NAME)); + // test mapTo + Context sourceContext = newSourceContext(); + SOAPMessage targetMessage = newTargetMessage(); + mapper.mapTo(sourceContext, new SOAPBindingData(targetMessage)); + Assert.assertEquals("John", getChildElement(targetMessage, FIRST_NAME).getTextContent()); + Assert.assertEquals("Doe", getChildElement(targetMessage, LAST_NAME).getTextContent()); + } + + @Test + public void testConfigContextMapping() throws Exception { + SOAPContextMapper mapper = new SOAPContextMapper(); + mapper.setSOAPHeadersType(SOAPHeadersType.CONFIG); + // test mapFrom + SOAPMessage sourceMessage = newSourceMessage(); + Context targetContext = newContext(); + mapper.mapFrom(new SOAPBindingData(sourceMessage), targetContext); + Assert.assertEquals(newConfiguration("John"), getPropertyValue(targetContext, FIRST_NAME)); + Assert.assertEquals(newConfiguration("Doe"), getPropertyValue(targetContext, LAST_NAME)); + // test mapTo + Context sourceContext = newSourceContext(); + SOAPMessage targetMessage = newTargetMessage(); + mapper.mapTo(sourceContext, new SOAPBindingData(targetMessage)); + Assert.assertEquals("John", getChildElement(targetMessage, FIRST_NAME).getTextContent()); + Assert.assertEquals("Doe", getChildElement(targetMessage, LAST_NAME).getTextContent()); + } + + @Test + public void testDomContextMapping() throws Exception { + SOAPContextMapper mapper = new SOAPContextMapper(); + mapper.setSOAPHeadersType(SOAPHeadersType.DOM); + // test mapFrom + SOAPMessage sourceMessage = newSourceMessage(); + Context targetContext = newContext(); + mapper.mapFrom(new SOAPBindingData(sourceMessage), targetContext); + Assert.assertEquals("John", toString((Element)getPropertyValue(targetContext, FIRST_NAME))); + Assert.assertEquals("Doe", toString((Element)getPropertyValue(targetContext, LAST_NAME))); + // test mapTo + Context sourceContext = newSourceContext(); + SOAPMessage targetMesssage = newTargetMessage(); + mapper.mapTo(sourceContext, new SOAPBindingData(targetMesssage)); + Assert.assertEquals("John", getChildElement(targetMesssage, FIRST_NAME).getTextContent()); + Assert.assertEquals("Doe", getChildElement(targetMesssage, LAST_NAME).getTextContent()); + } + +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/SOAPGatewayTest.java b/components/soap/src/test/java/org/switchyard/component/soap/SOAPGatewayTest.java new file mode 100644 index 000000000..26dcf44e8 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/SOAPGatewayTest.java @@ -0,0 +1,484 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.StringWriter; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.ServiceDomain; +import org.switchyard.common.net.SocketAddr; +import org.switchyard.component.soap.composer.SOAPComposition; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.config.model.SOAPNamespace; +import org.switchyard.component.soap.config.model.v1.V1SOAPBindingModel; +import org.switchyard.component.soap.util.SOAPUtil; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.InvocationFaultException; +import org.switchyard.test.Invoker; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import com.sun.net.httpserver.HttpContext; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +/** + * Contains tests for SOAPGateway. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +@RunWith(SwitchYardRunner.class) +public class SOAPGatewayTest { + + private static final int DEFAULT_THREAD_COUNT = 10; + private static final long DEFAULT_NO_OF_THREADS = 100; + + private ServiceDomain _domain; + + @org.switchyard.test.ServiceOperation("webservice-consumer11") + private Invoker _consumerService11; + + @org.switchyard.test.ServiceOperation("webservice-consumer11-classpath-wsdl") + private Invoker _consumerCPWsdl; + + @org.switchyard.test.ServiceOperation("webservice-consumer12") + private Invoker _consumerService12; + + @org.switchyard.test.ServiceOperation("webservice-consumer3") + private Invoker _consumerService3; + + private SOAPBindingModel _config; + private static URL _serviceURL; + private InboundHandler _soapInbound11; + private InboundHandler _soapInbound12; + private OutboundHandler _soapOutbound11_1; + private OutboundHandler _soapOutbound11_2; + private OutboundHandler _soapOutbound12_1; + private OutboundHandler _soapOutbound3; + private long _noOfThreads = DEFAULT_NO_OF_THREADS; + + private static ModelPuller _puller; + + private class WebServiceInvoker implements Callable { + + private long _threadNo; + + public WebServiceInvoker(long threadNo) { + _threadNo = threadNo; + } + + public String call() { + String input = "" + + " " + + " Thread " + _threadNo + "" + + " " + + ""; + String output = null; + + try { + HttpURLConnection con = (HttpURLConnection) _serviceURL.openConnection(); + con.setDoInput(true); + con.setDoOutput(true); + con.setRequestProperty("Content-type", "text/xml; charset=utf-8"); + OutputStream outStream = con.getOutputStream(); + outStream.write(input.getBytes()); + InputStream inStream = con.getInputStream(); + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + byte[] byteBuf = new byte[256]; + int len = inStream.read(byteBuf); + while (len > -1) { + byteStream.write(byteBuf, 0, len); + len = inStream.read(byteBuf); + } + outStream.close(); + inStream.close(); + byteStream.close(); + output = byteStream.toString(); + + } catch (IOException ioe) { + output = "" + ioe + ""; + } + return output; + } + } + + @Before + public void setUp() throws Exception { + _puller = new ModelPuller(); + + // Provide a switchyard service + SOAPProvider provider = new SOAPProvider(); + + CompositeModel composite = _puller.pull("/HelloSwitchYard.xml", getClass()); + composite.assertModelValid(); + + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (SOAPBindingModel)compositeService.getBindings().get(0); + + // Massive hack for Test Runner. Register both a service and a reference binding. + _domain.registerService(_config.getServiceName(), new HelloWebServiceInterface(), provider); + _domain.registerServiceReference(_config.getServiceName(), new HelloWebServiceInterface()); + + String host = System.getProperty("org.switchyard.test.soap.host", "localhost"); + String port = System.getProperty("org.switchyard.test.soap.port", "8080"); + + // Service exposed as WS + _soapInbound11 = new InboundHandler(_config, _domain); + + _config.setSocketAddr(new SocketAddr(host, Integer.parseInt(port))); + + _soapInbound11.start(); + + _serviceURL = new URL("http://" + host + ":" + port + "/HelloWebService"); + + // A WS Consumer as Service + SOAPBindingModel config2 = new V1SOAPBindingModel(SOAPNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config2.setWsdl(_serviceURL.toExternalForm() + "?wsdl"); + config2.setServiceName(_consumerService11.getServiceName()); + config2.setName("testGateway"); + _soapOutbound11_1 = new OutboundHandler(config2); + _soapOutbound11_1.start(); + // Hack for Test Runner. Register a service to test outbound. + _domain.registerService(_consumerService11.getServiceName(), new HelloWebServiceInterface(), _soapOutbound11_1); + + SOAPBindingModel config3 = new V1SOAPBindingModel(SOAPNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config3.setWsdl(_config.getWsdl()); + config3.setServiceName(_consumerCPWsdl.getServiceName()); + config3.setName("testGateway"); + _soapOutbound11_2 = new OutboundHandler(config3); + _soapOutbound11_2.start(); + // Hack for Test Runner. Register a service to test outbound. + _domain.registerService(_consumerCPWsdl.getServiceName(), new HelloWebServiceInterface(), _soapOutbound11_2); + + composite = _puller.pull("/HelloSwitchYard1.2.xml", getClass()); + composite.assertModelValid(); + + compositeService = composite.getServices().get(0); + SOAPBindingModel _config12 = (SOAPBindingModel)compositeService.getBindings().get(0); + _config12.setSocketAddr(new SocketAddr(host, Integer.parseInt(port))); + + // Massive hack for Test Runner. Register both a service and a reference binding. + _domain.registerService(_config12.getServiceName(), new HelloWebServiceInterface(), provider); + _domain.registerServiceReference(_config12.getServiceName(), new HelloWebServiceInterface()); + + // Service exposed as WS + _soapInbound12 = new InboundHandler(_config12, _domain); + _soapInbound12.start(); + + // We cannot use HelloWebServiceXXX, because the context path suffix XXX is ignored by JAXWS + URL serviceURL = new URL("http://" + host + ":" + port + "/HelloSOAP12Service"); + + SOAPBindingModel config4 = new V1SOAPBindingModel(SOAPNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config4.setWsdl(serviceURL.toExternalForm() + "?wsdl"); + config4.setServiceName(_consumerService12.getServiceName()); + config4.setName("testGateway"); + _soapOutbound12_1 = new OutboundHandler(config4); + _soapOutbound12_1.start(); + // Hack for Test Runner. Register a service to test outbound. + _domain.registerService(_consumerService12.getServiceName(), new HelloWebServiceInterface(), _soapOutbound12_1); + + config4.setServiceName(_consumerService3.getServiceName()); + config4.setEndpointAddress("http://localhost:8090/forever"); + config4.setTimeout(1300); + _soapOutbound3 = new OutboundHandler(config4); + _soapOutbound3.start(); + _domain.registerService(_consumerService3.getServiceName(), new HelloWebServiceInterface(), _soapOutbound3); + + XMLUnit.setIgnoreWhitespace(true); + } + + @After + public void tearDown() throws Exception { + _soapInbound11.stop(); + _soapInbound12.stop(); + } + + @Test + public void invokeWithClassPathResource() throws Exception { + Element input = SOAPUtil.parseAsDom("" + + " Hello" + + "").getDocumentElement(); + String rootCause = null; + try { + _consumerCPWsdl.operation("sayHello").sendInOut(input); + } catch (InvocationFaultException ife) { + rootCause = getRootCause(ife); + } + + // CXF replaces the url properly + if (rootCause != null) { + // A real URL here would depend on the test environment's host and port hence, + // it is sufficient to test that we actually loaded the WSDL from classpath + Assert.assertEquals("javax.xml.ws.WebServiceException: Unsupported endpoint address: REPLACE_WITH_ACTUAL_URL", rootCause); + } + } + + @Test + public void invokeOneWay() throws Exception { + Element input = SOAPUtil.parseAsDom("" + + " Hello" + + "").getDocumentElement(); + + _consumerService11.operation("helloWS").sendInOnly(input); + } + + @Test + public void soapGatewayReferenceTimeout() throws Exception { + Element input = SOAPUtil.parseAsDom("" + + " Hello" + + "").getDocumentElement(); + HttpServer httpServer = HttpServer.create(new InetSocketAddress(8090), 10); + httpServer.setExecutor(null); // creates a default executor + httpServer.start(); + HttpContext httpContext = httpServer.createContext("/forever", new HttpHandler() { + public void handle(HttpExchange exchange) { + try { + Thread.sleep(10000); + } catch (InterruptedException ie) { + //Ignore + }}}); + try { + Message responseMsg = _consumerService3.operation("sayHello").sendInOut(input); + } catch (Exception e) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(baos)); + Assert.assertTrue(baos.toString().contains("SocketTimeoutException: Read timed out")); + } + httpServer.stop(0); + } + + @Ignore // mime headers are not parsed into the SOAPMessage with CXF + @Test + public void invokeRequestResponse() throws Exception { + String input = "" + + " Magesh" + + ""; + + String output = "" + + " Hello Magesh! The soapAction received is \"uri:something:that:needs#tobevalid\"" + + ""; + + + Message responseMsg = _consumerService11.operation("sayHello").sendInOut(input); + + String response = toString(responseMsg.getContent(Node.class)); + XMLAssert.assertXMLEqual(output, response); + } + + @Ignore // mime headers are not parsed into the SOAPMessage with CXF + @Test + public void invokeRequestResponseSOAP12() throws Exception { + String input = "" + + " Magesh" + + ""; + + String output = "" + + " Hello Magesh! The soapAction received is application/soap+xml; charset=utf-8; action=\"uri:soap12:that:needs#tobevalid\"" + + ""; + + + Message responseMsg = _consumerService12.operation("sayHello").sendInOut(input); + + String response = toString(responseMsg.getContent(Node.class)); + XMLAssert.assertXMLEqual(output, response); + } + + private String toString(Node node) throws Exception + { + TransformerFactory transFactory = TransformerFactory.newInstance(); + Transformer transformer = transFactory.newTransformer(); + StringWriter sw = new StringWriter(); + DOMSource source = new DOMSource(node); + StreamResult result = new StreamResult(sw); + transformer.transform(source, result); + return sw.toString(); + } + + @Ignore + @Test + public void invokeRequestResponseFault() throws Exception { + String input = "" + + " " + + ""; + + String output = "" + + " SOAP-ENV:Server.AppError" + + " Invalid name" + + " " + + " Looks like you did not specify a name!" + + " 1000" + + " " + + ""; + + Message responseMsg = _consumerService11.operation("sayHello").sendInOut(input); + String response = toString(responseMsg.getContent(Node.class)); + XMLAssert.assertXMLEqual(output, response); + } + + @Ignore + @Test + public void invokeRequestResponseCustomFault() throws Exception { + String faultString = "" + + "errorcode=1000;" + + "Invalid name: Looks like you did not specify a name!" + + ""; + + String input = "" + + " " + + faultString + + ""; + + String output = "" + + "ns0:Fault" + + "Send failed" + + "" + + faultString + + "" + + ""; + + Message responseMsg = _consumerService11.operation("sayHello").sendInOut(input); + String response = toString(responseMsg.getContent(Node.class)); + XMLAssert.assertXMLEqual(output, response); + } + + @Test + public void invokeCustomFaultWithDetails() throws Exception { + String faultString = "" + + "errorcode=1000;" + + "Invalid name: Looks like you did not specify a name!" + + ""; + + String input = "" + + " " + + ""; + + String faultStr = "SOAPFaultInfo [_actor=null, _codeAsQName={http://schemas.xmlsoap.org/soap/envelope/}Server.AppError, " + + "_reasonTexts={}, _role=null, _string=Invalid name, _stringLocale=null, _subcodes=[], _detail=[detail: null]]"; + + MockHandler handler = new MockHandler(); + Exchange ex = _consumerService11.operation("sayHello").createExchange(handler); + + Message requestMsg = ex.createMessage().setContent(input); + ex.send(requestMsg); + handler.waitForFaultMessage(); + Exchange exchange = handler.getFaults().iterator().next(); + Property faultInfoProperty = exchange.getContext().getProperty(SOAPComposition.SOAP_FAULT_INFO); + Assert.assertNotNull(faultInfoProperty); + Assert.assertEquals(faultStr, faultInfoProperty.getValue().toString()); + } + + @Test + public void invokeMultiThreaded() throws Exception { + String output = null; + String response = null; + Collection> callables = new ArrayList>(); + for (int i = 0; i < _noOfThreads; i++) { + callables.add(new WebServiceInvoker(i)); + } + + ExecutorService executorService = Executors.newFixedThreadPool(DEFAULT_THREAD_COUNT); + Collection> futures = executorService.invokeAll(callables); + Assert.assertEquals(futures.size(), _noOfThreads); + int i = 0; + + for (Future future : futures) { + response = future.get(); + output = "" + + "" + + "" + + " " + + " Hello Thread " + i + "! The soapAction received is " + + " " + + ""; + XMLAssert.assertXMLEqual(output, response); + i++; + } + } + + private String getRootCause(Throwable t) { + if(t.getCause() != null){ + return getRootCause(t.getCause()); + } else { + return t.toString(); + } + } + + private static class HelloWebServiceInterface extends BaseService { + private static Set _operations = new HashSet(2); + static { + _operations.add(new InOutOperation("sayHello")); + _operations.add(new InOnlyOperation("helloWS")); + } + public HelloWebServiceInterface() { + super(_operations); + } + } +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/SOAPProvider.java b/components/soap/src/test/java/org/switchyard/component/soap/SOAPProvider.java new file mode 100644 index 000000000..80c508a5c --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/SOAPProvider.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.soap.util.SOAPUtil; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +/** + * A mock up WebService provider. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SOAPProvider extends BaseHandler { + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + Message message = exchange.createMessage(); + if (exchange.getContract().getProviderOperation().getExchangePattern().equals(ExchangePattern.IN_OUT)) { + Message receivedMessage = exchange.getMessage(); + Node request = receivedMessage.getContent(Node.class); + Element name = XMLHelper.getFirstChildElementByName(request, "arg0"); + Element fault = XMLHelper.getFirstChildElementByName(request, "CustomFaultMessage"); + + String toWhom = ""; + if (name != null) { + toWhom = name.getTextContent(); + } + String response = null; + if (toWhom.length() == 0) { + if (fault != null) { + // for testing sendFault() with the message which is not SOAP/Fault format + message.setContent(fault); + } else { + response = "" + + " SOAP-ENV:Server.AppError" + + " Invalid name" + + " " + + " Looks like you did not specify a name!" + + " 1000" + + " " + + ""; + setContent(message, response); + } + exchange.sendFault(message); + } else { + Property soapActionProp = exchange.getContext().getProperty("Soapaction"); + if (soapActionProp == null) { + soapActionProp = exchange.getContext().getProperty("SOAPAction"); + } + String soapAction = ""; + if (soapActionProp != null) { + soapAction = (String) soapActionProp.getValue(); + } else { + soapActionProp = exchange.getContext().getProperty("Content-Type"); + if (soapActionProp == null) { + soapActionProp = exchange.getContext().getProperty("Content-type"); + } + if (soapActionProp != null) { + soapAction = (String) soapActionProp.getValue(); + } + } + response = "" + + " Hello " + toWhom + "! The soapAction received is " + soapAction + "" + + ""; + setContent(message, response); + exchange.send(message); + } + } + } + + private void setContent(Message message, String response) { + try { + Document responseDom = SOAPUtil.parseAsDom(response); + message.setContent(responseDom.getDocumentElement()); + } catch (Exception e) { + // Generate fault + } + } +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/SOAPUtilTest.java b/components/soap/src/test/java/org/switchyard/component/soap/SOAPUtilTest.java new file mode 100644 index 000000000..411b6ebe8 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/SOAPUtilTest.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap; + +import javax.xml.soap.SOAPFault; +import javax.xml.soap.SOAPMessage; +import javax.xml.ws.soap.SOAPBinding; +import javax.xml.ws.soap.SOAPFaultException; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.component.soap.util.SOAPUtil; + +/** + * SOAPUtilTest + * + * @author Kevin Conner + * + */ +public class SOAPUtilTest { + @Test + public void testSOAP11EmptyFaultString() throws Exception { + final SOAPFault soapFault = SOAPUtil.createFault(new Throwable(""), SOAPBinding.SOAP11HTTP_BINDING, null); + + final SOAPMessage message = SOAPUtil.generateSOAP11Fault(new SOAPFaultException(soapFault)); + Assert.assertNotNull("SOAPMessage should have been returned", message); + } + + @Test + public void testSOAP12EmptyFaultString() throws Exception { + final SOAPFault soapFault = SOAPUtil.createFault(new Throwable(""), SOAPBinding.SOAP12HTTP_BINDING, null); + + final SOAPMessage message = SOAPUtil.generateSOAP12Fault(new SOAPFaultException(soapFault)); + Assert.assertNotNull("SOAPMessage should have been returned", message); + } +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/StandardDocLitTest.java b/components/soap/src/test/java/org/switchyard/component/soap/StandardDocLitTest.java new file mode 100644 index 000000000..8f1a0dee8 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/StandardDocLitTest.java @@ -0,0 +1,152 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import java.io.StringWriter; +import java.net.URL; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.common.net.SocketAddr; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.config.model.SOAPNamespace; +import org.switchyard.component.soap.config.model.v1.V1SOAPBindingModel; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.v1.V1CompositeReferenceModel; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.test.Invoker; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestKit; +import org.w3c.dom.Node; + +/** + * Contains tests for standard doclit (non-wrapped doclit). + * + * @author Mario Antollini + */ +@RunWith(SwitchYardRunner.class) +public class StandardDocLitTest { + + private SwitchYardTestKit _testKit; + + private ServiceDomain _domain = new ServiceDomainManager().createDomain(); + private SOAPBindingModel _config; + private static URL _serviceURL; + private InboundHandler _soapInbound; + private OutboundHandler _soapOutbound; + + @org.switchyard.test.ServiceOperation("webservice-consumer") + private Invoker consumerService; + + private static ModelPuller _puller; + + @Before + public void setUp() throws Exception { + + // Provide a switchyard service + DoclitSOAPProvider provider = new DoclitSOAPProvider(); + + String host = System.getProperty("org.switchyard.test.soap.host", "localhost"); + String port = System.getProperty("org.switchyard.test.soap.port", "48080"); + + _puller = new ModelPuller(); + CompositeModel composite = _puller.pull("/DoclitSwitchyard.xml", getClass()); + + CompositeServiceModel compositeService = composite.getServices().get(0); + _config = (SOAPBindingModel)compositeService.getBindings().get(0); + + _domain.registerService(_config.getServiceName(), new OrderServiceInterface(), provider); + _domain.registerServiceReference(_config.getServiceName(), new OrderServiceInterface()); + + _config.setSocketAddr(new SocketAddr(host, Integer.parseInt(port))); + + _soapInbound = new InboundHandler(_config, _domain); + + _soapInbound.start(); + + _serviceURL = new URL("http://" + host + ":" + port + "/OrderService"); + + // A WS Consumer as Service + SOAPBindingModel config2 = new V1SOAPBindingModel(SOAPNamespace.DEFAULT.uri()) { + @Override + public CompositeReferenceModel getReference() { + return new V1CompositeReferenceModel(); + } + }; + config2.setWsdl(_serviceURL.toExternalForm() + "?wsdl"); + config2.setServiceName(consumerService.getServiceName()); + config2.setName("testGateway"); + _soapOutbound = new OutboundHandler(config2); + _soapOutbound.start(); + _domain.registerService(consumerService.getServiceName(), new OrderServiceInterface(), _soapOutbound); + + XMLUnit.setIgnoreWhitespace(true); + } + + @After + public void tearDown() throws Exception { + // NOOP + } + + @Test + public void standardDocLitOperation() throws Exception { + + DOMSource domSource = new DOMSource(_testKit.readResourceDocument("/doclit_request.xml")); + Message responseMsg = consumerService.operation("submitOrder").sendInOut(toString(domSource.getNode())); + String response = toString(responseMsg.getContent(Node.class)); + _testKit.compareXMLToResource(response, "/doclit_response.xml"); + + } + + private static class OrderServiceInterface extends BaseService { + private static Set _operations = new HashSet(2); + static { + _operations.add(new InOutOperation("submitOrder")); + } + public OrderServiceInterface() { + super(_operations); + } + } + + private String toString(Node node) throws Exception + { + TransformerFactory transFactory = TransformerFactory.newInstance(); + Transformer transformer = transFactory.newTransformer(); + StringWriter sw = new StringWriter(); + DOMSource source = new DOMSource(node); + StreamResult result = new StreamResult(sw); + transformer.transform(source, result); + return sw.toString(); + } + +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/UnwrappedMessageTest.java b/components/soap/src/test/java/org/switchyard/component/soap/UnwrappedMessageTest.java new file mode 100644 index 000000000..6e48fa3bd --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/UnwrappedMessageTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import java.util.concurrent.TimeUnit; + +import junit.framework.Assert; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.metadata.InOutService; +import org.switchyard.test.MockHandler; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +/** + * Tests SOAP-specific message composer. + */ +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig( + config = "unwrapped-switchyard.xml", + mixins = {HTTPMixIn.class}) +public class UnwrappedMessageTest { + + private static final String UNWRAPPED_PAYLOAD = "unwrappedRequest.xml"; + private static final String WRAPPED_REPLY = "wrappedReply.xml"; + + private SwitchYardTestKit testKit; + private HTTPMixIn httpMixIn; + + @Test + public void testWrapUnwrap() throws Exception { + MockHandler provider = new MockHandler().forwardInToOut(); + testKit.registerInOutService("Payments", provider, new InOutService("submit")); + String reply = httpMixIn.postResource("http://localhost:18001/Payments", "wrappedRequest.xml"); + String receivedPayload = provider.getMessages().poll(300, TimeUnit.MILLISECONDS) + .getMessage().getContent(String.class); + + // verify request is unwrapped + XMLUnit.setIgnoreWhitespace(true); + Diff requestDiff = XMLUnit.compareXML(testKit.readResourceString(UNWRAPPED_PAYLOAD), receivedPayload); + Assert.assertTrue(requestDiff.toString(), requestDiff.similar()); + + // verify reply is wrapped + Diff replyDiff = XMLUnit.compareXML(testKit.readResourceString(WRAPPED_REPLY), reply); + Assert.assertTrue(replyDiff.toString(), replyDiff.similar()); + } +} \ No newline at end of file diff --git a/components/soap/src/test/java/org/switchyard/component/soap/WSDLUtilBindingStyleTest.java b/components/soap/src/test/java/org/switchyard/component/soap/WSDLUtilBindingStyleTest.java new file mode 100644 index 000000000..b078b3fda --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/WSDLUtilBindingStyleTest.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.xml.namespace.QName; + +import org.junit.Test; +import org.switchyard.component.soap.util.WSDLUtil; +import org.switchyard.SwitchYardException; + +/** + * Test of binding style discovery. + */ +public class WSDLUtilBindingStyleTest { + + private static final String TEST_WSDL = "BindingStyleTest.wsdl"; + + protected final void assertStyle(String portName, String bindingName, String style) throws Exception { + Service service = WSDLUtil.getService(TEST_WSDL, new PortName(portName + ":")); + + assertNotNull(service); + assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", portName)); + Port port = WSDLUtil.getPort(service, new PortName(bindingName)); + assertNotNull(port); + assertEquals(style, WSDLUtil.getStyle(port)); + } + + @Test + public void testSoapDocumentBinding() throws Exception { + assertStyle("DocumentBindingService", "DocumentBinding", WSDLUtil.DOCUMENT); + } + + @Test + public void testSoapRpcBinding() throws Exception { + assertStyle("RpcBindingService", "RpcBinding", "rpc"); + } + + @Test + public void testOperationRpcBinding() throws Exception { + assertStyle("OperationRpcBindingService", "OperationRpcBinding", "rpc"); + } + + @Test(expected = SwitchYardException.class) + public void testDocumentRpcMixedOperationsBinding() throws Exception { + assertStyle("DocumentRpcMixedOperationsService", "DocumentRpcMixedOperationsBinding", null); + } + + @Test(expected = SwitchYardException.class) + public void testRpcDocumentMixedOperationsBinding() throws Exception { + assertStyle("RpcDocumentMixedOperationsService", "RpcDocumentMixedOperationsBinding", null); + } + + @Test(expected = SwitchYardException.class) + public void testRpcDocument2MixedOperationsBinding() throws Exception { + assertStyle("RpcDocument2MixedOperationsService", "RpcDocument2MixedOperationsBinding", null); + } + +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/WSDLUtilTest.java b/components/soap/src/test/java/org/switchyard/component/soap/WSDLUtilTest.java new file mode 100644 index 000000000..233903f0c --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/WSDLUtilTest.java @@ -0,0 +1,273 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.soap; + +import java.util.HashSet; +import java.util.Set; + +import javax.wsdl.Definition; +import javax.wsdl.Port; +import javax.wsdl.Service; +import javax.wsdl.WSDLException; +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.component.soap.util.WSDLUtil; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; + +/** + * Tests for SOAPGateway's wsPort parameter. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class WSDLUtilTest { + + @Test + public void fullyQualifiedPortName() throws Exception { + PortName portName = new PortName("{urn:switchyard-component-soap:test-ws:1.0}GoodbyeWebService:GoodbyeWebServicePort"); + Service service = WSDLUtil.getService("MultiplePortService.wsdl", portName); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "GoodbyeWebService")); + Port port = WSDLUtil.getPort(service, portName); + Assert.assertNotNull(port); + Assert.assertEquals(port.getName(), "GoodbyeWebServicePort"); + } + + @Test + public void halfQualifiedPortName() throws Exception { + PortName portName = new PortName("HelloWebService:HelloWebServicePort"); + Service service = WSDLUtil.getService("MultiplePortService.wsdl", portName); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "HelloWebService")); + Port port = WSDLUtil.getPort(service, portName); + Assert.assertNotNull(port); + Assert.assertEquals(port.getName(), "HelloWebServicePort"); + } + + @Test + public void nonQualifiedPortName() throws Exception { + PortName portName = new PortName("HelloWebServicePortFrench"); + Service service = WSDLUtil.getService("MultiplePortService.wsdl", portName); + Assert.assertNotNull(service); + service = WSDLUtil.getService("MultiplePortService.wsdl", new PortName("HelloWebService:")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "HelloWebService")); + Port port = WSDLUtil.getPort(service, portName); + Assert.assertEquals(port.getName(), "HelloWebServicePortFrench"); + } + + @Test + public void nullPortName() throws Exception { + Service service = WSDLUtil.getService("MultiplePortService.wsdl", new PortName(null)); + Assert.assertNotNull(service); + Port port = WSDLUtil.getPort(service, new PortName(null)); + Assert.assertNotNull(port); + service = WSDLUtil.getService("MultiplePortService.wsdl", new PortName("HelloWebService:")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "HelloWebService")); + port = WSDLUtil.getPort(service, new PortName(null)); + Assert.assertEquals(port.getName(), "HelloWebServicePortFrench"); + } + + @Test(expected=WSDLException.class) + public void nonExistentService() throws Exception { + WSDLUtil.getService("MultiplePortService.wsdl", new PortName("NonexistentWebService:")); + } + + @Test(expected=WSDLException.class) + public void nonExistentPortName() throws Exception { + Service service = WSDLUtil.getService("MultiplePortService.wsdl", new PortName("HelloWebService:")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "HelloWebService")); + WSDLUtil.getPort(service, new PortName("HelloWebServiceSpanishPort")); + } + + @Test + public void soapAction() throws Exception { + Service service = WSDLUtil.getService("HelloWebService.wsdl", new PortName("HelloWebService:")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "HelloWebService")); + Port port = WSDLUtil.getPort(service, new PortName("HelloWebServicePort")); + Assert.assertNotNull(port); + String action = WSDLUtil.getSoapAction(port, new QName("urn:switchyard-component-soap:test-ws:1.0", "sayHello"), true); + Assert.assertEquals(action, "uri:something:that:needs#tobevalid"); + action = WSDLUtil.getSoapAction(port, new QName("urn:switchyard-component-soap:test-ws:1.0", "helloWS"), true); + Assert.assertEquals(action, ""); + + } + + @Test + public void soap12Action() throws Exception { + Service service = WSDLUtil.getService("HelloWebService1.2.wsdl", new PortName("HelloSOAP12Service:")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "HelloSOAP12Service")); + Port port = WSDLUtil.getPort(service, new PortName("HelloSOAP12ServicePort")); + Assert.assertNotNull(port); + String action = WSDLUtil.getSoapAction(port, new QName("urn:switchyard-component-soap:test-ws:1.0", "sayHello"), true); + Assert.assertEquals(action, "uri:soap12:that:needs#tobevalid"); + action = WSDLUtil.getSoapAction(port, new QName("urn:switchyard-component-soap:test-ws:1.0", "helloWS"), true); + Assert.assertEquals(action, ""); + } + + @Test + public void soapAddressing() throws Exception { + Definition definition = WSDLUtil.readWSDL("HelloWebServiceAddressing.wsdl"); + String targetNamespace = definition.getTargetNamespace(); + Service service = WSDLUtil.getService(definition, new PortName("HelloAddressingService:HelloSOAPAddressingServicePort")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName(targetNamespace, "HelloAddressingService")); + Port port = WSDLUtil.getPort(service, new PortName("HelloSOAPAddressingServicePort")); + Assert.assertNotNull(port); + Feature feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:true, AddressingRequired:false, MtomEnabled:false]", feature.toString()); + String action = WSDLUtil.getInputAction(port, new QName(targetNamespace, "sayHello"), true); + Assert.assertEquals("urn:switchyard-component-soap:test-ws:1.0:HelloAddressingService:sayHelloRequest", action); + action = WSDLUtil.getOutputAction(port, new QName(targetNamespace, "sayHello"), true); + Assert.assertEquals("urn:switchyard-component-soap:test-ws:1.0:HelloAddressingService:sayHelloResponse", action); + + port = WSDLUtil.getPort(service, new PortName("HelloSOAPAddressingServicePort2")); + Assert.assertNotNull(port); + feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:true, AddressingRequired:true, MtomEnabled:false]", feature.toString()); + action = WSDLUtil.getInputAction(port, new QName(targetNamespace, "sayHello"), true); + Assert.assertEquals("http://mysite/input", action); + action = WSDLUtil.getOutputAction(port, new QName(targetNamespace, "sayHello"), true); + Assert.assertEquals("http://mysite/output", action); + + port = WSDLUtil.getPort(service, new PortName("HelloSOAPAddressingServicePort3")); + Assert.assertNotNull(port); + feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:true, AddressingRequired:true, MtomEnabled:false]", feature.toString()); + action = WSDLUtil.getFaultAction(port, new QName(targetNamespace, "sayHello"), "UnknownMessage", true); + Assert.assertEquals("urn:switchyard-component-soap:test-ws:1.0:HelloAddressingService3:sayHello:Fault:UnknownMessage", action); + } + + @Test + public void soapMtom() throws Exception { + // Document policy ref + Definition definition = WSDLUtil.readWSDL("ImageServiceMtom.wsdl"); + Service service = WSDLUtil.getService(definition, new PortName("ImageService:ImageServicePort")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "ImageService")); + Port port = WSDLUtil.getPort(service, new PortName("ImageServicePort")); + Assert.assertNotNull(port); + Feature feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:false, AddressingRequired:false, MtomEnabled:true]", feature.toString()); + // Document policy ref another style + port = WSDLUtil.getPort(service, new PortName("ImageServicePort2")); + Assert.assertNotNull(port); + feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:false, AddressingRequired:false, MtomEnabled:true]", feature.toString()); + + // Document element def + definition = WSDLUtil.readWSDL("ImageServiceMtom2.wsdl"); + service = WSDLUtil.getService(definition, new PortName("ImageService:ImageServicePort")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "ImageService")); + port = WSDLUtil.getPort(service, new PortName("ImageServicePort")); + Assert.assertNotNull(port); + feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:false, AddressingRequired:false, MtomEnabled:true]", feature.toString()); + } + + @Test + public void importedWSDL() throws Exception { + Service service = WSDLUtil.getService("HelloWebServiceImport.wsdl", new PortName(null)); + Assert.assertNotNull(service); + Port port = WSDLUtil.getPort(service, new PortName("HelloWebServicePort")); + Assert.assertNotNull(port); + service = WSDLUtil.getService("HelloWebServiceImport.wsdl", new PortName("HelloWebService:")); + Assert.assertNotNull(service); + PortName portName = new PortName("{urn:switchyard-metadata-interface}HelloWebService:"); + service = WSDLUtil.getService("HelloWebServiceImport.wsdl", portName); + Assert.assertNotNull(service); + } + + @Test + public void soapMtomImportTypes() throws Exception { + // Document policy ref + Definition definition = WSDLUtil.readWSDL("ImageServiceMtomImportTypes.wsdl"); + Service service = WSDLUtil.getService(definition, new PortName("ImageService:ImageServicePort")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "ImageService")); + Port port = WSDLUtil.getPort(service, new PortName("ImageServicePort")); + Assert.assertNotNull(port); + Feature feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:false, AddressingRequired:false, MtomEnabled:true]", feature.toString()); + // Document policy ref another style + port = WSDLUtil.getPort(service, new PortName("ImageServicePort2")); + Assert.assertNotNull(port); + feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:false, AddressingRequired:false, MtomEnabled:true]", feature.toString()); + + // Document element def + definition = WSDLUtil.readWSDL("ImageServiceMtomImportTypes2.wsdl"); + service = WSDLUtil.getService(definition, new PortName("ImageService:ImageServicePort")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "ImageService")); + port = WSDLUtil.getPort(service, new PortName("ImageServicePort")); + Assert.assertNotNull(port); + feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:false, AddressingRequired:false, MtomEnabled:true]", feature.toString()); + + // RPC message definition + definition = WSDLUtil.readWSDL("ImageServiceMtomImportTypes3.wsdl"); + service = WSDLUtil.getService(definition, new PortName("ImageService:ImageServicePort")); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "ImageService")); + port = WSDLUtil.getPort(service, new PortName("ImageServicePort")); + Assert.assertNotNull(port); + feature = WSDLUtil.getFeature(definition, port, true); + Assert.assertEquals("[AddressingEnabled:false, AddressingRequired:false, MtomEnabled:true]", feature.toString()); + } + + /* + @Test + public void contracts() throws Exception { + Service service = WSDLUtil.getService("DoclitOrderService.wsdl", new PortName(null)); + Assert.assertNotNull(service); + Assert.assertEquals(service.getQName(), new QName("urn:switchyard-component-soap:test-ws:1.0", "OrderService")); + Port port = WSDLUtil.getPort(service, new PortName("OrderService:")); + Assert.assertNotNull(port); + Assert.assertEquals(port.getName(), "OrderServicePort"); + Map contracts = WSDLUtil.getContracts(port, new MockServiceReference(new OrderServiceInterface(), "OrderService")); + Assert.assertNotNull(contracts); + // One operation + Assert.assertEquals(contracts.size(), 1); + BaseExchangeContract contract = contracts.get("submitOrder"); + Assert.assertNotNull(contract); + BaseInvocationContract soapMetaData = contract.getInvokerInvocationMetaData(); + Assert.assertNotNull(soapMetaData); + // Input and output types + Assert.assertNotNull(soapMetaData.getInputType()); + Assert.assertEquals(soapMetaData.getInputType(), new QName("urn:switchyard-component-soap:test-ws:1.0", "order")); + Assert.assertNotNull(soapMetaData.getOutputType()); + Assert.assertEquals(soapMetaData.getOutputType(), new QName("urn:switchyard-component-soap:test-ws:1.0", "orderAck")); + } + */ + + private static class OrderServiceInterface extends BaseService { + private static Set _operations = new HashSet(2); + static { + _operations.add(new InOutOperation("submitOrder")); + } + public OrderServiceInterface() { + super(_operations); + } + } +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/config/model/SOAPBindingModelTest.java b/components/soap/src/test/java/org/switchyard/component/soap/config/model/SOAPBindingModelTest.java new file mode 100644 index 000000000..b968751c6 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/config/model/SOAPBindingModelTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; + +/** + * Test of SOAP binding model. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class SOAPBindingModelTest { + + private static final String SOAP_BINDING_SERVICE = "soap-binding-service.xml"; + private static final String SOAP_BINDING_REFERENCE = "soap-binding-reference.xml"; + private static final String SOAP_BINDING_INVALID = "soap-binding-invalid.xml"; + private static final String SOAP_BINDING_PROXY = "soap-binding-proxy.xml"; + private static final String SOAP_BINDING_AUTH = "soap-binding-auth.xml"; + + @Test + public void serviceBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + SOAPBindingModel binding = puller.pull(SOAP_BINDING_SERVICE, getClass()); + binding.assertModelValid(); + Assert.assertEquals("myendpoint", binding.getContextPath()); + EndpointConfigModel endpointConfig = binding.getEndpointConfig(); + Assert.assertEquals("myFile", endpointConfig.getConfigFile()); + Assert.assertEquals("myName", endpointConfig.getConfigName()); + MtomModel mtomConfig = binding.getMtomConfig(); + Assert.assertEquals(new Boolean(true), mtomConfig.isEnabled()); + Assert.assertEquals(new Integer(1300), mtomConfig.getThreshold()); + Assert.assertEquals(new Boolean(true), mtomConfig.isXopExpand()); + } + + @Test + public void referenceBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + SOAPBindingModel binding = puller.pull(SOAP_BINDING_REFERENCE, getClass()); + binding.assertModelValid(); + Assert.assertEquals("http://modified.com/phantom", binding.getEndpointAddress()); + Assert.assertEquals(new Integer(5000), binding.getTimeout()); + MtomModel mtomConfig = binding.getMtomConfig(); + Assert.assertEquals(new Boolean(true), mtomConfig.isEnabled()); + Assert.assertEquals(new Integer(1300), mtomConfig.getThreshold()); + Assert.assertEquals(new Boolean(true), mtomConfig.isXopExpand()); + } + + @Test + public void invalidBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + SOAPBindingModel binding = puller.pull(SOAP_BINDING_INVALID, getClass()); + Assert.assertTrue(!binding.isModelValid()); + } + + + @Test + public void proxyBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + SOAPBindingModel binding = puller.pull(SOAP_BINDING_PROXY, getClass()); + binding.assertModelValid(); + Assert.assertEquals("http://modified.com/phantom", binding.getEndpointAddress()); + ProxyModel proxyConfig = binding.getProxyConfig(); + Assert.assertEquals("192.168.1.2", proxyConfig.getHost()); + Assert.assertEquals("9090", proxyConfig.getPort()); + Assert.assertEquals("user", proxyConfig.getUser()); + Assert.assertEquals("password", proxyConfig.getPassword()); + Assert.assertEquals("HTTP", proxyConfig.getType()); + } + + @Test + public void authBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + SOAPBindingModel binding = puller.pull(SOAP_BINDING_AUTH, getClass()); + binding.assertModelValid(); + Assert.assertEquals("http://modified.com/phantom", binding.getEndpointAddress()); + NtlmAuthModel authConfig = binding.getNtlmAuthConfig(); + Assert.assertEquals("user", authConfig.getUser()); + Assert.assertEquals("password", authConfig.getPassword()); + Assert.assertEquals("domain", authConfig.getDomain()); + } + +} diff --git a/components/soap/src/test/java/org/switchyard/component/soap/config/model/v1/V1SOAPMessageComposerModelTest.java b/components/soap/src/test/java/org/switchyard/component/soap/config/model/v1/V1SOAPMessageComposerModelTest.java new file mode 100644 index 000000000..4f159ac19 --- /dev/null +++ b/components/soap/src/test/java/org/switchyard/component/soap/config/model/v1/V1SOAPMessageComposerModelTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.soap.config.model.v1; + +import junit.framework.Assert; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Test; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.config.model.SOAPNamespace; +import org.switchyard.config.model.ModelPuller; + +/** + * Test of atom binding model. + */ +public class V1SOAPMessageComposerModelTest { + + private static final String SOAP_BINDING = "soap-binding.xml"; + private static final String COMPOSER_FRAG = "message-composer.xml"; + + @Test + public void testReadConfigFragment() throws Exception { + ModelPuller puller = new ModelPuller(); + V1SOAPMessageComposerModel model = puller.pull(COMPOSER_FRAG, getClass()); + Assert.assertTrue("Unwrap should be true", model.isUnwrapped()); + } + + @Test + public void testReadConfigBinding() throws Exception { + ModelPuller puller = new ModelPuller(); + SOAPBindingModel model = puller.pull(SOAP_BINDING, getClass()); + Assert.assertTrue(model.isModelValid()); + Assert.assertTrue("Unwrap should be true", model.getSOAPMessageComposer().isUnwrapped()); + } + + @Test + public void testWriteConfig() throws Exception { + V1SOAPMessageComposerModel scm = new V1SOAPMessageComposerModel(SOAPNamespace.V_1_0.uri()); + scm.setUnwrapped(true); + + V1SOAPMessageComposerModel refModel = new ModelPuller() + .pull(COMPOSER_FRAG, getClass()); + + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(refModel.toString(), scm.toString()); + Assert.assertTrue(diff.toString(), diff.similar()); + } +} diff --git a/components/soap/src/test/resources/AnotherGoodbyeService.wsdl b/components/soap/src/test/resources/AnotherGoodbyeService.wsdl new file mode 100644 index 000000000..4732a7175 --- /dev/null +++ b/components/soap/src/test/resources/AnotherGoodbyeService.wsdl @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/AnotherGoodbyeWebService_schema1.xsd b/components/soap/src/test/resources/AnotherGoodbyeWebService_schema1.xsd new file mode 100644 index 000000000..d8517e6eb --- /dev/null +++ b/components/soap/src/test/resources/AnotherGoodbyeWebService_schema1.xsd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/BindingStyleTest.wsdl b/components/soap/src/test/resources/BindingStyleTest.wsdl new file mode 100644 index 000000000..c669f9e96 --- /dev/null +++ b/components/soap/src/test/resources/BindingStyleTest.wsdl @@ -0,0 +1,180 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/DoclitOrderService.wsdl b/components/soap/src/test/resources/DoclitOrderService.wsdl new file mode 100644 index 000000000..7cc3e1213 --- /dev/null +++ b/components/soap/src/test/resources/DoclitOrderService.wsdl @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/DoclitSwitchyard.xml b/components/soap/src/test/resources/DoclitSwitchyard.xml new file mode 100644 index 000000000..d83533806 --- /dev/null +++ b/components/soap/src/test/resources/DoclitSwitchyard.xml @@ -0,0 +1,27 @@ + + + + + + + DoclitOrderService.wsdl + {urn:switchyard-component-soap:test-ws:1.0}OrderService:OrderServicePort + + + + diff --git a/components/soap/src/test/resources/GoodbyeWebService_schema1.xsd b/components/soap/src/test/resources/GoodbyeWebService_schema1.xsd new file mode 100644 index 000000000..2371a12ae --- /dev/null +++ b/components/soap/src/test/resources/GoodbyeWebService_schema1.xsd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/HelloSwitchYard.xml b/components/soap/src/test/resources/HelloSwitchYard.xml new file mode 100644 index 000000000..28befce82 --- /dev/null +++ b/components/soap/src/test/resources/HelloSwitchYard.xml @@ -0,0 +1,38 @@ + + + + + + + + + HelloWebService.wsdl + {urn:switchyard-component-soap:test-ws:1.0}HelloWebService:HelloWebServicePort + + + + + diff --git a/components/soap/src/test/resources/HelloSwitchYard1.2.xml b/components/soap/src/test/resources/HelloSwitchYard1.2.xml new file mode 100644 index 000000000..7ccece187 --- /dev/null +++ b/components/soap/src/test/resources/HelloSwitchYard1.2.xml @@ -0,0 +1,30 @@ + + + + + + + + + HelloWebService1.2.wsdl + {urn:switchyard-component-soap:test-ws:1.0}HelloSOAP12Service:HelloSOAP12ServicePort + + + + diff --git a/components/soap/src/test/resources/HelloWebService.wsdl b/components/soap/src/test/resources/HelloWebService.wsdl new file mode 100644 index 000000000..19d44d9ce --- /dev/null +++ b/components/soap/src/test/resources/HelloWebService.wsdl @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/HelloWebService1.2.wsdl b/components/soap/src/test/resources/HelloWebService1.2.wsdl new file mode 100644 index 000000000..bfbfa1dc6 --- /dev/null +++ b/components/soap/src/test/resources/HelloWebService1.2.wsdl @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/HelloWebServiceAddressing.wsdl b/components/soap/src/test/resources/HelloWebServiceAddressing.wsdl new file mode 100644 index 000000000..27f247bcf --- /dev/null +++ b/components/soap/src/test/resources/HelloWebServiceAddressing.wsdl @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/HelloWebServiceImport.wsdl b/components/soap/src/test/resources/HelloWebServiceImport.wsdl new file mode 100644 index 000000000..06c4354eb --- /dev/null +++ b/components/soap/src/test/resources/HelloWebServiceImport.wsdl @@ -0,0 +1,12 @@ + + + + + diff --git a/components/soap/src/test/resources/HelloWebServiceImportInterface.wsdl b/components/soap/src/test/resources/HelloWebServiceImportInterface.wsdl new file mode 100644 index 000000000..c68fc55df --- /dev/null +++ b/components/soap/src/test/resources/HelloWebServiceImportInterface.wsdl @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/HelloWebService_schema1.xsd b/components/soap/src/test/resources/HelloWebService_schema1.xsd new file mode 100644 index 000000000..38ec4c294 --- /dev/null +++ b/components/soap/src/test/resources/HelloWebService_schema1.xsd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/HelloWebService_schema2.xsd b/components/soap/src/test/resources/HelloWebService_schema2.xsd new file mode 100644 index 000000000..7eba30adc --- /dev/null +++ b/components/soap/src/test/resources/HelloWebService_schema2.xsd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtom.wsdl b/components/soap/src/test/resources/ImageServiceMtom.wsdl new file mode 100644 index 000000000..5c5147951 --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtom.wsdl @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtom2.wsdl b/components/soap/src/test/resources/ImageServiceMtom2.wsdl new file mode 100644 index 000000000..0c9a4d1ff --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtom2.wsdl @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtomImportTypes.wsdl b/components/soap/src/test/resources/ImageServiceMtomImportTypes.wsdl new file mode 100644 index 000000000..ef54c6d2b --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtomImportTypes.wsdl @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtomImportTypes2.wsdl b/components/soap/src/test/resources/ImageServiceMtomImportTypes2.wsdl new file mode 100644 index 000000000..2ffce22a1 --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtomImportTypes2.wsdl @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtomImportTypes3.wsdl b/components/soap/src/test/resources/ImageServiceMtomImportTypes3.wsdl new file mode 100644 index 000000000..1bb0c22dd --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtomImportTypes3.wsdl @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtomImported.wsdl b/components/soap/src/test/resources/ImageServiceMtomImported.wsdl new file mode 100644 index 000000000..5efc9ab97 --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtomImported.wsdl @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtomImported2.wsdl b/components/soap/src/test/resources/ImageServiceMtomImported2.wsdl new file mode 100644 index 000000000..654d0436b --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtomImported2.wsdl @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtomImported3.wsdl b/components/soap/src/test/resources/ImageServiceMtomImported3.wsdl new file mode 100644 index 000000000..51403f70e --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtomImported3.wsdl @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageServiceMtomImportedMessages3.wsdl b/components/soap/src/test/resources/ImageServiceMtomImportedMessages3.wsdl new file mode 100644 index 000000000..9fbff01e9 --- /dev/null +++ b/components/soap/src/test/resources/ImageServiceMtomImportedMessages3.wsdl @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/ImageService_schema1.xsd b/components/soap/src/test/resources/ImageService_schema1.xsd new file mode 100644 index 000000000..3d91fb555 --- /dev/null +++ b/components/soap/src/test/resources/ImageService_schema1.xsd @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/MultiplePortService.wsdl b/components/soap/src/test/resources/MultiplePortService.wsdl new file mode 100644 index 000000000..0a20055e7 --- /dev/null +++ b/components/soap/src/test/resources/MultiplePortService.wsdl @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/RPClitOrderService.wsdl b/components/soap/src/test/resources/RPClitOrderService.wsdl new file mode 100644 index 000000000..69aa10bc2 --- /dev/null +++ b/components/soap/src/test/resources/RPClitOrderService.wsdl @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/RPClitSwitchyard.xml b/components/soap/src/test/resources/RPClitSwitchyard.xml new file mode 100644 index 000000000..a9414291f --- /dev/null +++ b/components/soap/src/test/resources/RPClitSwitchyard.xml @@ -0,0 +1,27 @@ + + + + + + + RPClitOrderService.wsdl + {urn:switchyard-component-soap:test-ws:1.0}OrderServiceRPC:OrderServiceRPCPort + + + + diff --git a/components/soap/src/test/resources/doclit_request.xml b/components/soap/src/test/resources/doclit_request.xml new file mode 100644 index 000000000..b726e3163 --- /dev/null +++ b/components/soap/src/test/resources/doclit_request.xml @@ -0,0 +1,5 @@ + + PO-19838-XYZ + BUTTER + 200 + \ No newline at end of file diff --git a/components/soap/src/test/resources/doclit_response.xml b/components/soap/src/test/resources/doclit_response.xml new file mode 100644 index 000000000..89dda95ed --- /dev/null +++ b/components/soap/src/test/resources/doclit_response.xml @@ -0,0 +1,7 @@ + + + + PO-19838-XYZ + true + Order Accepted + diff --git a/components/soap/src/test/resources/log4j.properties b/components/soap/src/test/resources/log4j.properties new file mode 100644 index 000000000..b74529992 --- /dev/null +++ b/components/soap/src/test/resources/log4j.properties @@ -0,0 +1,21 @@ +# The logging properties used during tests.. +# +log4j.rootLogger=INFO, file, stdout + +log4j.logger.org.switchyard.component.soap=INFO + + +#log4j.logger.org.apache.camel.impl.converter=DEBUG + + +# 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.file=org.apache.log4j.FileAppender +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n +log4j.appender.file.file=target/soap-tests.log +log4j.appender.file.append=true diff --git a/components/soap/src/test/resources/log4j.xml b/components/soap/src/test/resources/log4j.xml new file mode 100644 index 000000000..c277e7363 --- /dev/null +++ b/components/soap/src/test/resources/log4j.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/Payments.wsdl b/components/soap/src/test/resources/org/switchyard/component/soap/Payments.wsdl new file mode 100644 index 000000000..bb38d6a32 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/Payments.wsdl @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-auth.xml b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-auth.xml new file mode 100644 index 000000000..3c5c90d84 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-auth.xml @@ -0,0 +1,9 @@ + + Foo.wsdl + http://modified.com/phantom + + user + password + domain + + diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-invalid.xml b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-invalid.xml new file mode 100644 index 000000000..7211101bf --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-invalid.xml @@ -0,0 +1,5 @@ + + Foo.wsdl + myendpoint + http://modified.com/phantom + diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-proxy.xml b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-proxy.xml new file mode 100644 index 000000000..d85175107 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-proxy.xml @@ -0,0 +1,11 @@ + + Foo.wsdl + http://modified.com/phantom + + HTTP + 192.168.1.2 + 9090 + user + password + + diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-reference.xml b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-reference.xml new file mode 100644 index 000000000..ccfa237a4 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-reference.xml @@ -0,0 +1,6 @@ + + Foo.wsdl + http://modified.com/phantom + 5000 + + diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-service.xml b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-service.xml new file mode 100644 index 000000000..acabb0283 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/soap-binding-service.xml @@ -0,0 +1,6 @@ + + Foo.wsdl + myendpoint + + + diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/config/model/v1/message-composer.xml b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/v1/message-composer.xml new file mode 100644 index 000000000..e13c3010a --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/v1/message-composer.xml @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/config/model/v1/soap-binding.xml b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/v1/soap-binding.xml new file mode 100644 index 000000000..a6c167ff0 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/config/model/v1/soap-binding.xml @@ -0,0 +1,4 @@ + + + Foo.wsdl + \ No newline at end of file diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/unwrapped-switchyard.xml b/components/soap/src/test/resources/org/switchyard/component/soap/unwrapped-switchyard.xml new file mode 100644 index 000000000..5752566c6 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/unwrapped-switchyard.xml @@ -0,0 +1,27 @@ + + + + + + + + target/test-classes/org/switchyard/component/soap/Payments.wsdl + :18001 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/unwrappedRequest.xml b/components/soap/src/test/resources/org/switchyard/component/soap/unwrappedRequest.xml new file mode 100644 index 000000000..d4893c9e5 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/unwrappedRequest.xml @@ -0,0 +1,5 @@ + + + 100.00 + 50 + \ No newline at end of file diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/wrappedReply.xml b/components/soap/src/test/resources/org/switchyard/component/soap/wrappedReply.xml new file mode 100644 index 000000000..81a4ca1f4 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/wrappedReply.xml @@ -0,0 +1,12 @@ + + + + + + + 100.00 + 50 + + + + \ No newline at end of file diff --git a/components/soap/src/test/resources/org/switchyard/component/soap/wrappedRequest.xml b/components/soap/src/test/resources/org/switchyard/component/soap/wrappedRequest.xml new file mode 100644 index 000000000..a02dc9728 --- /dev/null +++ b/components/soap/src/test/resources/org/switchyard/component/soap/wrappedRequest.xml @@ -0,0 +1,12 @@ + + + + + + + 100.00 + 50 + + + + \ No newline at end of file diff --git a/components/soap/src/test/resources/rpclit_request.xml b/components/soap/src/test/resources/rpclit_request.xml new file mode 100644 index 000000000..314600c64 --- /dev/null +++ b/components/soap/src/test/resources/rpclit_request.xml @@ -0,0 +1,5 @@ + + PO-121212-XYZ + BUTTER + 200 + \ No newline at end of file diff --git a/components/soap/src/test/resources/rpclit_response.xml b/components/soap/src/test/resources/rpclit_response.xml new file mode 100644 index 000000000..7be572741 --- /dev/null +++ b/components/soap/src/test/resources/rpclit_response.xml @@ -0,0 +1,8 @@ + + + + PO-121212-XYZ + true + Order Accepted + + diff --git a/components/test/mixins/activemq/pom.xml b/components/test/mixins/activemq/pom.xml new file mode 100644 index 000000000..9bf55868d --- /dev/null +++ b/components/test/mixins/activemq/pom.xml @@ -0,0 +1,57 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-test-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-component-test-mixin-activemq + jar + SwitchYard: ActiveMQ Test MixIn + ActiveMQ Test MixIn classes + http://switchyard.org + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-test-mixin-naming + + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + org.apache.activemq + activemq-client + + + org.apache.activemq + activemq-broker + + + org.apache.activemq + activemq-rar + rar + + + diff --git a/components/test/mixins/activemq/src/main/java/org/switchyard/component/test/mixins/activemq/ActiveMQMixIn.java b/components/test/mixins/activemq/src/main/java/org/switchyard/component/test/mixins/activemq/ActiveMQMixIn.java new file mode 100644 index 000000000..030d41326 --- /dev/null +++ b/components/test/mixins/activemq/src/main/java/org/switchyard/component/test/mixins/activemq/ActiveMQMixIn.java @@ -0,0 +1,147 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.activemq; + +import java.io.File; + +import javax.jms.Connection; +import javax.jms.JMSException; +import javax.jms.Session; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.activemq.broker.BrokerFactory; +import org.apache.activemq.broker.BrokerService; +import org.switchyard.SwitchYardException; +import org.switchyard.test.mixins.AbstractTestMixIn; + +/** + * ActiveMQ Test Mix In. + */ +public class ActiveMQMixIn extends AbstractTestMixIn { + + private String _config; + private String _url = ActiveMQConnectionFactory.DEFAULT_BROKER_URL; + private String _user = ActiveMQConnectionFactory.DEFAULT_USER; + private String _passwd = ActiveMQConnectionFactory.DEFAULT_PASSWORD; + + /** + * Embedded broker. + */ + private BrokerService _broker; + + private Connection _connection; + + /** + * Default constructor. + */ + public ActiveMQMixIn() { + this(null); + } + + /** + * Constructor. + * @param config Name of ActiveMQ configuration file (spring xml context). + */ + public ActiveMQMixIn(String config) { + _config = config; + } + + @Override + public void initialize() { + super.initialize(); + try { + if (_config == null) { + _broker = new BrokerService(); + _broker.setStartAsync(true); + _broker.setBrokerName("default"); + _broker.setUseJmx(false); + _broker.setPersistent(false); + _broker.setDataDirectoryFile(new File(System.getProperty("java.io.tmpdir"), "activemq-data")); + _broker.addConnector(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL); + _broker.setUseShutdownHook(false); + } else { + _broker = BrokerFactory.createBroker(_config); + } + + _broker.start(); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Set user to connect. + * @param user user + * @return this instance + */ + public ActiveMQMixIn setUser(String user) { + _user = user; + return this; + } + + /** + * Set password to connect. + * @param passwd password + * @return this instance + */ + public ActiveMQMixIn setPassword(String passwd) { + _passwd = passwd; + return this; + } + + /** + * Set configuration file. + * @param config configuration + * @return this instance + */ + public ActiveMQMixIn setConfig(String config) { + _config = config; + return this; + } + + @Override + public void uninitialize() { + try { + if (_connection != null) { + _connection.close(); + } + if (_broker != null) { + _broker.stop(); + } + } catch (final Exception e) { + throw new RuntimeException(e); + } finally { + // always clean JNDI context + super.uninitialize(); + } + } + + /** + * Get a JMS Session from an ActiveMQ connection. + * @return JMS Session + */ + public Session getSession() { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(_url); + try { + if (_connection == null) { + _connection = connectionFactory.createConnection(_user, _passwd); + _connection.start(); + } + return _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + } catch (JMSException e) { + throw new SwitchYardException(e); + } + } + +} diff --git a/components/test/mixins/activemq/src/test/java/org/switchyard/component/test/mixins/activemq/ActiveMQMixInTest.java b/components/test/mixins/activemq/src/test/java/org/switchyard/component/test/mixins/activemq/ActiveMQMixInTest.java new file mode 100644 index 000000000..4a83dead4 --- /dev/null +++ b/components/test/mixins/activemq/src/test/java/org/switchyard/component/test/mixins/activemq/ActiveMQMixInTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.activemq; + +import javax.jms.JMSException; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.TextMessage; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Unit test for {@link ActiveMQMixIn}. + */ +public class ActiveMQMixInTest { + + private static ActiveMQMixIn activeMQMixIn; + + @BeforeClass + public static void setup() { + activeMQMixIn = new ActiveMQMixIn(); + activeMQMixIn.initialize(); + } + + @AfterClass + public static void tearDown() { + activeMQMixIn.uninitialize(); + } + + @Test + public void getClientSession() { + final Session clientSession = activeMQMixIn.getSession(); + Assert.assertNotNull(clientSession); + } + + @Test + public void createQueue() throws JMSException { + final Session session = activeMQMixIn.getSession(); + Queue queue = session.createQueue("foo"); + + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("bar")); + producer.close(); + + MessageConsumer consumer = session.createConsumer(queue); + TextMessage msg = (TextMessage) consumer.receive(); + consumer.close(); + + Assert.assertEquals("bar", msg.getText()); + session.close(); + } + +} diff --git a/components/test/mixins/activemq/src/test/resources/META-INF/beans.xml b/components/test/mixins/activemq/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/test/mixins/activemq/src/test/resources/activemq.xml b/components/test/mixins/activemq/src/test/resources/activemq.xml new file mode 100644 index 000000000..ccebf04dd --- /dev/null +++ b/components/test/mixins/activemq/src/test/resources/activemq.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/components/test/mixins/activemq/src/test/resources/log4j.xml b/components/test/mixins/activemq/src/test/resources/log4j.xml new file mode 100644 index 000000000..0b2a242af --- /dev/null +++ b/components/test/mixins/activemq/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/test/mixins/amqp/pom.xml b/components/test/mixins/amqp/pom.xml new file mode 100644 index 000000000..9797eaae0 --- /dev/null +++ b/components/test/mixins/amqp/pom.xml @@ -0,0 +1,52 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-test-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-component-test-mixin-amqp + jar + SwitchYard: AMQP MixIn + AMQP Test MixIn classes + http://switchyard.org + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-test-mixin-naming + + + + org.apache.qpid + qpid-client + + + org.apache.qpid + qpid-broker + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + diff --git a/components/test/mixins/amqp/src/main/java/org/switchyard/test/mixins/amqp/AMQPMixIn.java b/components/test/mixins/amqp/src/main/java/org/switchyard/test/mixins/amqp/AMQPMixIn.java new file mode 100644 index 000000000..1bf983758 --- /dev/null +++ b/components/test/mixins/amqp/src/main/java/org/switchyard/test/mixins/amqp/AMQPMixIn.java @@ -0,0 +1,190 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.mixins.amqp; + +import java.io.File; +import java.io.InputStream; +import java.net.URL; +import java.util.Properties; + +import javax.jms.ConnectionFactory; +import javax.jms.Destination; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.apache.qpid.client.AMQConnectionFactory; +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.server.Broker; +import org.apache.qpid.server.BrokerOptions; +import org.switchyard.component.test.mixins.naming.NamingMixIn; +import org.switchyard.deploy.internal.AbstractDeployment; +import org.switchyard.SwitchYardException; +import org.switchyard.test.MixInDependencies; +import org.switchyard.test.mixins.AbstractTestMixIn; + +/** + * AMQMixIn helps developers test our AMQP Bindings on SwitchYard applications. + * + * The following files must be present in the classpath: + * + * - amqp.properties file is used to define the following parameters: + * - qpidConnectionfactory: connection factory url (e.g. qpidConnectionfactory = amqp://guest:guest@/test?brokerlist='tcp://localhost:5672') + * - queueExchange: queue exchange to be used as a destination (e.g. BURL:direct://amq.direct//ping?routingkey='#') + * - topicExchange: topic exchange to be used as a destination (e.g. BURL:topic://amq.topic//MyTopic?routingkey='#') + * + * - config.xml file used for Apache QPID configuration. + * - virtualhosts.xml file used for Apache QPID virtual host configurations. + * - log4j.xml file used for Apache Log4J configuration. + * - passwd file used for Apache QPID user credentials. + * + * @author: Eduardo de Vera + * Date: 11/11/12 + * Time: 7:22 PM + */ +@MixInDependencies(required = {NamingMixIn.class}) +public class AMQPMixIn extends AbstractTestMixIn { + + /** + * Connection factory location. + */ + public static final String JNDI_CONNECTION_FACTORY = "java:jboss/qpidConnectionFactory"; + + /** + * Test queue. + */ + public static final String DEFAULT_QUEUE_JNDI_LOCATION = "java:jboss/queueExchange"; + + /** + * Topic location. + */ + public static final String DEFAULT_TOPIC_JNDI_LOCATION = "java:jboss/topicExchange"; + + //amp.properties located in the classpath of the running Thread + private static final String AMQP_PROPERTIES_FILE = "/amqp.properties"; + private static final String LOG_XML = "/log4j.xml"; + private static final String CONFIG_XML = "/config.xml"; + private static final String QPID_WORK_DIRECTORY = "/qpid"; + private static final String SYS_PROP_QPID_HOME = "QPID_HOME"; + private static final String SYS_PROP_QPID_WORK = "QPID_WORK"; + protected static final String AMQP_PROPS_QPID_CONNECTIONFACTORY = "qpidConnectionfactory"; + protected static final String AMQP_PROPS_QUEUE_EXCHANGE = "queueExchange"; + protected static final String AMPQ_PROPS_TOPIC_EXCHANGE = "topicExchange"; + + private Broker _broker; + + private Properties _properties; + private String _qpidConnectionFactory; + private String _qpidQueueExchange; + private String _qpidTopicExchange; + + /** + * Initialize new instance of mixin and read configuration. + * + * @throws Exception In case of initialization failure. + */ + public AMQPMixIn() throws Exception { + _properties = new Properties(); + InputStream is = this.getClass().getResourceAsStream(AMQP_PROPERTIES_FILE); + try { + _properties.load(is); + _qpidConnectionFactory = _properties.getProperty(AMQP_PROPS_QPID_CONNECTIONFACTORY); + } finally { + is.close(); + } + if (_qpidConnectionFactory == null) { + throw new SwitchYardException("No connection factory configured. Please set "+ AMQP_PROPS_QPID_CONNECTIONFACTORY + + " in the "+AMQP_PROPERTIES_FILE+" file found in the class path of your application"); + } + + _qpidQueueExchange = _properties.getProperty(AMQP_PROPS_QUEUE_EXCHANGE); + _qpidTopicExchange = _properties.getProperty(AMPQ_PROPS_TOPIC_EXCHANGE); + + if (_qpidQueueExchange == null && _qpidTopicExchange == null) { + throw new SwitchYardException("No topic or queue configured. Please set either one by using " + + AMQP_PROPS_QUEUE_EXCHANGE + " or " + AMPQ_PROPS_TOPIC_EXCHANGE + " in your " + AMQP_PROPERTIES_FILE + " properties file."); + } + } + + /** + * Gets connection factory instance. + * + * @return Connection factory. + * @throws NamingException In case of lookup failure. + */ + public ConnectionFactory getConnectionFactory() throws NamingException { + return (ConnectionFactory) new InitialContext().lookup(JNDI_CONNECTION_FACTORY); + } + + /** + * Lookup given destination in JNDI tree. + * + * @param destinationName Destination name. + * @return Destination instance. + * @throws NamingException If lookup fails. + */ + public Destination getDestination(String destinationName) throws NamingException { + return (Destination) new InitialContext().lookup(destinationName); + } + + @Override + public void before(AbstractDeployment deployment) { + super.before(deployment); + } + + @Override + public void after(AbstractDeployment deployment) { + super.after(deployment); + } + + @Override + public void initialize() { + File file = new File(this.getClass().getResource("/").getFile()); + + System.setProperty(SYS_PROP_QPID_HOME, file.getPath()); + System.setProperty(SYS_PROP_QPID_WORK, file.getParent() + QPID_WORK_DIRECTORY); + + BrokerOptions options = new BrokerOptions(); + + String configFile = getClass().getResource(CONFIG_XML).getFile(); + options.setConfigFile(configFile); + URL log4j = getClass().getResource(LOG_XML); + if (log4j != null) { + options.setLogConfigFile(log4j.getFile()); + } + + _broker = new Broker(); + try { + _broker.startup(options); + Context context = new InitialContext(); + context.bind(JNDI_CONNECTION_FACTORY, new AMQConnectionFactory(_qpidConnectionFactory)); + if (_qpidQueueExchange != null) { + context.bind(DEFAULT_QUEUE_JNDI_LOCATION, AMQDestination.createDestination(_qpidQueueExchange)); + } + if (_qpidTopicExchange != null) { + context.bind(DEFAULT_TOPIC_JNDI_LOCATION, AMQDestination.createDestination(_qpidTopicExchange)); + } + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + @Override + public void uninitialize() { + if (_broker != null) { + _broker.shutdown(); + } + } + +} diff --git a/components/test/mixins/amqp/src/test/java/org/switchyard/test/mixins/amqp/AMQPMixInTest.java b/components/test/mixins/amqp/src/test/java/org/switchyard/test/mixins/amqp/AMQPMixInTest.java new file mode 100644 index 000000000..de0193577 --- /dev/null +++ b/components/test/mixins/amqp/src/test/java/org/switchyard/test/mixins/amqp/AMQPMixInTest.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.mixins.amqp; + +import javax.jms.Connection; +import javax.jms.Destination; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.TextMessage; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.SwitchYardException; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; + +/** + * Test for AMQMixIn + * + * @author: Eduardo de Vera + */ +@SwitchYardTestCaseConfig(mixins = AMQPMixIn.class) +@RunWith(SwitchYardRunner.class) +public class AMQPMixInTest { + + private AMQPMixIn _mixin; + + private Connection _connection; + + @Before + public void setUp() throws Exception { + _connection = _mixin.getConnectionFactory().createConnection(); + _connection.start(); + } + + @After + public void tearDown() { + try { + _connection.close(); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + @Test + public void testConnection() { + assertThat(_connection, is(notNullValue())); + } + + @Test + public void testSendMessageToQueue() throws Exception { + assertMessageSendAndReceive(AMQPMixIn.DEFAULT_QUEUE_JNDI_LOCATION, "Hello queued world!"); + } + + @Test + public void testSendMessageToTopic() throws Exception { + assertMessageSendAndReceive(AMQPMixIn.DEFAULT_TOPIC_JNDI_LOCATION, "Hello topical world!"); + } + + private void assertMessageSendAndReceive(String destinationName, String messageText) throws Exception { + Session session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destination = (Destination) _mixin.getDestination(destinationName); + + MessageProducer messageProducer = session.createProducer(destination); + MessageConsumer messageConsumer = session.createConsumer(destination); + + TextMessage message = session.createTextMessage(messageText); + messageProducer.send(message); + + message = (TextMessage) messageConsumer.receive(); + assertThat(message.getText(), is(equalTo(messageText))); + } +} diff --git a/components/test/mixins/amqp/src/test/resources/amqp.properties b/components/test/mixins/amqp/src/test/resources/amqp.properties new file mode 100644 index 000000000..403d012bf --- /dev/null +++ b/components/test/mixins/amqp/src/test/resources/amqp.properties @@ -0,0 +1,15 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +qpidConnectionfactory = amqp://guest:guest@/?brokerlist='tcp://localhost:5672' +queueExchange = BURL:direct://amq.direct//ping?routingkey='ping' +topicExchange = BURL:topic://amq.topic//MyTopic?routingkey='#' + No newline at end of file diff --git a/components/test/mixins/amqp/src/test/resources/config.xml b/components/test/mixins/amqp/src/test/resources/config.xml new file mode 100644 index 000000000..f2b8dfd1e --- /dev/null +++ b/components/test/mixins/amqp/src/test/resources/config.xml @@ -0,0 +1,55 @@ + + + + ${QPID_HOME} + ${QPID_WORK} + ${prefix} + + ${QPID_HOME}/lib/plugins + ${QPID_WORK}/cache + + + 65535 + en_US + + + + + + org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase + + + passwordFile + ${conf}/passwd + + + + + false + + + ${conf}/virtualhosts.xml + + + 0 + 2.0 + + + true + + + ON + + \ No newline at end of file diff --git a/camel-amqp-binding/src/test/resources/passwd b/components/test/mixins/amqp/src/test/resources/passwd similarity index 100% rename from camel-amqp-binding/src/test/resources/passwd rename to components/test/mixins/amqp/src/test/resources/passwd diff --git a/components/test/mixins/amqp/src/test/resources/virtualhosts.xml b/components/test/mixins/amqp/src/test/resources/virtualhosts.xml new file mode 100644 index 000000000..95f762e54 --- /dev/null +++ b/components/test/mixins/amqp/src/test/resources/virtualhosts.xml @@ -0,0 +1,55 @@ + + + + test + + + test + + + org.apache.qpid.server.store.MemoryMessageStore + + + + 30000 + 50 + + queue + + amq.direct + 4235264 + + 2117632 + + 600000 + + + + + ping + + amq.direct + 4235264 + + 2117632 + + 600000 + + + + + + + diff --git a/components/test/mixins/cdi/pom.xml b/components/test/mixins/cdi/pom.xml new file mode 100644 index 000000000..1ea679582 --- /dev/null +++ b/components/test/mixins/cdi/pom.xml @@ -0,0 +1,56 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-test-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-component-test-mixin-cdi + jar + SwitchYard: CDI Test MixIn + CDI MixIn classes + http://switchyard.org + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard.components + switchyard-component-test-mixin-naming + + + + org.jboss.spec.javax.resource + jboss-connector-api_1.6_spec + + + org.jboss.weld.se + weld-se-core + + + org.jboss.weld + weld-spi + + + diff --git a/components/test/mixins/cdi/src/main/java/org/switchyard/component/test/mixins/cdi/CDIMixIn.java b/components/test/mixins/cdi/src/main/java/org/switchyard/component/test/mixins/cdi/CDIMixIn.java new file mode 100644 index 000000000..dfc470595 --- /dev/null +++ b/components/test/mixins/cdi/src/main/java/org/switchyard/component/test/mixins/cdi/CDIMixIn.java @@ -0,0 +1,294 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.test.mixins.cdi; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.AnnotatedType; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.BeanManager; +import javax.enterprise.inject.spi.InjectionTarget; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.jboss.weld.bootstrap.api.Bootstrap; +import org.jboss.weld.bootstrap.spi.Deployment; +import org.jboss.weld.environment.se.Weld; +import org.jboss.weld.environment.se.WeldContainer; +import org.jboss.weld.environment.se.events.ContainerInitialized; +import org.jboss.weld.resources.spi.ResourceLoader; +import org.junit.Assert; +import org.switchyard.ServiceDomain; +import org.switchyard.SwitchYardException; +import org.switchyard.common.type.Classes; +import org.switchyard.component.test.mixins.naming.NamingMixIn; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.internal.AbstractDeployment; +import org.switchyard.test.MixInDependencies; +import org.switchyard.test.SimpleTestDeployment; +import org.switchyard.test.TestMixIn; +import org.switchyard.test.mixins.AbstractTestMixIn; + +/** + * CDI Test Mix-In for deploying the Weld CDI Standalone Edition container. + * + * @author tom.fennelly@gmail.com + */ +@MixInDependencies(required={NamingMixIn.class}) +public class CDIMixIn extends AbstractTestMixIn { + private static final String BINDING_CONTEXT = "java:comp"; + private static final String BEAN_MANAGER_NAME = "BeanManager"; + + private static final Pattern[] RESOURCE_FILTER_PATTERNS = new Pattern[] { + Pattern.compile(".*jbpm-.*-services.*beans\\.xml"), + Pattern.compile(".*jbpm-runtime-manager.*beans\\.xml"), + Pattern.compile(".*jbpm-human-task-.*beans\\.xml") + }; + + private Weld _weld; + private WeldContainer _weldContainer; + private AbstractDeployment _simpleCdiDeployment; + private InjectionTarget _testInjectionTarget; + private CreationalContext _testCreationalContext; + + @Override + public void initialize() { + super.initialize(); + + // Deploy the weld container... + _weld = new Weld() { + @Override + protected Deployment createDeployment(final ResourceLoader resourceLoader, Bootstrap bootstrap) { + ResourceLoader filterLoader = new ResourceLoader() { + public void cleanup() { + resourceLoader.cleanup(); + } + public Class classForName(String name) { + return resourceLoader.classForName(name); + } + public URL getResource(String name) { + return filter(resourceLoader.getResource(name)); + } + public Collection getResources(String name) { + Collection urls = new ArrayList(); + for (URL url : resourceLoader.getResources(name)) { + url = filter(url); + if (url != null) { + urls.add(url); + } + } + return urls; + } + private URL filter(URL url) { + if (url != null) { + for (Pattern pattern : RESOURCE_FILTER_PATTERNS) { + if (pattern.matcher(url.toString()).matches()) { + return null; + } + } + } + return url; + } + }; + Deployment deployment = super.createDeployment(filterLoader, bootstrap); + if (getTestKit() != null) { + List mixins = getTestKit().getMixIns(); + for (TestMixIn mixin : mixins) { + if (mixin instanceof CDIMixInParticipant) { + try { + ((CDIMixInParticipant) mixin).participate(deployment); + } catch (Exception e) { + throw new SwitchYardException("Can not initialize Weld due CDIMixIn initialization error", e); + } + } + } + } + return deployment; + } + }; + _weldContainer = _weld.initialize(); + _weldContainer.event().select(ContainerInitialized.class).fire(new ContainerInitialized()); + + // And bind the BeanManager instance into java:comp... + try { + Context ctx = (Context) new InitialContext().lookup(BINDING_CONTEXT); + ctx.rebind(BEAN_MANAGER_NAME, getBeanManager()); + } catch (NamingException e) { + e.printStackTrace(); + Assert.fail("Failed to bind BeanManager into '" + BINDING_CONTEXT + "'."); + } + + injectCDIBeans(); + } + + @Override + public void before(AbstractDeployment deployment) { + if (deployment instanceof SimpleTestDeployment) { + // Not a user defined configuration based test... deploy the Services and Transformers + // found by the CDI discovery process... + @SuppressWarnings("unchecked") + Class simpleCdiDeploymentType = (Class) Classes.forName("org.switchyard.component.bean.internal.SimpleCDIDeployment", getClass()); + if (simpleCdiDeploymentType == null) { + if (getTestKit() != null && getTestKit().getTestInstance().getClass().getPackage() == CDIMixIn.class.getPackage()) { + return; // not fatal for unit tests of CDIMixIn since they can't depend on the bean component as this would create a cyclic Maven dependency. + } else { + Assert.fail("Failed to locate the SimpleCDIDeployment class on the classpath. Module must include the SwitchYard Bean Component as one of its depedencies."); + } + } + try { + _simpleCdiDeployment = simpleCdiDeploymentType.newInstance(); + _simpleCdiDeployment.setParentDeployment(deployment); + ServiceDomain domain = new ServiceDomainManager().createDomain(); + _simpleCdiDeployment.init(domain, getTestKit().getActivators()); + _simpleCdiDeployment.start(); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Failed to manually deploy Bean Service. Exception: " + e.getMessage()); + } + } + } + + /** + * Get the CDI {@link BeanManager}. + * @return The CDI {@link BeanManager}. + */ + public BeanManager getBeanManager() { + return _weldContainer.getBeanManager(); + } + + /** + * Get the {@link javax.inject.Named @Named} CDI {@link Bean}. + * @param name The name of the bean. + * @return The {@link javax.inject.Named @Named} CDI {@link Bean}. + */ + public Bean getBean(String name) { + BeanManager beanManager = getBeanManager(); + Set> beans = beanManager.getBeans(name); + + if (beans != null && !beans.isEmpty()) { + return beans.iterator().next(); + } else { + throw new IllegalStateException("Unable to find CDI bean @Named '" + name + "'. \n\t - Check for a typo in the name. \n\t - Make sure the Class is annotated with the @Name annotation."); + } + } + + /** + * Get the CDI {@link Bean} associated with CDI the specified type. + * @param type The bean type. + * @return The the CDI {@link Bean} associated with CDI the specified type. + */ + public Bean getBean(Class type) { + BeanManager beanManager = getBeanManager(); + Set> beans = beanManager.getBeans(type); + + if (beans != null && !beans.isEmpty()) { + return beans.iterator().next(); + } else { + throw new IllegalStateException("Unable to find CDI bean of type '" + type.getName() + "'."); + } + } + + /** + * Get the object instance associated with a {@link javax.inject.Named @Named} CDI {@link Bean}. + * @param name The name of the bean. + * @return The object instance associated with a {@link javax.inject.Named @Named} CDI {@link Bean}. + */ + public Object getObject(String name) { + return createBeanInstance(getBean(name)); + } + + /** + * Get the object instance associated with a {@link javax.inject.Named @Named} CDI {@link Bean}. + * @param name The name of the bean. + * @param type The bean type. + * @return The object instance associated with a {@link javax.inject.Named @Named} CDI {@link Bean}. + * + * @param Type. + */ + public T getObject(String name, Class type) { + return type.cast(getObject(name)); + } + + /** + * Get the object instance associated with CDI {@link Bean} of the specified type. + * @param type The bean type. + * @return The object instance associated with CDI {@link Bean} of the specified type. + * + * @param Type. + */ + public T getObject(Class type) { + return type.cast(createBeanInstance(getBean(type))); + } + + @Override + public void after(AbstractDeployment deployment) { + if (_simpleCdiDeployment != null) { + _simpleCdiDeployment.stop(); + _simpleCdiDeployment.destroy(); + } + } + + @Override + public synchronized void uninitialize() { + disposeCDIBeans(); + + if (_weld != null) { + _weld.shutdown(); + _weld = null; + } else { + Thread.dumpStack(); + } + + // Clean up JNDI tree + super.uninitialize(); + } + + private Object createBeanInstance(Bean bean) { + BeanManager beanManager = getBeanManager(); + CreationalContext creationalContext = beanManager.createCreationalContext(null); + + return beanManager.getReference(bean, bean.getBeanClass(), creationalContext); + } + + @SuppressWarnings("unchecked") + private void injectCDIBeans() { + BeanManager beanManager = getBeanManager(); + Object testInstance = getTestKit() != null ? getTestKit().getTestInstance() : null; + if (beanManager != null && testInstance != null) { + // delegate dependency injection and lifecycle callbacks to the CDI container + AnnotatedType type = beanManager.createAnnotatedType((Class) testInstance.getClass()); + _testInjectionTarget = beanManager.createInjectionTarget(type); + _testCreationalContext = beanManager.createCreationalContext(null); + _testInjectionTarget.inject(getTestKit().getTestInstance(), _testCreationalContext); + _testInjectionTarget.postConstruct(getTestKit().getTestInstance()); + } + } + + private void disposeCDIBeans() { + if (_testInjectionTarget != null) { + Object testInstance = getTestKit().getTestInstance(); + _testInjectionTarget.preDestroy(testInstance); + _testInjectionTarget.dispose(testInstance); + _testCreationalContext.release(); + } + } +} diff --git a/components/test/mixins/cdi/src/main/java/org/switchyard/component/test/mixins/cdi/CDIMixInParticipant.java b/components/test/mixins/cdi/src/main/java/org/switchyard/component/test/mixins/cdi/CDIMixInParticipant.java new file mode 100644 index 000000000..d16a46516 --- /dev/null +++ b/components/test/mixins/cdi/src/main/java/org/switchyard/component/test/mixins/cdi/CDIMixInParticipant.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.cdi; + +import org.jboss.weld.bootstrap.spi.Deployment; + +/** + * Interface for MixIns which are interested in populating Weld deployment during + * startup of CDI MixIn. + */ +public interface CDIMixInParticipant { + + /** + * Method called after Weld SE deployment is created. + * + * @param deployment Weld deployment instance. + * @throws Exception If something goes wrong and CDI environment can not be + * populated with necessary beans. + */ + void participate(Deployment deployment) throws Exception; + + +} diff --git a/components/test/mixins/cdi/src/test/java/org/switchyard/component/test/mixins/cdi/CDIMixInInjectionTest.java b/components/test/mixins/cdi/src/test/java/org/switchyard/component/test/mixins/cdi/CDIMixInInjectionTest.java new file mode 100644 index 000000000..2944f5bc6 --- /dev/null +++ b/components/test/mixins/cdi/src/test/java/org/switchyard/component/test/mixins/cdi/CDIMixInInjectionTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.test.mixins.cdi; + +import javax.inject.Inject; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.test.SwitchYardTestCaseConfig; + +class ExampleBean { +} + +@RunWith(SwitchYardRunner.class) +@SwitchYardTestCaseConfig(mixins = CDIMixIn.class) +public class CDIMixInInjectionTest { + + @Inject + private ExampleBean exampleBean; + + @Test + public void test() { + Assert.assertNotNull(exampleBean); + } +} diff --git a/components/test/mixins/cdi/src/test/java/org/switchyard/component/test/mixins/cdi/CDIMixInStopStartTest.java b/components/test/mixins/cdi/src/test/java/org/switchyard/component/test/mixins/cdi/CDIMixInStopStartTest.java new file mode 100644 index 000000000..a86b72bb8 --- /dev/null +++ b/components/test/mixins/cdi/src/test/java/org/switchyard/component/test/mixins/cdi/CDIMixInStopStartTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.test.mixins.cdi; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.SwitchYardRunner; +import org.switchyard.component.test.mixins.naming.NamingMixIn; + +/** + * @author tom.fennelly@gmail.com + */ +@RunWith(SwitchYardRunner.class) +public class CDIMixInStopStartTest { + + @Test + public void test() { + NamingMixIn namingMixIn = new NamingMixIn(); + CDIMixIn cdiMixIn = new CDIMixIn(); + + namingMixIn.initialize(); + cdiMixIn.initialize(); + cdiMixIn.uninitialize(); + namingMixIn.uninitialize(); + } +} diff --git a/components/test/mixins/cdi/src/test/resources/META-INF/beans.xml b/components/test/mixins/cdi/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/test/mixins/cdi/src/test/resources/log4j.xml b/components/test/mixins/cdi/src/test/resources/log4j.xml new file mode 100644 index 000000000..0b2a242af --- /dev/null +++ b/components/test/mixins/cdi/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/test/mixins/hornetq/pom.xml b/components/test/mixins/hornetq/pom.xml new file mode 100644 index 000000000..bcd8e77ad --- /dev/null +++ b/components/test/mixins/hornetq/pom.xml @@ -0,0 +1,64 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-test-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-component-test-mixin-hornetq + jar + SwitchYard: HornetQ Test MixIn + HornetQ Test MixIn classes + http://switchyard.org + + + + org.switchyard.components + switchyard-component-test-mixin-naming + + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + org.hornetq + hornetq-ra + + + org.hornetq + hornetq-commons + + + org.hornetq + hornetq-core-client + + + org.hornetq + hornetq-jms-client + + + org.hornetq + hornetq-server + + + org.hornetq + hornetq-jms-server + + + diff --git a/components/test/mixins/hornetq/src/main/java/org/switchyard/component/test/mixins/hornetq/HornetQMixIn.java b/components/test/mixins/hornetq/src/main/java/org/switchyard/component/test/mixins/hornetq/HornetQMixIn.java new file mode 100644 index 000000000..2da2eefe0 --- /dev/null +++ b/components/test/mixins/hornetq/src/main/java/org/switchyard/component/test/mixins/hornetq/HornetQMixIn.java @@ -0,0 +1,671 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.hornetq; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.ObjectInputStream; +import java.io.Reader; +import java.io.StringWriter; +import java.io.Writer; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.jms.BytesMessage; +import javax.jms.Connection; +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.ObjectMessage; +import javax.jms.Queue; +import javax.jms.Session; +import javax.jms.TextMessage; +import javax.jms.Topic; + +import org.junit.Assert; + +import org.apache.log4j.Logger; +import org.hornetq.api.core.HornetQBuffer; +import org.hornetq.api.core.HornetQException; +import org.hornetq.api.core.TransportConfiguration; +import org.hornetq.api.core.client.ClientConsumer; +import org.hornetq.api.core.client.ClientMessage; +import org.hornetq.api.core.client.ClientProducer; +import org.hornetq.api.core.client.ClientSession; +import org.hornetq.api.core.client.ClientSessionFactory; +import org.hornetq.api.core.client.HornetQClient; +import org.hornetq.api.core.client.ServerLocator; +import org.hornetq.core.config.Configuration; +import org.hornetq.core.registry.JndiBindingRegistry; +import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory; +import org.hornetq.core.remoting.impl.netty.TransportConstants; +import org.hornetq.jms.client.HornetQConnectionFactory; +import org.hornetq.jms.client.HornetQQueue; +import org.hornetq.jms.client.HornetQTopic; +import org.hornetq.jms.server.embedded.EmbeddedJMS; +import org.switchyard.test.MixInDependencies; +import org.switchyard.test.mixins.AbstractTestMixIn; +import org.switchyard.component.test.mixins.naming.NamingMixIn; + +/** + * HornetQ Test Mix In. + * + * @author Daniel Bevenius + */ +@MixInDependencies(required={NamingMixIn.class}) +public class HornetQMixIn extends AbstractTestMixIn { + + private static final String HORNETQ_CONF_FILE = "hornetq-configuration.xml"; + private static final String HORNETQ_JMS_CONF_FILE = "hornetq-jms.xml"; + + private static final String HOST_PROP_NAME = "hornetqmixin.host"; + private static final String PORT_PROP_NAME = "hornetqmixin.port"; + private static final String HTTP_UPGRADE_ENABLED_PROP_NAME = "hornetqmixin.http.upgrade.enabled"; + // TODO Use TransportConstants.HTTP_UPGRADE_ENABLED_PROP_NAME instead once we upgrade to HornetQ 2.4.x + private static final String HORNETQ_HTTP_UPGRADE_ENABLED_PROP_NAME = "http-upgrade-enabled"; + + private Logger _logger = Logger.getLogger(HornetQMixIn.class); + private boolean _startEmbedded; + private Map _transportParams; + private String _user = null; + private String _passwd = null; + private EmbeddedJMS _embeddedJMS; + private ServerLocator _serverLocator; + private ClientSessionFactory _clientSessionFactory; + private ClientSession _clientSession; + + private HornetQConnectionFactory _jmsConnectionFactory; + private Connection _jmsConnection; + private Session _jmsSession; + + /** + * Default constructor. + */ + public HornetQMixIn() { + this(true); + } + + /** + * Constructor. + * @param embedded true if you want to start embedded HornetQ server, + * or false if you want to connect to remote HornetQ server. + */ + public HornetQMixIn(boolean embedded) { + _startEmbedded = embedded; + _transportParams = new HashMap(); + String host = System.getProperty(HOST_PROP_NAME); + if (host == null) { + host = TransportConstants.DEFAULT_HOST; + } + _transportParams.put(TransportConstants.HOST_PROP_NAME, host); + String port = System.getProperty(PORT_PROP_NAME); + if (port == null) { + port = Integer.toString(TransportConstants.DEFAULT_PORT); + } + _transportParams.put(TransportConstants.PORT_PROP_NAME, port); + String upgrade = System.getProperty(HTTP_UPGRADE_ENABLED_PROP_NAME); + if (upgrade != null) { + _transportParams.put(HORNETQ_HTTP_UPGRADE_ENABLED_PROP_NAME, upgrade); + } + } + + @Override + public void initialize() { + super.initialize(); + if (_startEmbedded) { + _embeddedJMS = new EmbeddedJMS(); + _embeddedJMS.setConfigResourcePath(HORNETQ_CONF_FILE); + _embeddedJMS.setJmsConfigResourcePath(HORNETQ_JMS_CONF_FILE); + try { + _embeddedJMS.setRegistry(new JndiBindingRegistry()); + _embeddedJMS.start(); + } catch (final Exception e) { + throw new RuntimeException(e); + } + } + } + + /** + * Set host address to connect. + * @param host address + * @return this instance + */ + public HornetQMixIn setHost(String host) { + _transportParams.put(TransportConstants.HOST_PROP_NAME, host); + return this; + } + + /** + * Set port number to connect. + * @param port port number + * @return this instance + */ + public HornetQMixIn setPort(int port) { + _transportParams.put(TransportConstants.PORT_PROP_NAME, port); + return this; + } + + /** + * Set http-upgrade-enabled. + * @param upgrade http-upgrade-enabled + * @return this instance + */ + public HornetQMixIn setHttpUpgradeEnabled(boolean upgrade) { + _transportParams.put(HORNETQ_HTTP_UPGRADE_ENABLED_PROP_NAME, upgrade); + return this; + } + + /** + * Set a transport parameter. + * @param key key + * @param value value + * @return this instance + */ + public HornetQMixIn setTransportParameter(String key, Object value) { + _transportParams.put(key, value); + return this; + } + + /** + * Set user to connect. + * @param user user + * @return this instance + */ + public HornetQMixIn setUser(String user) { + _user = user; + return this; + } + + /** + * Set password to connect. + * @param passwd password + * @return this instance + */ + public HornetQMixIn setPassword(String passwd) { + _passwd = passwd; + return this; + } + + /** + * Gets the HornetQ {@link Configuration}. + * + * @return Configuration the HornetQ configuration used for this Embedded Server. + * Return null if this HornetQMixIn instance is initialized for remote HornetQ Server. + */ + public Configuration getConfiguration() { + if (_embeddedJMS == null) { + return null; + } + + return _embeddedJMS.getHornetQServer().getConfiguration(); + } + + private static TransportConfiguration[] getTransports(final Configuration from) { + final Collection transports = from.getConnectorConfigurations().values(); + return transports.toArray(new TransportConfiguration[]{}); + } + + @Override + public void uninitialize() { + try { + HornetQMixIn.closeSession(_clientSession); + HornetQMixIn.closeSessionFactory(_clientSessionFactory); + HornetQMixIn.closeServerLocator(_serverLocator); + + HornetQMixIn.closeJMSSession(_jmsSession); + HornetQMixIn.closeJMSConnection(_jmsConnection); + HornetQMixIn.closeJMSConnectionFactory(_jmsConnectionFactory); + + if (_embeddedJMS != null) { + _embeddedJMS.stop(); + } + } catch (final Exception e) { + throw new RuntimeException(e); + } finally { + // always clean JNDI context + super.uninitialize(); + } + } + + /** + * By giving tests access to the {@link ClientSession} enables test to be able to + * create queues, consumers, and producers. + * + * @return {@link ClientSession} which can be used to create queues/topics, consumers/producers. + */ + public ClientSession getClientSession() { + if (_clientSession != null) { + return _clientSession; + } + + return createClientSession(); + } + + /** + * Close the existing ClientSession if exists and create new one. + * @return ClientSession instance + */ + public ClientSession createClientSession() { + closeSession(_clientSession); + + try { + if (_serverLocator == null || _clientSessionFactory == null) { + if (_startEmbedded) { + _serverLocator = HornetQClient.createServerLocatorWithoutHA(getTransports(getConfiguration())); + _clientSessionFactory = _serverLocator.createSessionFactory(); + } else { + _serverLocator = HornetQClient.createServerLocatorWithoutHA( + new TransportConfiguration(NettyConnectorFactory.class.getName(), _transportParams)); + _clientSessionFactory = _serverLocator.createSessionFactory(); + } + } + + _clientSession = _clientSessionFactory.createSession(_user, + _passwd, + false, + true, + true, + _serverLocator.isPreAcknowledge(), + _serverLocator.getAckBatchSize()); + _clientSession.start(); + return _clientSession; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Creates a HornetQ {@link ClientMessage} with the passed-in String as the body. + * + * @param body the String to be used as the messages payload(body) + * @return ClientMessage with the passed-in String as its payload. + */ + public ClientMessage createMessage(final String body) { + final ClientMessage message = getClientSession().createMessage(true); + message.getBodyBuffer().writeBytes(body.getBytes()); + return message; + } + + /** + * Load a resource from classpath with the passed-in String and create a HornetQ + * {@link ClientMessage} using the content of resource as its payload. + * + * @param path resource path + * @return ClientMessage with the resource as its payload. + */ + public ClientMessage createMessageFromResource(final String path) { + InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); + String payload = getStringFromInputStream(stream); + return createMessage(payload); + } + + /** + * Reads the body of a HornetQ {@link ClientMessage} as an Object. + * + * @param msg the HornetQ {@link ClientMessage}. + * @return Object the object read. + * @throws Exception if an error occurs while trying to read the body content. + */ + public Object readObjectFromMessage(final ClientMessage msg) throws Exception { + byte[] bytes = new byte[msg.getBodySize()]; + final HornetQBuffer bodyBuffer = msg.getBodyBuffer(); + bodyBuffer.readBytes(bytes); + + Object result = null; + try { + final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); + result = in.readObject(); + } catch (Exception e) { + _logger.warn("Caught an Exception during deserializing object. Then trying to read as String"); + _logger.debug("",e); + result = new String(bytes); + } + + return result; + } + + /** + * Reads the body of a HornetQ {@link ClientMessage} as an String and perform String compare between + * the message payload and specified expected String. + * @param msg the HornetQ {@link ClientMessage} + * @param expected expected String in the message body + * @return actual String in the message body + * @throws Exception if an error occurs while trying to read the body content. + */ + public String readMessageAndTestString(final ClientMessage msg, final String expected) throws Exception { + Object payload = readObjectFromMessage(msg); + Assert.assertTrue(payload instanceof String); + Assert.assertEquals(expected, (String)payload); + return (String)payload; + } + + + /** + * By giving tests access to the {@link Session} enables test to be able to + * create queues, consumers, and producers. + * + * @return {@link Session} which can be used to create queues/topics, consumers/producers. + */ + public Session getJMSSession() { + if (_jmsSession != null) { + return _jmsSession; + } + return createJMSSession(); + } + + /** + * Close the existing Session if exists and create new one. + * @return Session instance + */ + public Session createJMSSession() { + closeJMSSession(_jmsSession); + + try { + if (_jmsConnectionFactory == null || _jmsConnection == null) { + if (_startEmbedded) { + _jmsConnectionFactory = new HornetQConnectionFactory(false, getTransports(getConfiguration())); + } else { + _jmsConnectionFactory = new HornetQConnectionFactory(false, + new TransportConfiguration(NettyConnectorFactory.class.getName(), _transportParams)); + } + _jmsConnection = _jmsConnectionFactory.createConnection(_user, _passwd); + _jmsConnection.start(); + } + _jmsSession = _jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + return _jmsSession; + } catch (JMSException e) { + throw new RuntimeException(e); + } + } + + /** + * Creates a JMS {@link ObjectMessage} with the passed-in String as the body. + * + * @param body the String to be used as the messages payload(body) + * @return ObjectMessage with the passed-in String as its payload. + * @throws JMSException if an error occurs while creating the message. + */ + public ObjectMessage createJMSMessage(final String body) throws JMSException { + return _jmsSession.createObjectMessage(body); + } + + /** + * Load a resource from classpath with the passed-in String and create a JMS + * {@link Message} using the content of resource as its payload. + * + * @param path resource path + * @return ClientMessage with the resource as its payload. + * @throws JMSException if an error occurs while creating the message. + */ + public Message createJMSMessageFromResource(final String path) throws JMSException { + InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path); + String payload = getStringFromInputStream(stream); + return createJMSMessage(payload); + } + + /** + * Reads the body of a JMS {@link Message} as an Object. + * + * @param msg the JMS {@link Message}. + * @return the object read. + * @throws JMSException if an error occurs while trying to read the body content. + */ + public Object readObjectFromJMSMessage(final Message msg) throws JMSException { + Assert.assertTrue(msg instanceof ObjectMessage); + ObjectMessage objMsg = (ObjectMessage)msg; + return objMsg.getObject(); + } + + /** + * Reads the body of a JMS {@link Message} as a byte[]. + * + * @param msg JMS {@link Message} + * @return the byte[] read. + * @throws JMSException if an error occurs while trying to read the body content. + */ + public byte[] readBytesFromJMSMessage(final Message msg) throws JMSException { + Assert.assertTrue(msg instanceof BytesMessage); + BytesMessage bsMsg = (BytesMessage)msg; + if (bsMsg.getBodyLength() >= Integer.MAX_VALUE) { + Assert.fail("Message body is too large[" + bsMsg.getBodyLength() + "]: extract it manually."); + } + byte[] ba = new byte[(int)bsMsg.getBodyLength()]; + bsMsg.readBytes(ba); + return ba; + } + /** + * Reads the body of a JMS {@link Message} as a String. + * @param msg the JMS {@link Message}. + * @return the string read. + * @throws JMSException if an error occurs while trying to read the body content. + */ + public String readStringFromJMSMessage(final Message msg) throws JMSException { + if (msg instanceof TextMessage) { + TextMessage txt = (TextMessage)msg; + return txt.getText(); + } else if (msg instanceof ObjectMessage) { + return (String)readObjectFromJMSMessage(msg); + } else if (msg instanceof BytesMessage) { + return new String(readBytesFromJMSMessage(msg)); + } + throw new RuntimeException("The message body could not be extracted as String: " + msg); + } + /** + * Reads the body of a JMS {@link Message} as an String and perform String compare between + * the message payload and specified expected String. + * @param msg the JMS {@link Message}. + * @param expected expected String in the message body + * @return actual String in the message body + * @throws JMSException if an error occurs while trying to read the body content. + */ + public String readJMSMessageAndTestString(final Message msg, final String expected) throws JMSException { + String payload = readStringFromJMSMessage(msg); + Assert.assertEquals(expected, (String)payload); + return payload; + } + /** + * Closes the passed-in {@link ServerLocator}. + * + * @param serverLocator the {@link ServerLocator} instance to close. + */ + public static void closeServerLocator(final ServerLocator serverLocator) { + if (serverLocator != null) { + serverLocator.close(); + } + } + + /** + * Closes the passed-in {@link ClientSessionFactory}. + * + * @param factory the {@link ClientSessionFactory} instance to close. + */ + public static void closeSessionFactory(final ClientSessionFactory factory) { + if (factory != null) { + factory.close(); + } + } + + /** + * Closes the passed-in {@link ClientSession}. + * + * @param session the {@link ClientSession} instance to close. + */ + public static void closeSession(final ClientSession session) { + if (session != null) { + try { + session.close(); + } catch (final HornetQException ignore) { + ignore.printStackTrace(); + } + } + } + + /** + * Closes the passed-in {@link ClientConsumer}. + * + * @param consumer the {@link ClientConsumer} instance to close. + */ + public static void closeClientConsumer(final ClientConsumer consumer) { + if (consumer != null) { + try { + consumer.close(); + } catch (final HornetQException ignore) { + ignore.printStackTrace(); + } + } + } + + /** + * Closes the passed-in {@link ClientProducer}. + * + * @param producer the {@link ClientProducer} to close. + */ + public static void closeClientProducer(final ClientProducer producer) { + if (producer != null) { + try { + producer.close(); + } catch (final HornetQException ignore) { + ignore.printStackTrace(); + } + } + } + + /** + * Closes the passed-in {@link ConnectionFactory}. + * + * @param cf the {@link HornetQConnectionFactory} instance to close. + */ + public static void closeJMSConnectionFactory(final HornetQConnectionFactory cf) { + if (cf != null) { + cf.close(); + } + } + + /** + * Closes the passed-in {@link Connection}. + * + * @param conn the {@link Connection} instance to close. + */ + public static void closeJMSConnection(final Connection conn) { + if (conn != null) { + try { + conn.close(); + } catch (JMSException ignore) { + ignore.printStackTrace(); + } + } + } + + /** + * Closes the passed-in {@link Session}. + * + * @param session the {@link Session} instance to close. + */ + public static void closeJMSSession(final Session session) { + if (session != null) { + try { + session.close(); + } catch (JMSException ignore) { + ignore.printStackTrace(); + } + } + } + + /** + * Closes the passed-in {@link MessageConsumer}. + * + * @param consumer the {@link MessageConsumer} instance to close. + */ + public static void closeJMSConsumer(final MessageConsumer consumer) { + if (consumer != null) { + try { + consumer.close(); + } catch (final JMSException ignore) { + ignore.printStackTrace(); + } + } + } + + /** + * Closes the passed-in {@link MessageProducer}. + * + * @param producer the {@link MessageProducer} to close. + */ + public static void closeJMSProducer(final MessageProducer producer) { + if (producer != null) { + try { + producer.close(); + } catch (final JMSException ignore) { + ignore.printStackTrace(); + } + } + } + + /** + * Get {@link Queue} instance from core queue name. + * @param name core queue name + * @return {@link Queue} object + */ + public static Queue getJMSQueue(final String name) { + return new HornetQQueue(name); + } + + /** + * Get {@link Topic} instance from core topic name. + * @param name core topic name + * @return {@link Topic} object + */ + public static Topic getJMSTopic(final String name) { + return new HornetQTopic(name); + } + + /** + * Create String object from InputStream + * @param source source to read + * @return String object extracted from InputStream + */ + private String getStringFromInputStream(InputStream source) { + Writer writer = new StringWriter(); + Reader reader = null; + char[] buffer = new char[1024]; + try { + + reader = new BufferedReader( + new InputStreamReader(source, "UTF-8")); + int n; + while ((n = reader.read(buffer)) != -1) { + writer.write(buffer, 0, n); + } + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + try { + if (reader != null) { + reader.close(); + } + if (source != null) { + source.close(); + } + } catch (IOException ignore) { + ignore.printStackTrace(); + } + } + return writer.toString(); + } +} diff --git a/components/test/mixins/hornetq/src/test/java/org/switchyard/component/test/mixins/hornetq/HornetQMixInTest.java b/components/test/mixins/hornetq/src/test/java/org/switchyard/component/test/mixins/hornetq/HornetQMixInTest.java new file mode 100644 index 000000000..b2b7ebbbd --- /dev/null +++ b/components/test/mixins/hornetq/src/test/java/org/switchyard/component/test/mixins/hornetq/HornetQMixInTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.hornetq; + +import org.hornetq.api.core.HornetQException; +import org.hornetq.api.core.SimpleString; +import org.hornetq.api.core.client.ClientSession; +import org.hornetq.api.core.client.ClientSession.BindingQuery; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.naming.NamingMixIn; + +/** + * Unit test for {@link HornetQMixIn}. + * + * @author Daniel Bevenius + * + */ +public class HornetQMixInTest { + + private static NamingMixIn namingMixIn; + private static HornetQMixIn hornetQMixIn; + + @BeforeClass + public static void setup() { + namingMixIn = new NamingMixIn(); + namingMixIn.initialize(); + hornetQMixIn = new HornetQMixIn(); + hornetQMixIn.initialize(); + } + + @AfterClass + public static void tearDown() { + hornetQMixIn.uninitialize(); + namingMixIn.uninitialize(); + } + + @Test + public void getClientSession() { + final ClientSession clientSession = hornetQMixIn.getClientSession(); + Assert.assertNotNull(clientSession); + } + + @Test + public void createQueue() throws HornetQException { + final ClientSession clientSession = hornetQMixIn.getClientSession(); + final SimpleString queueName = new SimpleString("testQueue"); + clientSession.createQueue(queueName, queueName); + final BindingQuery bindingQuery = clientSession.bindingQuery(queueName); + Assert.assertTrue(bindingQuery.isExists()); + Assert.assertEquals(1, bindingQuery.getQueueNames().size()); + final SimpleString actualQueueName = bindingQuery.getQueueNames().get(0); + Assert.assertEquals(queueName, actualQueueName); + } + +} diff --git a/components/test/mixins/hornetq/src/test/resources/META-INF/beans.xml b/components/test/mixins/hornetq/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/test/mixins/hornetq/src/test/resources/hornetq-configuration.xml b/components/test/mixins/hornetq/src/test/resources/hornetq-configuration.xml new file mode 100644 index 000000000..8cdd9794c --- /dev/null +++ b/components/test/mixins/hornetq/src/test/resources/hornetq-configuration.xml @@ -0,0 +1,32 @@ + + + target/data/paging + target/data/bindings + false + target/data/journal + 10 + target/data/large-messages + false + + + + org.hornetq.core.remoting.impl.invm.InVMConnectorFactory + + + org.hornetq.core.remoting.impl.netty.NettyConnectorFactory + + + + + + + org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory + + + org.hornetq.core.remoting.impl.netty.NettyAcceptorFactory + + + + + + \ No newline at end of file diff --git a/components/test/mixins/hornetq/src/test/resources/hornetq-jms.xml b/components/test/mixins/hornetq/src/test/resources/hornetq-jms.xml new file mode 100644 index 000000000..d0d23ef67 --- /dev/null +++ b/components/test/mixins/hornetq/src/test/resources/hornetq-jms.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + true + + + + + true + + + \ No newline at end of file diff --git a/components/test/mixins/hornetq/src/test/resources/log4j.xml b/components/test/mixins/hornetq/src/test/resources/log4j.xml new file mode 100644 index 000000000..0b2a242af --- /dev/null +++ b/components/test/mixins/hornetq/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/test/mixins/http/pom.xml b/components/test/mixins/http/pom.xml new file mode 100644 index 000000000..51f1ab725 --- /dev/null +++ b/components/test/mixins/http/pom.xml @@ -0,0 +1,39 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-test-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-component-test-mixin-http + jar + SwitchYard: HTTP Test MixIn + HTTP Test MixIn classes + http://switchyard.org + + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents + httpcore + + + diff --git a/components/test/mixins/http/src/main/java/org/switchyard/component/test/mixins/http/HTTPMixIn.java b/components/test/mixins/http/src/main/java/org/switchyard/component/test/mixins/http/HTTPMixIn.java new file mode 100644 index 000000000..e391920cc --- /dev/null +++ b/components/test/mixins/http/src/main/java/org/switchyard/component/test/mixins/http/HTTPMixIn.java @@ -0,0 +1,485 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.test.mixins.http; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import javax.net.ssl.SSLContext; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpHead; +import org.apache.http.client.methods.HttpOptions; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.FileEntity; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; +import org.apache.log4j.Logger; +import org.junit.Assert; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.test.mixins.AbstractTestMixIn; + +/** + * HTTP Test Mix In. + * + * @author tom.fennelly@gmail.com + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class HTTPMixIn extends AbstractTestMixIn { + private static Logger _logger = Logger.getLogger(HTTPMixIn.class); + + /** + * Constant representing HTTP DELETE method. + */ + public static final String HTTP_DELETE = "DELETE"; + + /** + * Constant representing HTTP GET method. + */ + public static final String HTTP_GET = "GET"; + + /** + * Constant representing HTTP HEAD method. + */ + public static final String HTTP_HEAD = "HEAD"; + + /** + * Constant representing HTTP POST method. + */ + public static final String HTTP_POST = "POST"; + + /** + * Constant representing HTTP PUT method. + */ + public static final String HTTP_PUT = "PUT"; + + /** + * Constant representing HTTP OPTIONS method. + */ + public static final String HTTP_OPTIONS = "OPTIONS"; + + private HttpClient _httpClient; + private String _contentType = "text/xml"; + private HashMap _requestHeaders = new HashMap(); + private HashMap _expectedHeaders = new HashMap(); + private boolean _dumpMessages = false; + private SSLContext _sslContext; + + /** + * Default constructor. + */ + public HTTPMixIn() { + super(); + } + + /** + * Create a new HTTPMixIn. + * + * @param sslContext SSLContext to use for secure connections. + */ + public HTTPMixIn(SSLContext sslContext) { + this(); + _sslContext = sslContext; + } + + /** + * Set the content type. + *

+ * Default content type is "text/xml". + * + * @param contentType The content type. + * @return This HTTPMixIn instance. + */ + public HTTPMixIn setContentType(String contentType) { + this._contentType = contentType; + return this; + } + + @Override + public void initialize() { + _httpClient = HttpClientBuilder.create().setSslcontext(_sslContext).build(); + } + + /** + * Send the specified request payload to the specified HTTP endpoint using the method specified. + * @param endpointURL The HTTP endpoint URL. + * @param request The request payload. + * @param method The request method. + * @return The HTTP response code. + */ + public int sendStringAndGetStatus(String endpointURL, String request, String method) { + HttpResponse httpResponse = sendStringAndGetMethod(endpointURL, request, method); + int status = httpResponse.getStatusLine().getStatusCode(); + if ((httpResponse.getEntity() != null) && (httpResponse.getEntity().getContentLength() == -1)) { + _httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.SECONDS); + } else { + EntityUtils.consumeQuietly(httpResponse.getEntity()); + } + return status; + } + + /** + * Send the specified request payload to the specified HTTP endpoint using the method specified. + * @param endpointURL The HTTP endpoint URL. + * @param request The request payload. + * @param method The request method. + * @return The HTTP response payload. + */ + public String sendString(String endpointURL, String request, String method) { + String response = null; + try { + HttpResponse httpResponse = sendStringAndGetMethod(endpointURL, request, method); + response = EntityUtils.toString(httpResponse.getEntity()); + } catch (IOException ioe) { + _logger.error("Unable to get response", ioe); + } + return response; + } + + /** + * Send the specified request payload to the specified HTTP endpoint using the method specified. + * @param endpointURL The HTTP endpoint URL. + * @param request The request payload. + * @param method The request method. + * @return The HttpResponse object. + */ + public HttpResponse sendStringAndGetMethod(String endpointURL, String request, String method) { + if (_dumpMessages) { + _logger.info("Sending a " + method + " request to [" + endpointURL + "]"); + _logger.info("Request body:[" + request + "]"); + } + HttpRequestBase httpMethod = null; + HttpResponse response = null; + try { + if (method.equals(HTTP_PUT)) { + httpMethod = new HttpPut(endpointURL); + ((HttpPut)httpMethod).setEntity(new StringEntity(request, _contentType, "UTF-8")); + } else if (method.equals(HTTP_POST)) { + httpMethod = new HttpPost(endpointURL); + ((HttpPost)httpMethod).setEntity(new StringEntity(request, _contentType, "UTF-8")); + } else if (method.equals(HTTP_DELETE)) { + httpMethod = new HttpDelete(endpointURL); + } else if (method.equals(HTTP_OPTIONS)) { + httpMethod = new HttpOptions(endpointURL); + } else if (method.equals(HTTP_HEAD)) { + httpMethod = new HttpHead(endpointURL); + } else { + httpMethod = new HttpGet(endpointURL); + } + response = execute(httpMethod); + } catch (UnsupportedEncodingException e) { + _logger.error("Unable to set request entity", e); + } + return response; + } + + /** + * POST the specified request payload to the specified HTTP endpoint. + * @param endpointURL The HTTP endpoint URL. + * @param request The request payload. + * @return The HTTP response payload. + */ + public String postString(String endpointURL, String request) { + if (_dumpMessages) { + _logger.info("Sending a POST request to [" + endpointURL + "]"); + _logger.info("Request body:[" + request + "]"); + } + + HttpPost postMethod = new HttpPost(endpointURL); + try { + postMethod.setEntity(new StringEntity(request, _contentType, "UTF-8")); + } catch (UnsupportedEncodingException e) { + _logger.error("Unable to set request entity", e); + } + HttpResponse httpResponse = execute(postMethod); + try { + return EntityUtils.toString(httpResponse.getEntity()); + } catch (IOException ioe) { + _logger.error("Unable to get response entity", ioe); + } + return null; + } + + /** + * POST the specified request payload to the specified HTTP endpoint. + * @param endpointURL The HTTP endpoint URL. + * @param request The file resource containing the request payload. + * @return The HTTP response payload. + */ + public String postFile(String endpointURL, String request) { + + FileEntity requestEntity = + new FileEntity(new File(request), "text/xml; charset=utf-8"); + + if (_dumpMessages) { + _logger.info("Sending a POST request to [" + endpointURL + "]"); + ByteArrayOutputStream target = new ByteArrayOutputStream(); + try { + requestEntity.writeTo(target); + _logger.info("Request body:[" + target.toString() + "]"); + } catch (IOException e) { + _logger.error("Unable to write FileEntity to stream", e); + } + } + + HttpPost postMethod = new HttpPost(endpointURL); + postMethod.setEntity(requestEntity); + HttpResponse httpResponse = execute(postMethod); + try { + return EntityUtils.toString(httpResponse.getEntity()); + } catch (IOException ioe) { + _logger.error("Unable to get response entity", ioe); + } + return null; + } + + /** + * POST the specified String request to the specified HTTP endpoint and perform an XML compare + * between the HTTP response and the specified expected response String. + * @param endpointURL The HTTP endpoint URL. + * @param request The classpath resource to be posted to the endpoint. + * @param expectedResponse The String to use to perform the XML test on the response. + * @return The HTTP response payload. + */ + public String postStringAndTestXML(String endpointURL, String request, String expectedResponse) { + String response = postString(endpointURL, request); + SwitchYardTestKit.compareXMLToString(response, expectedResponse); + return response; + } + + /** + * POST the specified classpath resource to the specified HTTP endpoint. + * @param endpointURL The HTTP endpoint URL. + * @param requestResource The classpath resource to be posted to the endpoint. + * @return The HTTP method. + */ + public HttpResponse postResourceAndGetMethod(String endpointURL, String requestResource) { + if (_dumpMessages) { + _logger.info("Sending a POST request to [" + endpointURL + "]"); + InputStream input = getTestKit().getResourceAsStream(requestResource); + ByteArrayOutputStream tmp = new ByteArrayOutputStream(); + byte[] data = new byte[4096]; + int l = 0; + try { + while ((l = input.read(data)) >= 0) { + tmp.write(data, 0, l); + } + _logger.info("Request body:[" + new String(tmp.toByteArray()) + "]"); + } catch (IOException e) { + _logger.error("Unexpected Exception while reading request resource", e); + } + } + + HttpPost postMethod = new HttpPost(endpointURL); + InputStream requestStream = getTestKit().getResourceAsStream(requestResource); + HttpResponse response = null; + try { + if (_contentType != null) { + ContentType contentType = null; + if (_contentType.contains("charset")) { + contentType = ContentType.create(_contentType); + } else { + contentType = ContentType.create(_contentType, "utf-8"); + } + postMethod.setEntity(new InputStreamEntity(requestStream, requestStream.available(), contentType)); + } else { + postMethod.setEntity(new InputStreamEntity(requestStream, requestStream.available())); + } + response = execute(postMethod); + } catch (IOException ioe) { + _logger.error("Unable to get response entity", ioe); + } finally { + try { + requestStream.close(); + } catch (IOException e) { + Assert.fail("Unexpected exception closing HTTP request resource stream."); + } + } + return response; + } + + /** + * POST the specified classpath resource to the specified HTTP endpoint. + * @param endpointURL The HTTP endpoint URL. + * @param requestResource The classpath resource to be posted to the endpoint. + * @return The HTTP response payload. + */ + public String postResource(String endpointURL, String requestResource) { + String response = null; + try { + HttpResponse httpResponse = postResourceAndGetMethod(endpointURL, requestResource); + int status = httpResponse.getStatusLine().getStatusCode(); + if (_logger.isDebugEnabled()) { + _logger.debug("Response returned status code " + status); + } + response = EntityUtils.toString(httpResponse.getEntity()); + } catch (IOException ioe) { + _logger.error("Unable to get response", ioe); + } + return response; + } + + /** + * POST the specified classpath resource to the specified HTTP endpoint and perform an XML compare + * between the HTTP response and the specified expected classpath response resource. + * @param endpointURL The HTTP endpoint URL. + * @param requestResource The classpath resource to be posted to the endpoint. + * @param expectedResponseResource The classpath resource to use to perform the XML test on the response. + * @return The HTTP response payload. + */ + public String postResourceAndTestXML(String endpointURL, String requestResource, String expectedResponseResource) { + String response = postResource(endpointURL, requestResource); + getTestKit().compareXMLToResource(response, expectedResponseResource); + return response; + } + /** + * POST the specified classpath resource to the specified HTTP endpoint. + * @param endpointURL The HTTP endpoint URL. + * @param requestResource The classpath resource to be posted to the endpoint. + * @return The HTTP status code. + */ + public int postResourceAndGetStatus(String endpointURL, String requestResource) { + HttpResponse httpResponse = postResourceAndGetMethod(endpointURL, requestResource); + int status = httpResponse.getStatusLine().getStatusCode(); + if ((httpResponse.getEntity() != null) && (httpResponse.getEntity().getContentLength() == -1)) { + _httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.SECONDS); + } else { + EntityUtils.consumeQuietly(httpResponse.getEntity()); + } + return status; + } + + /** + * Execute the supplied HTTP Method. + * + * @param method The HTTP Method. + * @return The HTTP Response. + */ + public HttpResponse execute(HttpRequestBase method) { + if (_httpClient == null) { + Assert.fail("HTTPMixIn not initialized. You must call the initialize() method before using this MixIn"); + } + + for (String key : _requestHeaders.keySet()) { + method.setHeader(new BasicHeader(key, _requestHeaders.get(key))); + } + + if (_dumpMessages) { + for (Header header : method.getAllHeaders()) { + _logger.info("Request header:[" + header.getName() + "=" + header.getValue() + "]"); + } + } + + HttpResponse response = null; + try { + response = _httpClient.execute(method); + } catch (Exception e) { + Assert.fail("Exception invoking HTTP endpoint '" + method.getURI() + "': " + e.getMessage()); + } + + if (_dumpMessages) { + for (Header header : response.getAllHeaders()) { + _logger.info("Received response header:[" + header.getName() + "=" + header.getValue() + "]"); + } + _logger.info("Received response body:[" + response + "]"); + } + + for (String key : _expectedHeaders.keySet()) { + Header actual = response.getFirstHeader(key); + Assert.assertNotNull("Checking response header:[" + key + "]", actual); + Assert.assertEquals("Checking response header:[" + key + "]", _expectedHeaders.get(key), actual.getValue()); + } + + return response; + } + + /** + * Set a request header. + * @param name header name + * @param value header value + * @return this instance + */ + public HTTPMixIn setRequestHeader(String name, String value) { + _requestHeaders.put(name, value); + return this; + } + + /** + * Set the list of request headers. + * @param headers request headers in HashMap + * @return this instance + */ + public HTTPMixIn setRequestHeaders(Map headers) { + _requestHeaders.clear(); + _requestHeaders.putAll(headers); + return this; + } + + /** + * Set a expected response header. + * @param name header name + * @param value header value + * @return this instance + */ + public HTTPMixIn setExpectedHeader(String name, String value) { + _expectedHeaders.put(name, value); + return this; + } + + /** + * Set the list of expected response headers. + * @param headers expected response headers in HashMap + * @return this instance + */ + public HTTPMixIn setExpectedHeaders(Map headers) { + _expectedHeaders.clear(); + _expectedHeaders.putAll(headers); + return this; + } + + /** + * Whether to dump the request/response message into log or not. + * @param dumpMessages Whether to dump the request/response message into log or not + * @return this instance + */ + public HTTPMixIn setDumpMessages(boolean dumpMessages) { + _dumpMessages = dumpMessages; + return this; + } + + @Override + public void uninitialize() { + if (_httpClient != null) { + _httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.SECONDS); + _httpClient.getConnectionManager().shutdown(); + } + } +} diff --git a/components/test/mixins/http/src/test/resources/META-INF/beans.xml b/components/test/mixins/http/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/test/mixins/http/src/test/resources/log4j.xml b/components/test/mixins/http/src/test/resources/log4j.xml new file mode 100644 index 000000000..0b2a242af --- /dev/null +++ b/components/test/mixins/http/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/test/mixins/jca/pom.xml b/components/test/mixins/jca/pom.xml new file mode 100644 index 000000000..82fb1e4a3 --- /dev/null +++ b/components/test/mixins/jca/pom.xml @@ -0,0 +1,61 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-test-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-component-test-mixin-jca + jar + SwitchYard: JCA Test MixIn + JCA Test MixIn classes + http://switchyard.org + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-test-mixin-naming + + + org.switchyard.components + switchyard-component-test-mixin-cdi + + + + org.jboss.as + jboss-as-transactions + + + org.jboss.jbossts.jts + jbossjts-jacorb + + + org.jboss.weld + weld-spi + + + org.mockito + mockito-all + test + + + diff --git a/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/LocalArjunaTransactionServices.java b/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/LocalArjunaTransactionServices.java new file mode 100644 index 000000000..32d093a76 --- /dev/null +++ b/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/LocalArjunaTransactionServices.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.transaction; + +import javax.transaction.Status; +import javax.transaction.Synchronization; +import javax.transaction.SystemException; +import javax.transaction.UserTransaction; + +import org.jboss.weld.transaction.spi.TransactionServices; + +import com.arjuna.ats.jta.common.JTAEnvironmentBean; + +/** + * Transaction services using arjuna to manage transaction. + */ +public class LocalArjunaTransactionServices implements TransactionServices { + + private final JTAEnvironmentBean _jtaEnvironmentBean; + + /** + * Creates new local transaction services. + * + * @param jtaEnvironmentBean Arjuna jta bean. + */ + public LocalArjunaTransactionServices(JTAEnvironmentBean jtaEnvironmentBean) { + this._jtaEnvironmentBean = jtaEnvironmentBean; + } + + @Override + public void registerSynchronization(Synchronization synchronizedObserver) { + _jtaEnvironmentBean.getTransactionSynchronizationRegistry() + .registerInterposedSynchronization(synchronizedObserver); + } + + @Override + public UserTransaction getUserTransaction() { + return _jtaEnvironmentBean.getUserTransaction(); + } + + @Override + public boolean isTransactionActive() { + try { + final int status = getUserTransaction().getStatus(); + return status == Status.STATUS_ACTIVE + || status == Status.STATUS_COMMITTING + || status == Status.STATUS_MARKED_ROLLBACK + || status == Status.STATUS_PREPARED + || status == Status.STATUS_PREPARING + || status == Status.STATUS_ROLLING_BACK; + } catch (SystemException e) { + throw new RuntimeException(e); + } + } + + @Override + public void cleanup() { + } + + @Override + public String toString() { + return "Local Arjuna Transaction"; + } +} diff --git a/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/TransactionMixIn.java b/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/TransactionMixIn.java new file mode 100644 index 000000000..fd1898461 --- /dev/null +++ b/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/TransactionMixIn.java @@ -0,0 +1,127 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.transaction; + +import java.util.Iterator; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.transaction.TransactionManager; +import javax.transaction.TransactionSynchronizationRegistry; +import javax.transaction.UserTransaction; + +import org.apache.log4j.Logger; +import org.jboss.weld.bootstrap.spi.Deployment; +import org.switchyard.SwitchYardException; +import org.switchyard.test.MixInDependencies; +import org.switchyard.test.TestMixIn; +import org.switchyard.test.mixins.AbstractTestMixIn; +import org.switchyard.component.test.mixins.cdi.CDIMixInParticipant; +import org.switchyard.component.test.mixins.naming.NamingMixIn; + +import com.arjuna.ats.jta.common.JTAEnvironmentBean; +import com.arjuna.ats.jta.common.jtaPropertyManager; + +/** + * Mixin which bounds JTA beans in JNDI tree. + * + * @author Lukasz Dywicki + */ +@MixInDependencies(required={NamingMixIn.class}) +public class TransactionMixIn extends AbstractTestMixIn + implements CDIMixInParticipant { + + /** + * Location of persistent store for tx logs. + */ + private String _storeDir = "target/tx-store"; + private JTAEnvironmentBean _jtaEnvironmentBean; + private Logger _logger = Logger.getLogger(TransactionMixIn.class); + + @Override + public void initialize() { + if (getTestKit() != null) { + Iterator mixins = getTestKit().getMixIns().iterator(); + while (_jtaEnvironmentBean == null && mixins.hasNext()) { + TestMixIn testMixIn = mixins.next(); + if (testMixIn instanceof TransactionMixInParticipant) { + try { + _logger.debug("Trying to locate JTA environment using " + testMixIn); + _jtaEnvironmentBean = ((TransactionMixInParticipant) testMixIn).locateEnvironmentBean(); + } catch (Throwable e) { + throw new SwitchYardException("Exception during locating arjuna environment bean", e); + } + } + } + } + + try { + if (_jtaEnvironmentBean == null) { + System.setProperty("ObjectStoreEnvironmentBean.objectStoreDir", _storeDir); + System.setProperty("com.arjuna.ats.arjuna.objectstore.objectStoreDir", _storeDir); + _jtaEnvironmentBean = jtaPropertyManager.getJTAEnvironmentBean(); + _jtaEnvironmentBean.setTransactionManagerClassName(com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple.class.getName()); + _jtaEnvironmentBean.setUserTransactionClassName(com.arjuna.ats.internal.jta.transaction.arjunacore.UserTransactionImple.class.getName()); + _jtaEnvironmentBean.setTransactionSynchronizationRegistryClassName(com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple.class.getName()); + + InitialContext initialContext = new InitialContext(); + initialContext.bind("java:jboss/TransactionManager", _jtaEnvironmentBean.getTransactionManager()); + initialContext.bind("java:jboss/UserTransaction", _jtaEnvironmentBean.getUserTransaction()); + initialContext.bind("java:jboss/TransactionSynchronizationRegistry", _jtaEnvironmentBean.getTransactionSynchronizationRegistry()); + } + } catch (NamingException e) { + throw new SwitchYardException("Unable to bind transaction manager in JNDI", e); + } + } + + /** + * Returns an instance of UserTransaction. + * @return UserTransaction + */ + public UserTransaction getUserTransaction() { + return _jtaEnvironmentBean.getUserTransaction(); + } + + /** + * Returns the TransactionManager used by the TransactionMixIn. + * @return TransactionManager instance + */ + public TransactionManager getTransactionManager() { + return _jtaEnvironmentBean.getTransactionManager(); + } + + /** + * Returns the SynchronizationRegistry used by the TransactionMixIn. + * @return SynchronizationRegistry instance + */ + public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() { + return _jtaEnvironmentBean.getTransactionSynchronizationRegistry(); + } + + /** + * Returns JTAEnvironmentBean used by the TransactionMixIn. + * @return JTAEnvironmentBean instance + */ + public JTAEnvironmentBean getEnvironmentBean() { + return _jtaEnvironmentBean; + } + + @Override + public void participate(Deployment deployment) throws Exception { + deployment.getServices().add(org.jboss.weld.transaction.spi.TransactionServices.class, + new LocalArjunaTransactionServices(_jtaEnvironmentBean)); + } + + +} diff --git a/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/TransactionMixInParticipant.java b/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/TransactionMixInParticipant.java new file mode 100644 index 000000000..0ff7876e3 --- /dev/null +++ b/components/test/mixins/jca/src/main/java/org/switchyard/component/test/mixins/transaction/TransactionMixInParticipant.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.transaction; + +import com.arjuna.ats.jta.common.JTAEnvironmentBean; + +/** + * Helper interface which lets abstract {@link JTAEnvironmentBean} lookup. + */ +public interface TransactionMixInParticipant { + + /** + * Locates Arjuna environment bean, if null value is returned then + * TransactionMixIn will continue looking it in next participant. If all + * participants will return null value then default JTAEnvironmentBean will + * be used. + * + * @return Instance of environment bean or null. + * @throws Throwable In case of failure to look up. + */ + JTAEnvironmentBean locateEnvironmentBean() throws Throwable; + +} diff --git a/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/CDIMixInWithTransactionTest.java b/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/CDIMixInWithTransactionTest.java new file mode 100644 index 000000000..da29979ed --- /dev/null +++ b/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/CDIMixInWithTransactionTest.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; + +import javax.naming.NamingException; +import javax.transaction.UserTransaction; + +import org.junit.Assert; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.test.TestMixIn; +import org.switchyard.component.test.mixins.cdi.CDIMixIn; +import org.switchyard.component.test.mixins.naming.NamingMixIn; +import org.switchyard.component.test.mixins.transaction.TransactionMixIn; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +/** + * Unit test which checks usage of {@link CDIMixIn} together with {@link TransactionMixIn}. + */ +public class CDIMixInWithTransactionTest { + + private static TransactionMixIn transactionMixIn; + private static NamingMixIn namingMixIn; + private static CDIMixIn cdiMixIn; + private static MyTransactionMixInParticipant myTxMixInParticipant; + private static boolean _transactionMixInParticipantInvoked = false; + + @BeforeClass + public static void setup() { + namingMixIn = new NamingMixIn(); + transactionMixIn = new TransactionMixIn(); + cdiMixIn = new CDIMixIn(); + myTxMixInParticipant = new MyTransactionMixInParticipant(new Callable() { + @Override + public Object call() throws Exception { + _transactionMixInParticipantInvoked = true; + return null; + } + }); + List mixins = new ArrayList(Arrays.asList(namingMixIn,transactionMixIn,cdiMixIn,myTxMixInParticipant)); + SwitchYardTestKit testkit = mock(SwitchYardTestKit.class); + when(testkit.getMixIns()).thenReturn(mixins); + namingMixIn.setTestKit(testkit); + transactionMixIn.setTestKit(testkit); + cdiMixIn.setTestKit(testkit); + myTxMixInParticipant.setTestKit(testkit); + namingMixIn.initialize(); + transactionMixIn.initialize(); + cdiMixIn.initialize(); + myTxMixInParticipant.initialize(); + } + + @AfterClass + public static void tearDown() { + myTxMixInParticipant.uninitialize(); + cdiMixIn.uninitialize(); + transactionMixIn.uninitialize(); + namingMixIn.uninitialize(); + } + + @Test + public void testUserTransaction() throws Exception { + assertNotNull(getUserTransaction()); + } + + @Test + public void testTransactionMixInParticipant() { + Assert.assertTrue(_transactionMixInParticipantInvoked); + } + + private UserTransaction getUserTransaction() throws NamingException { + return cdiMixIn.getObject(UserTransaction.class); + } + +} diff --git a/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/MyTransactionMixInParticipant.java b/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/MyTransactionMixInParticipant.java new file mode 100644 index 000000000..d0b8e8852 --- /dev/null +++ b/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/MyTransactionMixInParticipant.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins; + +import java.util.concurrent.Callable; + +import org.switchyard.component.test.mixins.transaction.TransactionMixInParticipant; +import org.switchyard.test.mixins.AbstractTestMixIn; + +import com.arjuna.ats.jta.common.JTAEnvironmentBean; + +/** + * A mock TransactionMixInParticipant. + */ +class MyTransactionMixInParticipant extends AbstractTestMixIn implements TransactionMixInParticipant { + private Callable callback; + public MyTransactionMixInParticipant(Callable callback) { + this.callback = callback; + } + + @Override + public JTAEnvironmentBean locateEnvironmentBean() throws Throwable { + callback.call(); + return null; + } + +} \ No newline at end of file diff --git a/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/TransactionMixInTest.java b/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/TransactionMixInTest.java new file mode 100644 index 000000000..72ffd9ec3 --- /dev/null +++ b/components/test/mixins/jca/src/test/java/org/switchyard/component/test/mixins/TransactionMixInTest.java @@ -0,0 +1,108 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.transaction.Status; +import javax.transaction.Synchronization; +import javax.transaction.TransactionSynchronizationRegistry; +import javax.transaction.UserTransaction; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import org.switchyard.component.test.mixins.naming.NamingMixIn; +import org.switchyard.component.test.mixins.transaction.TransactionMixIn; + +import static org.junit.Assert.assertSame; + +/** + * Unit test for {@link TransactionMixIn}. + * + * @author Lukasz Dywicki + */ +public class TransactionMixInTest { + + private static TransactionMixIn transactionMixIn; + private static NamingMixIn namingMixIn; + + @BeforeClass + public static void setup() { + namingMixIn = new NamingMixIn(); + namingMixIn.initialize(); + transactionMixIn = new TransactionMixIn(); + transactionMixIn.initialize(); + } + + @AfterClass + public static void tearDown() { + transactionMixIn.uninitialize(); + } + + @Test + public void testTransaction() throws Exception { + UserTransaction transaction = getUserTransaction(); + transaction.begin(); + + transaction.commit(); + } + + @Ignore // Fails with EAP6 + @Test + public void shouldUseSameInstance() throws Exception { + assertSame(getUserTransaction(), transactionMixIn.getUserTransaction()); + } + + private UserTransaction getUserTransaction() throws NamingException { + return (UserTransaction) new InitialContext().lookup("java:jboss/UserTransaction"); + } + + @Test + public void testTransactionSynchronizationRegistry() throws Exception { + UserTransaction transaction = getUserTransaction(); + transaction.begin(); + TransactionSynchronizationRegistry tsr = getTransactionSynchronizationRegistry(); + TestSynchronization sync = new TestSynchronization(); + tsr.registerInterposedSynchronization(sync); + transaction.commit(); + Assert.assertTrue(sync.beforeCompletionInvoked); + Assert.assertTrue(sync.afterCompletionInvoked); + Assert.assertEquals(Status.STATUS_COMMITTED, sync.transactionStatus); + } + + private TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() throws NamingException { + return (TransactionSynchronizationRegistry) new InitialContext().lookup("java:jboss/TransactionSynchronizationRegistry"); + } + + private class TestSynchronization implements Synchronization { + private boolean beforeCompletionInvoked = false; + private boolean afterCompletionInvoked = false; + private int transactionStatus = Status.STATUS_NO_TRANSACTION; + + @Override + public void afterCompletion(int status) { + afterCompletionInvoked = true; + transactionStatus = status; + } + + @Override + public void beforeCompletion() { + beforeCompletionInvoked = true; + } + } +} diff --git a/components/test/mixins/jca/src/test/resources/META-INF/beans.xml b/components/test/mixins/jca/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/test/mixins/jca/src/test/resources/log4j.xml b/components/test/mixins/jca/src/test/resources/log4j.xml new file mode 100644 index 000000000..0b2a242af --- /dev/null +++ b/components/test/mixins/jca/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/test/mixins/naming/pom.xml b/components/test/mixins/naming/pom.xml new file mode 100644 index 000000000..c862213cd --- /dev/null +++ b/components/test/mixins/naming/pom.xml @@ -0,0 +1,40 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-test-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-component-test-mixin-naming + jar + SwitchYard: Naming Test MixIn + Naming MixIn classes + http://switchyard.org + + + org.jboss.as + jboss-as-naming + + + org.jboss.logmanager + log4j-jboss-logmanager + + + + + diff --git a/components/test/mixins/naming/src/main/java/org/switchyard/component/test/mixins/naming/NamingMixIn.java b/components/test/mixins/naming/src/main/java/org/switchyard/component/test/mixins/naming/NamingMixIn.java new file mode 100644 index 000000000..fe55db2c4 --- /dev/null +++ b/components/test/mixins/naming/src/main/java/org/switchyard/component/test/mixins/naming/NamingMixIn.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.test.mixins.naming; + +import javax.naming.CompositeName; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +import org.jboss.as.naming.InMemoryNamingStore; +import org.jboss.as.naming.NamingContext; +import org.jboss.as.naming.context.NamespaceContextSelector; +import org.junit.Assert; +import org.switchyard.test.mixins.AbstractTestMixIn; + +/** + * Code related to JNDI stuff. + * + * @author Tomohisa Igarashi + * @author Lukasz Dywicki + */ +public class NamingMixIn extends AbstractTestMixIn { + + private static final String INITIAL_CONTEXT_FACTORY_NAME = "org.jboss.as.naming.InitialContextFactory"; + private static final CompositeName EMPTY_NAME = new CompositeName(); + + /** + * Instance of context shared with children classes. + */ + private static InitialContext initialContext = null; + + @Override + public void initialize() { + String factoryName = System.getProperty(Context.INITIAL_CONTEXT_FACTORY); + if (factoryName != null && !factoryName.equals(INITIAL_CONTEXT_FACTORY_NAME)) { + return; + } + + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY_NAME); + NamingContext.initializeNamingManager(); + NamespaceContextSelector.setDefault(new NamespaceContextSelector() { + public Context getContext(String identifier) { + try { + return (Context) new InitialContext().lookup(EMPTY_NAME); + } catch (NamingException e) { + throw new RuntimeException(e); + } + } + }); + + setInitialContext(); + } + + private synchronized void setInitialContext() { + if (initialContext == null) { + try { + initialContext = new InitialContext(); + try { + Context.class.cast(initialContext.lookup("java:comp")); + } catch (Exception e) { + initialContext.createSubcontext("java:comp"); + } + } catch (NamingException e) { + Assert.fail("Failed to create context : " + e.getMessage()); + } + } + } + + /** + * Returns the InitialContext used in the NamingMixIn. + * @return InitialContext instance + */ + public InitialContext getInitialContext() { + return initialContext; + } + + @Override + public void uninitialize() { + NamingContext.setActiveNamingStore(new InMemoryNamingStore()); + } +} diff --git a/components/test/mixins/naming/src/test/resources/META-INF/beans.xml b/components/test/mixins/naming/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/test/mixins/naming/src/test/resources/log4j.xml b/components/test/mixins/naming/src/test/resources/log4j.xml new file mode 100644 index 000000000..0b2a242af --- /dev/null +++ b/components/test/mixins/naming/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/test/mixins/smooks/pom.xml b/components/test/mixins/smooks/pom.xml new file mode 100644 index 000000000..8450ca6ea --- /dev/null +++ b/components/test/mixins/smooks/pom.xml @@ -0,0 +1,43 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-component-test-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-component-test-mixin-smooks + jar + SwitchYard: Smooks Test MixIn + Smooks Test MixIn classes + http://switchyard.org + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + + xmlunit + xmlunit + + + diff --git a/components/test/mixins/smooks/src/main/java/org/switchyard/component/test/mixins/smooks/SmooksMixIn.java b/components/test/mixins/smooks/src/main/java/org/switchyard/component/test/mixins/smooks/SmooksMixIn.java new file mode 100644 index 000000000..36b314263 --- /dev/null +++ b/components/test/mixins/smooks/src/main/java/org/switchyard/component/test/mixins/smooks/SmooksMixIn.java @@ -0,0 +1,110 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.component.test.mixins.smooks; + +import javax.xml.namespace.QName; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.test.mixins.AbstractTestMixIn; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.SmooksTransformType; +import org.switchyard.transform.config.model.TransformNamespace; +import org.switchyard.transform.config.model.v1.V1SmooksTransformModel; + +/** + * Smooks test {@link org.switchyard.test.TestMixIn mix-in}. + * + * @author tom.fennelly@gmail.com + */ +public class SmooksMixIn extends AbstractTestMixIn { + + private boolean _dumpResultsToSysout = false; + + /** + * Dump transform results to system out. + *

+ * Used for test debugging purposes. + * + * @param dumpResultsToSysout True to dump result, otherwise false. + */ + public void dumpResultsToSysout(boolean dumpResultsToSysout) { + this._dumpResultsToSysout = dumpResultsToSysout; + } + + /** + * Test the Smooks Java/XML binding. + *

+ * This test method provides a round-trip Java/XML binding test. It uses the Smooks SwitchYard transformer + * (created from the specified {@code bindingConfigResPath}) to read the specified {@code xmlResPath} from the + * test classpath, bind its XML content to an instance of the specified {@code javaType} + * ({@link SmooksTransformType#XML2JAVA}) and then serializes that {@code javaType} instance back to XML + * ({@link SmooksTransformType#JAVA2XML}), comparing the serialized XML to the XML specified by the + * {@code xmlResPath}, failing if they don't match. + * + * @param javaType The Java type. + * @param bindingConfigResPath The Smooks java binding configuration. This path can be relative to + * the java package containing the test class using this {@link org.switchyard.test.TestMixIn}. + * @param xmlResPath The XML classpath resource used to bind to the {@code javaType}. This path can be relative to + * the java package containing the test class using this {@link org.switchyard.test.TestMixIn}. + */ + public void testJavaXMLReadWrite(Class javaType, String bindingConfigResPath, String xmlResPath) { + Transformer xml2JavaTransformer = newTransformer(bindingConfigResPath, SmooksTransformType.XML2JAVA); + Transformer java2xmlTransformer = newTransformer(bindingConfigResPath, SmooksTransformType.JAVA2XML); + String xml = getTestKit().readResourceString(xmlResPath); + + // XML to Java... + Object javaObject = xml2JavaTransformer.transform(xml); + Assert.assertNotNull("XML to Java transformation failed. null object returned.", javaObject); + Assert.assertTrue("XML to Java transformation failed. Wrong type returned. Expected '" + javaType.getName() + "' but got '" + javaObject.getClass().getName() + "'.", javaType.isInstance(javaObject)); + if (_dumpResultsToSysout) { + System.out.println("------------XML to Java Result:\n" + javaObject); + System.out.println("-------------------------------"); + } + + // Java to XML... + String xmlResult = (String) java2xmlTransformer.transform(javaObject); + Assert.assertNotNull("Java to XML transformation failed. null object returned.", javaObject); + if (_dumpResultsToSysout) { + System.out.println("------------Java to XML Result:\n" + xmlResult); + System.out.println("-------------------------------"); + } + + // Compare the serialized Java Object XML to the XML used to create Java Object... should be the same... + XMLUnit.setIgnoreWhitespace(true); + try { + XMLAssert.assertXMLEqual(xml, xmlResult); + } catch (Exception e) { + Assert.fail("Unexpected error performing XML comparison."); + } + } + + /** + * Create a new Smooks {@link Transformer} instance. + * @param smooksConfigResPath The Smooks configuration classpath resource path. + * @param transformerType The Smooks transformer type. + * @return The Transformer instance. + */ + public Transformer newTransformer(String smooksConfigResPath, SmooksTransformType transformerType) { + TransformModel transformModel = new V1SmooksTransformModel(TransformNamespace.DEFAULT.uri()) + .setConfig(smooksConfigResPath) + .setTransformType(transformerType) + .setFrom(new QName("from")).setTo(new QName("to")); + + return getTestKit().newTransformer(transformModel); + } +} diff --git a/components/test/mixins/smooks/src/test/resources/META-INF/beans.xml b/components/test/mixins/smooks/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/components/test/mixins/smooks/src/test/resources/log4j.xml b/components/test/mixins/smooks/src/test/resources/log4j.xml new file mode 100644 index 000000000..0b2a242af --- /dev/null +++ b/components/test/mixins/smooks/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/test/pom.xml b/components/test/pom.xml new file mode 100644 index 000000000..a2b32b3fd --- /dev/null +++ b/components/test/pom.xml @@ -0,0 +1,75 @@ + + + + 4.0.0 + switchyard-component-test-parent + pom + SwitchYard: Component Test Parent + The parent for SwitchYard component test modules + http://switchyard.org + + org.switchyard.components + switchyard-components-parent + 2.1.0-SNAPSHOT + ../pom.xml + + + mixins/amqp + mixins/activemq + mixins/naming + mixins/cdi + mixins/hornetq + mixins/http + mixins/jca + mixins/smooks + + + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-test + + + + log4j + log4j + + + junit + junit + compile + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + org.slf4j + slf4j-ext + + + diff --git a/components/torquebox/README b/components/torquebox/README new file mode 100644 index 000000000..94809a945 --- /dev/null +++ b/components/torquebox/README @@ -0,0 +1,4 @@ +TorqueBox components. + +For now, you need to manually build these components. They are not part of the main build because they require +Maven 3 and TorqueBox (or one of its dependencies e.g. ruby - need to narrow down) to be installed and configured. \ No newline at end of file diff --git a/components/torquebox/as6-int/pom.xml b/components/torquebox/as6-int/pom.xml new file mode 100644 index 000000000..982901890 --- /dev/null +++ b/components/torquebox/as6-int/pom.xml @@ -0,0 +1,99 @@ + + + + + + + org.switchyard.components + switchyard-components-parent + 0.7.0.Final + ../../pom.xml + + 4.0.0 + + switchyard-component-torquebox-int + Switchyard: TorqueBox JBoss AS6 Integration + The TorqueBox JBoss AS6 Integration Implementation + http://switchyard.org + + jar + + + 3.0 + + + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-deploy + + + org.jboss.deployers + jboss-deployers-impl + + + org.jboss.deployers + jboss-deployers-core-spi + + + org.jboss.deployers + jboss-deployers-vfs + + + org.jboss + jboss-vfs + + + org.jboss.deployers + jboss-deployers-vfs-spi + + + log4j + log4j + + + junit + junit + + + org.torquebox + torquebox-base-int + provided + + + + + + torquebox-repository + Torquebox Maven Repository + http://repository-torquebox.forge.cloudbees.com/release/ + default + + never + + + never + + + + + diff --git a/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/ServiceInvoker.java b/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/ServiceInvoker.java new file mode 100644 index 000000000..2908a3f0b --- /dev/null +++ b/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/ServiceInvoker.java @@ -0,0 +1,187 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deployment.torquebox; + +import org.jruby.RubyHash; +import org.jruby.runtime.builtin.IRubyObject; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.ServiceReference; +import org.switchyard.metadata.BaseExchangeContract; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.metadata.java.JavaService; + +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Service Invoker. + * + * @author tom.fennelly@gmail.com + */ +public class ServiceInvoker { + + private ServiceReference _serviceReference; + + /** + * Public constructor. + * @param serviceReference Reference to the target Service. + */ + public ServiceInvoker(ServiceReference serviceReference) { + if (serviceReference == null) { + throw new IllegalArgumentException("null 'serviceReference' arg in method call."); + } + this._serviceReference = serviceReference; + } + + /** + * Send a message hash to the specified operation. + * @param operationName The operation name. + * @param rubyHash The message hash. + * @return The response object if an IN_OUT operation was invoked, otherwise null. + * @throws Throwable An exception occurred while invoking the target operation. + */ + public Object send(String operationName, RubyHash rubyHash) throws Throwable { + if (operationName == null) { + throw new IllegalArgumentException("null 'operationName' argument."); + } + if (rubyHash == null) { + throw new IllegalArgumentException("null 'rubyHash' argument."); + } + + ServiceOperation operation = _serviceReference.getInterface().getOperation(operationName); + + if (operation == null) { + throw new IllegalArgumentException("Unknown operation name '" + operationName + "' on Service '" + _serviceReference.getName() + "'."); + } + + // Clone the RubyHash to convert it to a normal Map based graph. This makes it possible + // to more safely transport the payload data out of the ruby app via a SwitchYard Exchange... + Map payload = deepClone(rubyHash); + + // Create the exchange contract... + BaseExchangeContract exchangeContract = new BaseExchangeContract(operation); + + // Set the input type... + exchangeContract.getInvokerInvocationMetaData().setInputType(JavaService.toMessageType(payload.getClass())); + + if (operation.getExchangePattern() == ExchangePattern.IN_OUT) { + final BlockingQueue responseQueue = new ArrayBlockingQueue(1); + + AtomicReference responseExchangeHandler = new AtomicReference(new ExchangeHandler() { + public void handleMessage(Exchange exchange) throws HandlerException { + responseQueue.offer(exchange); + } + + public void handleFault(Exchange exchange) { + responseQueue.offer(exchange); + } + }); + + Exchange exchange = _serviceReference.createExchange(exchangeContract, responseExchangeHandler.get()); + Message message = exchange.createMessage().setContent(payload); + + exchange.send(message); + Exchange exchangeOut = null; + try { + exchangeOut = responseQueue.take(); + } catch (InterruptedException e) { + throw new SwitchYardException("Operation '" + operationName + "' on Service '" + _serviceReference.getName() + "' interrupted.", e); + } + + if (exchangeOut.getState() == ExchangeState.OK) { + return exchangeOut.getMessage().getContent(); + } else { + Object failureObj = exchangeOut.getMessage().getContent(); + if (failureObj instanceof Throwable) { + if (failureObj instanceof InvocationTargetException) { + throw ((Throwable)failureObj).getCause(); + } else { + throw (Throwable) failureObj; + } + } else { + throw new SwitchYardException("Service invocation failure. Service '" + _serviceReference.getName() + "', operation '" + operationName + "'. Non Throwable failure message payload: " + failureObj); + } + } + } else { + Exchange exchange = _serviceReference.createExchange(exchangeContract); + Message message = exchange.createMessage().setContent(payload); + + exchange.send(message); + } + + return null; + } + + /** + * Create a deep clone of the supplied {@link Map} instance. + * @param sourceMap The Map to be cloned. + * @return The cloned Map. + */ + public static Map deepClone(Map sourceMap) { + Map map = new LinkedHashMap(); + Set> mapEntries = sourceMap.entrySet(); + + for (Map.Entry entry : mapEntries) { + map.put(entry.getKey(), deepClone(entry.getValue())); + } + + return map; + } + + private static Collection deepClone(Collection sourceCollection) { + Collection collection = createCollection(sourceCollection.getClass()); + + for (Object entry : sourceCollection) { + collection.add(deepClone(entry)); + } + + return collection; + } + + private static Object deepClone(Object object) { + if (object instanceof Map) { + return deepClone((Map)object); + } else if (object instanceof Collection) { + return deepClone((Collection)object); + } else if (object instanceof IRubyObject) { + return object.toString(); + } + return object; + } + + private static Collection createCollection(Class colClass) { + if (Set.class.isAssignableFrom(colClass)) { + return new LinkedHashSet(); + } else if (List.class.isAssignableFrom(colClass)) { + return new ArrayList(); + } else { + return new ArrayList(); + } + } +} diff --git a/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/SwitchYardServiceFinder.java b/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/SwitchYardServiceFinder.java new file mode 100644 index 000000000..512d4d42f --- /dev/null +++ b/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/SwitchYardServiceFinder.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deployment.torquebox; + +import org.switchyard.ServiceReference; +import org.switchyard.deploy.ServiceDomainManager; + +import javax.xml.namespace.QName; + +/** + * Service Finder. + * + * @author tom.fennelly@gmail.com + */ +public class SwitchYardServiceFinder { + + private ServiceDomainManager _domainManager; + + /** + * Set the {@link ServiceDomainManager}. + * @param domainManager The domain manager. + */ + public void setDomainManager(ServiceDomainManager domainManager) { + this._domainManager = domainManager; + } + + /** + * Get a ServiceInvoker for the specified service name. + * @param serviceName The service name. + * @return The Service Invoker instance. + */ + public ServiceInvoker getServiceInvoker(String serviceName) { + if (serviceName == null) { + throw new IllegalArgumentException("null 'serviceName' arg in method call."); + } + + QName serviceQName = QName.valueOf(serviceName); + ServiceReference serviceReference = _domainManager.findService(serviceQName, null); + + if (serviceReference == null) { + throw new IllegalArgumentException("Unable to find service '" + serviceName + "'."); + } + + return new ServiceInvoker(serviceReference); + } + + /** + * Create a finder bean name for the specified application name. + * @param applicationName The application name. + * @return The finder bean name. + */ + public static String beanName(String applicationName) { + return "switchyard." + SwitchYardServiceFinder.class.getSimpleName() + "." + applicationName; + } +} diff --git a/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/SwitchYardServiceFinderDeployer.java b/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/SwitchYardServiceFinderDeployer.java new file mode 100644 index 000000000..834226e33 --- /dev/null +++ b/components/torquebox/as6-int/src/main/java/org/switchyard/deployment/torquebox/SwitchYardServiceFinderDeployer.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deployment.torquebox; + +import org.jboss.beans.metadata.spi.BeanMetaData; +import org.jboss.beans.metadata.spi.builder.BeanMetaDataBuilder; +import org.jboss.deployers.spi.DeploymentException; +import org.jboss.deployers.spi.deployer.DeploymentStages; +import org.jboss.deployers.structure.spi.DeploymentUnit; +import org.switchyard.deploy.ServiceDomainManager; +import org.torquebox.base.metadata.RubyApplicationMetaData; +import org.torquebox.injection.AbstractRubyComponentDeployer; +import org.torquebox.mc.AttachmentUtils; + +/** + * Deployer for the deployment's {@link SwitchYardServiceFinder} bean instance. + * @author tom.fennelly@gmail.com + */ +public class SwitchYardServiceFinderDeployer extends AbstractRubyComponentDeployer { + + private ServiceDomainManager _domainManager; + + /** + * Public constructor. + */ + public SwitchYardServiceFinderDeployer() { + setAllInputs(true); + addInput(RubyApplicationMetaData.class); + addOutput(BeanMetaData.class); + setStage(DeploymentStages.REAL); + } + + /** + * Set the deployment's {@link ServiceDomainManager} instance. + * @param domainManager The {@link ServiceDomainManager} instance. + */ + public void setDomainManager(ServiceDomainManager domainManager) { + this._domainManager = domainManager; + } + + @Override + public void deploy(DeploymentUnit unit) throws DeploymentException { + RubyApplicationMetaData rubyAppMetaData = unit.getAttachment(RubyApplicationMetaData.class); + + if (rubyAppMetaData == null) { + return; + } + + String beanName = SwitchYardServiceFinder.beanName(unit.getName()); + BeanMetaDataBuilder beanBuilder = BeanMetaDataBuilder.createBuilder(beanName, SwitchYardServiceFinder.class.getName()); + + beanBuilder.addPropertyMetaData("domainManager", _domainManager); + + BeanMetaData beanMetaData = beanBuilder.getBeanMetaData(); + + AttachmentUtils.attach(unit, beanMetaData); + } +} diff --git a/components/torquebox/as6-int/src/main/resources/META-INF/switchyard-deployers-jboss-beans.xml b/components/torquebox/as6-int/src/main/resources/META-INF/switchyard-deployers-jboss-beans.xml new file mode 100644 index 000000000..7c8bf985d --- /dev/null +++ b/components/torquebox/as6-int/src/main/resources/META-INF/switchyard-deployers-jboss-beans.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/components/torquebox/as6-int/src/test/java/org/switchyard/deployment/torquebox/RubyUtil.java b/components/torquebox/as6-int/src/test/java/org/switchyard/deployment/torquebox/RubyUtil.java new file mode 100644 index 000000000..9dd287422 --- /dev/null +++ b/components/torquebox/as6-int/src/test/java/org/switchyard/deployment/torquebox/RubyUtil.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deployment.torquebox; + +import org.jruby.Ruby; +import org.jruby.ast.Node; +import org.jruby.runtime.builtin.IRubyObject; + +import java.io.InputStream; + +/** + * @author tom.fennelly@gmail.com + */ +public class RubyUtil { + + public static IRubyObject evalScriptlet(InputStream scriptStream) { + Ruby ruby = Ruby.newInstance(); + Node scriptNode = ruby.parseFromMain(scriptStream, "test.rb"); + return ruby.runInterpreter(scriptNode); + } +} diff --git a/components/torquebox/as6-int/src/test/java/org/switchyard/deployment/torquebox/ServiceInvokerTest.java b/components/torquebox/as6-int/src/test/java/org/switchyard/deployment/torquebox/ServiceInvokerTest.java new file mode 100644 index 000000000..01c94052d --- /dev/null +++ b/components/torquebox/as6-int/src/test/java/org/switchyard/deployment/torquebox/ServiceInvokerTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deployment.torquebox; + +import org.jruby.RubyHash; +import org.jruby.runtime.builtin.IRubyObject; +import org.junit.Assert; +import org.junit.Test; + +import java.util.List; +import java.util.Map; + +/** + * @author tom.fennelly@gmail.com + */ +public class ServiceInvokerTest { + + @Test + public void test_deepClone() { + RubyHash rubyHash = (RubyHash) RubyUtil.evalScriptlet(getClass().getResourceAsStream("/order1.rb")); + Map deepClone = ServiceInvoker.deepClone(rubyHash); + + Map header = (Map) deepClone.get("header"); + Assert.assertFalse(header instanceof IRubyObject); + Assert.assertEquals(1234L, header.get("orderId")); + + List items = (List) deepClone.get("items"); + Assert.assertFalse(items instanceof IRubyObject); + Assert.assertEquals(2, items.size()); + } +} diff --git a/components/torquebox/as6-int/src/test/resources/order1.rb b/components/torquebox/as6-int/src/test/resources/order1.rb new file mode 100644 index 000000000..d1bcf6cea --- /dev/null +++ b/components/torquebox/as6-int/src/test/resources/order1.rb @@ -0,0 +1,23 @@ +@order = { + + "header" => { + "orderId" => 1234, + "originType" => "catalog", + "customerDetails" => { + "custId" => 1234, + "name" => "Seamus Ungabunga" + } + }, + + "items" => [ + { + "itemId" => 1234, + "productId" => "X" + }, + { + "itemId" => 1235, + "productId" => "Y" + } + ] + +} \ No newline at end of file diff --git a/components/torquebox/gem/lib/gem_hook.rb b/components/torquebox/gem/lib/gem_hook.rb new file mode 100644 index 000000000..27e4d0dec --- /dev/null +++ b/components/torquebox/gem/lib/gem_hook.rb @@ -0,0 +1,2 @@ + +require 'switchyard/find' diff --git a/components/torquebox/gem/lib/switchyard/find.rb b/components/torquebox/gem/lib/switchyard/find.rb new file mode 100644 index 000000000..66a221263 --- /dev/null +++ b/components/torquebox/gem/lib/switchyard/find.rb @@ -0,0 +1,36 @@ +# Copyright 2008-2011 Red Hat, Inc, and individual contributors. +# +# This is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation; either version 2.1 of +# the License, or (at your option) any later version. +# +# This software is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this software; if not, write to the Free +# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +# 02110-1301 USA, or see the FSF site: http://www.fsf.org. + +require 'switchyard' + +module Switchyard + class Find + + def self.service(serviceName) + finderBeanName = Java::org.switchyard.deployment.torquebox.SwitchYardServiceFinder.beanName(TorqueBox.application_name) + finderBean = TorqueBox::Kernel.lookup(finderBeanName) + + if finderBean.nil? + puts "Failed to find SwitchYard Service Finder bean for TorqueBox application '" + finderBeanName.getName() + "'." + @serviceInvoker = nil + else + @serviceInvoker = finderBean.getServiceInvoker(serviceName); + end + end + + end +end diff --git a/components/torquebox/gem/pom.xml b/components/torquebox/gem/pom.xml new file mode 100644 index 000000000..81d917346 --- /dev/null +++ b/components/torquebox/gem/pom.xml @@ -0,0 +1,105 @@ + + + + + + org.torquebox + gem-parent + 1.0.0.CR2 + + + 4.0.0 + rubygems + switchyard + java-gem + 0.7.0.Final + Switchyard: Ruby Gem + Ruby Gem for running on Torquebox + + + 3.0.5 + + + + 3.0 + + + + + rubygems + activesupport + ${version.rails3} + gem + test + + + rubygems + i18n + 0.5.0 + gem + test + + + + + + + de.saumya.mojo + gem-maven-plugin + + + default-package + + true + + + + default-install + install + + + + + + + + + torquebox-repository + Torquebox Maven Repository + http://repository-torquebox.forge.cloudbees.com/release/ + default + + never + + + never + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + https://repository.jboss.org/nexus/content/groups/public/ + default + + never + + + never + + + + + diff --git a/components/torquebox/pom.xml b/components/torquebox/pom.xml new file mode 100644 index 000000000..cbec6f706 --- /dev/null +++ b/components/torquebox/pom.xml @@ -0,0 +1,41 @@ + + + + 4.0.0 + + org.switchyard.components + switchyard-components-torquebox + 0.7.0.Final + + pom + + SwitchYard: TorqueBox Components + SwitchYard: TorqueBox Components + http://switchyard.org + + + JBoss by Red Hat + http://jboss.org + + + + as6-int + gem + + + diff --git a/console/.gitignore b/console/.gitignore new file mode 100644 index 000000000..e4d0c021d --- /dev/null +++ b/console/.gitignore @@ -0,0 +1,12 @@ +.idea +.project +.settings +.classpath +overlays +target/ +.gwt/ +*.iml +*.ipr +*.iws +.checkstyle +.fbExcludeFilterFile diff --git a/console/README.md b/console/README.md new file mode 100644 index 000000000..b80b3e730 --- /dev/null +++ b/console/README.md @@ -0,0 +1,5 @@ +# SwitchYard Console + +This repository contains the SwitchYard web console. + + diff --git a/console/app/.gitignore b/console/app/.gitignore new file mode 100644 index 000000000..7e6206d28 --- /dev/null +++ b/console/app/.gitignore @@ -0,0 +1,2 @@ +war/ +gwt-unitCache/ diff --git a/console/app/pom.xml b/console/app/pom.xml new file mode 100644 index 000000000..29f01099e --- /dev/null +++ b/console/app/pom.xml @@ -0,0 +1,73 @@ + + + + + + org.jboss.as + jboss-as-console-build + 2.2.8.Final + + 4.0.0 + org.switchyard.console + switchyard-console-application + 2.1.0-SNAPSHOT + war + SwitchYard: Management Console Application + Integrated AS7 console application, which includes the SwitchYard extension. + + + org.switchyard.console + switchyard-console-extension + ${project.version} + provided + + + org.switchyard.console + switchyard-console-extension + ${project.version} + sources + provided + + + + + + org.codehaus.mojo + gwt-maven-plugin + + + -1 + ${project.build.directory} + + + + org.codehaus.mojo + build-helper-maven-plugin + + + + add-source + + + + + + ${project.build.directory}/generated-sources/apt + + + + + + diff --git a/console/app/readme.txt b/console/app/readme.txt new file mode 100644 index 000000000..349e53f28 --- /dev/null +++ b/console/app/readme.txt @@ -0,0 +1,3 @@ +This project packages the core AS7 console and the SwitchYard extension into a +single WAR. The resulting artifact can be used to replace the default console +module in AS7. \ No newline at end of file diff --git a/console/app/src/main/webapp/WEB-INF/web.xml b/console/app/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000..856e3fbd2 --- /dev/null +++ b/console/app/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,38 @@ + + + + + gwtProxy + org.jboss.as.console.server.proxy.XmlHttpProxyServlet + + config.name + gwt-proxy.properties + + 1 + + + + uploadProxy + org.jboss.as.console.server.proxy.XmlHttpProxyServlet + + config.name + upload-proxy.properties + + 1 + + + + gwtProxy + /app/proxy/* + + + + uploadProxy + /app/upload/* + + + diff --git a/console/as7-core/pom.xml b/console/as7-core/pom.xml new file mode 100644 index 000000000..4d31e0b09 --- /dev/null +++ b/console/as7-core/pom.xml @@ -0,0 +1,187 @@ + + + + + + switchyard-console-parent + org.switchyard.console + 0.8.0.Final + ../pom.xml + + 4.0.0 + switchyard-console-as7-core + SwitchYard: AS7 Core Console Module + Bundles the core AS7 console as a GWT module. Includes minor customizations to support extensions. + + ${project.build.directory}/dependency/as-console + + + + org.jboss.as + console-spi + + + org.jboss.ballroom + widgets + + + javax.validation + validation-api + + + com.google.gwt + gwt-user + + + com.google.code + gwt-visualization + + + com.google.code.gwt-log + gwt-log + + + com.gwtplatform + gwtp-mvp-client + + compile + + + com.google.inject + guice + + + com.google.inject.extensions + guice-assistedinject + + + com.google.gwt.inject + gin + + + com.google.gwt + gwt-dev + provided + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack-jboss-as-sources + generate-sources + + unpack + + + + + org.jboss.as + jboss-as-console + ${version.jbossas.console} + sources + jar + org/jboss/as/console/client/Console.java,org/jboss/as/console/client/shared/SubsystemMetaData.java,org/jboss/as/console/client/domain/runtime/DomainRuntimeNavigation.java,org/jboss/as/console/client/standalone/runtime/StandaloneRuntimeNavigation.java,org/jboss/dmr/client/DataInput.java,org/jboss/dmr/client/IEEE754.java,org/jboss/as/console/client/shared/runtime/plain/PlainColumnView.java,META-INF/*.SF,META-INF/*.RSA,META-INF/*.DSA,apt/** + ${asConsoleIncludesDirectory}/java + + + + + + unpack-jboss-as-resources + generate-sources + + unpack + + + + + org.jboss.as + jboss-as-console + ${version.jbossas.console} + resources + jar + images/**,App.html,index.html + ${asConsoleIncludesDirectory}/resources + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + process-sources + + add-source + + + + ${asConsoleIncludesDirectory}/java + + + + + add-resources + process-sources + + add-resource + + + + + ${asConsoleIncludesDirectory}/resources + + + + + + + + maven-assembly-plugin + + + package-gwt-module + package + + single + + + + + + src/main/assembly/module.xml + + + + + + maven-checkstyle-plugin + + true + + + + + diff --git a/console/as7-core/readme.txt b/console/as7-core/readme.txt new file mode 100644 index 000000000..885fa914a --- /dev/null +++ b/console/as7-core/readme.txt @@ -0,0 +1,32 @@ +This project bundles the existing AS7 console as a GWT module. + +This project also includes minor updates which allow the core console to be +extended (e.g. adding items to the subsystem navigation tree). + +This project will be removed once the extension mechanisms and module packaging +are available in an AS7 console release. + +The following is a list of modifications to the underlying AS7 console source: +src/main/java/org/jboss/as/console/client/Console.java + - modified "MODULES" initialization to: + public final static CoreUI MODULES = GWT.create(GinjectorSingleton.class).getCoreUI(); +src/main/java/org/jboss/as/console/client/shared/SubsystemMetaData.java + - add extension hooks to the end of "groups" initialization: + SubsystemExtensionProcessor extensionProcessor = GWT.create(SubsystemExtensionProcessor.class); + extensionProcessor.processExtensions(groups); +org/jboss/as/console/client/domain/runtime/DomainRuntimeNavigation.java + - integrate subsystem extensions: + metricPredicates.addAll(SubsystemMetaData.getRuntimeExtensions()); +org/jboss/as/console/client/standalone/runtime/StandaloneRuntimeNavigation.java + - integrate subsystem extensions: + metricPredicates.addAll(SubsystemMetaData.getRuntimeExtensions()); + +The following files work around GWT compiler bugs that affect DMR deserialization. These can be removed once patched upstream. + org/jboss/dmr/client/DataInput.java + org/jboss/dmr/client/IEEE754.java + +The following uses the specified comparison column as the baseline: + org/jboss/as/console/client/shared/runtime/plain/PlainColumnView.java + +Added files for extension processing and integration. + diff --git a/console/as7-core/src/main/assembly/module.xml b/console/as7-core/src/main/assembly/module.xml new file mode 100644 index 000000000..7be8c5e8c --- /dev/null +++ b/console/as7-core/src/main/assembly/module.xml @@ -0,0 +1,32 @@ + + module + + jar + + false + + + ${project.build.sourceDirectory} + / + + **/* + + + + ${asConsoleIncludesDirectory}/java + / + + **/* + + + + + + true + + org.switchyard.console:switchyard-console-as7-core + + + + \ No newline at end of file diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/Console.java b/console/as7-core/src/main/java/org/jboss/as/console/client/Console.java new file mode 100644 index 000000000..3f6a196d2 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/Console.java @@ -0,0 +1,230 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jboss.as.console.client; + +import com.allen_sauer.gwt.log.client.Log; +import com.google.gwt.core.client.EntryPoint; +import com.google.gwt.core.client.GWT; +import com.google.gwt.core.client.RunAsyncCallback; +import com.google.gwt.core.client.Scheduler; +import com.google.gwt.event.shared.EventBus; +import com.google.gwt.user.client.Command; +import com.google.gwt.user.client.Window; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.gwt.user.client.ui.HTMLPanel; +import com.google.gwt.user.client.ui.RootLayoutPanel; +import com.google.gwt.user.client.ui.Widget; +import com.gwtplatform.mvp.client.DelayedBindRegistry; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import org.jboss.as.console.client.core.BootstrapContext; +import org.jboss.as.console.client.core.LoadingPanel; +import org.jboss.as.console.client.core.UIConstants; +import org.jboss.as.console.client.core.UIDebugConstants; +import org.jboss.as.console.client.core.UIMessages; +import org.jboss.as.console.client.core.bootstrap.BootstrapProcess; +import org.jboss.as.console.client.core.bootstrap.ChoseProcessor; +import org.jboss.as.console.client.core.bootstrap.EagerLoadProfiles; +import org.jboss.as.console.client.core.bootstrap.ExecutionMode; +import org.jboss.as.console.client.core.bootstrap.LoadMainApp; +import org.jboss.as.console.client.core.bootstrap.RegisterSubsystems; +import org.jboss.as.console.client.core.bootstrap.RemoveLoadingPanel; +import org.jboss.as.console.client.core.gin.Composite; +import org.jboss.as.console.client.core.gin.GinjectorSingleton; +import org.jboss.as.console.client.core.message.Message; +import org.jboss.as.console.client.core.message.MessageCenter; +import org.jboss.as.console.client.plugins.SubsystemRegistry; +import org.jboss.as.console.client.shared.help.HelpSystem; + +import java.util.EnumSet; +/** +* Main application entry point. +* Executes a two phased init process: +*
    +*
  1. Identify management model (standalone vs. domain) +*
  2. Load main application +*
+* +* @author Heiko Braun +*/ +public class Console implements EntryPoint { + + public final static Composite MODULES = GWT.create(GinjectorSingleton.class).getCoreUI(); + public final static UIConstants CONSTANTS = GWT.create(UIConstants.class); + public final static UIDebugConstants DEBUG_CONSTANTS = GWT.create(UIDebugConstants.class); + public final static UIMessages MESSAGES = GWT.create(UIMessages.class); + + public void onModuleLoad() { + // Defer all application initialisation code to onModuleLoad2() so that the + // UncaughtExceptionHandler can catch any unexpected exceptions. + Log.setUncaughtExceptionHandler(); + + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + onModuleLoad2(); + } + }); + } + + public void onModuleLoad2() { + + // load console css bundle + ConsoleResources.INSTANCE.css().ensureInjected(); + + // display the loading panel + final Widget loadingPanel = new LoadingPanel().asWidget(); + RootLayoutPanel.get().add(loadingPanel); + + GWT.runAsync(new RunAsyncCallback() { + public void onFailure(Throwable caught) { + Window.alert("Failed to load application components!"); + } + + public void onSuccess() { + DelayedBindRegistry.bind(MODULES); + + // ordered bootstrap + final BootstrapProcess bootstrap = new BootstrapProcess(); + + bootstrap.addHook(new ExecutionMode(MODULES.getBootstrapContext(), MODULES.getDispatchAsync())); + bootstrap.addHook(new RegisterSubsystems(MODULES.getSubsystemRegistry())); + bootstrap.addHook(new ChoseProcessor(MODULES.getBootstrapContext())); + bootstrap.addHook(new EagerLoadProfiles(MODULES.getProfileStore(), MODULES.getCurrentSelectedProfile())); + bootstrap.addHook(new RemoveLoadingPanel(loadingPanel)); + bootstrap.addHook(new LoadMainApp(MODULES.getBootstrapContext(), MODULES.getPlaceManager(), MODULES.getTokenFormatter())); + + // viz can be loaded in background ... + //bootstrap.addHook(new LoadGoogleViz()); + + bootstrap.execute(new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + error("Bootstrap failed", caught.getMessage()); + } + + @Override + public void onSuccess(Boolean wasSuccessfull) { + if(!wasSuccessfull) + { + // currently we only deal with authentication errors + RootLayoutPanel.get().remove(loadingPanel); + + String cause = ""; + if(MODULES.getBootstrapContext().getLastError()!=null) + cause = MODULES.getBootstrapContext().getLastError().getMessage(); + + HTMLPanel explanation = new HTMLPanel("

The web console could not be loaded.

"+cause+"
"); + RootLayoutPanel.get().add(explanation); + } + + } + }); + } + + }); + } + + public static void info(String message) { + getMessageCenter().notify( + new Message(message, Message.Severity.Info) + ); + } + + public static void error(String message) { + getMessageCenter().notify( + new Message(message, Message.Severity.Error) + ); + } + + public static void error(String message, String detail) { + getMessageCenter().notify( + new Message(message, detail, Message.Severity.Error) + ); + } + + public static void warning(String message) { + getMessageCenter().notify( + new Message(message, Message.Severity.Warning) + ); + } + + public static void warning(String message, boolean sticky) { + Message msg = sticky ? + new Message(message, Message.Severity.Warning, EnumSet.of(Message.Option.Sticky)) : + new Message(message, Message.Severity.Warning); + + getMessageCenter().notify(msg); + } + + public static void warning(String message, String detail, boolean sticky) { + Message msg = sticky ? + new Message(message, detail, Message.Severity.Warning, EnumSet.of(Message.Option.Sticky)) : + new Message(message, detail, Message.Severity.Warning); + + + getMessageCenter().notify(msg); + } + + public static void warning(String message, String detail) { + getMessageCenter().notify( + new Message(message, detail, Message.Severity.Warning) + ); + } + + public static void schedule(final Command cmd) + { + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + cmd.execute(); + } + }); + } + + public static EventBus getEventBus() { + return MODULES.getEventBus(); + } + + public static MessageCenter getMessageCenter() { + return MODULES.getMessageCenter(); + } + + public static PlaceManager getPlaceManager() { + return MODULES.getPlaceManager(); + } + + public static BootstrapContext getBootstrapContext() + { + return MODULES.getBootstrapContext(); + } + + public static HelpSystem getHelpSystem() { + return MODULES.getHelpSystem(); + } + + + @Deprecated + public static native boolean visAPILoaded() /*-{ + if ($wnd['google'] && $wnd.google['load']) { + return true; + } + return false; + }-*/; + + + public static SubsystemRegistry getSubsystemRegistry() { + return MODULES.getSubsystemRegistry(); + } +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/core/gin/CoreUISingleton.java b/console/as7-core/src/main/java/org/jboss/as/console/client/core/gin/CoreUISingleton.java new file mode 100644 index 000000000..258f57ae8 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/core/gin/CoreUISingleton.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.console.client.core.gin; + +import com.google.gwt.core.client.GWT; + +/** + * CoreUISingleton + * + *

+ * Serves up CoreUI. + * + * @author Rob Cernich + */ +public class CoreUISingleton implements GinjectorSingleton { + + private static final Composite INSTANCE = GWT.create(Composite.class); + + @Override + public Composite getCoreUI() { + return INSTANCE; + } + +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/core/gin/GinjectorSingleton.java b/console/as7-core/src/main/java/org/jboss/as/console/client/core/gin/GinjectorSingleton.java new file mode 100644 index 000000000..6718d21c0 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/core/gin/GinjectorSingleton.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.console.client.core.gin; + +/** + * GinjectorSingleton + * + *

+ * Simple API which uses deferred binding to initialize the application + * Ginjector. This can be implemented by console aggregators to provide an + * extended CoreUI Ginjector (i.e. a Ginjector that includes extended + * presentation bindings in addition to CoreUI). + * + *

+ * For example: + * + *

+ * 
+ * private static final CoreUI instance = GWT.create(CoreUI.class);
+ * 
+ * public CoreUI getCoreUI() {
+ *    return instance;
+ * }
+ * 
+ * 
+ * + * @author Rob Cernich + */ +public interface GinjectorSingleton { + + /** + * @return the CoreUI Ginjector. + */ + Composite getCoreUI(); +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/domain/runtime/DomainRuntimeNavigation.java b/console/as7-core/src/main/java/org/jboss/as/console/client/domain/runtime/DomainRuntimeNavigation.java new file mode 100644 index 000000000..7537af05f --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/domain/runtime/DomainRuntimeNavigation.java @@ -0,0 +1,174 @@ +package org.jboss.as.console.client.domain.runtime; + +import com.google.gwt.user.client.ui.ListBox; +import com.google.gwt.user.client.ui.ScrollPanel; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import org.jboss.as.console.client.Console; +import org.jboss.as.console.client.core.NameTokens; +import org.jboss.as.console.client.domain.hosts.ServerPicker; +import org.jboss.as.console.client.domain.model.Host; +import org.jboss.as.console.client.domain.model.ServerInstance; +import org.jboss.as.console.client.shared.SubsystemMetaData; +import org.jboss.as.console.client.shared.model.SubsystemRecord; +import org.jboss.as.console.client.widgets.nav.Predicate; +import org.jboss.ballroom.client.layout.LHSNavTree; +import org.jboss.ballroom.client.layout.LHSNavTreeItem; +import org.jboss.ballroom.client.layout.LHSTreeSection; +import org.jboss.ballroom.client.widgets.forms.ComboBox; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author Heiko Braun + * @date 11/2/11 + */ +class DomainRuntimeNavigation { + + private VerticalPanel stack; + private VerticalPanel layout; + + private ServerPicker serverPicker; + + private List metricPredicates = new ArrayList(); + private List runtimePredicates = new ArrayList(); + + private ScrollPanel scroll; + private LHSNavTree navigation; + private LHSTreeSection metricLeaf; + private LHSTreeSection runtimeLeaf; + + public Widget asWidget() + { + layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); + + stack = new VerticalPanel(); + stack.setStyleName("fill-layout-width"); + + + // ---------------------------------------------------- + + serverPicker = new ServerPicker(); + stack.add(serverPicker.asWidget()); + + // ---------------------------------------------------- + + navigation = new LHSNavTree("domain-runtime"); + navigation.getElement().setAttribute("aria-label", "Profile Tasks"); + + //Tree statusTree = new LHSNavTree("domain-runtime"); + + LHSTreeSection domainLeaf = new LHSTreeSection("Domain"); + navigation.addItem(domainLeaf); + + + //domainLeaf.addItem(new LHSNavTreeItem("Overview", "")); + + LHSNavTreeItem serverInstances= new LHSNavTreeItem(Console.CONSTANTS.common_label_serverInstances(), NameTokens.InstancesPresenter); + domainLeaf.addItem(serverInstances); + domainLeaf.addItem(serverInstances); + + domainLeaf.addItem(new LHSNavTreeItem("Manage Deployments", NameTokens.DeploymentsPresenter)); + + + //DisclosurePanel statusPanel = new DisclosureStackPanel("Domain Status").asWidget(); + //statusPanel.setContent(statusTree); + //stack.add(statusPanel); + + // ------------- + + metricLeaf = new LHSTreeSection("Server Status"); + navigation.addItem(metricLeaf); + + LHSNavTreeItem datasources = new LHSNavTreeItem("Datasources", NameTokens.DataSourceMetricPresenter); + LHSNavTreeItem jmsQueues = new LHSNavTreeItem("JMS Destinations", NameTokens.JmsMetricPresenter); + LHSNavTreeItem web = new LHSNavTreeItem("Web", NameTokens.WebMetricPresenter); + LHSNavTreeItem tx = new LHSNavTreeItem("Transactions", NameTokens.TXMetrics); + LHSNavTreeItem jpa = new LHSNavTreeItem("JPA", NameTokens.JPAMetricPresenter); + LHSNavTreeItem naming = new LHSNavTreeItem("JNDI View", NameTokens.JndiPresenter); + + + metricPredicates.add(new Predicate("datasources", datasources)); + metricPredicates.add(new Predicate("messaging", jmsQueues)); + metricPredicates.add(new Predicate("web", web)); + metricPredicates.add(new Predicate("transactions", tx)); + metricPredicates.add(new Predicate("jpa", jpa)); + metricPredicates.add(new Predicate("naming", naming)); + + // BEGIN: SwitchYard additions + metricPredicates.addAll(SubsystemMetaData.getRuntimeMetricsExtensions()); + // END: SwitchYard additions + + // --- + + runtimeLeaf = new LHSTreeSection("Runtime Operations"); + navigation.addItem(runtimeLeaf); + + LHSNavTreeItem osgi = new LHSNavTreeItem("OSGi", NameTokens.OSGiRuntimePresenter); + runtimePredicates.add(new Predicate("osgi", osgi)); + + // BEGIN: SwitchYard additions + runtimePredicates.addAll(SubsystemMetaData.getRuntimeOperationsExtensions()); + // END: SwitchYard additions + + // ---------------------------------------------------- + + navigation.expandTopLevel(); + + stack.add(navigation); + + layout.add(stack); + + scroll = new ScrollPanel(layout); + + return scroll; + } + + public void setHosts(List hosts) { + + serverPicker.setHosts(hosts); + + } + + public void setServer(List server) { + + serverPicker.setServers(server); + } + + public void setSubsystems(List subsystems) { + + + metricLeaf.removeItems(); + runtimeLeaf.removeItems(); + + LHSNavTreeItem jvm = new LHSNavTreeItem("JVM", NameTokens.HostVMMetricPresenter); + metricLeaf.addItem(jvm); + + // match subsystems + for(SubsystemRecord subsys : subsystems) + { + + for(Predicate predicate : metricPredicates) + { + if(predicate.matches(subsys.getKey())) + metricLeaf.addItem(predicate.getNavItem()); + } + + for(Predicate predicate : runtimePredicates) + { + if(predicate.matches(subsys.getKey())) + runtimeLeaf.addItem(predicate.getNavItem()); + } + } + + final LHSNavTreeItem webservices = new LHSNavTreeItem("Webservices", NameTokens.WebServiceRuntimePresenter); + metricLeaf.addItem(webservices); + + navigation.expandTopLevel(); + + } + +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemExtension.java b/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemExtension.java new file mode 100644 index 000000000..35da584aa --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemExtension.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.console.client.shared; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * SubsystemExtension + * + * Provides information about a subsytem extension (e.g. group name, items list) + * + * @author Rob Cernich + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface SubsystemExtension { + + /** + * Used to define a "group" in the subsystem tree. + */ + public @interface SubsystemGroupDefinition { + /** + * The name of the group. + */ + String name(); + + /** + * The items within the group. + */ + SubsystemItemDefinition[] items(); + } + + /** + * Used to define an item in the subsystem tree. + */ + public @interface SubsystemItemDefinition { + /** + * The (display) name of the item. + */ + String name(); + + /** + * The name token identifying the presenter for this item. + */ + String presenter(); + } + + /** + * The subsystem groups supported by the extension. + */ + SubsystemGroupDefinition[] groups(); + + /** + * A runtime operations group item provided by the subsystem. + */ + SubsystemItemDefinition[] runtime() default {}; + + /** + * A runtime metrics group item provided by the subsystem. + */ + SubsystemItemDefinition[] metrics() default {}; + + /** + * The subsystem name for the item. Must match the name used to identify the + * subsystem within the server configuration. + */ + String subsystem(); + +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemExtensionProcessor.java b/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemExtensionProcessor.java new file mode 100644 index 000000000..549a7b383 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemExtensionProcessor.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.console.client.shared; + +import java.util.List; +import java.util.Map; + +import org.jboss.as.console.client.widgets.nav.Predicate; + +/** + * SubsystemExtensionProcessor + * + * Processes subsystem extensions and adds them to the groups list. + * + * @author Rob Cernich + */ +public interface SubsystemExtensionProcessor { + + /** + * Adds entries corresponding to extended subsystems. + * + * @param groups the container for the groups. + */ + public void processProfileExtensions(Map groups); + + /** + * Retrieves runtime metrics predicates registered by subsystem extensions. + * + * @return predicates registered by subsystem extensions. + */ + public List getRuntimeMetricsExtensions(); + + /** + * Retrieves runtime operations predicates registered by subsystem + * extensions. + * + * @return predicates registered by subsystem extensions. + */ + public List getRuntimeOperationsExtensions(); + +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemMetaData.java b/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemMetaData.java new file mode 100644 index 000000000..ba6089c5f --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/shared/SubsystemMetaData.java @@ -0,0 +1,247 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jboss.as.console.client.shared; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.client.core.NameTokens; +import org.jboss.as.console.client.plugins.SubsystemExtension; +import org.jboss.as.console.client.plugins.SubsystemRegistry; +import org.jboss.as.console.client.shared.model.SubsystemRecord; +import org.jboss.as.console.client.widgets.nav.Predicate; + +import com.google.gwt.core.client.GWT; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Heiko Braun + * @date 3/29/11 + */ +@Deprecated +public class SubsystemMetaData { + + static Map groups = new LinkedHashMap(); + static List runtimeMetricsExtensions; + static List runtimeOperationsExtensions; + + private static final String CONNECTOR = "Connector"; + + private static final String MESSAGING = "Messaging"; + + private static final String CORE = "Core"; + + private static final String CONTAINER = "Container"; + + private static final String OSGI = "OSGi"; + + private static final String INFINISPAN = "Infinispan"; + + private static final String SECURITY = "Security"; + + private static final String WEB = "Web"; + + private static final String OTHER = "Other"; + + static { + + // specify groups and the order they appear + groups.put(CORE, new SubsystemGroup(CORE)); + groups.put(CONNECTOR, new SubsystemGroup(CONNECTOR)); + groups.put(MESSAGING, new SubsystemGroup(MESSAGING)); + groups.put(CONTAINER, new SubsystemGroup(CONTAINER)); + groups.put(SECURITY, new SubsystemGroup(SECURITY)); + groups.put(WEB, new SubsystemGroup(WEB)); + groups.put(OSGI, new SubsystemGroup(OSGI)); + groups.put(INFINISPAN, new SubsystemGroup(INFINISPAN)); + groups.put(OTHER, new SubsystemGroup(OTHER)); + + // assign actual subsystems + groups.get(CONNECTOR).getItems().add(new SubsystemGroupItem("JCA", "jca")); + groups.get(CONNECTOR).getItems().add(new SubsystemGroupItem("Datasources", "datasources")); + groups.get(CONNECTOR).getItems().add(new SubsystemGroupItem("Resource Adapters", "resource-adapters")); + groups.get(CONNECTOR).getItems().add(new SubsystemGroupItem("Connector", "connector",Boolean.TRUE)); + groups.get(CONNECTOR).getItems().add(new SubsystemGroupItem("Mail", "mail")); + + groups.get(WEB).getItems().add(new SubsystemGroupItem("Servlet/HTTP", "web")); + groups.get(WEB).getItems().add(new SubsystemGroupItem("Web Services", "webservices")); + groups.get(WEB).getItems().add(new SubsystemGroupItem("JAXRS", "jaxrs",Boolean.TRUE)); + groups.get(WEB).getItems().add(new SubsystemGroupItem("mod_cluster", "modcluster", NameTokens.ModclusterPresenter)); + + groups.get(MESSAGING).getItems().add(new SubsystemGroupItem("Destinations", "messaging")); + + groups.get(CORE).getItems().add(new SubsystemGroupItem("Threads", "threads", Boolean.TRUE)); + groups.get(CORE).getItems().add(new SubsystemGroupItem("Logging", "logging")); + groups.get(CORE).getItems().add(new SubsystemGroupItem("Deployment Scanners", "deployment-scanner")); + groups.get(CORE).getItems().add(new SubsystemGroupItem("Remoting", "remoting",Boolean.TRUE)); + groups.get(CORE).getItems().add(new SubsystemGroupItem("Threads", NameTokens.BoundedQueueThreadPoolPresenter)); + groups.get(CORE).getItems().add(new SubsystemGroupItem("JMX", "jmx")); + groups.get(CORE).getItems().add(new SubsystemGroupItem("Config Admin", NameTokens.ConfigAdminPresenter)); + groups.get(CORE).getItems().add(new SubsystemGroupItem("JGroups", NameTokens.JGroupsPresenter)); + + groups.get(CONTAINER).getItems().add(new SubsystemGroupItem("Naming", "naming", !Console.getBootstrapContext().isStandalone())); + groups.get(CONTAINER).getItems().add(new SubsystemGroupItem("EJB 3", "ejb3")); + groups.get(CONTAINER).getItems().add(new SubsystemGroupItem("EE", "ee")); + //groups.get(CONTAINER).getItems().add(new SubsystemGroupItem("Transactions", "transactions")); + groups.get(CONTAINER).getItems().add(new SubsystemGroupItem("Weld", "weld",Boolean.TRUE)); + groups.get(CONTAINER).getItems().add(new SubsystemGroupItem("JPA", "jpa")); + groups.get(CONTAINER).getItems().add(new SubsystemGroupItem("JacORB", "jacorb")); + + groups.get(SECURITY).getItems().add(new SubsystemGroupItem("Security Subsystem", "security", NameTokens.SecuritySubsystemPresenter)); + groups.get(SECURITY).getItems().add(new SubsystemGroupItem("Security Domains", "security", NameTokens.SecurityDomainsPresenter)); + + groups.get(OSGI).getItems().add(new SubsystemGroupItem("Framework", "osgi", NameTokens.OSGiConfigurationPresenter)); + + groups.get(INFINISPAN).getItems().add(new SubsystemGroupItem("Cache Containers", NameTokens.Infinispan, NameTokens.CacheContainerPresenter)); + groups.get(INFINISPAN).getItems().add(new SubsystemGroupItem("Local Caches", NameTokens.Infinispan, NameTokens.LocalCachePresenter)); + groups.get(INFINISPAN).getItems().add(new SubsystemGroupItem("Invalidation Caches", NameTokens.Infinispan, NameTokens.InvalidationCachePresenter)); + groups.get(INFINISPAN).getItems().add(new SubsystemGroupItem("Replicated Caches", NameTokens.Infinispan, NameTokens.ReplicatedCachePresenter)); + groups.get(INFINISPAN).getItems().add(new SubsystemGroupItem("Distributed Caches", NameTokens.Infinispan, NameTokens.DistributedCachePresenter)); + + groups.get(OTHER).getItems().add(new SubsystemGroupItem("SAR", "sar",Boolean.TRUE)); + groups.get(OTHER).getItems().add(new SubsystemGroupItem("Arquillian", "arquillian",Boolean.TRUE)); + + + SubsystemExtensionProcessor extensionProcessor = GWT.create(SubsystemExtensionProcessor.class); + extensionProcessor.processProfileExtensions(groups); + runtimeMetricsExtensions = extensionProcessor.getRuntimeMetricsExtensions(); + runtimeOperationsExtensions = extensionProcessor.getRuntimeOperationsExtensions(); + } + + public static void bootstrap(SubsystemRegistry registry) { + + List defaults = new ArrayList(); + + for(String groupName : groups.keySet()) + { + SubsystemGroup group = groups.get(groupName); + for(SubsystemGroupItem item : group.getItems()) + { + if(!item.isDisabled()) + { + defaults.add(new SubsystemExtension( + item.getName(), item.getPresenter(), + group.getName(), item.getKey()) + ); + } + } + } + + registry.getExtensions().addAll(defaults); + + } + + public static Map getGroups() { + return groups; + } + + /** + * @return the runtime extensions + */ + public static List getRuntimeMetricsExtensions() { + return runtimeMetricsExtensions; + } + + /** + * @return the runtime extensions + */ + public static List getRuntimeOperationsExtensions() { + return runtimeOperationsExtensions; + } + + public static SubsystemGroup getGroupForKey(String subsysKey) + { + SubsystemGroup matchingGroup = null; + + for(String groupName : groups.keySet()) + { + SubsystemGroup group = groups.get(groupName); + for(SubsystemGroupItem item : group.getItems()) + { + if(item.getKey().equals(subsysKey) + && item.isDisabled() == false) + { + matchingGroup = group; + break; + } + } + + if(matchingGroup!=null) + break; + } + + // found one? + if(null==matchingGroup) + matchingGroup = groups.get(OTHER); + + return matchingGroup; + } + + public static String[] getDefaultSubsystem(String preferred, List existing) + { + if(existing.isEmpty()) + throw new RuntimeException("No subsystem provided!"); + + SubsystemRecord chosen = null; + for(SubsystemRecord subsys : existing) + { + if(subsys.getKey().equals(preferred)) + { + chosen = subsys; + break; + } + } + + if(null==chosen) + chosen = existing.get(0); + + + return resolveTokens(chosen.getKey()); + } + + public static String[] resolveTokens(String key) { + String[] token = new String[2]; + + final SubsystemRegistry subsystemRegistry = Console.MODULES.getSubsystemRegistry(); + for(SubsystemExtension ext : subsystemRegistry.getExtensions()) + { + if(ext.getKey().equals(key)) + { + token[0] = ext.getName(); + token[1] = ext.getToken(); + break; + } + } + + /*for(String groupName : groups.keySet()) + { + SubsystemGroup group = groups.get(groupName); + for(SubsystemGroupItem item : group.getItems()) + { + if(item.getKey().equals(key) + && item.isDisabled() == false) + { + token[0] = item.getName(); + token[1] = item.getPresenter(); + break; + } + } + } */ + + return token; + } +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/shared/runtime/plain/PlainColumnView.java b/console/as7-core/src/main/java/org/jboss/as/console/client/shared/runtime/plain/PlainColumnView.java new file mode 100644 index 000000000..522f1cec9 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/shared/runtime/plain/PlainColumnView.java @@ -0,0 +1,226 @@ +package org.jboss.as.console.client.shared.runtime.plain; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.jboss.as.console.client.shared.help.HelpSystem; +import org.jboss.as.console.client.shared.help.MetricHelpPanel; +import org.jboss.as.console.client.shared.help.StaticHelpPanel; +import org.jboss.as.console.client.shared.runtime.Metric; +import org.jboss.as.console.client.shared.runtime.Sampler; +import org.jboss.as.console.client.shared.runtime.charts.Column; +import org.jboss.as.console.client.shared.runtime.charts.StackedBar; + +import com.google.gwt.dom.client.Style; +import com.google.gwt.user.client.ui.FlexTable; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.HasHorizontalAlignment; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + + +/** + * @author Heiko Braun + * @date 10/25/11 + */ +public class PlainColumnView implements Sampler { + + private Column[] columns = null; + private FlexTable grid; + private String title; + private int ROW_OFFSET = 1; + + private List stacks = new LinkedList(); + + // default width and height + private int width = 100; + private Style.Unit unit = Style.Unit.PCT; + private HelpSystem.AddressCallback address = null; + private StaticHelpPanel staticHelp; + private Map columnIndexes = new HashMap(); + + @Deprecated + public PlainColumnView(String title) { + this.title = title; + } + + public PlainColumnView(String title, HelpSystem.AddressCallback address) { + this.title = title; + this.address = address; + } + + public PlainColumnView setColumns(Column... columns) { + this.columns = columns; + return this; + } + + public PlainColumnView setWidth(int width, Style.Unit unit) { + this.width = width; + this.unit = unit; + return this; + } + + @Override + public Widget asWidget() { + + + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); + + layout.add(new HTML("
"+title+"
")); + + grid = new FlexTable(); + grid.getElement().setAttribute("width", width+unit.getType()+""); + + // header columns + grid.setHTML(0, 0, "Metric"); + grid.setHTML(0, 1, "Actual"); + grid.setHTML(0, 2, " "); + + grid.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT); + + // actual values + int row = ROW_OFFSET; + for(Column c : columns) + { + grid.setHTML(row, 0, "
"+c.getLabel() + ":
"); + grid.setHTML(row, 1, ""); + + stacks.add(new StackedBar()); + + if(c.getComparisonColumn()!=null) + { + StackedBar stack = stacks.get(row - ROW_OFFSET); + grid.setWidget(row, 2, stack.asWidget()); + stack.setRatio(0,0); + } + else + grid.setText(row, 2, ""); + + grid.getCellFormatter().setHorizontalAlignment(row, 1, HasHorizontalAlignment.ALIGN_RIGHT); + + if(!c.isVisible()) + grid.getRowFormatter().setVisible(row, false); + if(c.isBaseline()) + grid.getRowFormatter().addStyleName(row, "metric-table-baseline"); + + columnIndexes.put(c, row - ROW_OFFSET); + + row++; + } + + grid.getCellFormatter().setStyleName(0,0,"metric-table-header"); + grid.getCellFormatter().setStyleName(0,1,"metric-table-header"); + grid.getCellFormatter().setStyleName(0,2,"metric-table-header"); + grid.getCellFormatter().setWidth(0, 2, "50%"); + + + if(null==staticHelp && address!=null) + { + MetricHelpPanel helpPanel = new MetricHelpPanel(address, this.columns); + //helpPanel.setAligned(true); + layout.add(helpPanel.asWidget()); + } + else if(staticHelp!=null) + { + layout.add(staticHelp.asWidget()); + } + + layout.add(grid); + + return layout; + } + + @Override + public void addSample(Metric metric) { + int row=ROW_OFFSET; + int baselineIndex = getBaseLineIndex(); + + // check if they match + if(baselineIndex>metric.numSamples()) + throw new RuntimeException("Illegal baseline index "+baselineIndex+" on number of samples "+metric.numSamples()); + + Long baseline = baselineIndex >= 0 ? + Long.valueOf(metric.get(baselineIndex)) : -1; + + for(Column c : columns) + { + int dataIndex = row - ROW_OFFSET; + String actualValue = metric.get(dataIndex); + + if(null==actualValue) + throw new RuntimeException("Metric value at index "+dataIndex+" is null"); + + grid.setText(row, 1, actualValue ); + + if(c.getComparisonColumn()!=null) + { + stacks.get(dataIndex).setRatio(getComparisonValue(metric, c.getComparisonColumn()), Double.valueOf(actualValue)); + } + row++; + } + + } + + public int getBaseLineIndex() { + int i=0; + boolean didMatch = false; + for(Column c : columns) + { + if(c.isBaseline()) + { + didMatch=true; + break; + } + i++; + } + + return didMatch ? i : -1; + } + + @Override + public void clearSamples() { + int row=ROW_OFFSET; + + for(Column c : columns) + { + int dataIndex = row - ROW_OFFSET; + + // clear the 'Actual' value + grid.setText(row, 1, ""); + + // cleanup stackbar if used + if(c.getComparisonColumn()!=null ) + { + stacks.get(dataIndex).setRatio(0,0); + } + else if(c.getComparisonColumn()!=null ) + { + throw new RuntimeException("Comparison column specified, but no baseline set!"); + } + + row++; + } + } + + @Override + public long numSamples() { + return 1; + } + + @Override + public void recycle() { + + } + + public PlainColumnView setStaticHelp(StaticHelpPanel helpPanel) { + this.staticHelp = helpPanel; + return this; + } + + private long getComparisonValue(Metric metric, Column comparisonColumn) { + return Long.parseLong(metric.get(columnIndexes.get(comparisonColumn))); + } +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/client/standalone/runtime/StandaloneRuntimeNavigation.java b/console/as7-core/src/main/java/org/jboss/as/console/client/standalone/runtime/StandaloneRuntimeNavigation.java new file mode 100644 index 000000000..4fb474794 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/client/standalone/runtime/StandaloneRuntimeNavigation.java @@ -0,0 +1,149 @@ +package org.jboss.as.console.client.standalone.runtime; + +import com.google.gwt.user.client.ui.ScrollPanel; +import com.google.gwt.user.client.ui.TreeItem; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import org.jboss.as.console.client.core.NameTokens; +import org.jboss.as.console.client.shared.SubsystemMetaData; +import org.jboss.as.console.client.shared.model.SubsystemRecord; +import org.jboss.as.console.client.widgets.nav.Predicate; +import org.jboss.ballroom.client.layout.LHSTreeSection; +import org.jboss.ballroom.client.layout.LHSNavTree; +import org.jboss.ballroom.client.layout.LHSNavTreeItem; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Heiko Braun + * @date 11/2/11 + */ +public class StandaloneRuntimeNavigation { + + private VerticalPanel stack; + private VerticalPanel layout; + + private List subsystems; + + private List metricPredicates = new ArrayList(); + private List runtimePredicates = new ArrayList(); + + private ScrollPanel scroll; + private TreeItem metricLeaf; + private TreeItem runtimeLeaf; + private LHSNavTree navigation; + + public Widget asWidget() + { + layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); + + stack = new VerticalPanel(); + stack.setStyleName("fill-layout-width"); + + // ---------------------------------------------------- + + + navigation = new LHSNavTree("standalone-runtime"); + navigation.getElement().setAttribute("aria-label", "Runtime Tasks"); + + // ---------------------------------------------------- + + TreeItem serverLeaf = new LHSTreeSection("Server", true); + + LHSNavTreeItem server = new LHSNavTreeItem("Configuration", NameTokens.StandaloneServerPresenter); + + serverLeaf.addItem(server); + serverLeaf.addItem(new LHSNavTreeItem("Manage Deployments", NameTokens.DeploymentListPresenter)); + navigation.addItem(serverLeaf); + + + // ------------- + + metricLeaf = new LHSTreeSection("Status"); + + + LHSNavTreeItem datasources = new LHSNavTreeItem("Datasources", "ds-metrics"); + LHSNavTreeItem jmsQueues = new LHSNavTreeItem("JMS Destinations", "jms-metrics"); + LHSNavTreeItem web = new LHSNavTreeItem("Web", "web-metrics"); + LHSNavTreeItem tx = new LHSNavTreeItem("Transactions", "tx-metrics"); + LHSNavTreeItem jpa = new LHSNavTreeItem("JPA", NameTokens.JPAMetricPresenter); + LHSNavTreeItem ws = new LHSNavTreeItem("Webservices", NameTokens.WebServiceRuntimePresenter); + LHSNavTreeItem naming = new LHSNavTreeItem("JNDI View", NameTokens.JndiPresenter); + + metricPredicates.add(new Predicate("datasources", datasources)); + metricPredicates.add(new Predicate("messaging", jmsQueues)); + metricPredicates.add(new Predicate("web", web)); + metricPredicates.add(new Predicate("transactions", tx)); + metricPredicates.add(new Predicate("jpa", jpa)); + metricPredicates.add(new Predicate("webservices", ws)); + metricPredicates.add(new Predicate("naming", naming)); + + // BEGIN: SwitchYard additions + metricPredicates.addAll(SubsystemMetaData.getRuntimeMetricsExtensions()); + // END: SwitchYard additions + + navigation.addItem(metricLeaf); + + + // --- + + runtimeLeaf = new LHSTreeSection("Runtime Operations"); + + + LHSNavTreeItem osgi = new LHSNavTreeItem("OSGi", NameTokens.OSGiRuntimePresenter); + + runtimePredicates.add(new Predicate("osgi", osgi)); + + // BEGIN: SwitchYard additions + runtimePredicates.addAll(SubsystemMetaData.getRuntimeOperationsExtensions()); + // END: SwitchYard additions + + navigation.addItem(runtimeLeaf); + + // ---------------------------------------------------- + + // --- + stack.add(navigation); + layout.add(stack); + + scroll = new ScrollPanel(layout); + + navigation.expandTopLevel(); + + return scroll; + } + + + + public void setSubsystems(List subsystems) { + + + metricLeaf.removeItems(); + runtimeLeaf.removeItems(); + + metricLeaf.addItem( new LHSNavTreeItem("JVM", NameTokens.VirtualMachine)); + // match subsystems + for(SubsystemRecord subsys : subsystems) + { + + for(Predicate predicate : metricPredicates) + { + if(predicate.matches(subsys.getKey())) + metricLeaf.addItem(predicate.getNavItem()); + } + + for(Predicate predicate : runtimePredicates) + { + if(predicate.matches(subsys.getKey())) + runtimeLeaf.addItem(predicate.getNavItem()); + } + } + + navigation.expandTopLevel(); + + } + + +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/rebind/extensions/SubsystemExtensionProcessorGenerator.java b/console/as7-core/src/main/java/org/jboss/as/console/rebind/extensions/SubsystemExtensionProcessorGenerator.java new file mode 100644 index 000000000..7c3b6b839 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/rebind/extensions/SubsystemExtensionProcessorGenerator.java @@ -0,0 +1,184 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.console.rebind.extensions; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.jboss.as.console.client.shared.SubsystemExtension; +import org.jboss.as.console.client.shared.SubsystemExtension.SubsystemGroupDefinition; +import org.jboss.as.console.client.shared.SubsystemExtension.SubsystemItemDefinition; +import org.jboss.as.console.client.shared.SubsystemExtensionProcessor; +import org.jboss.as.console.client.shared.SubsystemGroup; +import org.jboss.as.console.client.shared.SubsystemGroupItem; +import org.jboss.as.console.client.widgets.nav.Predicate; +import org.jboss.ballroom.client.layout.LHSNavTreeItem; + +import com.google.gwt.core.ext.Generator; +import com.google.gwt.core.ext.GeneratorContext; +import com.google.gwt.core.ext.TreeLogger; +import com.google.gwt.core.ext.UnableToCompleteException; +import com.google.gwt.core.ext.typeinfo.JClassType; +import com.google.gwt.core.ext.typeinfo.TypeOracle; +import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; +import com.google.gwt.user.rebind.SourceWriter; + +/** + * SubsystemExtensionProcessorGenerator + * + * GWT code generator for SubsystemExtensionProcessor. A code generator is used + * because reflection cannot be used on the client side. This generator scans + * for classes annotated with SubsystemExtension and adds them to the manager. + * + * @author Rob Cernich + */ +public class SubsystemExtensionProcessorGenerator extends Generator { + + @Override + public String generate(TreeLogger logger, GeneratorContext context, String typeName) + throws UnableToCompleteException { + TypeOracle typeOracle = context.getTypeOracle(); + JClassType subsystemExtensionManager = typeOracle.findType(typeName); + if (subsystemExtensionManager == null) { + logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null); + throw new UnableToCompleteException(); + } + if (subsystemExtensionManager.isInterface() == null) { + logger.log(TreeLogger.ERROR, subsystemExtensionManager.getQualifiedSourceName() + " is not an interface", + null); + throw new UnableToCompleteException(); + } + + List subsystemExtensions = new ArrayList(); + for (JClassType type : typeOracle.getTypes()) { + if (type.isAnnotationPresent(SubsystemExtension.class)) { + subsystemExtensions.add(type.getAnnotation(SubsystemExtension.class)); + } + } + + String packageName = subsystemExtensionManager.getPackage().getName(); + String className = subsystemExtensionManager.getSimpleSourceName() + "Impl"; + + generateClass(logger, context, packageName, className, subsystemExtensions); + + return packageName + "." + className; + } + + private void generateClass(TreeLogger logger, GeneratorContext context, String packageName, String className, + List subsystemExtensions) { + PrintWriter pw = context.tryCreate(logger, packageName, className); + if (pw == null) { + return; + } + + ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className); + + // imports + composerFactory.addImport(ArrayList.class.getCanonicalName()); + composerFactory.addImport(LinkedHashMap.class.getCanonicalName()); + composerFactory.addImport(List.class.getCanonicalName()); + composerFactory.addImport(Map.class.getCanonicalName()); + composerFactory.addImport(SubsystemExtensionProcessor.class.getCanonicalName()); + composerFactory.addImport(SubsystemGroup.class.getCanonicalName()); + composerFactory.addImport(SubsystemGroupItem.class.getCanonicalName()); + composerFactory.addImport(Predicate.class.getCanonicalName()); + composerFactory.addImport(LHSNavTreeItem.class.getCanonicalName()); + + // interface + composerFactory.addImplementedInterface(SubsystemExtensionProcessor.class.getCanonicalName()); + + SourceWriter sw = composerFactory.createSourceWriter(context, pw); + + // begin class definition + sw.indent(); + + // fields + sw.println("private final Map extensionGroups = new LinkedHashMap();"); + sw.println("private final List _runtimeMetricsExtensions = new ArrayList();"); + sw.println("private final List _runtimeOperationsExtensions = new ArrayList();"); + + // constructor + sw.println("public " + className + "() {"); + sw.indent(); + for (SubsystemExtension extension : subsystemExtensions) { + for (SubsystemGroupDefinition groupDef : extension.groups()) { + sw.println("SubsystemGroup group;"); + sw.println("if (extensionGroups.containsKey(\"%s\")) {", groupDef.name()); + sw.indentln("group = extensionGroups.get(\"%s\");", groupDef.name()); + sw.println("} else {"); + sw.indent(); + sw.println("group = new SubsystemGroup(\"%s\");", groupDef.name()); + sw.println("extensionGroups.put(group.getName(), group);"); + sw.outdent(); + sw.println("}"); + for (SubsystemItemDefinition itemDef : groupDef.items()) { + sw.println("group.getItems().add(new SubsystemGroupItem(\"%s\", \"%s\", \"%s\"));", itemDef.name(), + extension.subsystem(), itemDef.presenter()); + } + } + for (SubsystemItemDefinition runtimeItemDef : extension.metrics()) { + sw.println("_runtimeMetricsExtensions.add(new Predicate(\"%s\", new LHSNavTreeItem(\"%s\", \"%s\")));", + extension.subsystem(), runtimeItemDef.name(), runtimeItemDef.presenter()); + } + for (SubsystemItemDefinition runtimeItemDef : extension.runtime()) { + sw.println("_runtimeOperationsExtensions.add(new Predicate(\"%s\", new LHSNavTreeItem(\"%s\", \"%s\")));", + extension.subsystem(), runtimeItemDef.name(), runtimeItemDef.presenter()); + } + } + sw.outdent(); + sw.println("}"); + + // methods + // processProfileExtensions + sw.println("public void processProfileExtensions(Map groups) {"); + sw.indent(); + sw.println("for (Map.Entry entry : extensionGroups.entrySet()) {"); + sw.indent(); + sw.println("if (groups.containsKey(entry.getKey())) {"); + sw.indent(); + sw.println("SubsystemGroup group = groups.get(entry.getKey());"); + sw.println("group.getItems().addAll(entry.getValue().getItems());"); + sw.outdent(); + sw.println("} else {"); + sw.indent(); + sw.println("SubsystemGroup group = entry.getValue();"); + sw.println("groups.put(group.getName(), group);"); + sw.outdent(); + sw.println("}"); + sw.outdent(); + sw.println("}"); + sw.outdent(); + sw.println("}"); + + // getRuntimeMetricsExtensions + sw.println("public List getRuntimeMetricsExtensions() {"); + sw.indentln("return _runtimeMetricsExtensions;"); + sw.println("}"); + + // getRuntimeOperationsExtensions + sw.println("public List getRuntimeOperationsExtensions() {"); + sw.indentln("return _runtimeOperationsExtensions;"); + sw.println("}"); + + // close it out + sw.outdent(); + sw.println("}"); + + context.commit(logger, pw); + } + +} diff --git a/console/as7-core/src/main/java/org/jboss/as/console/rebind/extensions/SubsystemExtensionProcessorImpl.java b/console/as7-core/src/main/java/org/jboss/as/console/rebind/extensions/SubsystemExtensionProcessorImpl.java new file mode 100644 index 000000000..701386ac4 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/as/console/rebind/extensions/SubsystemExtensionProcessorImpl.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.as.console.rebind.extensions; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.jboss.as.console.client.shared.SubsystemExtension; +import org.jboss.as.console.client.shared.SubsystemExtension.SubsystemGroupDefinition; +import org.jboss.as.console.client.shared.SubsystemExtension.SubsystemItemDefinition; +import org.jboss.as.console.client.shared.SubsystemExtensionProcessor; +import org.jboss.as.console.client.shared.SubsystemGroup; +import org.jboss.as.console.client.shared.SubsystemGroupItem; +import org.jboss.as.console.client.widgets.nav.Predicate; +import org.jboss.ballroom.client.layout.LHSNavTreeItem; + +/** + * SubsystemExtensionProcessorImpl + * + * Template for what the generator should be creating. + * + * @author Rob Cernich + */ +public class SubsystemExtensionProcessorImpl implements SubsystemExtensionProcessor { + + private final Map _extensionGroups = new LinkedHashMap(); + private final List _runtimeMetricsExtensions = new ArrayList(); + private final List _runtimeOperationsExtensions = new ArrayList(); + + /** + * Create a new SubsystemExtensionProcessorImpl. + */ + public SubsystemExtensionProcessorImpl() { + SubsystemExtension extension = null; + for (SubsystemGroupDefinition groupDef : extension.groups()) { + SubsystemGroup group; + if (_extensionGroups.containsKey(groupDef.name())) { + group = _extensionGroups.get(groupDef.name()); + } else { + group = new SubsystemGroup(groupDef.name()); + _extensionGroups.put(group.getName(), group); + } + + for (SubsystemItemDefinition itemDef : groupDef.items()) { + group.getItems() + .add(new SubsystemGroupItem(itemDef.name(), extension.subsystem(), itemDef.presenter())); + } + } + + for (SubsystemItemDefinition runtimeItemDef : extension.metrics()) { + _runtimeMetricsExtensions.add(new Predicate(extension.subsystem(), new LHSNavTreeItem( + runtimeItemDef.name(), runtimeItemDef.presenter()))); + } + for (SubsystemItemDefinition runtimeItemDef : extension.runtime()) { + _runtimeOperationsExtensions.add(new Predicate(extension.subsystem(), new LHSNavTreeItem(runtimeItemDef + .name(), runtimeItemDef.presenter()))); + } + } + + @Override + public void processProfileExtensions(Map groups) { + for (Map.Entry entry : _extensionGroups.entrySet()) { + if (groups.containsKey(entry.getKey())) { + SubsystemGroup group = groups.get(entry.getKey()); + group.getItems().addAll(entry.getValue().getItems()); + } else { + SubsystemGroup group = entry.getValue(); + groups.put(group.getName(), group); + } + } + } + + @Override + public List getRuntimeMetricsExtensions() { + return _runtimeMetricsExtensions; + } + + @Override + public List getRuntimeOperationsExtensions() { + return _runtimeOperationsExtensions; + } + +} diff --git a/console/as7-core/src/main/java/org/jboss/dmr/client/DataInput.java b/console/as7-core/src/main/java/org/jboss/dmr/client/DataInput.java new file mode 100644 index 000000000..bc4931621 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/dmr/client/DataInput.java @@ -0,0 +1,148 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jboss.dmr.client; + +import java.io.IOException; + +import com.google.gwt.ajaxloader.client.ArrayHelper; + +/** + * see also http://quake2-gwt-port.googlecode.com/hg/src/com/google/gwt/corp/emul/java/io/DataInputStream.java?r=5c7c4b545ff4a8875b4cab5d77492d37e150d46b + */ +public class DataInput { + private int pos = 0; + private byte[] bytes; + + public DataInput(byte[] bytes) { + this.bytes = bytes; + } + + public int read() throws IOException { + if (pos >= bytes.length) + return -1; + + return bytes[pos++] & 0xFF; + } + + public boolean readBoolean() throws IOException { + return readByte() != 0; + } + + public byte readByte() throws IOException { + int i = read(); + if (i == -1) { + throw new RuntimeException("EOF"); + } + return (byte) i; + } + + public char readChar() throws IOException { + int a = readUnsignedByte(); + int b = readUnsignedByte(); + return (char) ((a << 8) | b); + } + + public double readDouble() throws IOException { + // byte doubleBytes[] = new byte[8]; + // readFully(doubleBytes); + return IEEE754.toDouble(ArrayHelper.toJsArrayInteger(bytes[pos++], bytes[pos++], bytes[pos++], bytes[pos++], + bytes[pos++], bytes[pos++], bytes[pos++], bytes[pos++])); + } + + public float readFloat() throws IOException { + return IEEE754.toFloat(bytes[pos++], bytes[pos++], bytes[pos++], bytes[pos++]); + } + + public int readInt() throws IOException { + int a = readUnsignedByte(); + int b = readUnsignedByte(); + int c = readUnsignedByte(); + int d = readUnsignedByte(); + return (a << 24) | (b << 16) | (c << 8) | d; + } + + public String readLine() throws IOException { + throw new RuntimeException("readline NYI"); + } + + public long readLong() throws IOException { + long a = readInt(); + long b = readInt() & 0x0ffffffff; + return (a << 32) | b; + } + + public short readShort() throws IOException { + int a = readUnsignedByte(); + int b = readUnsignedByte(); + return (short) ((a << 8) | b); + } + + public String readUTF() throws IOException { + int bytes = readUnsignedShort(); + StringBuilder sb = new StringBuilder(); + + while (bytes > 0) { + bytes -= readUtfChar(sb); + } + + return sb.toString(); + } + + private int readUtfChar(StringBuilder sb) throws IOException { + int a = readUnsignedByte(); + if ((a & 0x80) == 0) { + sb.append((char) a); + return 1; + } + if ((a & 0xe0) == 0xb0) { + int b = readUnsignedByte(); + sb.append((char) (((a & 0x1F) << 6) | (b & 0x3F))); + return 2; + } + if ((a & 0xf0) == 0xe0) { + int b = readUnsignedByte(); + int c = readUnsignedByte(); + sb.append((char) (((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))); + return 3; + } + throw new IllegalArgumentException("Illegal byte " + a); + } + + public int readUnsignedByte() throws IOException { + int i = read(); + if (i == -1) { + throw new RuntimeException("EOF"); + } + return i; + } + + public int readUnsignedShort() throws IOException { + int a = readUnsignedByte(); + int b = readUnsignedByte(); + return ((a << 8) | b); + } + + public int skipBytes(int n) throws IOException { + // note: This is actually a valid implementation of this method, rendering it quite useless... + return 0; + } + + public void readFully(byte[] b) { + for (int i = 0; i < b.length; i++) { + b[i] = bytes[pos++]; + } + } + +} diff --git a/console/as7-core/src/main/java/org/jboss/dmr/client/IEEE754.java b/console/as7-core/src/main/java/org/jboss/dmr/client/IEEE754.java new file mode 100644 index 000000000..ec2e33d71 --- /dev/null +++ b/console/as7-core/src/main/java/org/jboss/dmr/client/IEEE754.java @@ -0,0 +1,199 @@ +/* + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. +*/ +package org.jboss.dmr.client; + +import com.google.gwt.core.client.JsArrayInteger; + +public class IEEE754 { + + public static native JsArrayInteger fromFloat(float v)/*-{ + var ebits = 8; + var fbits = 23; + var bias = (1 << (ebits - 1)) - 1; + + // Compute sign, exponent, fraction + var s, e, f; + if (isNaN(v)) { + e = (1 << bias) - 1; f = 1; s = 0; + } + else if (v === Infinity || v === -Infinity) { + e = (1 << bias) - 1; f = 0; s = (v < 0) ? 1 : 0; + } + else if (v === 0) { + e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; + } + else { + s = v < 0; + v = Math.abs(v); + + if (v >= Math.pow(2, 1 - bias)) { + var ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); + e = ln + bias; + f = v * Math.pow(2, fbits - ln) - Math.pow(2, fbits); + } + else { + e = 0; + f = v / Math.pow(2, 1 - bias - fbits); + } + } + + // Pack sign, exponent, fraction + var i, bits = []; + for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } + for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } + bits.push(s ? 1 : 0); + bits.reverse(); + var str = bits.join(''); + + // Bits to bytes + var bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; + }-*/; + + public static native float toFloat(byte b1, byte b2, byte b3, byte b4)/*-{ + var ebits = 8; + var fbits = 23; + var bytes = arguments; + + // Bytes to bits + var bits = []; + for (var i = bytes.length; i; i -= 1) { + var byteA = bytes[i - 1]; + for (var j = 8; j; j -= 1) { + bits.push(byteA % 2 ? 1 : 0); byteA = byteA >> 1; + } + } + bits.reverse(); + var str = bits.join(''); + + // Unpack sign, exponent, fraction + var bias = (1 << (ebits - 1)) - 1; + var s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + var e = parseInt(str.substring(1, 1 + ebits), 2); + var f = parseInt(str.substring(1 + ebits), 2); + + // Produce number + if (e === (1 << ebits) - 1) { + return f !== 0 ? NaN : s * Infinity; + } + else if (e > 0) { + return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); + } + else if (f !== 0) { + return s * Math.pow(2, -(bias-1)) * (f / Math.pow(2, fbits)); + } + else { + return s * 0; + } + }-*/; + + public static native JsArrayInteger fromDouble(double v)/*-{ + var ebits = 11; + var fbits = 52; + var bias = (1 << (ebits - 1)) - 1; + + // Compute sign, exponent, fraction + var s, e, f; + if (isNaN(v)) { + e = (1 << bias) - 1; f = 1; s = 0; + } + else if (v === Infinity || v === -Infinity) { + e = (1 << bias) - 1; f = 0; s = (v < 0) ? 1 : 0; + } + else if (v === 0) { + e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; + } + else { + s = v < 0; + v = Math.abs(v); + + if (v >= Math.pow(2, 1 - bias)) { + var ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias); + e = ln + bias; + f = v * Math.pow(2, fbits - ln) - Math.pow(2, fbits); + } + else { + e = 0; + f = v / Math.pow(2, 1 - bias - fbits); + } + } + + // Pack sign, exponent, fraction + var i, bits = []; + for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } + for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } + bits.push(s ? 1 : 0); + bits.reverse(); + var str = bits.join(''); + + // Bits to bytes + var bytes = []; + while (str.length) { + bytes.push(parseInt(str.substring(0, 8), 2)); + str = str.substring(8); + } + return bytes; + }-*/; + + public static native double toDouble(JsArrayInteger bytes) /*-{ + var ebits = 11; + var fbits = 52; + + // Bytes to bits + var bits = []; + for (var i = bytes.length; i; i -= 1) { + var byteA = bytes[i - 1]; + for (var j = 8; j; j -= 1) { + bits.push(byteA % 2 ? 1 : 0); byteA = byteA >> 1; + } + } + bits.reverse(); + var str = bits.join(''); + + // Unpack sign, exponent, fraction + var bias = (1 << (ebits - 1)) - 1; + var s = parseInt(str.substring(0, 1), 2) ? -1 : 1; + var e = parseInt(str.substring(1, 1 + ebits), 2); + var f = parseInt(str.substring(1 + ebits), 2); + + // Produce number + if (e === (1 << ebits) - 1) { + return f !== 0 ? NaN : s * Infinity; + } + else if (e > 0) { + return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); + } + else if (f !== 0) { + return s * Math.pow(2, -(bias-1)) * (f / Math.pow(2, fbits)); + } + else { + return s * 0; + } + }-*/; + +// function fromIEEE754Double(b) { return fromIEEE754(b, 11, 52); } +// function toIEEE754Double(v) { return toIEEE754(v, 11, 52); } +// function fromIEEE754Single(b) { return fromIEEE754(b, 8, 23); } +// function toIEEE754Single(v) { return toIEEE754(v, 8, 23); } + +} diff --git a/console/component/bean/pom.xml b/console/component/bean/pom.xml new file mode 100644 index 000000000..fef1d4d42 --- /dev/null +++ b/console/component/bean/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-bean + SwitchYard: Bean Component Console Extension + Provides customized UI for the SwitchYard Bean component. + + + org.switchyard.console + switchyard-console-component-core + provided + + + diff --git a/console/component/bean/src/main/java/org/switchyard/console/component/bean/ComponentExtension.gwt.xml b/console/component/bean/src/main/java/org/switchyard/console/component/bean/ComponentExtension.gwt.xml new file mode 100644 index 000000000..6285cf25d --- /dev/null +++ b/console/component/bean/src/main/java/org/switchyard/console/component/bean/ComponentExtension.gwt.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/console/component/bean/src/main/java/org/switchyard/console/component/bean/client/BeanComponentProvider.java b/console/component/bean/src/main/java/org/switchyard/console/component/bean/client/BeanComponentProvider.java new file mode 100644 index 000000000..b757a27df --- /dev/null +++ b/console/component/bean/src/main/java/org/switchyard/console/component/bean/client/BeanComponentProvider.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.bean.client; + +import org.switchyard.console.components.client.extension.BaseComponentProvider; +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +/** + * BeanComponentProvider + * + * ComponentProvider for the Bean component. + * + * @author Rob Cernich + */ +@ComponentExtension(displayName = "Bean", componentName = "org.switchyard.component.bean", activationTypes = "bean") +public class BeanComponentProvider extends BaseComponentProvider { + + @Override + public ComponentConfigurationView createConfigurationView() { + return new BaseComponentConfigurationView() { + @Override + protected String getComponentName() { + return "Bean"; + } + }; + } + +} diff --git a/console/component/bpel/pom.xml b/console/component/bpel/pom.xml new file mode 100644 index 000000000..aadd64391 --- /dev/null +++ b/console/component/bpel/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-bpel + SwitchYard: BPEL Component Console Extension + Provides customized UI for the SwitchYard BPEL component. + + + org.switchyard.console + switchyard-console-component-core + provided + + + diff --git a/console/component/bpel/src/main/java/org/switchyard/console/component/bpel/ComponentExtension.gwt.xml b/console/component/bpel/src/main/java/org/switchyard/console/component/bpel/ComponentExtension.gwt.xml new file mode 100644 index 000000000..6285cf25d --- /dev/null +++ b/console/component/bpel/src/main/java/org/switchyard/console/component/bpel/ComponentExtension.gwt.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/console/component/bpel/src/main/java/org/switchyard/console/component/bpel/client/BPELComponentProvider.java b/console/component/bpel/src/main/java/org/switchyard/console/component/bpel/client/BPELComponentProvider.java new file mode 100644 index 000000000..4e7cdf562 --- /dev/null +++ b/console/component/bpel/src/main/java/org/switchyard/console/component/bpel/client/BPELComponentProvider.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.bpel.client; + +import org.switchyard.console.components.client.extension.BaseComponentProvider; +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +/** + * BPELComponentProvider + * + * ComponentProvider for the BPEL component. + * + * @author Rob Cernich + */ +@ComponentExtension(displayName = "BPEL", componentName = "org.switchyard.component.bpel", activationTypes = "bpel") +public class BPELComponentProvider extends BaseComponentProvider { + + @Override + public ComponentConfigurationView createConfigurationView() { + return new BaseComponentConfigurationView() { + @Override + protected String getComponentName() { + return "BPEL"; + } + }; + } + +} diff --git a/console/component/bpm/pom.xml b/console/component/bpm/pom.xml new file mode 100644 index 000000000..02a0b75f5 --- /dev/null +++ b/console/component/bpm/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-bpm + SwitchYard: BPM Component Console Extension + Provides customized UI for the SwitchYard BPM component. + + + org.switchyard.console + switchyard-console-component-core + provided + + + diff --git a/console/component/bpm/src/main/java/org/switchyard/console/component/bpm/ComponentExtension.gwt.xml b/console/component/bpm/src/main/java/org/switchyard/console/component/bpm/ComponentExtension.gwt.xml new file mode 100644 index 000000000..6285cf25d --- /dev/null +++ b/console/component/bpm/src/main/java/org/switchyard/console/component/bpm/ComponentExtension.gwt.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/console/component/bpm/src/main/java/org/switchyard/console/component/bpm/client/BPMComponentProvider.java b/console/component/bpm/src/main/java/org/switchyard/console/component/bpm/client/BPMComponentProvider.java new file mode 100644 index 000000000..a1a3e7c8e --- /dev/null +++ b/console/component/bpm/src/main/java/org/switchyard/console/component/bpm/client/BPMComponentProvider.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.bpm.client; + +import org.switchyard.console.components.client.extension.BaseComponentProvider; +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +/** + * BPMComponentProvider + * + * ComponentProvider for the BPM component. + * + * @author Rob Cernich + */ +@ComponentExtension(displayName = "BPM", componentName = "org.switchyard.component.bpm", activationTypes = "bpm") +public class BPMComponentProvider extends BaseComponentProvider { + + @Override + public ComponentConfigurationView createConfigurationView() { + return new BaseComponentConfigurationView() { + @Override + protected String getComponentName() { + return "BPM"; + } + }; + } + +} diff --git a/console/component/camel/pom.xml b/console/component/camel/pom.xml new file mode 100644 index 000000000..5d5812dbf --- /dev/null +++ b/console/component/camel/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-camel + SwitchYard: Camel Component Console Extension + Provides customized UI for the SwitchYard Camel component. + + + org.switchyard.console + switchyard-console-component-core + provided + + + diff --git a/console/component/camel/src/main/java/org/switchyard/console/component/camel/ComponentExtension.gwt.xml b/console/component/camel/src/main/java/org/switchyard/console/component/camel/ComponentExtension.gwt.xml new file mode 100644 index 000000000..6285cf25d --- /dev/null +++ b/console/component/camel/src/main/java/org/switchyard/console/component/camel/ComponentExtension.gwt.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/console/component/camel/src/main/java/org/switchyard/console/component/camel/client/CamelComponentProvider.java b/console/component/camel/src/main/java/org/switchyard/console/component/camel/client/CamelComponentProvider.java new file mode 100644 index 000000000..5114413cf --- /dev/null +++ b/console/component/camel/src/main/java/org/switchyard/console/component/camel/client/CamelComponentProvider.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.camel.client; + +import org.switchyard.console.components.client.extension.BaseComponentProvider; +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +/** + * CamelComponentProvider + * + * ComponentProvider for the Camel component. + * + * @author Rob Cernich + */ +@ComponentExtension(displayName = "Camel", componentName = "org.switchyard.component.camel", activationTypes = { "camel", "direct", + "file" }) +public class CamelComponentProvider extends BaseComponentProvider { + + @Override + public ComponentConfigurationView createConfigurationView() { + return new BaseComponentConfigurationView() { + @Override + protected String getComponentName() { + return "Camel"; + } + }; + } + +} diff --git a/console/component/clojure/pom.xml b/console/component/clojure/pom.xml new file mode 100644 index 000000000..87f267cf1 --- /dev/null +++ b/console/component/clojure/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-clojure + SwitchYard: Clojure Component Console Extension + Provides customized UI for the SwitchYard Clojure component. + + + org.switchyard.console + switchyard-console-component-core + provided + + + diff --git a/console/component/clojure/src/main/java/org/switchyard/console/component/clojure/ComponentExtension.gwt.xml b/console/component/clojure/src/main/java/org/switchyard/console/component/clojure/ComponentExtension.gwt.xml new file mode 100644 index 000000000..6285cf25d --- /dev/null +++ b/console/component/clojure/src/main/java/org/switchyard/console/component/clojure/ComponentExtension.gwt.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/console/component/clojure/src/main/java/org/switchyard/console/component/clojure/client/ClojureComponentProvider.java b/console/component/clojure/src/main/java/org/switchyard/console/component/clojure/client/ClojureComponentProvider.java new file mode 100644 index 000000000..fc795deba --- /dev/null +++ b/console/component/clojure/src/main/java/org/switchyard/console/component/clojure/client/ClojureComponentProvider.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.clojure.client; + +import org.switchyard.console.components.client.extension.BaseComponentProvider; +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +/** + * ClojureComponentProvider + * + * ComponentProvider for the Clojure component. + * + * @author Rob Cernich + */ +@ComponentExtension(displayName = "Clojure", componentName = "ClojureComponent", activationTypes = "clojure") +public class ClojureComponentProvider extends BaseComponentProvider { + + @Override + public ComponentConfigurationView createConfigurationView() { + return new BaseComponentConfigurationView() { + @Override + protected String getComponentName() { + return "Clojure"; + } + }; + } + +} diff --git a/console/component/core/pom.xml b/console/component/core/pom.xml new file mode 100644 index 000000000..9a61617c6 --- /dev/null +++ b/console/component/core/pom.xml @@ -0,0 +1,52 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-core + SwitchYard: Console Core Component Module + Provides API for component specific extensions to the SwitchYard console. + + + com.google.gwt + gwt-dev + provided + + + + + + + org.codehaus.mojo + gwt-maven-plugin + + + + i18n + + + + + org.switchyard.console.components.client.ui.Messages + + + + + diff --git a/console/component/core/src/main/java/org/switchyard/console/components/ComponentExtensionAPI.gwt.xml b/console/component/core/src/main/java/org/switchyard/console/components/ComponentExtensionAPI.gwt.xml new file mode 100644 index 000000000..1a38114f4 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/ComponentExtensionAPI.gwt.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/extension/BaseComponentProvider.java b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/BaseComponentProvider.java new file mode 100644 index 000000000..234e36640 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/BaseComponentProvider.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.extension; + +import org.switchyard.console.components.client.ui.BaseComponentConfigurationPresenter; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +import com.google.web.bindery.event.shared.EventBus; + +/** + * BaseComponentProvider + * + * A base implementation which ComponentExtension implementers may extend. + * + * @author Rob Cernich + */ +public class BaseComponentProvider implements DefaultComponentProvider { + + /** + * Create a new BaseComponentProvider. + */ + public BaseComponentProvider() { + } + + @Override + public ComponentConfigurationPresenter createConfigurationPresenter(EventBus eventBus, + ComponentConfigurationView view) { + return new BaseComponentConfigurationPresenter(eventBus, view); + } + + @Override + public ComponentConfigurationView createConfigurationView() { + return new BaseComponentConfigurationView(); + } + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentExtension.java b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentExtension.java new file mode 100644 index 000000000..f7bc8aaa1 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentExtension.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.extension; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * ComponentExtension + * + * Marks a class which provides support for a specific SwitchYard component. The + * class will provide a configuration view for the component, plus service + * implementation and binding views where applicable. + * + * @author Rob Cernich + */ +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface ComponentExtension { + + /** + * The name of the component to which this extension applies. + */ + String componentName(); + + /** + * The activation types to which this extension applies. + */ + String[] activationTypes(); + + /** + * The name to display for this component. + */ + String displayName(); + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentProvider.java b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentProvider.java new file mode 100644 index 000000000..856378225 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentProvider.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.extension; + +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +import com.google.web.bindery.event.shared.EventBus; + +/** + * ComponentProvider + * + * Interface to be implemented by ComponentProvider extensions. Extenders should + * consider using {@link BaseComponentProvider}. + * + * @author Rob Cernich + */ +public interface ComponentProvider { + + /** + * Creates a new presenter for handling {@link Component} system + * configuration. + * + * @param eventBus the EventBus. + * @param view the corresponding view. + * + * @return a new presenter. + */ + public ComponentConfigurationPresenter createConfigurationPresenter(EventBus eventBus, + ComponentConfigurationView view); + + /** + * Creates a new view for handling {@link Component} system configuration. + * + * @return a new view. + */ + public ComponentConfigurationView createConfigurationView(); + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentProviders.java b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentProviders.java new file mode 100644 index 000000000..a50df9720 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/ComponentProviders.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.extension; + +import java.util.Map; + +import org.switchyard.console.components.client.internal.ComponentExtensionManager; + +import com.google.inject.Inject; + +/** + * ComponentProviders + * + * A wrapper which provides access to ComponentProvider implementations + * contributed using the ComponentExtension annotation, as well as default + * provider for use when a specified provider is not available. + * + * @author Rob Cernich + */ +public class ComponentProviders implements ComponentExtensionManager { + + private final ComponentProvider _defaultProvider; + private final ComponentExtensionManager _extensionManager; + + /** + * Create a new ComponentProviders. + * + * @param defaultProvider the default ComponentProvider. + * @param extensionManager the ComponentExtensionManager. + */ + @Inject + public ComponentProviders(DefaultComponentProvider defaultProvider, ComponentExtensionManager extensionManager) { + _defaultProvider = defaultProvider; + _extensionManager = extensionManager; + } + + @Override + public Map getExtensionProviders() { + return _extensionManager.getExtensionProviders(); + } + + @Override + public ComponentProviderProxy getExtensionProviderByTypeName(String typeName) { + return _extensionManager.getExtensionProviderByTypeName(typeName); + } + + @Override + public ComponentProviderProxy getExtensionProviderByComponentName(String componentName) { + return _extensionManager.getExtensionProviderByComponentName(componentName); + } + + /** + * @return the default ComponentProvider. + */ + public ComponentProvider getDefaultProvider() { + return _defaultProvider; + } +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/extension/DefaultComponentProvider.java b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/DefaultComponentProvider.java new file mode 100644 index 000000000..1b8e4a1a7 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/DefaultComponentProvider.java @@ -0,0 +1,24 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.extension; + +/** + * DefaultComponentProvider + * + * A simple marker which can be used for injecting a default ComponentProvider. + * + * @author Rob Cernich + */ +public interface DefaultComponentProvider extends ComponentProvider { +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/extension/DefaultComponentProviderImpl.java b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/DefaultComponentProviderImpl.java new file mode 100644 index 000000000..01ecc7e0c --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/extension/DefaultComponentProviderImpl.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.extension; + +/** + * DefaultComponentProviderImpl + * + * A default implementation for a default ComponentProvider. + * + * @author Rob Cernich + */ +public class DefaultComponentProviderImpl extends BaseComponentProvider implements DefaultComponentProvider { + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/internal/ComponentExtensionManager.java b/console/component/core/src/main/java/org/switchyard/console/components/client/internal/ComponentExtensionManager.java new file mode 100644 index 000000000..604d52145 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/internal/ComponentExtensionManager.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.internal; + +import java.util.Map; + +import org.switchyard.console.components.client.extension.ComponentProvider; + +/** + * ComponentExtensionManager + * + * Provides an object for retrieving ComponentProvider implementations within + * the console application. + * + * @see ComponentExtension. + * + * @author Rob Cernich + */ +public interface ComponentExtensionManager { + + /** + * ComponentProviderProxy + * + * A proxy to the underlying ComponentProvider. The proxy also provides + * runtime access to the information specified within the annotation (e.g. + * displayName). + * + * @see ComponentExtension. + * + * @author Rob Cernich + */ + public interface ComponentProviderProxy extends ComponentProvider { + /** + * @return the displayName as specified in the annotation. + */ + public String getDisplayName(); + } + + /** + * @return all registered component providers. + */ + public Map getExtensionProviders(); + + /** + * @param typeName the activation type. + * + * @return the component provider; null if no provider is registered for + * this type. + */ + public ComponentProviderProxy getExtensionProviderByTypeName(String typeName); + + /** + * @param componentName the name of the SwitchYard component. + * + * @return the component provider; null if no provider is registered for the + * component. + */ + public ComponentProviderProxy getExtensionProviderByComponentName(String componentName); + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/internal/ComponentProviderProxyImpl.java b/console/component/core/src/main/java/org/switchyard/console/components/client/internal/ComponentProviderProxyImpl.java new file mode 100644 index 000000000..ae4e6dd8f --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/internal/ComponentProviderProxyImpl.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.internal; + +import org.switchyard.console.components.client.extension.ComponentProvider; +import org.switchyard.console.components.client.internal.ComponentExtensionManager.ComponentProviderProxy; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +import com.google.web.bindery.event.shared.EventBus; + +/** + * ComponentProviderProxyImpl + * + * Wraps a ComponentProvider annotated with a ComponentExtension. + * + * @see ComponentExtension + * @see ComponentExtensionManager + * + * @author Rob Cernich + */ +public abstract class ComponentProviderProxyImpl implements ComponentProviderProxy { + + private String _displayName; + private ComponentProvider _delegate; + + /** + * Create a new ComponentProviderProxyImpl. + * + * @param displayName the displayName specified in the annotation. + */ + protected ComponentProviderProxyImpl(String displayName) { + _displayName = displayName; + } + + /** + * @return the displayName specified on the annotated ComponentProvider. + */ + public String getDisplayName() { + return _displayName; + } + + @Override + public ComponentConfigurationPresenter createConfigurationPresenter(EventBus eventBus, + ComponentConfigurationView view) { + return getDelegate().createConfigurationPresenter(eventBus, view); + } + + @Override + public ComponentConfigurationView createConfigurationView() { + return getDelegate().createConfigurationView(); + } + + /** + * @return a new ComponentProvider. + */ + protected abstract ComponentProvider instantiate(); + + private ComponentProvider getDelegate() { + if (_delegate == null) { + _delegate = instantiate(); + } + return _delegate; + } +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/model/Component.java b/console/component/core/src/main/java/org/switchyard/console/components/client/model/Component.java new file mode 100644 index 000000000..4c8d51b35 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/model/Component.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.model; + +import java.util.Map; +import java.util.Set; + +/** + * Component + * + * Represents a SwitchYard component. + * + * @author Rob Cernich + */ +public interface Component { + + /** + * @return the name of the SwitchYard component. + */ + public String getName(); + + /** + * @param name the name of the SwitchYard component. + */ + public void setName(String name); + + /** + * @return component activation types, e.g. bean, soap, etc. + */ + public Set getActivationTypes(); + + /** + * @param types component activation types. + */ + public void setActivationTypes(Set types); + + /** + * @return component properties. + */ + public Map getProperties(); + + /** + * @param properties component properties. + */ + public void setProperties(Map properties); + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/ui/BaseComponentConfigurationPresenter.java b/console/component/core/src/main/java/org/switchyard/console/components/client/ui/BaseComponentConfigurationPresenter.java new file mode 100644 index 000000000..6fcc482d9 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/ui/BaseComponentConfigurationPresenter.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.ui; + +import com.google.web.bindery.event.shared.EventBus; + +/** + * BaseComponentConfigurationPresenter + * + * A base implementation for ComponentConfigurationPresenter. + * + * @author Rob Cernich + */ +public class BaseComponentConfigurationPresenter extends ComponentConfigurationPresenter { + + /** + * Create a new BaseComponentConfigurationPresenter. + * + * @param eventBus the EventBus. + * @param view the view. + */ + public BaseComponentConfigurationPresenter(EventBus eventBus, ComponentConfigurationView view) { + super(eventBus, view); + } + + @Override + protected void onBind() { + super.onBind(); + getView().setPresenter(this); + } + + @Override + protected void onUnbind() { + getView().setPresenter(null); + super.onUnbind(); + } + + @Override + protected void onReset() { + super.onReset(); + // nothing to do + } + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/ui/BaseComponentConfigurationView.java b/console/component/core/src/main/java/org/switchyard/console/components/client/ui/BaseComponentConfigurationView.java new file mode 100644 index 000000000..03696fb9e --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/ui/BaseComponentConfigurationView.java @@ -0,0 +1,203 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.ui; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map.Entry; + +import org.jboss.ballroom.client.widgets.ContentGroupLabel; +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.components.client.model.Component; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +import com.google.gwt.core.client.GWT; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.user.client.ui.Label; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.ListDataProvider; +import com.gwtplatform.mvp.client.ViewImpl; + +/** + * BaseComponentConfigurationView + * + * Base implementation for ComponentConfigurationView. This implementation + * provides controls for displaying: name, activation types and a table for + * properties. + * + * Extenders may override {@link #createComponentDetailsWidget()} and + * {@link #updateComponentDetails()} to provide customized controls for + * editing/viewing the component's configuration. + * + * @author Rob Cernich + */ +public class BaseComponentConfigurationView extends ViewImpl implements ComponentConfigurationView { + + private static final Messages MESSAGES = GWT.create(Messages.class); + + private Label _componentNameLabel; + private Widget _widget; + private ComponentConfigurationPresenter _presenter; + private Component _component; + private ListDataProvider> _propertiesData; + + @Override + public Widget asWidget() { + if (_widget == null) { + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + + _componentNameLabel = createComponentNameLabel(); + if (_componentNameLabel != null) { + layout.add(_componentNameLabel); + } + + Widget details = createComponentDetailsWidget(); + if (details != null) { + layout.add(details); + } + + _widget = layout; + } + return _widget; + } + + @Override + public void setPresenter(ComponentConfigurationPresenter presenter) { + _presenter = presenter; + } + + @Override + public void setComponent(Component component) { + _component = component; + updateControls(); + } + + /** + * @return the presenter managing the view. + */ + protected ComponentConfigurationPresenter getPresenter() { + return _presenter; + } + + /** + * @return the component being edited/viewed. + */ + protected Component getComponent() { + return _component; + } + + /** + * @return a control for viewing the component's name. + */ + protected Label createComponentNameLabel() { + return new ContentGroupLabel(""); //$NON-NLS-1$ + } + + /** + * @return a control for viewing the component's activation types. + */ + protected Label createComponentTypeLabel() { + return new ContentGroupLabel(""); //$NON-NLS-1$ + } + + /** + * @return a control for viewing configuration details. + */ + @SuppressWarnings("unchecked") + protected Widget createComponentDetailsWidget() { + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + layout.add(new ContentGroupLabel(MESSAGES.label_configuredProperties())); + + DefaultCellTable> table = new DefaultCellTable>(5); + TextColumn> nameColumn = new TextColumn>() { + @Override + public String getValue(Entry object) { + return object.getKey(); + } + }; + nameColumn.setSortable(true); + + TextColumn> valueColumn = new TextColumn>() { + @Override + public String getValue(Entry object) { + return object.getValue(); + } + }; + + table.addColumn(nameColumn, MESSAGES.label_name()); + table.addColumn(valueColumn, MESSAGES.label_value()); + + layout.add(table); + + _propertiesData = new ListDataProvider>(); + _propertiesData.addDataDisplay(table); + + return layout; + } + + /** + * Update controls after the component has been changed/modified. + */ + protected void updateControls() { + updateComponentName(); + updateComponentDetails(); + } + + /** + * Update the name controls. + */ + protected void updateComponentName() { + if (_componentNameLabel == null) { + return; + } + _componentNameLabel.setText(getComponentNameLabelText()); + } + + /** + * Update the component details controls. + */ + protected void updateComponentDetails() { + Component component = getComponent(); + List> properties; + if (component == null || component.getProperties() == null) { + properties = Collections.emptyList(); + } else { + properties = new ArrayList>(component.getProperties().entrySet()); + } + _propertiesData.setList(properties); + } + + /** + * @return the component name to be displayed in the name controls; default + * is {@link Component#getName()}. + */ + protected String getComponentName() { + String name; + if (getComponent() == null) { + name = null; + } else { + name = getComponent().getName(); + } + return name; + } + + private String getComponentNameLabelText() { + return MESSAGES.label_nameInstance(getComponentName()); + } + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/ui/ComponentConfigurationPresenter.java b/console/component/core/src/main/java/org/switchyard/console/components/client/ui/ComponentConfigurationPresenter.java new file mode 100644 index 000000000..0ef15cfe7 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/ui/ComponentConfigurationPresenter.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.client.ui; + +import org.switchyard.console.components.client.model.Component; + +import com.google.web.bindery.event.shared.EventBus; +import com.gwtplatform.mvp.client.PresenterWidget; +import com.gwtplatform.mvp.client.View; + +/** + * ComponentConfigurationPresenter + * + * This class defines the API for the component presenter in the core console + * UI. Component extensions must extend this class for their presenter logic. + * + * @author Rob Cernich + */ +public abstract class ComponentConfigurationPresenter extends + PresenterWidget { + + /** + * ComponentConfigurationView + * + * This class defines the view API for the component view in the core + * console UI. Component extensions must extend this class for their view + * logic. + * + * @author Rob Cernich + */ + public interface ComponentConfigurationView extends View { + + /** + * @param presenter the presenter managing the view. + */ + public void setPresenter(ComponentConfigurationPresenter presenter); + + /** + * @param component the component being edited/viewed. + */ + public void setComponent(Component component); + } + + /** + * Create a new ComponentConfigurationPresenter. + * + * @param eventBus the EventBus. + * @param view the view. + */ + protected ComponentConfigurationPresenter(final EventBus eventBus, final ComponentConfigurationView view) { + super(false, eventBus, view); + } + + /** + * @param component the component being edited/viewed + */ + public void setComponent(Component component) { + getView().setComponent(component); + } + +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/client/ui/Messages.properties b/console/component/core/src/main/java/org/switchyard/console/components/client/ui/Messages.properties new file mode 100644 index 000000000..13898eda2 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/client/ui/Messages.properties @@ -0,0 +1,4 @@ +label_configuredProperties=Configured Properties +label_name=Name +label_nameInstance=Name: {0} +label_value=Value diff --git a/console/component/core/src/main/java/org/switchyard/console/components/rebind/ComponentExtensionManagerGenerator.java b/console/component/core/src/main/java/org/switchyard/console/components/rebind/ComponentExtensionManagerGenerator.java new file mode 100644 index 000000000..4386774c9 --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/rebind/ComponentExtensionManagerGenerator.java @@ -0,0 +1,180 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.rebind; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.extension.ComponentProvider; +import org.switchyard.console.components.client.internal.ComponentExtensionManager; +import org.switchyard.console.components.client.internal.ComponentProviderProxyImpl; + +import com.google.gwt.core.client.GWT; +import com.google.gwt.core.ext.Generator; +import com.google.gwt.core.ext.GeneratorContext; +import com.google.gwt.core.ext.TreeLogger; +import com.google.gwt.core.ext.UnableToCompleteException; +import com.google.gwt.core.ext.typeinfo.JClassType; +import com.google.gwt.core.ext.typeinfo.TypeOracle; +import com.google.gwt.user.rebind.ClassSourceFileComposerFactory; +import com.google.gwt.user.rebind.SourceWriter; +import com.google.inject.Inject; + +/** + * ComponentExtensionManagerGenerator + * + * GWT code generator for ComponentExtensionManager. A code generator is used + * because reflection cannot be used on the client side. This generator scans + * for classes annotated with ComponentExtension and adds them to the manager. + * + * @author Rob Cernich + */ +public class ComponentExtensionManagerGenerator extends Generator { + + @Override + public String generate(TreeLogger logger, GeneratorContext context, String typeName) + throws UnableToCompleteException { + TypeOracle typeOracle = context.getTypeOracle(); + JClassType componentExtensionManager = typeOracle.findType(typeName); + if (componentExtensionManager == null) { + logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null); + throw new UnableToCompleteException(); + } + if (componentExtensionManager.isInterface() == null) { + logger.log(TreeLogger.ERROR, componentExtensionManager.getQualifiedSourceName() + " is not an interface", + null); + throw new UnableToCompleteException(); + } + + JClassType componentProvider = typeOracle.findType(ComponentProvider.class.getCanonicalName()); + if (componentProvider == null) { + logger.log(TreeLogger.ERROR, "Unable to find metadata for type 'ComponentProvider'", null); + throw new UnableToCompleteException(); + } + + List componentExtensionClasses = new ArrayList(); + for (JClassType type : typeOracle.getTypes()) { + if (type.isAnnotationPresent(ComponentExtension.class)) { + if (type.isClass() == null || type.isAbstract()) { + // type must be a class that can be instantiated + logger.log(TreeLogger.ERROR, "ComponentExtension type '" + type.getQualifiedSourceName() + + "' cannot be instantiated.", null); + throw new UnableToCompleteException(); + } else if (!type.isDefaultInstantiable()) { + // type must have default constructor + logger.log(TreeLogger.ERROR, "ComponentExtension type '" + type.getQualifiedSourceName() + + "' does not provide a default constructor.", null); + throw new UnableToCompleteException(); + } else if (!type.isAssignableTo(componentProvider)) { + // type must implement ComponentProvider + logger.log(TreeLogger.ERROR, "ComponentExtension type '" + type.getQualifiedSourceName() + + "' does not implement ComponentProvider.", null); + throw new UnableToCompleteException(); + } + componentExtensionClasses.add(type); + } + } + + String packageName = componentExtensionManager.getPackage().getName(); + String className = componentExtensionManager.getSimpleSourceName() + "Impl"; + + generateClass(logger, context, packageName, className, componentExtensionClasses); + + return packageName + "." + className; + } + + private void generateClass(TreeLogger logger, GeneratorContext context, String packageName, String className, + List componentExtensionClasses) { + PrintWriter pw = context.tryCreate(logger, packageName, className); + if (pw == null) { + return; + } + + ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName, className); + + // imports + composerFactory.addImport(HashMap.class.getCanonicalName()); + composerFactory.addImport(Map.class.getCanonicalName()); + composerFactory.addImport(ComponentProvider.class.getCanonicalName()); + composerFactory.addImport(ComponentExtensionManager.class.getCanonicalName()); + composerFactory.addImport(ComponentProviderProxyImpl.class.getCanonicalName()); + composerFactory.addImport(GWT.class.getCanonicalName()); + composerFactory.addImport(Inject.class.getCanonicalName()); + + // interface + composerFactory.addImplementedInterface(ComponentExtensionManager.class.getCanonicalName()); + + SourceWriter sw = composerFactory.createSourceWriter(context, pw); + + // fields + sw.println("private Map _providers = new HashMap();"); + sw.println("private Map _typeToName = new HashMap();"); + + // constructor + sw.println("public " + className + "() {"); + sw.indent(); + for (JClassType extensionClass : componentExtensionClasses) { + ComponentExtension extensionAnnotation = extensionClass.getAnnotation(ComponentExtension.class); + sw.println("_providers.put(\"" + extensionAnnotation.componentName() + + "\", new ComponentProviderProxyImpl(\"" + extensionAnnotation.displayName() + "\") {"); + sw.indent(); + sw.println("public ComponentProvider instantiate() {"); + sw.indentln("return GWT.create(" + extensionClass.getQualifiedSourceName() + ".class);"); + sw.println("}"); + sw.outdent(); + sw.println("});"); + for (String type : extensionAnnotation.activationTypes()) { + sw.println("_typeToName.put(\"" + type + "\", \"" + extensionAnnotation.componentName() + "\");"); + } + } + sw.outdent(); + sw.println("}"); + + // methods + // getExtensionProviders + sw.println("public Map getExtensionProviders() {"); + sw.indentln("return _providers;"); + sw.println("}"); + + // getExtensionProviderByComponentName + sw.println("public ComponentProviderProxy getExtensionProviderByComponentName(String componentName) {"); + sw.indent(); + sw.println("if (_providers.containsKey(componentName)) {"); + sw.indentln("return _providers.get(componentName);"); + sw.println("}"); + sw.println("return null;"); + sw.outdent(); + sw.println("}"); + + // getExtensionProviderByTypeName + sw.println("public ComponentProviderProxy getExtensionProviderByTypeName(String typeName) {"); + sw.indent(); + sw.println("if (_typeToName.containsKey(typeName)) {"); + sw.indentln("return getExtensionProviderByComponentName(_typeToName.get(typeName));"); + sw.println("}"); + sw.println("return null;"); + sw.outdent(); + sw.println("}"); + + // close it out + sw.outdent(); + sw.println("}"); + + context.commit(logger, pw); + } +} diff --git a/console/component/core/src/main/java/org/switchyard/console/components/rebind/ComponentExtensionManagerImpl.java b/console/component/core/src/main/java/org/switchyard/console/components/rebind/ComponentExtensionManagerImpl.java new file mode 100644 index 000000000..96066303d --- /dev/null +++ b/console/component/core/src/main/java/org/switchyard/console/components/rebind/ComponentExtensionManagerImpl.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.components.rebind; + +import java.util.HashMap; +import java.util.Map; + +import org.switchyard.console.components.client.extension.ComponentProvider; +import org.switchyard.console.components.client.internal.ComponentExtensionManager; +import org.switchyard.console.components.client.internal.ComponentProviderProxyImpl; + +import com.google.gwt.core.client.GWT; + +/** + * ComponentExtensionManagerImpl + * + * This is a template ComponentExtensionManager implementation used to help code + * the generator. + * + * @author Rob Cernich + */ +public class ComponentExtensionManagerImpl implements ComponentExtensionManager { + + private Map _providers = new HashMap(); + private Map _typeToName = new HashMap(); + + /** + * Create a new ComponentExtensionManagerImpl. + */ + public ComponentExtensionManagerImpl() { + final Class componentProvider = null; + _providers.put("componentName", new ComponentProviderProxyImpl("displayName") { + public ComponentProvider instantiate() { + return GWT.create(componentProvider); + } + }); + _typeToName.put("typeName", "componentName"); + } + + @Override + public Map getExtensionProviders() { + return _providers; + } + + @Override + public ComponentProviderProxy getExtensionProviderByComponentName(String componentName) { + if (_providers.containsKey(componentName)) { + return _providers.get(componentName); + } + return null; + } + + @Override + public ComponentProviderProxy getExtensionProviderByTypeName(String typeName) { + if (_typeToName.containsKey(typeName)) { + return getExtensionProviderByComponentName(_typeToName.get(typeName)); + } + return null; + } + +} diff --git a/console/component/hornetq/pom.xml b/console/component/hornetq/pom.xml new file mode 100644 index 000000000..380f7cbfa --- /dev/null +++ b/console/component/hornetq/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-hornetq + SwitchYard: HornetQ Component Console Extension + Provides customized UI for the SwitchYard HornetQ component. + + + org.switchyard.console + switchyard-console-component-core + provided + + + diff --git a/console/component/hornetq/src/main/java/org/switchyard/console/component/hornetq/ComponentExtension.gwt.xml b/console/component/hornetq/src/main/java/org/switchyard/console/component/hornetq/ComponentExtension.gwt.xml new file mode 100644 index 000000000..6285cf25d --- /dev/null +++ b/console/component/hornetq/src/main/java/org/switchyard/console/component/hornetq/ComponentExtension.gwt.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/console/component/hornetq/src/main/java/org/switchyard/console/component/hornetq/client/HornetQComponentProvider.java b/console/component/hornetq/src/main/java/org/switchyard/console/component/hornetq/client/HornetQComponentProvider.java new file mode 100644 index 000000000..3493a69e6 --- /dev/null +++ b/console/component/hornetq/src/main/java/org/switchyard/console/component/hornetq/client/HornetQComponentProvider.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.hornetq.client; + +import org.switchyard.console.components.client.extension.BaseComponentProvider; +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +/** + * HornetQComponentProvider + * + * ComponentProvider for the HornetQ component. + * + * @author Rob Cernich + */ +@ComponentExtension(displayName = "HornetQ", componentName = "org.switchyard.component.hornetq", activationTypes = "hornetq") +public class HornetQComponentProvider extends BaseComponentProvider { + + @Override + public ComponentConfigurationView createConfigurationView() { + return new BaseComponentConfigurationView() { + @Override + protected String getComponentName() { + return "HornetQ"; + } + }; + } + +} diff --git a/console/component/pom.xml b/console/component/pom.xml new file mode 100644 index 000000000..9b3dacef8 --- /dev/null +++ b/console/component/pom.xml @@ -0,0 +1,90 @@ + + + + 4.0.0 + + switchyard-console-parent + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-components + pom + SwitchYard: Console System Components + Base pom for console system component UI contributions. + + core + bean + bpel + bpm + camel + clojure + hornetq + rules + soap + + + + org.jboss.ballroom + widgets + + + com.google.gwt + gwt-user + + + com.gwtplatform + gwtp-mvp-client + + + com.google.inject + guice + + + com.google.gwt.inject + gin + + + junit + junit + test + + + com.google.gwt + gwt-dev + jar + test + + + + + + org.codehaus.mojo + gwt-maven-plugin + + + + resources + + + + + TRACE + -Xmx512m + + + + + diff --git a/console/component/rules/pom.xml b/console/component/rules/pom.xml new file mode 100644 index 000000000..8d6bbebd3 --- /dev/null +++ b/console/component/rules/pom.xml @@ -0,0 +1,33 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-rules + SwitchYard: Rules Component Console Extension + Provides customized UI for the SwitchYard Rules component. + + + org.switchyard.console + switchyard-console-component-core + provided + + + diff --git a/console/component/rules/src/main/java/org/switchyard/console/component/rules/ComponentExtension.gwt.xml b/console/component/rules/src/main/java/org/switchyard/console/component/rules/ComponentExtension.gwt.xml new file mode 100644 index 000000000..6285cf25d --- /dev/null +++ b/console/component/rules/src/main/java/org/switchyard/console/component/rules/ComponentExtension.gwt.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/console/component/rules/src/main/java/org/switchyard/console/component/rules/client/RulesComponentProvider.java b/console/component/rules/src/main/java/org/switchyard/console/component/rules/client/RulesComponentProvider.java new file mode 100644 index 000000000..7b4e79461 --- /dev/null +++ b/console/component/rules/src/main/java/org/switchyard/console/component/rules/client/RulesComponentProvider.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.rules.client; + +import org.switchyard.console.components.client.extension.BaseComponentProvider; +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +/** + * RulesComponentProvider + * + * ComponentProvider for the Rules component. + * + * @author Rob Cernich + */ +@ComponentExtension(displayName = "Rules", componentName = "org.switchyard.component.rules", activationTypes = "rules") +public class RulesComponentProvider extends BaseComponentProvider { + + @Override + public ComponentConfigurationView createConfigurationView() { + return new BaseComponentConfigurationView() { + @Override + protected String getComponentName() { + return "Rules"; + } + }; + } + +} diff --git a/console/component/soap/pom.xml b/console/component/soap/pom.xml new file mode 100644 index 000000000..848df1689 --- /dev/null +++ b/console/component/soap/pom.xml @@ -0,0 +1,52 @@ + + + + 4.0.0 + + switchyard-console-components + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-console-component-soap + SwitchYard: SOAP Component Console Extension + Provides customized UI for the SwitchYard SOAP component. + + + org.switchyard.console + switchyard-console-component-core + provided + + + + + + + org.codehaus.mojo + gwt-maven-plugin + + + + i18n + + + + + org.switchyard.console.component.soap.client.Messages + + + + + diff --git a/console/component/soap/src/main/java/org/switchyard/console/component/soap/ComponentExtension.gwt.xml b/console/component/soap/src/main/java/org/switchyard/console/component/soap/ComponentExtension.gwt.xml new file mode 100644 index 000000000..6285cf25d --- /dev/null +++ b/console/component/soap/src/main/java/org/switchyard/console/component/soap/ComponentExtension.gwt.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/Messages.properties b/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/Messages.properties new file mode 100644 index 000000000..acbc2d0e0 --- /dev/null +++ b/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/Messages.properties @@ -0,0 +1,3 @@ +constant_notSet= +label_configuredProperties=Configured Properties +label_socketAddress=Socket Address ({0}) diff --git a/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/SOAPComponentConfigurationView.java b/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/SOAPComponentConfigurationView.java new file mode 100644 index 000000000..a51442849 --- /dev/null +++ b/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/SOAPComponentConfigurationView.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.soap.client; + +import java.util.Collections; + +import org.jboss.ballroom.client.widgets.ContentGroupLabel; +import org.jboss.ballroom.client.widgets.forms.DefaultGroupRenderer; +import org.jboss.ballroom.client.widgets.forms.FormItem; +import org.jboss.ballroom.client.widgets.forms.RenderMetaData; +import org.jboss.ballroom.client.widgets.forms.TextItem; +import org.switchyard.console.components.client.ui.BaseComponentConfigurationView; + +import com.google.gwt.core.client.GWT; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * SOAPComponentConfigurationView + * + * Customized component configuration view for the SOAP component. + * + * @author Rob Cernich + */ +public class SOAPComponentConfigurationView extends BaseComponentConfigurationView { + + private static final Messages MESSAGES = GWT.create(Messages.class); + private static final String SOCKET_ADDR = "socketAddr"; //$NON-NLS-1$ + + private TextItem _socketAddr; + + @SuppressWarnings("rawtypes") + @Override + protected Widget createComponentDetailsWidget() { + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + layout.add(new ContentGroupLabel(MESSAGES.label_configuredProperties())); + + String title = MESSAGES.label_socketAddress(SOCKET_ADDR); + _socketAddr = new TextItem(SOCKET_ADDR, title) { + @Override + public void setValue(String value) { + if (value == null || value.length() == 0) { + value = MESSAGES.constant_notSet(); + } + super.setValue(value); + } + }; + + RenderMetaData metaData = new RenderMetaData(); + metaData.setNumColumns(1); + metaData.setTitleWidth(title.length()); + layout.add(new DefaultGroupRenderer().render(metaData, "null", //$NON-NLS-1$ + Collections. singletonMap(SOCKET_ADDR, _socketAddr))); + + return layout; + } + + @Override + protected void updateComponentDetails() { + if (getComponent() == null || getComponent().getProperties() == null) { + _socketAddr.setValue(null); + } else { + _socketAddr.setValue(getComponent().getProperties().get(SOCKET_ADDR)); + } + } + + @Override + protected String getComponentName() { + return "SOAP"; //$NON-NLS-1$ + } + +} diff --git a/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/SOAPComponentProvider.java b/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/SOAPComponentProvider.java new file mode 100644 index 000000000..b6d385741 --- /dev/null +++ b/console/component/soap/src/main/java/org/switchyard/console/component/soap/client/SOAPComponentProvider.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.component.soap.client; + +import org.switchyard.console.components.client.extension.BaseComponentProvider; +import org.switchyard.console.components.client.extension.ComponentExtension; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +/** + * SOAPComponentProvider + * + * ComponentProvider for the SOAP component. + * + * @author Rob Cernich + */ +@ComponentExtension(displayName = "SOAP", componentName = "org.switchyard.component.soap", activationTypes = "soap") +public class SOAPComponentProvider extends BaseComponentProvider { + + @Override + public ComponentConfigurationView createConfigurationView() { + return new SOAPComponentConfigurationView(); + } + +} diff --git a/console/gwt/.gitignore b/console/gwt/.gitignore new file mode 100644 index 000000000..8d5c92d8a --- /dev/null +++ b/console/gwt/.gitignore @@ -0,0 +1,5 @@ +/target +/.project +/.settings +/.gwt +/.classpath diff --git a/console/gwt/developer.txt b/console/gwt/developer.txt new file mode 100644 index 000000000..ae58ab847 --- /dev/null +++ b/console/gwt/developer.txt @@ -0,0 +1,29 @@ +1. Eclipse configuration + 1. Import using Import... "Existing Maven Projects" + 2. After importing, open project properties. + 1. On the Google->Web Application page: + 1. Ensure "This project has a WAR directory" is checked. + 2. Change the WAR directory to point to + ${project.build.directory}/${project.build.finalName} (e.g. + "target/switchyard-console-gwt-0.1.0-SNAPSHOT"). + 3. Make sure "Launch and deploy from this directory..." is checked. + 2. On the Google->Web Toolkit page: + 1. Ensure "Use Google Web Toolkit" is checked. + 2. Ensure "Use specific SDK" is selected and is pointing to the + maven dependencies (e.g. ~/.m2/repository/com/google/gwt/...). + 3. To run you can do one of the following: + 1. Right-click project and select Run as->Web Application. This will + launch the application from within Eclipse. + 2. Right-click module file (e.g. Application.gwt.xml) and select + Run as->GWT application. This will launch an external GWT console. + +2. Running in Eclipse (using Run as -> Web Application) + 1. In the run configuration, you will need to add the following jars to the + bootstrap entries on the classpath tab: + jboss-logging-.jar + xnio-api-.jar + xnio-nio-.jar + These jars should come from your AS installation. If you are + experiencing other ClassNotFoundExceptions, you will need to add those + jars to the bootstrap entries as well. This is to workaround + classLoader issues in gwt-dev. diff --git a/console/gwt/pom.xml b/console/gwt/pom.xml new file mode 100644 index 000000000..a77a75bfe --- /dev/null +++ b/console/gwt/pom.xml @@ -0,0 +1,156 @@ + + + + + + switchyard-console-parent + org.switchyard.console + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-console-extension + SwitchYard: AS7 Management Console Extension + AS7 management console extension supporting the SwitchYard runtime. + + + org.jboss.as + jboss-as-console-core + + + org.jboss.as + jboss-as-console-dmr + + + org.jboss.as + console-spi + + + org.jboss.ballroom + widgets + + + com.google.gwt + gwt-user + + + com.google.inject + guice + + + com.google.gwt.inject + gin + + + com.gwtplatform + gwtp-mvp-client + + + com.google.code.gwt-log + gwt-log + + + org.switchyard.console + switchyard-console-component-core + + + org.switchyard.console + switchyard-console-component-bean + + + org.switchyard.console + switchyard-console-component-bpel + + + org.switchyard.console + switchyard-console-component-bpm + + + org.switchyard.console + switchyard-console-component-camel + + + org.switchyard.console + switchyard-console-component-clojure + + + org.switchyard.console + switchyard-console-component-hornetq + + + org.switchyard.console + switchyard-console-component-rules + + + org.switchyard.console + switchyard-console-component-soap + + + junit + junit + test + + + com.google.gwt + gwt-dev + provided + + + + + + + org.codehaus.mojo + gwt-maven-plugin + + + + resources + test + + + + + + + FF3,IE7 + org.switchyard.console.client.Messages + TRACE + htmlunit + -Xmx512m + 2 + + + + + maven-surefire-plugin + + + **/GwtTest*.java + + + + + + diff --git a/console/gwt/src/main/java/org/switchyard/console/Extensions.gwt.xml b/console/gwt/src/main/java/org/switchyard/console/Extensions.gwt.xml new file mode 100644 index 000000000..285441280 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/Extensions.gwt.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/console/gwt/src/main/java/org/switchyard/console/SwitchYard.gwt.xml b/console/gwt/src/main/java/org/switchyard/console/SwitchYard.gwt.xml new file mode 100644 index 000000000..eaa4f62bd --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/SwitchYard.gwt.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/console/gwt/src/main/java/org/switchyard/console/client/BeanFactory.java b/console/gwt/src/main/java/org/switchyard/console/client/BeanFactory.java new file mode 100644 index 000000000..59292f09a --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/BeanFactory.java @@ -0,0 +1,112 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client; + +import org.jboss.as.console.spi.BeanFactoryExtension; +import org.switchyard.console.client.model.Application; +import org.switchyard.console.client.model.ArtifactReference; +import org.switchyard.console.client.model.ArtifactReferenceCategory; +import org.switchyard.console.client.model.Binding; +import org.switchyard.console.client.model.ComponentReference; +import org.switchyard.console.client.model.ComponentService; +import org.switchyard.console.client.model.MessageMetrics; +import org.switchyard.console.client.model.QNameCategory; +import org.switchyard.console.client.model.Reference; +import org.switchyard.console.client.model.Service; +import org.switchyard.console.client.model.ServiceMetrics; +import org.switchyard.console.client.model.SystemDetails; +import org.switchyard.console.client.model.Throttling; +import org.switchyard.console.client.model.Transformer; +import org.switchyard.console.components.client.model.Component; + +import com.google.web.bindery.autobean.shared.AutoBean; +import com.google.web.bindery.autobean.shared.AutoBeanFactory; + +/** + * BeanFactory + * + * Factory for SwitchYard specific model beans. + * + * @author Rob Cernich + */ +@BeanFactoryExtension +@AutoBeanFactory.Category({QNameCategory.class, ArtifactReferenceCategory.class}) +public interface BeanFactory extends AutoBeanFactory { + + /** + * @return a new AutoBean + */ + AutoBean systemDetails(); + + /** + * @return a new AutoBean + */ + AutoBean application(); + + /** + * @return a new AutoBean + */ + AutoBean component(); + + /** + * @return a new AutoBean + */ + AutoBean service(); + + /** + * @return a new AutoBean + */ + AutoBean reference(); + + /** + * @return a new AutoBean + */ + AutoBean componentService(); + + /** + * @return a new AutoBean + */ + AutoBean binding(); + + /** + * @return a new AutoBean + */ + AutoBean transformer(); + + /** + * @return a new AutoBean + */ + AutoBean componentReference(); + + /** + * @return a new AutoBean + */ + AutoBean messageMetrics(); + + /** + * @return a new AutoBean + */ + AutoBean serviceMetrics(); + + /** + * @return a new AutoBean + */ + AutoBean artifactReference(); + + /** + * @return a new AutoBean + */ + AutoBean throttling(); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/Messages.java b/console/gwt/src/main/java/org/switchyard/console/client/Messages.java new file mode 100644 index 000000000..8a3115290 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/Messages.java @@ -0,0 +1,1092 @@ +package org.switchyard.console.client; + +/** + * Interface to represent the messages contained in resource bundle: + * 'src/main/java/org/switchyard/console/client/Messages.properties'. + * + * This interface is maintained manually because the i18n goal does not handle + * number formats (parameters are string). Also, GWT does not support integer + * formats. To maintain, run mvn gwt:i18n. This will produce a new Messages + * class in target/generated-sources/gwt. Merge the newly generated file into + * this file. + */ +public interface Messages extends com.google.gwt.i18n.client.Messages { + + /** + * Translated "Details...". + * + * @return translated "Details..." + */ + @DefaultMessage("Details...") + @Key("button_details") + String button_details(); + + /** + * Translated "View Configuration...". + * + * @return translated "View Configuration..." + */ + @DefaultMessage("View Configuration...") + @Key("button_viewConfiguration") + String button_viewConfiguration(); + + /** + * Translated "View Details...". + * + * @return translated "View Details..." + */ + @DefaultMessage("View Details...") + @Key("button_viewDetails") + String button_viewDetails(); + + /** + * Translated "". + * + * @return translated "" + */ + @DefaultMessage("") + @Key("constant_inherited") + String constant_inherited(); + + /** + * Translated "Unknown". + * + * @return translated "Unknown" + */ + @DefaultMessage("Unknown") + @Key("constant_unknown") + String constant_unknown(); + + /** + * Translated "Displays details for a specific application. Select an application to see its implementation details.". + * + * @return translated "Displays details for a specific application. Select an application to see its implementation details." + */ + @DefaultMessage("Displays details for a specific application. Select an application to see its implementation details.") + @Key("description_applicationDetails") + String description_applicationDetails(); + + /** + * Translated "Displays a list of deployed SwitchYard applications. Select an application to see more details.". + * + * @return translated "Displays a list of deployed SwitchYard applications. Select an application to see more details." + */ + @DefaultMessage("Displays a list of deployed SwitchYard applications. Select an application to see more details.") + @Key("description_applications") + String description_applications(); + + /** + * Translated "Displays all artifacts referenced throughout the system, along with the applications referencing a specific artifact.". + * + * @return translated "Displays all artifacts referenced throughout the system, along with the applications referencing a specific artifact." + */ + @DefaultMessage("Displays all artifacts referenced throughout the system, along with the applications referencing a specific artifact.") + @Key("description_artifactReferences") + String description_artifactReferences(); + + /** + * Translated "Displays message metrics for a selected reference.". + * + * @return translated "Displays message metrics for a selected reference." + */ + @DefaultMessage("Displays message metrics for a selected reference.") + @Key("description_referenceMetrics") + String description_referenceMetrics(); + + /** + * Translated "Displays details for the selected service.". + * + * @return translated "Displays details for the selected service." + */ + @DefaultMessage("Displays details for the selected service.") + @Key("description_serviceDetails") + String description_serviceDetails(); + + /** + * Translated "Displays message metrics for a selected service.". + * + * @return translated "Displays message metrics for a selected service." + */ + @DefaultMessage("Displays message metrics for a selected service.") + @Key("description_serviceMetrics") + String description_serviceMetrics(); + + /** + * Translated "Displays a list of deployed SwitchYard references. Select a reference to see more details.". + * + * @return translated "Displays a list of deployed SwitchYard references. Select a reference to see more details." + */ + @DefaultMessage("Displays a list of deployed SwitchYard references. Select a reference to see more details.") + @Key("description_switchYardReferences") + String description_switchYardReferences(); + + /** + * Translated "Displays details about the SwitchYard runtime.". + * + * @return translated "Displays details about the SwitchYard runtime." + */ + @DefaultMessage("Displays details about the SwitchYard runtime.") + @Key("description_switchYardRuntime") + String description_switchYardRuntime(); + + /** + * Translated "Displays a list of deployed SwitchYard services. Select a service to see more details.". + * + * @return translated "Displays a list of deployed SwitchYard services. Select a service to see more details." + */ + @DefaultMessage("Displays a list of deployed SwitchYard services. Select a service to see more details.") + @Key("description_switchYardServices") + String description_switchYardServices(); + + /** + * Translated "Displays message metrics for the SwitchYard subsystem.". + * + * @return translated "Displays message metrics for the SwitchYard subsystem." + */ + @DefaultMessage("Displays message metrics for the SwitchYard subsystem.") + @Key("description_systemMetrics") + String description_systemMetrics(); + + /** + * Translated "Could not load all reference metrics.". + * + * @return translated "Could not load all reference metrics." + */ + @DefaultMessage("Could not load all reference metrics.") + @Key("error_allReferenceMetricsLoad") + String error_allReferenceMetricsLoad(); + + /** + * Translated "Could not load all service metrics.". + * + * @return translated "Could not load all service metrics." + */ + @DefaultMessage("Could not load all service metrics.") + @Key("error_allServiceMetricsLoad") + String error_allServiceMetricsLoad(); + + /** + * Translated "Could not load information for application: {0}". + * @param arg0 application name + * @return translated "Could not load information for application: {0}" + */ + @DefaultMessage("Could not load information for application: {0}") + @Key("error_applicationLoad") + String error_applicationLoad(String arg0); + + /** + * Translated "Could not load artifact references.". + * + * @return translated "Could not load artifact references." + */ + @DefaultMessage("Could not load artifact references.") + @Key("error_artifactsLoad") + String error_artifactsLoad(); + + /** + * Translated "Comparison column specified, but no baseline set!". + * + * @return translated "Comparison column specified, but no baseline set!" + */ + @DefaultMessage("Comparison column specified, but no baseline set!") + @Key("error_comparisonColumnWithoutBaseline") + String error_comparisonColumnWithoutBaseline(); + + /** + * Translated "Could not load information for component: {0}". + * @param arg0 component name + * @return translated "Could not load information for component: {0}" + */ + @DefaultMessage("Could not load information for component: {0}") + @Key("error_componentLoad") + String error_componentLoad(String arg0); + + /** + * Translated "Illegal baseline index {0,number} on number of samples {1,number}.". + * @param arg0 baseline index + * @param arg1 sample index + * @return translated "Illegal baseline index {0,number} on number of samples {1,number}." + */ + @DefaultMessage("Illegal baseline index {0,number} on number of samples {1,number}.") + @Key("error_illegalBaselineIndex") + String error_illegalBaselineIndex(int arg0, int arg1); + + /** + * Translated "Metric value at index {0,number} is null". + * @param arg0 index + * @return translated "Metric value at index {0,number} is null" + */ + @DefaultMessage("Metric value at index {0,number} is null") + @Key("error_metricIsNullAtIndex") + String error_metricIsNullAtIndex(int arg0); + + /** + * Translated "Cannot reveal application details. No application specified.". + * + * @return translated "Cannot reveal application details. No application specified." + */ + @DefaultMessage("Cannot reveal application details. No application specified.") + @Key("error_navigateToApplication") + String error_navigateToApplication(); + + /** + * Translated "Cannot reveal reference details. No reference or application specified.". + * + * @return translated "Cannot reveal reference details. No reference or application specified." + */ + @DefaultMessage("Cannot reveal reference details. No reference or application specified.") + @Key("error_navigateToReference") + String error_navigateToReference(); + + /** + * Translated "Cannot reveal service details. No service or application specified.". + * + * @return translated "Cannot reveal service details. No service or application specified." + */ + @DefaultMessage("Cannot reveal service details. No service or application specified.") + @Key("error_navigateToService") + String error_navigateToService(); + + /** + * Translated "Could not load information for reference: {0} from application: {1}". + * @param arg0 reference name + * @param arg1 application name + * @return translated "Could not load information for reference: {0} from application: {1}" + */ + @DefaultMessage("Could not load information for reference: {0} from application: {1}") + @Key("error_referenceLoad") + String error_referenceLoad(String arg0, String arg1); + + /** + * Translated "Failure resetting metrics for {0}: {1}". + * @param arg0 entity name + * @param arg1 error message + * @return translated "Failure resetting metrics for {0}: {1}" + */ + @DefaultMessage("Failure resetting metrics for {0}: {1}") + @Key("error_resetObjectMetrics") + String error_resetObjectMetrics(String arg0, String arg1); + + /** + * Translated "Failure resetting system metrics: {0}". + * @param arg0 error message + * @return translated "Failure resetting system metrics: {0}" + */ + @DefaultMessage("Failure resetting system metrics: {0}") + @Key("error_resetSystemMetrics") + String error_resetSystemMetrics(String arg0); + + /** + * Translated "Could not load information for service: {0} from application: {1}". + * @param arg0 service name + * @param arg1 application name + * @return translated "Could not load information for service: {0} from application: {1}" + */ + @DefaultMessage("Could not load information for service: {0} from application: {1}") + @Key("error_serviceLoad") + String error_serviceLoad(String arg0, String arg1); + + /** + * Translated "Could not load metrics for service: {0}". + * @param arg0 service name + * @return translated "Could not load metrics for service: {0}" + */ + @DefaultMessage("Could not load metrics for service: {0}") + @Key("error_serviceMetricsLoad") + String error_serviceMetricsLoad(String arg0); + + /** + * Translated "Failure setting property: {0}". + * @param arg0 property name + * @return translated "Failure setting property: {0}" + */ + @DefaultMessage("Failure setting property: {0}") + @Key("error_setProperty") + String error_setProperty(String arg0); + + /** + * Translated "Failure starting gateway for {0}: {1}". + * @param arg0 gateway name + * @param arg1 error message + * @return translated "Failure starting gateway for {0}: {1}" + */ + @DefaultMessage("Failure starting gateway for {0}: {1}") + @Key("error_startGateway") + String error_startGateway(String arg0, String arg1); + + /** + * Translated "Failure stopping gateway for {0}: {1}". + * @param arg0 gateway name + * @param arg1 error message + * @return translated "Failure stopping gateway for {0}: {1}" + */ + @DefaultMessage("Failure stopping gateway for {0}: {1}") + @Key("error_stopGateway") + String error_stopGateway(String arg0, String arg1); + + /** + * Translated "Could not load metrics for system". + * + * @return translated "Could not load metrics for system" + */ + @DefaultMessage("Could not load metrics for system") + @Key("error_systemMetricsLoad") + String error_systemMetricsLoad(); + + /** + * Translated "Unknown error". + * + * @return translated "Unknown error" + */ + @DefaultMessage("Unknown error") + @Key("error_unknown") + String error_unknown(); + + /** + * Translated "Failure updating throttling details for {0}: {1}". + * @param arg0 service name + * @param arg1 error message + * @return translated "Failure updating throttling details for {0}: {1}" + */ + @DefaultMessage("Failure updating throttling details for {0}: {1}") + @Key("error_updateThrottling") + String error_updateThrottling(String arg0, String arg1); + + /** + * Translated "Actual". + * + * @return translated "Actual" + */ + @DefaultMessage("Actual") + @Key("label_actual") + String label_actual(); + + /** + * Translated "Application". + * + * @return translated "Application" + */ + @DefaultMessage("Application") + @Key("label_application") + String label_application(); + + /** + * Translated "Application Details". + * + * @return translated "Application Details" + */ + @DefaultMessage("Application Details") + @Key("label_applicationDetails") + String label_applicationDetails(); + + /** + * Translated "Application Name". + * + * @return translated "Application Name" + */ + @DefaultMessage("Application Name") + @Key("label_applicationName") + String label_applicationName(); + + /** + * Translated "Application Namespace". + * + * @return translated "Application Namespace" + */ + @DefaultMessage("Application Namespace") + @Key("label_applicationNamespace") + String label_applicationNamespace(); + + /** + * Translated "Applications". + * + * @return translated "Applications" + */ + @DefaultMessage("Applications") + @Key("label_applications") + String label_applications(); + + /** + * Translated "Applications Using Artifact". + * + * @return translated "Applications Using Artifact" + */ + @DefaultMessage("Applications Using Artifact") + @Key("label_applicationsUsingArtifacts") + String label_applicationsUsingArtifacts(); + + /** + * Translated "Artifact References". + * + * @return translated "Artifact References" + */ + @DefaultMessage("Artifact References") + @Key("label_artifactReferences") + String label_artifactReferences(); + + /** + * Translated "Artifacts". + * + * @return translated "Artifacts" + */ + @DefaultMessage("Artifacts") + @Key("label_artifacts") + String label_artifacts(); + + /** + * Translated "Average Processing Time". + * + * @return translated "Average Processing Time" + */ + @DefaultMessage("Average Processing Time") + @Key("label_averageProcessingTime") + String label_averageProcessingTime(); + + /** + * Translated "Average Time". + * + * @return translated "Average Time" + */ + @DefaultMessage("Average Time") + @Key("label_averageTime") + String label_averageTime(); + + /** + * Translated "Component Details". + * + * @return translated "Component Details" + */ + @DefaultMessage("Component Details") + @Key("label_componentDetails") + String label_componentDetails(); + + /** + * Translated "Component Services". + * + * @return translated "Component Services" + */ + @DefaultMessage("Component Services") + @Key("label_componentServices") + String label_componentServices(); + + /** + * Translated "Configuration". + * + * @return translated "Configuration" + */ + @DefaultMessage("Configuration") + @Key("label_configuration") + String label_configuration(); + + /** + * Translated "Core Runtime". + * + * @return translated "Core Runtime" + */ + @DefaultMessage("Core Runtime") + @Key("label_coreRuntime") + String label_coreRuntime(); + + /** + * Translated "Details". + * + * @return translated "Details" + */ + @DefaultMessage("Details") + @Key("label_details") + String label_details(); + + /** + * Translated "Enabled". + * + * @return translated "Enabled" + */ + @DefaultMessage("Enabled") + @Key("label_enabled") + String label_enabled(); + + /** + * Translated "Fault Count". + * + * @return translated "Fault Count" + */ + @DefaultMessage("Fault Count") + @Key("label_faultCount") + String label_faultCount(); + + /** + * Translated "Fault %". + * + * @return translated "Fault %" + */ + @DefaultMessage("Fault %") + @Key("label_faultPercent") + String label_faultPercent(); + + /** + * Translated "From". + * + * @return translated "From" + */ + @DefaultMessage("From") + @Key("label_from") + String label_from(); + + /** + * Translated "Gateway Configuration". + * + * @return translated "Gateway Configuration" + */ + @DefaultMessage("Gateway Configuration") + @Key("label_gatewayConfiguration") + String label_gatewayConfiguration(); + + /** + * Translated "Gateway Metrics". + * + * @return translated "Gateway Metrics" + */ + @DefaultMessage("Gateway Metrics") + @Key("label_gatewayMetrics") + String label_gatewayMetrics(); + + /** + * Translated "Gateways". + * + * @return translated "Gateways" + */ + @DefaultMessage("Gateways") + @Key("label_gateways") + String label_gateways(); + + /** + * Translated "Implementation". + * + * @return translated "Implementation" + */ + @DefaultMessage("Implementation") + @Key("label_implementation") + String label_implementation(); + + /** + * Translated "Implementation Details". + * + * @return translated "Implementation Details" + */ + @DefaultMessage("Implementation Details") + @Key("label_implementationDetails") + String label_implementationDetails(); + + /** + * Translated "{0} implementation". + * @param arg0 implementation name + * @return translated "{0} implementation" + */ + @DefaultMessage("{0} implementation") + @Key("label_implementationInstance") + String label_implementationInstance(String arg0); + + /** + * Translated "Installed Components". + * + * @return translated "Installed Components" + */ + @DefaultMessage("Installed Components") + @Key("label_installedComponents") + String label_installedComponents(); + + /** + * Translated "Interface". + * + * @return translated "Interface" + */ + @DefaultMessage("Interface") + @Key("label_interface") + String label_interface(); + + /** + * Translated "Max. Processing Time". + * + * @return translated "Max. Processing Time" + */ + @DefaultMessage("Max. Processing Time") + @Key("label_maxProcessingTime") + String label_maxProcessingTime(); + + /** + * Translated "Maximum Requests". + * + * @return translated "Maximum Requests" + */ + @DefaultMessage("Maximum Requests") + @Key("label_maximumRequests") + String label_maximumRequests(); + + /** + * Translated "Message Count". + * + * @return translated "Message Count" + */ + @DefaultMessage("Message Count") + @Key("label_messageCount") + String label_messageCount(); + + /** + * Translated "Message Counts". + * + * @return translated "Message Counts" + */ + @DefaultMessage("Message Counts") + @Key("label_messageCounts") + String label_messageCounts(); + + /** + * Translated "Metric". + * + * @return translated "Metric" + */ + @DefaultMessage("Metric") + @Key("label_metric") + String label_metric(); + + /** + * Translated "Min. Processing Time". + * + * @return translated "Min. Processing Time" + */ + @DefaultMessage("Min. Processing Time") + @Key("label_minProcessingTime") + String label_minProcessingTime(); + + /** + * Translated "Name". + * + * @return translated "Name" + */ + @DefaultMessage("Name") + @Key("label_name") + String label_name(); + + /** + * Translated "Namespace". + * + * @return translated "Namespace" + */ + @DefaultMessage("Namespace") + @Key("label_namespace") + String label_namespace(); + + /** + * Translated "Operation Metrics". + * + * @return translated "Operation Metrics" + */ + @DefaultMessage("Operation Metrics") + @Key("label_operationMetrics") + String label_operationMetrics(); + + /** + * Translated "Processing Times". + * + * @return translated "Processing Times" + */ + @DefaultMessage("Processing Times") + @Key("label_processingTimes") + String label_processingTimes(); + + /** + * Translated "Promoted Service". + * + * @return translated "Promoted Service" + */ + @DefaultMessage("Promoted Service") + @Key("label_promotedService") + String label_promotedService(); + + /** + * Translated "Properties". + * + * @return translated "Properties" + */ + @DefaultMessage("Properties") + @Key("label_properties") + String label_properties(); + + /** + * Translated "Raw Configuration". + * + * @return translated "Raw Configuration" + */ + @DefaultMessage("Raw Configuration") + @Key("label_rawConfiguration") + String label_rawConfiguration(); + + /** + * Translated "Reference Details". + * + * @return translated "Reference Details" + */ + @DefaultMessage("Reference Details") + @Key("label_referenceDetails") + String label_referenceDetails(); + + /** + * Translated "Reference Message Metrics". + * + * @return translated "Reference Message Metrics" + */ + @DefaultMessage("Reference Message Metrics") + @Key("label_referenceMessageMetrics") + String label_referenceMessageMetrics(); + + /** + * Translated "Reference Metrics". + * + * @return translated "Reference Metrics" + */ + @DefaultMessage("Reference Metrics") + @Key("label_referenceMetrics") + String label_referenceMetrics(); + + /** + * Translated "Referenced Service Metrics". + * + * @return translated "Referenced Service Metrics" + */ + @DefaultMessage("Referenced Service Metrics") + @Key("label_referencedServiceMetrics") + String label_referencedServiceMetrics(); + + /** + * Translated "References". + * + * @return translated "References" + */ + @DefaultMessage("References") + @Key("label_references") + String label_references(); + + /** + * Translated "Referencing Applications". + * + * @return translated "Referencing Applications" + */ + @DefaultMessage("Referencing Applications") + @Key("label_referencingApplications") + String label_referencingApplications(); + + /** + * Translated "Reset". + * + * @return translated "Reset" + */ + @DefaultMessage("Reset") + @Key("label_reset") + String label_reset(); + + /** + * Translated "Reset All Metrics". + * + * @return translated "Reset All Metrics" + */ + @DefaultMessage("Reset All Metrics") + @Key("label_resetAllMetrics") + String label_resetAllMetrics(); + + /** + * Translated "Reset Metrics". + * + * @return translated "Reset Metrics" + */ + @DefaultMessage("Reset Metrics") + @Key("label_resetMetrics") + String label_resetMetrics(); + + /** + * Translated "Runtime Details". + * + * @return translated "Runtime Details" + */ + @DefaultMessage("Runtime Details") + @Key("label_runtimeDetails") + String label_runtimeDetails(); + + /** + * Translated "Service Details". + * + * @return translated "Service Details" + */ + @DefaultMessage("Service Details") + @Key("label_serviceDetails") + String label_serviceDetails(); + + /** + * Translated "Service Message Metrics". + * + * @return translated "Service Message Metrics" + */ + @DefaultMessage("Service Message Metrics") + @Key("label_serviceMessageMetrics") + String label_serviceMessageMetrics(); + + /** + * Translated "Service Metrics". + * + * @return translated "Service Metrics" + */ + @DefaultMessage("Service Metrics") + @Key("label_serviceMetrics") + String label_serviceMetrics(); + + /** + * Translated "Service Operation Metrics". + * + * @return translated "Service Operation Metrics" + */ + @DefaultMessage("Service Operation Metrics") + @Key("label_serviceOperationMetrics") + String label_serviceOperationMetrics(); + + /** + * Translated "Services". + * + * @return translated "Services" + */ + @DefaultMessage("Services") + @Key("label_services") + String label_services(); + + /** + * Translated "Start". + * + * @return translated "Start" + */ + @DefaultMessage("Start") + @Key("label_start") + String label_start(); + + /** + * Translated "Start/Stop". + * + * @return translated "Start/Stop" + */ + @DefaultMessage("Start/Stop") + @Key("label_startStop") + String label_startStop(); + + /** + * Translated "Status". + * + * @return translated "Status" + */ + @DefaultMessage("Status") + @Key("label_status") + String label_status(); + + /** + * Translated "Stop". + * + * @return translated "Stop" + */ + @DefaultMessage("Stop") + @Key("label_stop") + String label_stop(); + + /** + * Translated "Success Count". + * + * @return translated "Success Count" + */ + @DefaultMessage("Success Count") + @Key("label_successCount") + String label_successCount(); + + /** + * Translated "SwitchYard Applications". + * + * @return translated "SwitchYard Applications" + */ + @DefaultMessage("SwitchYard Applications") + @Key("label_switchYardApplications") + String label_switchYardApplications(); + + /** + * Translated "SwitchYard Artifact References". + * + * @return translated "SwitchYard Artifact References" + */ + @DefaultMessage("SwitchYard Artifact References") + @Key("label_switchYardArtifactReferences") + String label_switchYardArtifactReferences(); + + /** + * Translated "SwitchYard Message Metrics". + * + * @return translated "SwitchYard Message Metrics" + */ + @DefaultMessage("SwitchYard Message Metrics") + @Key("label_switchYardMessageMetrics") + String label_switchYardMessageMetrics(); + + /** + * Translated "SwitchYard References". + * + * @return translated "SwitchYard References" + */ + @DefaultMessage("SwitchYard References") + @Key("label_switchYardReferences") + String label_switchYardReferences(); + + /** + * Translated "SwitchYard Runtime". + * + * @return translated "SwitchYard Runtime" + */ + @DefaultMessage("SwitchYard Runtime") + @Key("label_switchYardRuntime") + String label_switchYardRuntime(); + + /** + * Translated "SwitchYard Runtime Details". + * + * @return translated "SwitchYard Runtime Details" + */ + @DefaultMessage("SwitchYard Runtime Details") + @Key("label_switchYardRuntimeDetails") + String label_switchYardRuntimeDetails(); + + /** + * Translated "SwitchYard Services". + * + * @return translated "SwitchYard Services" + */ + @DefaultMessage("SwitchYard Services") + @Key("label_switchYardServices") + String label_switchYardServices(); + + /** + * Translated "System". + * + * @return translated "System" + */ + @DefaultMessage("System") + @Key("label_system") + String label_system(); + + /** + * Translated "System Message Metrics". + * + * @return translated "System Message Metrics" + */ + @DefaultMessage("System Message Metrics") + @Key("label_systemMessageMetrics") + String label_systemMessageMetrics(); + + /** + * Translated "Target Namespace". + * + * @return translated "Target Namespace" + */ + @DefaultMessage("Target Namespace") + @Key("label_targetNamespace") + String label_targetNamespace(); + + /** + * Translated "Throttling". + * + * @return translated "Throttling" + */ + @DefaultMessage("Throttling") + @Key("label_throttling") + String label_throttling(); + + /** + * Translated "Time %". + * + * @return translated "Time %" + */ + @DefaultMessage("Time %") + @Key("label_timePercent") + String label_timePercent(); + + /** + * Translated "Time Period (millis)". + * + * @return translated "Time Period (millis)" + */ + @DefaultMessage("Time Period (millis)") + @Key("label_timePeriod") + String label_timePeriod(); + + /** + * Translated "To". + * + * @return translated "To" + */ + @DefaultMessage("To") + @Key("label_to") + String label_to(); + + /** + * Translated "Total Count". + * + * @return translated "Total Count" + */ + @DefaultMessage("Total Count") + @Key("label_totalCount") + String label_totalCount(); + + /** + * Translated "Total Processing Time". + * + * @return translated "Total Processing Time" + */ + @DefaultMessage("Total Processing Time") + @Key("label_totalProcessingTime") + String label_totalProcessingTime(); + + /** + * Translated "Transformers". + * + * @return translated "Transformers" + */ + @DefaultMessage("Transformers") + @Key("label_transformers") + String label_transformers(); + + /** + * Translated "Type". + * + * @return translated "Type" + */ + @DefaultMessage("Type") + @Key("label_type") + String label_type(); + + /** + * Translated "URL". + * + * @return translated "URL" + */ + @DefaultMessage("URL") + @Key("label_url") + String label_url(); + + /** + * Translated "Validators". + * + * @return translated "Validators" + */ + @DefaultMessage("Validators") + @Key("label_validators") + String label_validators(); + + /** + * Translated "Version". + * + * @return translated "Version" + */ + @DefaultMessage("Version") + @Key("label_version") + String label_version(); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/NameTokens.java b/console/gwt/src/main/java/org/switchyard/console/client/NameTokens.java new file mode 100644 index 000000000..e76b47eb7 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/NameTokens.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client; + +/** + * NameTokens + * + * SwitchYard specific path tokens. + * + * @author Rob Cernich + */ +public final class NameTokens { + + private NameTokens() { + } + + /** The SwitchYard subsystem name. */ + public static final String SUBSYSTEM = "switchyard"; //$NON-NLS-1$ + + /** The subpath for the SwitchYard system configuration view. */ + public static final String SYSTEM_CONFIG_PRESENTER = "switchyard"; //$NON-NLS-1$ + /** The subpath for the SwitchYard applications view. */ + public static final String APPLICATIONS_PRESENTER = "sy-apps"; //$NON-NLS-1$ + /** The subpath for the SwitchYard artifacts view. */ + public static final String ARTIFACTS_PRESENTER = "sy-artifacts"; //$NON-NLS-1$ + /** The subpath for the SwitchYard services view. */ + public static final String SERVICES_PRESENTER = "sy-services"; //$NON-NLS-1$ + /** The subpath for the SwitchYard references view. */ + public static final String REFERENCES_PRESENTER = "sy-references"; //$NON-NLS-1$ + /** The subpath for the SwitchYard message metrics view. */ + public static final String METRICS_PRESENTER = "sy-metrics"; //$NON-NLS-1$ + /** The subpath for the SwitchYard runtime view. */ + public static final String RUNTIME_PRESENTER = "switchyard-runtime"; //$NON-NLS-1$ + /** The subpath for the SwitchYard runtime operations view. */ + public static final String RUNTIME_OPERATIONS_PRESENTER = APPLICATIONS_PRESENTER; + + /** The parameter name used for component name. */ + public static final String COMPONENT_NAME_PARAM = "component"; //$NON-NLS-1$ + /** The parameter name used for application name. */ + public static final String APPLICATION_NAME_PARAM = "application"; //$NON-NLS-1$ + /** The parameter name used for artifact reference key. */ + public static final String ARTIFACT_REFERENCE_KEY_PARAM = "artifactKey"; //$NON-NLS-1$ + /** The parameter name used for service name. */ + public static final String SERVICE_NAME_PARAM = "service"; //$NON-NLS-1$ + /** The parameter name used for reference name. */ + public static final String REFERENCE_NAME_PARAM = "reference"; //$NON-NLS-1$ + + /** The display text for the SwitchYard system configuration navigator item. */ + public static final String SYSTEM_CONFIG_TEXT = Singleton.MESSAGES.label_runtimeDetails(); + /** The display text for the SwitchYard applications navigator item. */ + public static final String APPLICATIONS_TEXT = Singleton.MESSAGES.label_applications(); + /** The display text for the SwitchYard artifact references navigator item. */ + public static final String ARTIFACT_REFERENCES_TEXT = Singleton.MESSAGES.label_artifacts(); + /** The display text for the SwitchYard services navigator item. */ + public static final String SERVICES_TEXT = Singleton.MESSAGES.label_services(); + /** The display text for the SwitchYard services navigator item. */ + public static final String REFERENCES_TEXT = Singleton.MESSAGES.label_references(); + /** The display text for the SwitchYard runtime navigator item. */ + public static final String RUNTIME_TEXT = "SwitchYard"; //$NON-NLS-1$ + + /** The "category" ID for the subsystems tree. */ + public static final String SUBSYSTEM_TREE_CATEGORY = "profiles"; //$NON-NLS-1$ + /** The "category" ID for the domain runtime tree. */ + public static final String SUBSYSTEM_DOMAIN_TREE_CATEGORY = "domain-runtime"; //$NON-NLS-1$ + /** The "category" ID for the standalone runtime tree. */ + public static final String SUBSYSTEM_STANDALONE_TREE_CATEGORY = "standalone-runtime"; //$NON-NLS-1$ + + /** + * @param name a string representation of a javax.xml.namespace.QName + * @return the QName components, {namespace,local} + */ + public static String[] parseQName(String name) { + if (name == null) { + return new String[] {"", "" }; //$NON-NLS-1$ //$NON-NLS-2$ + } + int namespaceEnd = name.indexOf('}'); + if (namespaceEnd > 0) { + return new String[] {name.substring(1, namespaceEnd), name.substring(namespaceEnd + 1) }; + } + return new String[] {"", name }; //$NON-NLS-1$ + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/Singleton.java b/console/gwt/src/main/java/org/switchyard/console/client/Singleton.java new file mode 100644 index 000000000..d920aafcd --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/Singleton.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client; + +import com.google.gwt.core.client.GWT; + +/** + * Singleton + * + * Provide access to unbound objects (e.g. Messages). + * + * @author Rob Cernich + */ +public final class Singleton { + + /** + * The internationalized UI messages used by the application. See + * Messages.properties. + */ + public static final Messages MESSAGES = GWT.create(Messages.class); + + private Singleton() { + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/gin/SwitchYardClientModule.java b/console/gwt/src/main/java/org/switchyard/console/client/gin/SwitchYardClientModule.java new file mode 100644 index 000000000..25eb36ab0 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/gin/SwitchYardClientModule.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.gin; + +import org.switchyard.console.client.Messages; +import org.switchyard.console.client.model.SwitchYardStore; +import org.switchyard.console.client.model.SwitchYardStoreImpl; +import org.switchyard.console.client.ui.application.ApplicationPresenter; +import org.switchyard.console.client.ui.application.ApplicationView; +import org.switchyard.console.client.ui.artifacts.ArtifactPresenter; +import org.switchyard.console.client.ui.artifacts.ArtifactReferencesView; +import org.switchyard.console.client.ui.component.ComponentConfigurationPresenterFactory; +import org.switchyard.console.client.ui.component.ComponentConfigurationViewFactory; +import org.switchyard.console.client.ui.component.ComponentPresenter; +import org.switchyard.console.client.ui.config.ConfigPresenter; +import org.switchyard.console.client.ui.config.ConfigView; +import org.switchyard.console.client.ui.metrics.MetricsPresenter; +import org.switchyard.console.client.ui.metrics.MetricsView; +import org.switchyard.console.client.ui.reference.ReferencePresenter; +import org.switchyard.console.client.ui.reference.ReferenceView; +import org.switchyard.console.client.ui.runtime.RuntimePresenter; +import org.switchyard.console.client.ui.runtime.RuntimeView; +import org.switchyard.console.client.ui.service.ServicePresenter; +import org.switchyard.console.client.ui.service.ServiceView; +import org.switchyard.console.components.client.extension.ComponentProviders; +import org.switchyard.console.components.client.extension.DefaultComponentProvider; +import org.switchyard.console.components.client.extension.DefaultComponentProviderImpl; + +import com.google.inject.Provider; +import com.google.inject.Singleton; +import com.gwtplatform.mvp.client.gin.AbstractPresenterModule; + +/** + * SwitchYardClientModule + * + * SwitchYard Ginjector bindings. + * + * @author Rob Cernich + */ +public class SwitchYardClientModule extends AbstractPresenterModule { + + protected void configure() { + // switchyard application + bind(SwitchYardStore.class).to(SwitchYardStoreImpl.class).in(Singleton.class); + bindPresenter(ConfigPresenter.class, ConfigPresenter.MyView.class, ConfigView.class, + ConfigPresenter.MyProxy.class); + bindPresenter(ApplicationPresenter.class, ApplicationPresenter.MyView.class, ApplicationView.class, + ApplicationPresenter.MyProxy.class); + bindPresenter(ArtifactPresenter.class, ArtifactPresenter.MyView.class, ArtifactReferencesView.class, + ArtifactPresenter.MyProxy.class); + bindPresenter(ServicePresenter.class, ServicePresenter.MyView.class, ServiceView.class, + ServicePresenter.MyProxy.class); + bindPresenter(ReferencePresenter.class, ReferencePresenter.MyView.class, ReferenceView.class, + ReferencePresenter.MyProxy.class); + bindPresenter(MetricsPresenter.class, MetricsPresenter.MyView.class, MetricsView.class, + MetricsPresenter.MyProxy.class); + bindPresenter(RuntimePresenter.class, RuntimePresenter.MyView.class, RuntimeView.class, + RuntimePresenter.MyProxy.class); + + // components + bindPresenterWidgetFactory(ComponentPresenter.PresenterFactory.class, + ComponentConfigurationPresenterFactory.class, ComponentPresenter.ViewFactory.class, + ComponentConfigurationViewFactory.class); + + bind(ComponentProviders.class).in(Singleton.class); + bind(DefaultComponentProvider.class).to(DefaultComponentProviderImpl.class); + + // messages + bind(Messages.class).toProvider(MessagesProvider.class); + } + + /** + * Binds the static, singleton instance of Messages. + */ + public static class MessagesProvider implements Provider { + @Override + public Messages get() { + return org.switchyard.console.client.Singleton.MESSAGES; + } + } +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/gin/SwitchYardGinjector.java b/console/gwt/src/main/java/org/switchyard/console/client/gin/SwitchYardGinjector.java new file mode 100644 index 000000000..2fecf2596 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/gin/SwitchYardGinjector.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.gin; + +import org.jboss.as.console.spi.GinExtension; +import org.switchyard.console.client.Messages; +import org.switchyard.console.client.ui.application.ApplicationPresenter; +import org.switchyard.console.client.ui.artifacts.ArtifactPresenter; +import org.switchyard.console.client.ui.config.ConfigPresenter; +import org.switchyard.console.client.ui.metrics.MetricsPresenter; +import org.switchyard.console.client.ui.reference.ReferencePresenter; +import org.switchyard.console.client.ui.runtime.RuntimePresenter; +import org.switchyard.console.client.ui.service.ServicePresenter; + +import com.google.gwt.inject.client.AsyncProvider; +import com.google.gwt.inject.client.GinModules; +import com.google.gwt.inject.client.Ginjector; + +/** + * Overall module configuration. + * + * @see SwitchYardClientModule + * + * @author Rob Cernich + */ +@GinModules(SwitchYardClientModule.class) +@GinExtension("org.switchyard.console.SwitchYard") +public interface SwitchYardGinjector extends Ginjector { + + /** + * @return the localized messages. + */ + Messages getMessages(); + + /** + * @return the ConfigPresenter configured for the module. + */ + AsyncProvider getConfigPresenter(); + + /** + * @return the ApplicationPresenter configured for the module. + */ + AsyncProvider getApplicationPresenter(); + + /** + * @return the ArtifactPresenter configured for the module. + */ + AsyncProvider getArtifactPresenter(); + + /** + * @return the ServicePresenter configured for the module. + */ + AsyncProvider getServicePresenter(); + + /** + * @return the ReferencePresenter configured for the module. + */ + AsyncProvider getReferencePresenter(); + + /** + * @return the MetricsPresenter configured for the module. + */ + AsyncProvider getSwitchYardMetricsPresenter(); + + /** + * @return the RuntimePresenter configured for the module. + */ + AsyncProvider getSwitchYardRuntimePresenter(); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Application.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Application.java new file mode 100644 index 000000000..1723ff769 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Application.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import java.util.List; + +import org.jboss.as.console.client.shared.properties.PropertyRecord; + +/** + * Application + * + * Represents a SwitchYard application. + * + * @author Rob Cernich + */ +public interface Application extends HasQName { + + /** + * @return the services provided by this application. + */ + public List getServices(); + + /** + * @param services the services provided by this application. + */ + public void setServices(List services); + + /** + * @return the references used by this application. + */ + public List getReferences(); + + /** + * @param references the references used by this application. + */ + public void setReferences(List references); + + /** + * @return the component services defined within this application. + */ + public List getComponentServices(); + + /** + * @param componentServices the component services defined within this + * application. + */ + public void setComponentServices(List componentServices); + + /** + * @return the transformers defined within this application. + */ + public List getTransformers(); + + /** + * @param transformers the transforms defined within this application. + */ + public void setTransformers(List transformers); + + /** + * @return the artifacts referenced by this application. + */ + public List getArtifacts(); + + /** + * @param artifacts the artifacts referenced by this application. + */ + public void setArtifacts(List artifacts); + + /** + * @return the validators used by this application. + */ + public List getValidators(); + + /** + * @param validators the validators used by this application. + */ + public void setValidators(List validators); + + /** + * @return the properties defined for this application + */ + public List getProperties(); + + /** + * @param properties the properties defined for this application. + */ + public void setProperties(List properties); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/ArtifactReference.java b/console/gwt/src/main/java/org/switchyard/console/client/model/ArtifactReference.java new file mode 100644 index 000000000..2c71343fe --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/ArtifactReference.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import java.util.List; + +/** + * ArtifactReference + * + *

+ * Represents an artifact reference in an application. + * + * @author Rob Cernich + */ +public interface ArtifactReference { + + /** + * @return the artifact name. + */ + String getName(); + + /** + * @param value the new artifact name. + */ + void setName(String value); + + /** + * @return the location of the artifact. + */ + String getUrl(); + + /** + * @param value the new location of the artifact. + */ + void setUrl(String value); + + /** + * @return the applications containing this reference. + */ + List getApplications(); + + /** + * @param value the applications containing this reference. + */ + void setApplications(List value); + + /** + * @return a value that uniquely identifies this reference. + */ + String key(); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/ArtifactReferenceCategory.java b/console/gwt/src/main/java/org/switchyard/console/client/model/ArtifactReferenceCategory.java new file mode 100644 index 000000000..91a4d97e7 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/ArtifactReferenceCategory.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import com.google.web.bindery.autobean.shared.AutoBean; + +/** + * QNameCategory + * + * Provides implementations for the non-property methods in HasQName. + * + * @author Rob Cernich + */ +public final class ArtifactReferenceCategory { + + private ArtifactReferenceCategory() { + } + + /** + * @param instance the bean instance. + * @return a unique identifier for the instance. + */ + public static String key(AutoBean instance) { + ArtifactReference ar = instance.as(); + return "" + ar.getName() + "::" + ar.getUrl(); //$NON-NLS-1$ //$NON-NLS-2$ + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Binding.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Binding.java new file mode 100644 index 000000000..e1464d1ca --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Binding.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * Binding + * + * Represents a gateway binding on a service. + * + * @author Rob Cernich + */ +public interface Binding { + + /** + * @return the name of binding (e.g. soap1) + */ + public String getName(); + + /** + * @param name the name of binding (e.g. soap1) + */ + public void setName(String name); + + /** + * @return the type of binding (e.g. soap) + */ + public String getType(); + + /** + * @param type the type of binding (e.g. soap) + */ + public void setType(String type); + + /** + * @return the raw configuration of the binding + */ + public String getConfiguration(); + + /** + * @param configuration the raw configuration of the binding. + */ + public void setConfiguration(String configuration); + + /** + * @return the state of the binding. + */ + public State getState(); + + /** + * @param state the state of the binding. + */ + public void setState(State state); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/ComponentReference.java b/console/gwt/src/main/java/org/switchyard/console/client/model/ComponentReference.java new file mode 100644 index 000000000..d1beaa17a --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/ComponentReference.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * ComponentReference + * + * Represents a SwitchYard component reference. + * + * @author Rob Cernich + */ +public interface ComponentReference extends HasQName { + + /** + * @return the interface name + */ + public String getInterface(); + + /** + * @param interfaceName the interface name + */ + public void setInterface(String interfaceName); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/ComponentService.java b/console/gwt/src/main/java/org/switchyard/console/client/model/ComponentService.java new file mode 100644 index 000000000..6b5417978 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/ComponentService.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import java.util.List; + +/** + * ComponentService + * + * Represents a SwitchYard component service. + * + * @author Rob Cernich + */ +public interface ComponentService extends HasQName { + + /** + * @return the interface name + */ + public String getInterface(); + + /** + * @param interfaceName the interface name + */ + public void setInterface(String interfaceName); + + /** + * @return the implementation name + */ + public String getImplementation(); + + /** + * @param implementation the implementation name + */ + public void setImplementation(String implementation); + + /** + * @return the references required by this component + */ + public List getReferences(); + + /** + * @param references the references required by this component + */ + public void setReferences(List references); + + /** + * @return the application name + */ + public String getApplication(); + + /** + * @param application the application name + */ + public void setApplication(String application); + + /** + * @return the raw configuration of the service component's implementation + */ + public String getImplementationConfiguration(); + + /** + * @param configuration the raw configuration of the service component's + * implementation + */ + public void setImplementationConfiguration(String configuration); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Domain.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Domain.java new file mode 100644 index 000000000..2b7a97d8c --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Domain.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import java.util.List; + +/** + * Domain + * + * Represents a SwitchYard configuration domain. + * + * @author Rob Cernich + */ +public interface Domain { + /** + * @return the domain's name. + */ + public String getName(); + + /** + * @return the transformers definined in this domain. + */ + public List getTransformers(); + + /** + * @return the properties defined in this domain. + */ + public List getProperties(); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/GatewayMetrics.java b/console/gwt/src/main/java/org/switchyard/console/client/model/GatewayMetrics.java new file mode 100644 index 000000000..208f2f367 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/GatewayMetrics.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * OperationMetrics + * + *

+ * Message metrics specific to a gateway/binding. + */ +public interface GatewayMetrics extends MessageMetrics { + + /** + * @return binding name + */ + String getName(); + + /** + * @param value binding name + */ + void setName(String value); + + /** + * @return binding type + */ + String getType(); + + /** + * @param value binding type + */ + void setType(String value); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/HasQName.java b/console/gwt/src/main/java/org/switchyard/console/client/model/HasQName.java new file mode 100644 index 000000000..44bc68d88 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/HasQName.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * HasQName + * + * Used with types where the "name" attribute represents a QName. + * + * @author Rob Cernich + */ +public interface HasQName { + + /** + * @return the name. + */ + public String getName(); + + /** + * @param name the name. + */ + public void setName(String name); + + /** + * @return the "local" part of the name. + */ + public String localName(); + + /** + * @return the "namespace" part of the name. + */ + public String namespace(); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/MessageMetrics.java b/console/gwt/src/main/java/org/switchyard/console/client/model/MessageMetrics.java new file mode 100644 index 000000000..70a5302d4 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/MessageMetrics.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import com.google.web.bindery.autobean.shared.AutoBean.PropertyName; + +/** + * MessageMetrics + * + *

+ * Model element for SwitchYard MessageMetrics. + * + * @author Rob Cernich + */ +public interface MessageMetrics { + + /** + * Return the number of successful messages. + * + * @return success count + */ + int getSuccessCount(); + + /** + * @param value success count + */ + void setSuccessCount(int value); + + /** + * Return the number of failed messages. + * + * @return fault count + */ + int getFaultCount(); + + /** + * @param value fault count + */ + void setFaultCount(int value); + + /** + * Return the total number of messages processed. This is equivalent to + * getSuccessCount() + getFaultCount(). + * + * @return total message count + */ + int getTotalCount(); + + /** + * @param value total count + */ + void setTotalCount(int value); + + /** + * Total processing time for all messages in TimeUnit.MILLISECONDS. + * + * @return total processing time + */ + @PropertyName("totalTime") + long getTotalProcessingTime(); + + /** + * @param value total processing time + */ + @PropertyName("totalTime") + void setTotalProcessingTime(long value); + + /** + * Average processing time for all messages in TimeUnit.MILLISECONDS. + * + * @return average processing time + */ + @PropertyName("averageTime") + Double getAverageProcessingTime(); + + /** + * @param value average processing time + */ + @PropertyName("averageTime") + void setAverageProcessingTime(Double value); + + /** + * Minimum processing time for a message in TimeUnit.MILLISECONDS. + * + * @return min processing time + */ + @PropertyName("minTime") + int getMinProcessingTime(); + + /** + * @param value min processing time + */ + @PropertyName("minTime") + void setMinProcessingTime(int value); + + /** + * Maximum processing time for a message in TimeUnit.MILLISECONDS. + * + * @return max processing time + */ + @PropertyName("maxTime") + int getMaxProcessingTime(); + + /** + * @param value max processing time + */ + @PropertyName("maxTime") + void setMaxProcessingTime(int value); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/OperationMetrics.java b/console/gwt/src/main/java/org/switchyard/console/client/model/OperationMetrics.java new file mode 100644 index 000000000..f4ecfc85b --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/OperationMetrics.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * OperationMetrics + * + *

+ * Message metrics specific to an operation. + */ +public interface OperationMetrics extends MessageMetrics { + + /** + * @return operation name + */ + String getName(); + + /** + * @param value operation name + */ + void setName(String value); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Property.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Property.java new file mode 100644 index 000000000..b55d5d5e1 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Property.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * Property + * + * Represents a SwitchYard configuration property. + * + * @author Rob Cernich + */ +public interface Property { + /** + * @return the name of this property. + */ + public String getName(); + + /** + * @return the value of this property. + */ + public String getValue(); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/QNameCategory.java b/console/gwt/src/main/java/org/switchyard/console/client/model/QNameCategory.java new file mode 100644 index 000000000..0cdc5e863 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/QNameCategory.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import org.switchyard.console.client.NameTokens; + +import com.google.web.bindery.autobean.shared.AutoBean; + +/** + * QNameCategory + * + * Provides implementations for the non-property methods in HasQName. + * + * @author Rob Cernich + */ +public final class QNameCategory { + + private QNameCategory() { + } + + /** + * @param instance the bean instance. + * @return the "local" part of the bean's name. + */ + public static String localName(AutoBean instance) { + String name = instance.as().getName(); + if (name == null) { + return null; + } + return NameTokens.parseQName(name)[1]; + } + + /** + * @param instance the bean instance. + * @return the "namespace" part of the bean's name. + */ + public static String namespace(AutoBean instance) { + String name = instance.as().getName(); + if (name == null) { + return null; + } + return NameTokens.parseQName(name)[0]; + } +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Reference.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Reference.java new file mode 100644 index 000000000..50eba7611 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Reference.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import java.util.List; + +/** + * Reference + * + * Represents a SwitchYard reference. + */ +public interface Reference extends HasQName { + + /** + * @return the interface name + */ + public String getInterface(); + + /** + * @param interfaceName the interface name + */ + public void setInterface(String interfaceName); + + /** + * @return the gateways + */ + List getGateways(); + + /** + * @param gateways the gateways + */ + public void setGateways(List gateways); + + /** + * @return the application name + */ + public String getApplication(); + + /** + * @param application the application name + */ + public void setApplication(String application); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Service.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Service.java new file mode 100644 index 000000000..db6723486 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Service.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import java.util.List; + +/** + * Service + * + * Represents a SwitchYard service. + * + * @author Rob Cernich + */ +public interface Service extends HasQName { + + /** + * @return the interface name + */ + public String getInterface(); + + /** + * @param interfaceName the interface name + */ + public void setInterface(String interfaceName); + + /** + * @return the promoted service's name + */ + public String getPromotedService(); + + /** + * @param promotedService the promoted service's name + */ + public void setPromotedService(String promotedService); + + /** + * @return the gateways + */ + List getGateways(); + + /** + * @param gateways the gateways + */ + public void setGateways(List gateways); + + /** + * @return the application name + */ + public String getApplication(); + + /** + * @param application the application name + */ + public void setApplication(String application); + + /** + * @return the throttling details for this service + */ + public Throttling getThrottling(); + + /** + * @param throttling details for this service + */ + public void setThrottling(Throttling throttling); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/ServiceMetrics.java b/console/gwt/src/main/java/org/switchyard/console/client/model/ServiceMetrics.java new file mode 100644 index 000000000..75ce70fc6 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/ServiceMetrics.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import java.util.List; + +/** + * ServiceMetrics + * + *

+ * Message metrics specific to a service/reference. + * + * @author Rob Cernich + */ +public interface ServiceMetrics extends MessageMetrics, HasQName { + + /** + * @return metrics for operations + */ + List getOperations(); + + /** + * @param value metrics for operations + */ + void setOperations(List value); + + /** + * @return metrics for referenced services + */ + List getReferences(); + + /** + * @param value metrics for referenced services + */ + void setReferences(List value); + + /** + * @return metrics for associated gateways + */ + List getGateways(); + + /** + * @param value metrics for associated gateways + */ + void setGateways(List value); + + /** + * @return the containing application + */ + String getApplication(); + + /** + * @param application the containing application + */ + void setApplication(String application); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/State.java b/console/gwt/src/main/java/org/switchyard/console/client/model/State.java new file mode 100644 index 000000000..56e5935e2 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/State.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * Used to represent the current state of the binding/gateway. + */ +public enum State { + /** No state. */ + NONE, + /** Starting. */ + STARTING, + /** Started. */ + STARTED, + /** Stopping. */ + STOPPING; +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/SwitchYardStore.java b/console/gwt/src/main/java/org/switchyard/console/client/model/SwitchYardStore.java new file mode 100644 index 000000000..9bbeffc03 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/SwitchYardStore.java @@ -0,0 +1,213 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.model; + +import java.util.List; +import java.util.Map; + +import org.jboss.as.console.client.shared.properties.PropertyRecord; +import org.switchyard.console.client.BeanFactory; +import org.switchyard.console.components.client.model.Component; + +import com.google.gwt.user.client.rpc.AsyncCallback; + +/** + * SwitchYardStore + * + * Interface used for loading domain objects. + * + * @author Rob Cernich + */ +public interface SwitchYardStore { + + /** + * @return the BeanFactory used by the store. + */ + BeanFactory getBeanFactory(); + + /** + * Load details about the SwitchYard subsystem. + * + * @param callback the callback. + */ + void loadSystemDetails(AsyncCallback callback); + + /** + * Load applications deployed on the SwitchYard subsystem. + * + * @param callback the callback. + */ + void loadApplications(AsyncCallback> callback); + + /** + * Load details for a specific application. + * + * @param applicationName the name of the application to load. + * @param callback the callback. + */ + void loadApplication(String applicationName, AsyncCallback callback); + + /** + * Load components registered with the SwitchYard subsystem. + * + * @param callback the callback. + */ + void loadComponents(AsyncCallback> callback); + + /** + * Load details for a specific component. + * + * @param componentName the name of the component to load. + * @param callback the callback. + */ + void loadComponent(String componentName, AsyncCallback callback); + + /** + * Load services deployed on the SwitchYard subsystem. + * + * @param callback the callback. + */ + void loadServices(AsyncCallback> callback); + + /** + * Load details for a specific service. + * + * @param serviceName the name of the service to load. + * @param applicationName the name of the application containing the + * service. + * @param callback the callback. + */ + void loadService(String serviceName, String applicationName, AsyncCallback callback); + + /** + * Loads message metrics for the specified service. + * + * @param serviceName the name of the service + * @param asyncCallback the callback + */ + void loadServiceMetrics(String serviceName, AsyncCallback asyncCallback); + + /** + * Loads message metrics for the specified service. + * + * @param asyncCallback the callback + */ + void loadAllServiceMetrics(AsyncCallback> asyncCallback); + + /** + * Loads message metrics for the specified service. + * + * @param asyncCallback the callback + */ + void loadAllReferenceMetrics(AsyncCallback> asyncCallback); + + /** + * Loads message metrics for the entire system. + * + * @param asyncCallback the callback + */ + void loadSystemMetrics(AsyncCallback asyncCallback); + + /** + * Loads artifact references for the entire system. + * + * @param asyncCallback the callback + */ + void loadArtifactReferences(AsyncCallback> asyncCallback); + + /** + * Load details for a specific reference. + * + * @param referenceName the name of the reference to load. + * @param applicationName the name of the application containing the + * reference. + * @param callback the callback. + */ + void loadReference(String referenceName, String applicationName, AsyncCallback callback); + + /** + * Load references deployed on the SwitchYard subsystem. + * + * @param callback the callback. + */ + void loadReferences(AsyncCallback> callback); + + /** + * Sets the property on the application. + * + * @param applicationName the application + * @param prop the property + * @param callback the callback + */ + void setApplicationProperty(String applicationName, PropertyRecord prop, final AsyncCallback callback); + + /** + * Resets all metrics in the system. + * + * @param callback the callback + */ + void resetSystemMetrics(AsyncCallback callback); + + /** + * Resets metrics for the named service/reference. + * + * @param name the name of the service/reference. + * @param applicationName the name of the containing application + * @param callback the callback. + */ + void resetMetrics(String name, String applicationName, AsyncCallback callback); + + /** + * Start the specified gateway/binding. + * + * @param name the gateway/binding name + * @param serviceName the service/reference name + * @param applicationName the application name + * @param callback the callback + */ + void startGateway(String name, String serviceName, String applicationName, AsyncCallback callback); + + /** + * Stop the specified gateway/binding. + * + * @param name the gateway/binding name + * @param serviceName the service/reference name + * @param applicationName the application name + * @param callback the callback + */ + void stopGateway(String name, String serviceName, String applicationName, AsyncCallback callback); + + /** + * Updates the throttling configuration for the specified service. + * + * @param service the service + * @param throttling the new throttling configuration + * @param callback the callback + */ + void updateThrottling(Service service, Throttling throttling, AsyncCallback callback); + + /** + * Create a new object from the change set. + * + * @param the type of object + * @param type the type of object + * @param original the original object + * @param changeSet the changes + * @param merge true if the new object should include values merged from the + * original + * @return a new object + */ + T processChangeSet(Class type, T original, Map changeSet, boolean merge); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/SwitchYardStoreImpl.java b/console/gwt/src/main/java/org/switchyard/console/client/model/SwitchYardStoreImpl.java new file mode 100644 index 000000000..b34b1e52e --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/SwitchYardStoreImpl.java @@ -0,0 +1,923 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +import static org.jboss.dmr.client.ModelDescriptionConstants.CHILD_TYPE; +import static org.jboss.dmr.client.ModelDescriptionConstants.FAILED; +import static org.jboss.dmr.client.ModelDescriptionConstants.NAME; +import static org.jboss.dmr.client.ModelDescriptionConstants.OP; +import static org.jboss.dmr.client.ModelDescriptionConstants.OP_ADDR; +import static org.jboss.dmr.client.ModelDescriptionConstants.READ_CHILDREN_NAMES_OPERATION; +import static org.jboss.dmr.client.ModelDescriptionConstants.READ_RESOURCE_OPERATION; +import static org.jboss.dmr.client.ModelDescriptionConstants.RECURSIVE; +import static org.jboss.dmr.client.ModelDescriptionConstants.RESULT; +import static org.jboss.dmr.client.ModelDescriptionConstants.SUBSYSTEM; +import static org.jboss.dmr.client.ModelDescriptionConstants.TYPE; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + +import org.jboss.as.console.client.shared.properties.PropertyRecord; +import org.jboss.as.console.client.shared.runtime.RuntimeBaseAddress; +import org.jboss.as.console.client.shared.subsys.Baseadress; +import org.jboss.as.console.client.widgets.forms.ApplicationMetaData; +import org.jboss.as.console.client.widgets.forms.EntityAdapter; +import org.jboss.as.console.client.widgets.forms.Mutator; +import org.jboss.as.console.client.widgets.forms.PropertyBinding; +import org.jboss.dmr.client.ModelNode; +import org.jboss.dmr.client.dispatch.DispatchAsync; +import org.jboss.dmr.client.dispatch.impl.DMRAction; +import org.jboss.dmr.client.dispatch.impl.DMRResponse; +import org.switchyard.console.client.BeanFactory; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.components.client.model.Component; + +import com.allen_sauer.gwt.log.client.Log; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.web.bindery.autobean.shared.AutoBeanCodex; + +/** + * SwitchYardStoreImpl + * + * SwitchYardStore implementation which uses JBoss DMR. + * + * @author Rob Cernich + */ +public class SwitchYardStoreImpl implements SwitchYardStore { + + // management api + private static final String APPLICATION_NAME = "application-name"; //$NON-NLS-1$ + private static final String GET_VERSION = "get-version"; //$NON-NLS-1$ + private static final String LIST_APPLICATIONS = "list-applications"; //$NON-NLS-1$ + private static final String LIST_SERVICES = "list-services"; //$NON-NLS-1$ + private static final String LIST_REFERENCES = "list-references"; //$NON-NLS-1$ + private static final String MODULE = "module"; //$NON-NLS-1$ + private static final String PROPERTY = "property"; //$NON-NLS-1$ + private static final String READ_APPLICATION = "read-application"; //$NON-NLS-1$ + private static final String READ_SERVICE = "read-service"; //$NON-NLS-1$ + private static final String READ_REFERENCE = "read-reference"; //$NON-NLS-1$ + private static final String SERVICE_NAME = "service-name"; //$NON-NLS-1$ + private static final String SET_APPLICATION_PROPERTY = "set-application-property"; //$NON-NLS-1$ + private static final String SHOW_METRICS = "show-metrics"; //$NON-NLS-1$ + private static final String RESET_METRICS = "reset-metrics"; //$NON-NLS-1$ + private static final String STOP_GATEWAY = "stop-gateway"; //$NON-NLS-1$ + private static final String START_GATEWAY = "start-gateway"; //$NON-NLS-1$ + private static final String SWITCHYARD = NameTokens.SUBSYSTEM; + private static final String THROTTLING = "throttling"; //$NON-NLS-1$ + private static final String UPDATE_THROTTLING = "update-throttling"; //$NON-NLS-1$ + private static final String SERVICE = "service"; //$NON-NLS-1$ + private static final String REFERENCE = "reference"; //$NON-NLS-1$ + private static final String ALL_WILDCARD = "*"; //$NON-NLS-1$ + private static final String PARSE_ERROR_MESSAGE = "Failed to parse data source representation"; //$NON-NLS-1$ + + private final DispatchAsync _dispatcher; + private final BeanFactory _factory; + private final ApplicationMetaData _metadata; + + /** + * Create a new SwitchYardStoreImpl. + * + * @param dispatcher the injected dispatcher. + * @param factory the injected bean factory. + * @param metadata the injected application metadata. + */ + @Inject + public SwitchYardStoreImpl(DispatchAsync dispatcher, BeanFactory factory, ApplicationMetaData metadata) { + this._dispatcher = dispatcher; + this._factory = factory; + this._metadata = metadata; + } + + @Override + public BeanFactory getBeanFactory() { + return _factory; + } + + @Override + public void loadSystemDetails(final AsyncCallback callback) { + // /subsystem=switchyard:get-version() + final ModelNode operation = new ModelNode(); + final ModelNode address = Baseadress.get(); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(OP).set(GET_VERSION); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get().get(RESULT); + SystemDetails systemDetails = null; + if (response.isDefined()) { + systemDetails = createSystemDetails(response); + } + + callback.onSuccess(systemDetails); + } + }); + } + + @Override + public void loadApplications(final AsyncCallback> callback) { + // /subsystem=switchyard:list-applications() + final List applications = new ArrayList(); + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(OP).set(LIST_APPLICATIONS); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get().get(RESULT); + if (response.isDefined()) { + for (final ModelNode applicationNode : response.asList()) { + try { + final Application application = _factory.application().as(); + application.setName(applicationNode.asString()); + applications.add(application); + } catch (IllegalArgumentException e) { + Log.error(PARSE_ERROR_MESSAGE, e); + } + } + + } + + callback.onSuccess(applications); + } + }); + } + + @Override + public void loadApplication(final String applicationName, final AsyncCallback callback) { + // /subsystem=switchyard:read-application(name=applicationName) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(READ_APPLICATION); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(NAME).set(applicationName); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(RESULT)) { + final Application application = createApplication(response.get(RESULT).asList().get(0)); + if (application != null) { + callback.onSuccess(application); + return; + } + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_applicationLoad(applicationName))); + } + }); + } + + @Override + public void loadComponents(final AsyncCallback> callback) { + // /subsystem=switchyard:read-children-names(child-type=module) + final List components = new ArrayList(); + + final ModelNode operation = new ModelNode(); + final ModelNode address = Baseadress.get(); + operation.get(OP).set(READ_CHILDREN_NAMES_OPERATION); + operation.get(CHILD_TYPE).set(MODULE); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get().get(RESULT); + if (response.isDefined()) { + for (final ModelNode componentNode : response.asList()) { + try { + final Component component = _factory.component().as(); + component.setName(componentNode.asString()); + components.add(component); + } catch (IllegalArgumentException e) { + Log.error(PARSE_ERROR_MESSAGE, e); + } + } + + } + + callback.onSuccess(components); + } + }); + } + + @Override + public void loadComponent(final String componentName, final AsyncCallback callback) { + // /subsystem=switchyard/module=componentName:read-resource(recursive=true) + + final ModelNode operation = new ModelNode(); + final ModelNode address = Baseadress.get(); + operation.get(OP).set(READ_RESOURCE_OPERATION); + operation.get(RECURSIVE).set(true); + address.add(SUBSYSTEM, SWITCHYARD); + address.add(MODULE, componentName); + operation.get(OP_ADDR).set(address); + operation.get(NAME).set(componentName); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(RESULT)) { + final Component component = createComponent(response.get(RESULT)); + if (component != null) { + // HACK + component.setName(componentName); + callback.onSuccess(component); + return; + } + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_componentLoad(componentName))); + } + }); + } + + @Override + public void loadServices(final AsyncCallback> callback) { + // /subsystem=switchyard:list-services() + final List services = new ArrayList(); + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(OP).set(LIST_SERVICES); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get().get(RESULT); + if (response.isDefined()) { + for (final ModelNode serviceNode : response.asList()) { + final Service service = createServiceStub(serviceNode); + if (service != null) { + services.add(service); + } + } + + } + + callback.onSuccess(services); + } + }); + } + + @Override + public void loadService(final String serviceName, final String applicationName, + final AsyncCallback callback) { + // /subsystem=switchyard:read-service(service-name=serviceName, + // application-name=applicationName) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(READ_SERVICE); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(SERVICE_NAME).set(serviceName); + operation.get(APPLICATION_NAME).set(applicationName); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(RESULT)) { + final Service service = createService(response.get(RESULT).asList().get(0)); + if (service != null) { + callback.onSuccess(service); + return; + } + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_serviceLoad(serviceName, applicationName))); + } + }); + } + + @Override + public void loadServiceMetrics(final String serviceName, final AsyncCallback callback) { + // /subsystem=switchyard:show-metrics(service-name=serviceName) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(SHOW_METRICS); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(SERVICE_NAME).set(serviceName); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(RESULT)) { + final List metrics = createServiceMetrics(response.get(RESULT)); + if (metrics != null && metrics.size() > 0) { + callback.onSuccess(metrics.get(0)); + return; + } + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_serviceMetricsLoad(serviceName))); + } + }); + } + + @Override + public void loadAllServiceMetrics(final AsyncCallback> callback) { + // /subsystem=switchyard:show-metrics(service-name=*, type=service) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(SHOW_METRICS); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(SERVICE_NAME).set(ALL_WILDCARD); + operation.get(TYPE).set(SERVICE); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(FAILED)) { + callback.onFailure(new Exception(Singleton.MESSAGES.error_allServiceMetricsLoad())); + } else if (response.hasDefined(RESULT)) { + final List metrics = createServiceMetrics(response.get(RESULT)); + callback.onSuccess(metrics); + } else { + callback.onSuccess(null); + } + } + }); + } + + @Override + public void loadAllReferenceMetrics(final AsyncCallback> callback) { + // /subsystem=switchyard:show-metrics(service-name=*, type=reference) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(SHOW_METRICS); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(SERVICE_NAME).set(ALL_WILDCARD); + operation.get(TYPE).set(REFERENCE); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(FAILED)) { + callback.onFailure(new Exception(Singleton.MESSAGES.error_allReferenceMetricsLoad())); + } else if (response.hasDefined(RESULT)) { + final List metrics = createServiceMetrics(response.get(RESULT)); + callback.onSuccess(metrics); + } else { + callback.onSuccess(null); + } + } + }); + } + + @Override + public void loadSystemMetrics(final AsyncCallback callback) { + // /subsystem=switchyard:show-metrics() + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(SHOW_METRICS); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(RESULT)) { + final MessageMetrics metrics = createMessageMetrics(response.get(RESULT).asList().get(0)); + if (metrics != null) { + callback.onSuccess(metrics); + return; + } + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_systemMetricsLoad())); + } + }); + } + + @Override + public void loadReferences(final AsyncCallback> callback) { + // /subsystem=switchyard:list-references() + final List references = new ArrayList(); + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(OP).set(LIST_REFERENCES); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get().get(RESULT); + if (response.isDefined()) { + for (final ModelNode referenceNode : response.asList()) { + final Reference reference = createReferenceStub(referenceNode); + if (reference != null) { + references.add(reference); + } + } + + } + + callback.onSuccess(references); + } + }); + } + + @Override + public void loadReference(final String referenceName, final String applicationName, + final AsyncCallback callback) { + // /subsystem=switchyard:read-reference(reference-name=referenceName, + // application-name=applicationName) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(READ_REFERENCE); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(SERVICE_NAME).set(referenceName); + operation.get(APPLICATION_NAME).set(applicationName); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(RESULT)) { + final Reference reference = createReference(response.get(RESULT).asList().get(0)); + if (reference != null) { + callback.onSuccess(reference); + return; + } + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_referenceLoad(referenceName, applicationName))); + } + }); + } + + @Override + public void loadArtifactReferences(final AsyncCallback> callback) { + // /subsystem=switchyard:read-application() + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(READ_APPLICATION); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (response.hasDefined(FAILED)) { + callback.onFailure(new Exception(Singleton.MESSAGES.error_artifactsLoad())); + } else if (response.hasDefined(RESULT)) { + Map references = new HashMap(); + for (ModelNode node : response.get(RESULT).asList()) { + Application application = createApplication(node); + if (application == null) { + continue; + } + List artifacts = application.getArtifacts(); + if (artifacts == null) { + continue; + } + for (ArtifactReference artifact : artifacts) { + if (references.containsKey(artifact.key())) { + artifact = references.get(artifact.key()); + } else { + ArtifactReference copy = getBeanFactory().artifactReference().as(); + copy.setName(artifact.getName()); + copy.setUrl(artifact.getUrl()); + copy.setApplications(new ArrayList()); + artifact = copy; + references.put(artifact.key(), artifact); + } + artifact.getApplications().add(application); + } + } + callback.onSuccess(new ArrayList(references.values())); + } else { + callback.onSuccess(null); + } + } + }); + } + + @Override + public void setApplicationProperty(final String applicationName, final PropertyRecord prop, + final AsyncCallback callback) { + // /subsystem=switchyard:set-application-property(name=applicationName, + // property=prop) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(SET_APPLICATION_PROPERTY); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(NAME).set(applicationName); + operation.get(PROPERTY).add(prop.getKey(), prop.getValue()); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (!response.hasDefined(FAILED)) { + callback.onSuccess(null); + return; + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_setProperty(prop.getKey()))); + } + }); + } + + @Override + public void resetSystemMetrics(final AsyncCallback callback) { + // /subsystem=switchyard:reset-metrics() + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(RESET_METRICS); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (!response.hasDefined(FAILED)) { + callback.onSuccess(null); + return; + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_resetSystemMetrics(response + .getFailureDescription()))); + } + }); + } + + @Override + public void resetMetrics(final String name, final String applicationName, final AsyncCallback callback) { + // /subsystem=switchyard:reset-metrics(name=name, + // application-name=applicationName) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(RESET_METRICS); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(NAME).set(name); + operation.get(APPLICATION_NAME).set(applicationName); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (!response.hasDefined(FAILED)) { + callback.onSuccess(null); + return; + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_resetObjectMetrics(name, + response.getFailureDescription()))); + } + }); + } + + @Override + public void stopGateway(final String name, final String serviceName, final String applicationName, + final AsyncCallback callback) { + // /subsystem=switchyard:stop-gateway(name=name, + // service-name=serviceName, application-name=applicationName) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(STOP_GATEWAY); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(NAME).set(name); + operation.get(SERVICE_NAME).set(serviceName); + operation.get(APPLICATION_NAME).set(applicationName); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (!response.hasDefined(FAILED)) { + callback.onSuccess(null); + return; + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_stopGateway(name, + response.getFailureDescription()))); + } + }); + } + + @Override + public void startGateway(final String name, final String serviceName, final String applicationName, + final AsyncCallback callback) { + // /subsystem=switchyard:start-gateway(name=name, + // service-name=serviceName, application-name=applicationName) + + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(START_GATEWAY); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(NAME).set(name); + operation.get(SERVICE_NAME).set(serviceName); + operation.get(APPLICATION_NAME).set(applicationName); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (!response.hasDefined(FAILED)) { + callback.onSuccess(null); + return; + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_startGateway(name, + response.getFailureDescription()))); + } + }); + } + + @Override + public void updateThrottling(final Service service, final Throttling throttling, final AsyncCallback callback) { + // /subsystem=switchyard:update-throttling(service-name=name, application-name=applicationName, throttling=throttling) + + final EntityAdapter entityAdapter = new EntityAdapter(Throttling.class, _metadata); + final ModelNode operation = new ModelNode(); + final ModelNode address = RuntimeBaseAddress.get(); + operation.get(OP).set(UPDATE_THROTTLING); + address.add(SUBSYSTEM, SWITCHYARD); + operation.get(OP_ADDR).set(address); + operation.get(SERVICE_NAME).set(service.getName()); + operation.get(APPLICATION_NAME).set(service.getApplication()); + operation.get(THROTTLING).set(entityAdapter.fromEntity(throttling)); + + _dispatcher.execute(new DMRAction(operation), new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + callback.onFailure(caught); + } + + @Override + public void onSuccess(DMRResponse result) { + final ModelNode response = result.get(); + if (!response.hasDefined(FAILED)) { + callback.onSuccess(null); + return; + } + callback.onFailure(new Exception(Singleton.MESSAGES.error_updateThrottling(service.localName(), + response.getFailureDescription()))); + } + }); + } + + @Override + public T processChangeSet(final Class type, final T original, final Map changeSet, + final boolean merge) { + final List properties = _metadata.getBeanMetaData(type).getProperties(); + final T newEntity = (T) _metadata.getFactory(type).create(); + @SuppressWarnings("unchecked") + final Mutator mutator = _metadata.getMutator(type); + + for (PropertyBinding property : properties) { + final String javaName = property.getJavaName(); + Object propertyValue = mutator.getValue(original, javaName); + Object changed = changeSet.get(javaName); + if (changed != null && !changed.equals(propertyValue)) { + mutator.setValue(newEntity, javaName, changed); + } else if (merge) { + mutator.setValue(newEntity, javaName, propertyValue); + } + } + return newEntity; + } + + private SystemDetails createSystemDetails(final ModelNode systemDetailsNode) { + try { + return AutoBeanCodex.decode(_factory, SystemDetails.class, systemDetailsNode.toJSONString(true)).as(); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + return null; + } + } + + private Application createApplication(final ModelNode applicationNode) { + try { + return AutoBeanCodex.decode(_factory, Application.class, applicationNode.toJSONString(true)).as(); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + return null; + } + } + + private Component createComponent(final ModelNode componentNode) { + try { + return AutoBeanCodex.decode(_factory, Component.class, componentNode.toJSONString(true)).as(); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + return null; + } + } + + private Service createServiceStub(final ModelNode serviceNode) { + try { + return AutoBeanCodex.decode(_factory, Service.class, serviceNode.toJSONString(true)).as(); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + return null; + } + } + + private Service createService(final ModelNode serviceNode) { + try { + return AutoBeanCodex.decode(_factory, Service.class, serviceNode.toJSONString(true)).as(); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + return null; + } + } + + private List createServiceMetrics(final ModelNode metricsNode) { + final List items = metricsNode.asList(); + final List metrics = new ArrayList(items.size()); + for (ModelNode item : items) { + try { + metrics.add(AutoBeanCodex.decode(_factory, ServiceMetrics.class, item.toJSONString(true)).as()); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + } + } + return metrics; + } + + private MessageMetrics createMessageMetrics(final ModelNode metricsNode) { + try { + return AutoBeanCodex.decode(_factory, MessageMetrics.class, metricsNode.toJSONString(true)).as(); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + return null; + } + } + + private Reference createReferenceStub(final ModelNode referenceNode) { + try { + return AutoBeanCodex.decode(_factory, Reference.class, referenceNode.toJSONString(true)).as(); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + return null; + } + } + + private Reference createReference(final ModelNode referenceNode) { + try { + return AutoBeanCodex.decode(_factory, Reference.class, referenceNode.toJSONString(true)).as(); + } catch (Exception e) { + Log.error(PARSE_ERROR_MESSAGE, e); + return null; + } + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/SystemDetails.java b/console/gwt/src/main/java/org/switchyard/console/client/model/SystemDetails.java new file mode 100644 index 000000000..7c34b281a --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/SystemDetails.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * SystemDetails + * + * Provides access to details about the SwitchYard system. + * + * @author Rob Cernich + */ +public interface SystemDetails { + + /** + * @return the runtime version. + */ + public String getVersion(); + + /** + * @param version the runtime version. + */ + public void setVersion(String version); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Throttling.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Throttling.java new file mode 100644 index 000000000..51b63b773 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Throttling.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * Throttling + *

+ * Throttling details associated switchyard object. + */ +public interface Throttling { + + /** + * @return true if throttling is enabled. + */ + Boolean isEnabled(); + + /** + * @param enabled true to enable throttling. + */ + void setEnabled(Boolean enabled); + + /** + * @return the maximum number of requests per time period. + */ + Integer getMaxRequests(); + + /** + * @param maxRequests the maximumn number of requests per time period. + */ + void setMaxRequests(Integer maxRequests); + + /** + * @return the time period, in milliseconds, over which requests are + * counted. + */ + Long getTimePeriod(); + + /** + * @param timePeriod the time period, in milliseconds, over which requests + * are counted. + */ + void setTimePeriod(Long timePeriod); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Transformer.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Transformer.java new file mode 100644 index 000000000..93c97e84a --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Transformer.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * Transformer + * + * Represents a SwitchYard configuration transform. + * + * @author Rob Cernich + */ +public interface Transformer { + /** + * @return the from type. + */ + public String getFrom(); + + /** + * @param from the from type. + */ + public void setFrom(String from); + + /** + * @return the to type. + */ + public String getTo(); + + /** + * @param to the to type. + */ + public void setTo(String to); + + /** + * @return the implementation type. + */ + public String getType(); + + /** + * @param type the implementation type. + */ + public void setType(String type); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/model/Validator.java b/console/gwt/src/main/java/org/switchyard/console/client/model/Validator.java new file mode 100644 index 000000000..004d3783b --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/model/Validator.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.model; + +/** + * Validator + * + * Represents a SwitchYard validator. + * + * @author Rob Cernich + */ +public interface Validator { + /** + * @return the type name. + */ + public String getName(); + + /** + * @param name the type name. + */ + public void setName(String name); + + /** + * @return the implementation type. + */ + public String getType(); + + /** + * @param type the implementation type. + */ + public void setType(String type); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationPresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationPresenter.java new file mode 100644 index 000000000..3af2c749f --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationPresenter.java @@ -0,0 +1,289 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.application; + +import java.util.List; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.client.shared.properties.PropertyManagement; +import org.jboss.as.console.client.shared.properties.PropertyRecord; +import org.jboss.as.console.spi.AccessControl; +import org.jboss.ballroom.client.layout.LHSHighlightEvent; +import org.switchyard.console.client.Messages; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Application; +import org.switchyard.console.client.model.ArtifactReference; +import org.switchyard.console.client.model.Reference; +import org.switchyard.console.client.model.Service; +import org.switchyard.console.client.model.SwitchYardStore; +import org.switchyard.console.client.ui.runtime.RuntimePresenter; + +import com.google.gwt.core.client.Scheduler; +import com.google.gwt.http.client.URL; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.inject.Inject; +import com.google.web.bindery.event.shared.EventBus; +import com.gwtplatform.mvp.client.Presenter; +import com.gwtplatform.mvp.client.View; +import com.gwtplatform.mvp.client.annotations.NameToken; +import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; +import com.gwtplatform.mvp.client.annotations.TabInfo; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import com.gwtplatform.mvp.client.proxy.PlaceRequest; +import com.gwtplatform.mvp.client.proxy.RevealContentEvent; +import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace; + +/** + * ApplicationPresenter + * + * Presenter for SwitchYard application. + * + * @author Rob Cernich + */ +public class ApplicationPresenter extends Presenter + implements PropertyManagement { + + /** + * MyProxy + * + * The proxy type associated with this presenter. + */ + @ProxyCodeSplit + @NameToken(NameTokens.APPLICATIONS_PRESENTER) + @AccessControl(resources = {"/{selected.host}/{selected.server}/subsystem=switchyard" }) + public interface MyProxy extends TabContentProxyPlace { + } + + @TabInfo(container = RuntimePresenter.class, priority = 1) + static String getLabel(Messages messages) { + return messages.label_applications(); + } + + /** + * MyView + * + * The view type associated with this presenter. + */ + public interface MyView extends View { + /** + * @param presenter the associated presenter. + */ + void setPresenter(ApplicationPresenter presenter); + + /** + * @param applications the applications deployed on the server. + */ + void setApplications(List applications); + + /** + * @param application the application being viewed/processed/edited. + */ + void setApplication(Application application); + } + + private final PlaceManager _placeManager; + private final SwitchYardStore _switchYardStore; + private String _applicationName; + + /** + * Create a new ApplicationPresenter. + * + * @param eventBus the injected EventBus. + * @param view the injected MyView. + * @param proxy the injected MyProxy. + * @param placeManager the injected PlaceManager. + * @param switchYardStore the injected SwitchYardStore. + */ + @Inject + public ApplicationPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, + SwitchYardStore switchYardStore) { + super(eventBus, view, proxy); + + _placeManager = placeManager; + _switchYardStore = switchYardStore; + } + + /** + * Notifies the presenter that the user has selected an application. The + * presenter will load the application details and pass them back to the + * view to be displayed. + * + * @param application the selected application. + */ + public void onApplicationSelected(Application application) { + PlaceRequest request = new PlaceRequest(NameTokens.APPLICATIONS_PRESENTER); + if (application != null) { + request = request.with(NameTokens.APPLICATION_NAME_PARAM, URL.encode(application.getName())); + } + _placeManager.revealRelativePlace(request, -1); + } + + /** + * Notifies the presenter that the user has selected an artifact reference. + * The presenter will navigate to the artifacts page. + * + * @param artifact the selected artifact. + */ + public void onArtifactSelected(ArtifactReference artifact) { + PlaceRequest request = new PlaceRequest(NameTokens.ARTIFACTS_PRESENTER); + if (artifact != null) { + request = request.with(NameTokens.ARTIFACT_REFERENCE_KEY_PARAM, URL.encode(artifact.key())); + } + _placeManager.revealRelativePlace(request, -1); + } + + /** + * Notifies the presenter that the user wishes to view details about a + * specific service. + * + * @param service the service. + * @param application the application containing the service. + */ + public void onNavigateToService(Service service, Application application) { + if (service == null || application == null) { + Console.error(Singleton.MESSAGES.error_navigateToService()); + return; + } + _placeManager.revealRelativePlace( + new PlaceRequest(NameTokens.SERVICES_PRESENTER).with(NameTokens.SERVICE_NAME_PARAM, + URL.encode(service.getName())).with(NameTokens.APPLICATION_NAME_PARAM, + URL.encode(application.getName())), -1); + } + + /** + * Notifies the presenter that the user wishes to view details about a + * specific reference. + * + * @param reference the reference. + * @param application the application containing the reference. + */ + public void onNavigateToReference(Reference reference, Application application) { + if (reference == null || application == null) { + Console.error(Singleton.MESSAGES.error_navigateToReference()); + return; + } + _placeManager.revealRelativePlace( + new PlaceRequest(NameTokens.REFERENCES_PRESENTER).with(NameTokens.REFERENCE_NAME_PARAM, + URL.encode(reference.getName())).with(NameTokens.APPLICATION_NAME_PARAM, + URL.encode(application.getName())), -1); + } + + @Override + public void onCreateProperty(String reference, PropertyRecord prop) { + } + + @Override + public void onDeleteProperty(String reference, PropertyRecord prop) { + } + + @Override + public void onChangeProperty(String reference, PropertyRecord prop) { + if (reference == null) { + return; + } + _switchYardStore.setApplicationProperty(reference, prop, new AsyncCallback() { + @Override + public void onSuccess(Void result) { + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + @Override + public void launchNewPropertyDialoge(String reference) { + } + + @Override + public void closePropertyDialoge() { + } + + @Override + protected void onBind() { + super.onBind(); + getView().setPresenter(this); + } + + @Override + public void prepareFromRequest(PlaceRequest request) { + super.prepareFromRequest(request); + _applicationName = request.getParameter(NameTokens.APPLICATION_NAME_PARAM, null); + if (_applicationName != null) { + _applicationName = URL.decode(_applicationName); + } + } + + @Override + protected void onReveal() { + super.onReveal(); + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + fireEvent(new LHSHighlightEvent(NameTokens.RUNTIME_OPERATIONS_PRESENTER)); + } + }); + } + + @Override + protected void onReset() { + super.onReset(); + + loadApplicationsList(); + loadApplication(); + } + + @Override + protected void revealInParent() { + RevealContentEvent.fire(this, RuntimePresenter.TYPE_SET_TAB_CONTENT, this); + } + + private void loadApplicationsList() { + _switchYardStore.loadApplications(new AsyncCallback>() { + @Override + public void onSuccess(List applications) { + getView().setApplications(applications); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void loadApplication() { + if (_applicationName == null) { + getView().setApplication(_switchYardStore.getBeanFactory().application().as()); + return; + } + _switchYardStore.loadApplication(_applicationName, new AsyncCallback() { + + @Override + public void onSuccess(Application result) { + getView().setApplication(result); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationReferencesList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationReferencesList.java new file mode 100644 index 000000000..3f68caa2b --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationReferencesList.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.application; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Application; +import org.switchyard.console.client.model.Reference; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.cell.client.ClickableTextCell; +import com.google.gwt.cell.client.FieldUpdater; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ApplicationReferencesList + * + * Wraps a table control for displaying an application's references. + * + * @author Rob Cernich + */ +public class ApplicationReferencesList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(Reference item) { + return item.getName(); + } + }; + + private Application _application; + private final ApplicationPresenter _presenter; + + ApplicationReferencesList(ApplicationPresenter presenter) { + super(Singleton.MESSAGES.label_references()); + _presenter = presenter; + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + Column nameColumn = new Column(new ClickableTextCell()) { + @Override + public String getValue(Reference reference) { + return reference.localName(); + } + }; + nameColumn.setFieldUpdater(new FieldUpdater() { + @Override + public void update(int index, Reference object, String value) { + _presenter.onNavigateToReference(object, _application); + } + }); + nameColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(nameColumn); + } + + /** + * @param application the application providing the data. + */ + public void setApplication(Application application) { + _application = application; + setData(application.getReferences()); + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationServicesEditor.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationServicesEditor.java new file mode 100644 index 000000000..39fc7090f --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationServicesEditor.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.application; + +import org.switchyard.console.client.model.Application; + +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * ApplicationServicesEditor + * + * Editor widget for SwitchYard application details. + * + * @author Rob Cernich + */ +public class ApplicationServicesEditor { + + private ApplicationPresenter _presenter; + + private ApplicationServicesList _applicationServicesList; + private ComponentServicesList _componentServicesList; + + /** + * Create a new ApplicationServicesEditor. + * + * @param presenter the associated presenter. + */ + public ApplicationServicesEditor(ApplicationPresenter presenter) { + _presenter = presenter; + } + + /** + * @return this editor as a Widget. + */ + public Widget asWidget() { + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + + _applicationServicesList = new ApplicationServicesList(_presenter); + _componentServicesList = new ComponentServicesList(); + + layout.add(_applicationServicesList.asWidget()); + layout.add(_componentServicesList.asWidget()); + + _componentServicesList.bind(_applicationServicesList); + + return layout; + } + + /** + * @param application the application being edited by this editor. + */ + public void setApplication(Application application) { + _applicationServicesList.setApplication(application); + _componentServicesList.setData(application.getComponentServices()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationServicesList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationServicesList.java new file mode 100644 index 000000000..3a01f3227 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationServicesList.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.application; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Application; +import org.switchyard.console.client.model.Service; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.cell.client.ClickableTextCell; +import com.google.gwt.cell.client.FieldUpdater; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ApplicationServicesList + * + * Wraps a table control for displaying an application's services. + * + * @author Rob Cernich + */ +public class ApplicationServicesList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(Service item) { + return item.getName(); + } + }; + + private Application _application; + private final ApplicationPresenter _presenter; + + ApplicationServicesList(ApplicationPresenter presenter) { + super(Singleton.MESSAGES.label_services()); + _presenter = presenter; + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + Column nameColumn = new Column(new ClickableTextCell()) { + @Override + public String getValue(Service service) { + return service.localName(); + } + }; + nameColumn.setFieldUpdater(new FieldUpdater() { + @Override + public void update(int index, Service object, String value) { + _presenter.onNavigateToService(object, _application); + } + }); + nameColumn.setSortable(true); + + TextColumn promotesColumn = new TextColumn() { + @Override + public String getValue(Service service) { + return NameTokens.parseQName(service.getPromotedService())[1]; + } + }; + promotesColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(promotesColumn, createColumnCommparator(promotesColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(promotesColumn, Singleton.MESSAGES.label_promotedService()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(nameColumn); + } + + /** + * @param application the application providing the data. + */ + public void setApplication(Application application) { + _application = application; + setData(application.getServices()); + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationTransformationsEditor.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationTransformationsEditor.java new file mode 100644 index 000000000..8ccb256ff --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationTransformationsEditor.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.application; + +import org.switchyard.console.client.model.Application; +import org.switchyard.console.client.ui.common.TransformersList; + +import com.google.gwt.user.client.ui.Widget; + +/** + * ApplicationTransformationsEditor + * + * Editor widget for SwitchYard application transform details. + * + * @author Rob Cernich + */ +public class ApplicationTransformationsEditor { + + private ApplicationPresenter _presenter; + private TransformersList _transformersList; + + /** + * Create a new ApplicationTransformationsEditor. + * + * @param presenter the associated presenter. + */ + public ApplicationTransformationsEditor(ApplicationPresenter presenter) { + _presenter = presenter; + } + + /** + * @return this editor as a Widget. + */ + public Widget asWidget() { + _transformersList = new TransformersList(); + + return _transformersList.asWidget(); + } + + /** + * @param application the application being edited by this editor. + */ + public void setApplication(Application application) { + _transformersList.setData(application.getTransformers()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationView.java new file mode 100644 index 000000000..a85c438e9 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationView.java @@ -0,0 +1,173 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.application; + +import java.util.ArrayList; +import java.util.List; + +import org.jboss.as.console.client.core.DisposableViewImpl; +import org.jboss.as.console.client.layout.OneToOneLayout; +import org.jboss.as.console.client.layout.SimpleLayout; +import org.jboss.as.console.client.shared.properties.PropertyEditor; +import org.jboss.as.console.client.shared.properties.PropertyManagement; +import org.jboss.as.console.client.shared.properties.PropertyRecord; +import org.jboss.ballroom.client.widgets.forms.Form; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Application; +import org.switchyard.console.client.ui.artifacts.ArtifactReferencesList; +import org.switchyard.console.client.ui.common.ValidatorsList; +import org.switchyard.console.client.ui.widgets.LocalNameFormItem; +import org.switchyard.console.client.ui.widgets.NamespaceFormItem; + +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.SelectionChangeEvent; +import com.google.gwt.view.client.SelectionChangeEvent.Handler; + +/** + * ApplicationView + * + * View for SwitchYard application details. + * + * @author Rob Cernich + */ +public class ApplicationView extends DisposableViewImpl implements ApplicationPresenter.MyView { + + private ApplicationPresenter _presenter; + + private Form _applicationDetailsForm; + private ApplicationServicesEditor _servicesEditor; + private ApplicationReferencesList _referencesEditor; + private PropertyEditor _propertiesEditor; + private ArtifactReferencesList _artifactReferencesList; + private ApplicationTransformationsEditor _transformationsEditor; + private ApplicationsList _applicationsList; + private Application _selectedApplication; + private ValidatorsList _validatorsList; + + @Override + public Widget createWidget() { + _applicationsList = new ApplicationsList(); + _applicationsList.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { + @Override + public void onSelectionChange(SelectionChangeEvent event) { + // prevent infinite recursion + if (_applicationsList.getSelection() != _selectedApplication) { + _presenter.onApplicationSelected(_applicationsList.getSelection()); + } + } + }); + + VerticalPanel applicationDetailsPanel = new VerticalPanel(); + applicationDetailsPanel.setStyleName("fill-layout-width"); //$NON-NLS-1$ + + _applicationDetailsForm = new Form(Application.class); + // XXX: '_' included in names to workaround bug in form builder + _applicationDetailsForm.setFields(new LocalNameFormItem("name_1", Singleton.MESSAGES.label_applicationName()), //$NON-NLS-1$ + new NamespaceFormItem("name_2", Singleton.MESSAGES.label_applicationNamespace())); //$NON-NLS-1$ + Widget formWidget = _applicationDetailsForm.asWidget(); + formWidget.getElement().setAttribute("style", "margin:15px"); //$NON-NLS-1$ //$NON-NLS-2$ + + _servicesEditor = new ApplicationServicesEditor(_presenter); + _referencesEditor = new ApplicationReferencesList(_presenter); + // read only for now + _propertiesEditor = new PropertyEditor(new PropertyManagement() { + @Override + public void onDeleteProperty(String reference, PropertyRecord prop) { + } + + @Override + public void onCreateProperty(String reference, PropertyRecord prop) { + } + + @Override + public void onChangeProperty(String reference, PropertyRecord prop) { + } + + @Override + public void launchNewPropertyDialoge(String reference) { + } + + @Override + public void closePropertyDialoge() { + } + }, true); + _artifactReferencesList = new ArtifactReferencesList(); + _transformationsEditor = new ApplicationTransformationsEditor(_presenter); + _validatorsList = new ValidatorsList(); + + _artifactReferencesList.addSelectionChangeHandler(new Handler() { + @Override + public void onSelectionChange(SelectionChangeEvent event) { + _presenter.onArtifactSelected(_artifactReferencesList.getSelection()); + } + }); + + // this creates the controls, but we can't use the layout, so we + // reparent the panel containing the controls + OneToOneLayout applicationDetailsLayout = new OneToOneLayout() + .setPlain(true) + .setHeadline(Singleton.MESSAGES.label_applicationDetails()) + .setDescription( + Singleton.MESSAGES.description_applicationDetails()) + .setMaster(null, formWidget).addDetail(Singleton.MESSAGES.label_services(), _servicesEditor.asWidget()) + .addDetail(Singleton.MESSAGES.label_references(), _referencesEditor.asWidget()) + .addDetail(Singleton.MESSAGES.label_properties(), _propertiesEditor.asWidget()) + .addDetail(Singleton.MESSAGES.label_artifacts(), _artifactReferencesList.asWidget()) + .addDetail(Singleton.MESSAGES.label_transformers(), _transformationsEditor.asWidget()) + .addDetail(Singleton.MESSAGES.label_validators(), _validatorsList.asWidget()); + applicationDetailsLayout.build(); + formWidget.getParent().setStyleName("fill-layout-width"); //$NON-NLS-1$ + + /* disable updating "key" field. */ + _propertiesEditor.getPropertyTable().getColumn(0).setFieldUpdater(null); + + SimpleLayout layout = new SimpleLayout() + .setPlain(true) + .setTitle(Singleton.MESSAGES.label_switchYardApplications()) + .setHeadline(Singleton.MESSAGES.label_applications()) + .setDescription( + Singleton.MESSAGES.description_applications()) + .addContent(Singleton.MESSAGES.label_applications(), _applicationsList.asWidget()) + .addContent(Singleton.MESSAGES.label_applicationDetails(), formWidget.getParent()); + return layout.build(); + } + + @Override + public void setPresenter(ApplicationPresenter presenter) { + _presenter = presenter; + } + + @Override + public void setApplications(List applications) { + _applicationsList.setData(applications); + } + + @Override + public void setApplication(Application application) { + _selectedApplication = application; + _applicationDetailsForm.clearValues(); + _applicationDetailsForm.edit(application); + _applicationsList.setSelection(application); + _artifactReferencesList.setData(application == null ? null : application.getArtifacts()); + _servicesEditor.setApplication(application); + _referencesEditor.setApplication(application); + _propertiesEditor.setProperties(application == null ? null : application.getName(), application == null + || application.getProperties() == null ? new ArrayList() : application.getProperties()); + _transformationsEditor.setApplication(application); + _validatorsList.setData(application == null ? null : application.getValidators()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationsList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationsList.java new file mode 100644 index 000000000..1a54b8d62 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ApplicationsList.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.application; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Application; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ApplicationsList + * + * Wraps a table control for displaying applications. + * + * @author Rob Cernich + */ +public class ApplicationsList extends AbstractDataTable { + + /** + * Create a new ApplicationsList. + */ + public ApplicationsList() { + this(Singleton.MESSAGES.label_applications()); + } + + /** + * Create a new ApplicationsList. + * + * @param title the title to display for the list + */ + public ApplicationsList(String title) { + super(title); + } + + @Override + protected ProvidesKey createKeyProvider() { + return new ProvidesKey() { + @Override + public Object getKey(Application item) { + return item.getName(); + } + }; + + } + + @SuppressWarnings("unchecked") + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + final TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(Application application) { + return application.localName(); + } + }; + nameColumn.setSortable(true); + + final TextColumn namespaceColumn = new TextColumn() { + @Override + public String getValue(Application application) { + return application.namespace(); + } + }; + namespaceColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(namespaceColumn, createColumnCommparator(namespaceColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(namespaceColumn, Singleton.MESSAGES.label_targetNamespace()); + table.addColumnSortHandler(sortHandler); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(namespaceColumn); + table.getColumnSortList().push(nameColumn); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ComponentReferencesList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ComponentReferencesList.java new file mode 100644 index 000000000..044c70e2e --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ComponentReferencesList.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.application; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.ComponentReference; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ComponentReferencesList + * + * Wraps a table control for displaying a service's references. + * + * @author Rob Cernich + */ +public class ComponentReferencesList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(ComponentReference item) { + return item.getName(); + } + }; + + ComponentReferencesList() { + super(Singleton.MESSAGES.label_references()); + } + + protected void createColumns(DefaultCellTable table, + ListDataProvider dataProvider) { + TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(ComponentReference reference) { + return reference.localName(); + } + }; + nameColumn.setSortable(true); + + TextColumn interfaceColumn = new TextColumn() { + @Override + public String getValue(ComponentReference reference) { + return reference.getInterface(); + } + }; + interfaceColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(interfaceColumn, createColumnCommparator(interfaceColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(interfaceColumn, Singleton.MESSAGES.label_interface()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(nameColumn); + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ComponentServicesList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ComponentServicesList.java new file mode 100644 index 000000000..3ff4f306c --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ComponentServicesList.java @@ -0,0 +1,155 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.application; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.jboss.ballroom.client.widgets.window.DefaultWindow; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.ComponentService; +import org.switchyard.console.client.model.Service; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.cell.client.ButtonCell; +import com.google.gwt.cell.client.FieldUpdater; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; +import com.google.gwt.view.client.SelectionChangeEvent; + +/** + * ComponentServicesList + * + * Wraps a table control for displaying an application's component services. + * + * @author Rob Cernich + */ +public class ComponentServicesList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(ComponentService item) { + return item.getName(); + } + }; + + private DefaultWindow _implementationDetailsWindow; + private ImplementationDetailsWidget _implementationDetailsWidget; + + ComponentServicesList() { + super(Singleton.MESSAGES.label_componentServices()); + } + + @Override + protected void createColumns(DefaultCellTable table, + ListDataProvider dataProvider) { + TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(ComponentService service) { + return service.localName(); + } + }; + nameColumn.setSortable(true); + + TextColumn interfaceColumn = new TextColumn() { + @Override + public String getValue(ComponentService service) { + return service.getInterface(); + } + }; + interfaceColumn.setSortable(true); + + Column implementationColumn = new Column( + new ButtonCell()) { + @Override + public String getValue(ComponentService dummy) { + return Singleton.MESSAGES.button_viewDetails(); + } + }; + implementationColumn.setFieldUpdater(new FieldUpdater() { + @Override + public void update(int index, ComponentService service, String value) { + showDetails(service); + } + }); + implementationColumn.setSortable(false); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(interfaceColumn, createColumnCommparator(interfaceColumn)); + sortHandler.setComparator(implementationColumn, createColumnCommparator(implementationColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(interfaceColumn, Singleton.MESSAGES.label_interface()); + table.addColumn(implementationColumn, Singleton.MESSAGES.label_implementation()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(nameColumn); + + createImplementationsDetailsWindow(); + } + + /** + * Bind this control to a {@link ApplicationServicesList}. + * + * @param applicationServicesList the {@link ApplicationServicesList} to listen to. + */ + public void bind(final ApplicationServicesList applicationServicesList) { + applicationServicesList.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { + @Override + public void onSelectionChange(SelectionChangeEvent event) { + Service selected = applicationServicesList.getSelection(); + if (selected == null) { + return; + } + String promotedServiceName = selected.getPromotedService(); + if (promotedServiceName == null) { + return; + } + for (ComponentService service : getData()) { + if (promotedServiceName.equals(KEY_PROVIDER.getKey(service))) { + setSelection(service); + return; + } + } + setSelection(null); + } + }); + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + + private void showDetails(ComponentService service) { + _implementationDetailsWidget.setService(service); + _implementationDetailsWindow.center(); + } + + private void createImplementationsDetailsWindow() { + _implementationDetailsWindow = new DefaultWindow(Singleton.MESSAGES.label_implementationDetails()); + _implementationDetailsWindow.setGlassEnabled(true); + _implementationDetailsWindow.setAutoHideEnabled(true); + _implementationDetailsWindow.setAutoHideOnHistoryEventsEnabled(true); + _implementationDetailsWindow.setWidth(600); + _implementationDetailsWindow.setHeight(360); + + _implementationDetailsWidget = new ImplementationDetailsWidget(); + _implementationDetailsWindow.setWidget(_implementationDetailsWidget.asWidget()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ImplementationDetailsWidget.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ImplementationDetailsWidget.java new file mode 100644 index 000000000..642d15c1c --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/application/ImplementationDetailsWidget.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.application; + +import org.jboss.ballroom.client.widgets.ContentGroupLabel; +import org.jboss.ballroom.client.widgets.ContentHeaderLabel; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.ComponentService; + +import com.google.gwt.dom.client.Element; +import com.google.gwt.user.client.DOM; +import com.google.gwt.user.client.ui.FlowPanel; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.ScrollPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * ImplementationDetailsWidget + * + * Provides a widget for displaying details about a component service's + * implementation. + * + * @author Rob Cernich + */ +public class ImplementationDetailsWidget { + + private ContentHeaderLabel _serviceNameLabel; + private ContentHeaderLabel _implementationTypeHeaderLabel; + private ComponentReferencesList _referencesList; + private Element _implementationDetails; + + /** + * Create a new ImplementationDetailsWidget. + */ + public ImplementationDetailsWidget() { + } + + /** + * @return the widget + */ + public Widget asWidget() { + FlowPanel content = new FlowPanel(); + content.setStyleName("fill-layout"); //$NON-NLS-1$ + + _serviceNameLabel = new ContentHeaderLabel(); + content.add(_serviceNameLabel); + + _implementationTypeHeaderLabel = new ContentHeaderLabel(); + content.add(_implementationTypeHeaderLabel); + + _referencesList = new ComponentReferencesList(); + content.add(_referencesList.asWidget()); + + _implementationDetails = DOM.createElement("pre"); //$NON-NLS-1$ + + Element code = DOM.createElement("code"); //$NON-NLS-1$ + code.appendChild(_implementationDetails); + + HTML html = new HTML(); + html.getElement().appendChild(code); + + content.add(new ContentGroupLabel(Singleton.MESSAGES.label_rawConfiguration())); + content.add(html); + + ScrollPanel panel = new ScrollPanel(); + panel.add(content); + + return panel; + } + + /** + * Updates the widget with the information from the specified service. + * + * @param service the service + */ + public void setService(ComponentService service) { + _serviceNameLabel.setText(service.localName()); + _implementationTypeHeaderLabel.setText(Singleton.MESSAGES.label_implementationInstance(service.getImplementation())); + _referencesList.setData(service.getReferences()); + _implementationDetails.setInnerText(service.getImplementationConfiguration()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactPresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactPresenter.java new file mode 100644 index 000000000..504ca6254 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactPresenter.java @@ -0,0 +1,186 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.artifacts; + +import java.util.List; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.client.shared.subsys.RevealStrategy; +import org.jboss.as.console.spi.AccessControl; +import org.jboss.ballroom.client.layout.LHSHighlightEvent; +import org.switchyard.console.client.Messages; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Application; +import org.switchyard.console.client.model.ArtifactReference; +import org.switchyard.console.client.model.SwitchYardStore; +import org.switchyard.console.client.ui.runtime.RuntimePresenter; + +import com.google.gwt.core.client.Scheduler; +import com.google.gwt.http.client.URL; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.inject.Inject; +import com.google.web.bindery.event.shared.EventBus; +import com.gwtplatform.mvp.client.Presenter; +import com.gwtplatform.mvp.client.View; +import com.gwtplatform.mvp.client.annotations.NameToken; +import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; +import com.gwtplatform.mvp.client.annotations.TabInfo; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import com.gwtplatform.mvp.client.proxy.PlaceRequest; +import com.gwtplatform.mvp.client.proxy.RevealContentEvent; +import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace; + +/** + * ArtifactPresenter + * + * Presenter for SwitchYard application. + * + * @author Rob Cernich + */ +public class ArtifactPresenter extends Presenter { + + /** + * MyProxy + * + * The proxy type associated with this presenter. + */ + @ProxyCodeSplit + @NameToken(NameTokens.ARTIFACTS_PRESENTER) + @AccessControl(resources = {"/{selected.host}/{selected.server}/subsystem=switchyard" }) + public interface MyProxy extends TabContentProxyPlace { + } + + @TabInfo(container = RuntimePresenter.class, priority = 4) + static String getLabel(Messages messages) { + return messages.label_artifacts(); + } + + /** + * MyView + * + * The view type associated with this presenter. + */ + public interface MyView extends View { + /** + * @param presenter the associated presenter. + */ + void setPresenter(ArtifactPresenter presenter); + + /** + * @param artifacts referenced by applications. + */ + void setArtifacts(List artifacts); + + /** + * @param artifactKey the selected artifact. + */ + void setSelectedArtifact(String artifactKey); + } + + private final PlaceManager _placeManager; + private final RevealStrategy _revealStrategy; + private final SwitchYardStore _switchYardStore; + private String _artifactKey; + + /** + * Create a new ArtifactPresenter. + * + * @param eventBus the injected EventBus. + * @param view the injected MyView. + * @param proxy the injected MyProxy. + * @param placeManager the injected PlaceManager. + * @param revealStrategy the RevealStrategy + * @param switchYardStore the injected SwitchYardStore. + */ + @Inject + public ArtifactPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, + RevealStrategy revealStrategy, SwitchYardStore switchYardStore) { + super(eventBus, view, proxy); + + _placeManager = placeManager; + _revealStrategy = revealStrategy; + _switchYardStore = switchYardStore; + } + + /** + * Navigates to the application page, displaying the details of the + * application. + * + * @param application the selected application + */ + public void onApplicationSelected(Application application) { + if (application == null) { + Console.error(Singleton.MESSAGES.error_navigateToApplication()); + return; + } + _placeManager.revealRelativePlace( + new PlaceRequest(NameTokens.APPLICATIONS_PRESENTER).with(NameTokens.APPLICATION_NAME_PARAM, + URL.encode(application.getName())), -1); + } + + @Override + protected void onBind() { + super.onBind(); + getView().setPresenter(this); + } + + @Override + public void prepareFromRequest(PlaceRequest request) { + super.prepareFromRequest(request); + _artifactKey = request.getParameter(NameTokens.ARTIFACT_REFERENCE_KEY_PARAM, null); + if (_artifactKey != null) { + _artifactKey = URL.decode(_artifactKey); + } + } + + @Override + protected void onReveal() { + super.onReveal(); + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + fireEvent(new LHSHighlightEvent(NameTokens.RUNTIME_OPERATIONS_PRESENTER)); + } + }); + } + + @Override + protected void onReset() { + super.onReset(); + loadArtifactReferences(); + } + + @Override + protected void revealInParent() { + RevealContentEvent.fire(this, RuntimePresenter.TYPE_SET_TAB_CONTENT, this); + } + + private void loadArtifactReferences() { + _switchYardStore.loadArtifactReferences(new AsyncCallback>() { + @Override + public void onSuccess(List artifacts) { + getView().setArtifacts(artifacts); + getView().setSelectedArtifact(_artifactKey); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactReferencesList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactReferencesList.java new file mode 100644 index 000000000..8abea2c42 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactReferencesList.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.artifacts; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.ArtifactReference; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ArtifactReferencesList + * + * Wraps a table control for displaying artifact references. + * + * @author Rob Cernich + */ +public class ArtifactReferencesList extends AbstractDataTable { + + /** + * Create a new ArtifactReferencesList. + */ + public ArtifactReferencesList() { + super(Singleton.MESSAGES.label_artifactReferences()); + } + + @Override + protected ProvidesKey createKeyProvider() { + return new ProvidesKey() { + @Override + public Object getKey(ArtifactReference item) { + return item.key(); + } + }; + + } + + @SuppressWarnings("unchecked") + @Override + protected void createColumns(DefaultCellTable table, + ListDataProvider dataProvider) { + final TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(ArtifactReference reference) { + return reference.getName(); + } + }; + nameColumn.setSortable(true); + + final TextColumn urlColumn = new TextColumn() { + @Override + public String getValue(ArtifactReference reference) { + return reference.getUrl(); + } + }; + urlColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(urlColumn, createColumnCommparator(urlColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(urlColumn, Singleton.MESSAGES.label_url()); + table.addColumnSortHandler(sortHandler); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(urlColumn); + table.getColumnSortList().push(nameColumn); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactReferencesView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactReferencesView.java new file mode 100644 index 000000000..1e6fa8324 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/artifacts/ArtifactReferencesView.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.artifacts; + +import java.util.List; + +import org.jboss.as.console.client.core.DisposableViewImpl; +import org.jboss.as.console.client.layout.SimpleLayout; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.ArtifactReference; +import org.switchyard.console.client.ui.application.ApplicationsList; +import org.switchyard.console.client.ui.artifacts.ArtifactPresenter.MyView; + +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.SelectionChangeEvent; +import com.google.gwt.view.client.SelectionChangeEvent.Handler; + +/** + * ArtifactReferencesView + * + *

+ * Displays artifacts and the applications referencing them. + * + * @author Rob Cernich + */ +public class ArtifactReferencesView extends DisposableViewImpl implements MyView { + + private ArtifactPresenter _presenter; + private ArtifactReferencesList _artifactReferencesList; + private ApplicationsList _applicationsList; + private ArtifactReference _selectedArtifact; + + @Override + public Widget createWidget() { + _artifactReferencesList = new ArtifactReferencesList(); + _applicationsList = new ApplicationsList(Singleton.MESSAGES.label_applicationsUsingArtifacts()); + + _artifactReferencesList.addSelectionChangeHandler(new Handler() { + @Override + public void onSelectionChange(SelectionChangeEvent event) { + if (_artifactReferencesList.getSelection() != _selectedArtifact) { + _selectedArtifact = _artifactReferencesList.getSelection(); + _applicationsList.setData(_selectedArtifact == null ? null : _selectedArtifact.getApplications()); + } + } + }); + + _applicationsList.addSelectionChangeHandler(new Handler() { + @Override + public void onSelectionChange(SelectionChangeEvent event) { + _presenter.onApplicationSelected(_applicationsList.getSelection()); + } + }); + + SimpleLayout layout = new SimpleLayout() + .setPlain(true) + .setTitle(Singleton.MESSAGES.label_switchYardArtifactReferences()) + .setHeadline(Singleton.MESSAGES.label_artifactReferences()) + .setDescription( + Singleton.MESSAGES.description_artifactReferences()) + .addContent(Singleton.MESSAGES.label_artifactReferences(), _artifactReferencesList.asWidget()) + .addContent(Singleton.MESSAGES.label_referencingApplications(), _applicationsList.asWidget()); + + return layout.build(); + } + + @Override + public void setPresenter(ArtifactPresenter presenter) { + _presenter = presenter; + } + + @Override + public void setArtifacts(List artifacts) { + _artifactReferencesList.setData(artifacts); + } + + @Override + public void setSelectedArtifact(String artifactKey) { + if (artifactKey == null) { + _artifactReferencesList.setSelection(null); + return; + } + + List artifacts = _artifactReferencesList.getData(); + if (artifacts == null) { + return; + } + for (ArtifactReference artifact : artifacts) { + if (artifactKey.equals(artifact.key())) { + _artifactReferencesList.setSelection(artifact); + return; + } + } + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/common/AbstractDataTable.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/AbstractDataTable.java new file mode 100644 index 000000000..ad878bf40 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/AbstractDataTable.java @@ -0,0 +1,161 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.common; + +import java.util.Comparator; +import java.util.List; + +import org.jboss.ballroom.client.widgets.ContentGroupLabel; +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.jboss.ballroom.client.widgets.tables.DefaultPager; + +import com.google.gwt.event.shared.HandlerRegistration; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; +import com.google.gwt.view.client.SelectionChangeEvent; +import com.google.gwt.view.client.SingleSelectionModel; + +/** + * AbstractDataTable + * + * Wraps a table control for displaying data. + * + * @param the type of data displayed by the table. + * + * @author Rob Cernich + */ +public abstract class AbstractDataTable { + + private VerticalPanel _layout; + private SingleSelectionModel _selectionModel; + private DefaultCellTable _table; + private ListDataProvider _dataProvider; + + protected AbstractDataTable(String label) { + _layout = new VerticalPanel(); + _layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + _layout.getElement().setAttribute("style", "padding-top:5px;"); //$NON-NLS-1$ //$NON-NLS-2$ + + _table = new DefaultCellTable(5); + + ProvidesKey keyProvider = createKeyProvider(); + + _selectionModel = createSelectionModel(keyProvider); + _table.setSelectionModel(_selectionModel); + + _dataProvider = new ListDataProvider(keyProvider); + _dataProvider.addDataDisplay(_table); + + createColumns(_table, _dataProvider); + + DefaultPager pager = new DefaultPager(); + pager.setDisplay(_table); + + _layout.add(new ContentGroupLabel(label)); + _layout.add(_table); + _layout.add(pager); + } + + /** + * @return this object's widget. + */ + public Widget asWidget() { + return _layout; + } + + /** + * Register a selection change handler with the list. + * + * @param handler the handler + * @return the {@link HandlerRegistration} + */ + public HandlerRegistration addSelectionChangeHandler(SelectionChangeEvent.Handler handler) { + return _selectionModel.addSelectionChangeHandler(handler); + } + + /** + * @return the selected item + */ + public T getSelection() { + return _selectionModel.getSelectedObject(); + } + + /** + * Selects the specified item in the list. + * + * @param selection the item to select. + */ + public void setSelection(T selection) { + _selectionModel.setSelected(selection, true); + } + + /** + * @param data the data. + */ + public void setData(List data) { + _dataProvider.getList().clear(); + if (data != null) { + _dataProvider.getList().addAll(data); + ColumnSortEvent.fire(_table, _table.getColumnSortList()); + } + } + + /** + * @return the data associated with the list. + */ + public List getData() { + return _dataProvider.getList(); + } + + /** + * @return a new key provider for the table. + */ + protected abstract ProvidesKey createKeyProvider(); + + protected SingleSelectionModel createSelectionModel(ProvidesKey keyProvider) { + return new AlwaysFireSingleSelectionModel(keyProvider); + } + + protected Comparator createColumnCommparator(final Column column) { + return new Comparator() { + @Override + public int compare(T o1, T o2) { + return column.getValue(o1).compareToIgnoreCase(column.getValue(o2)); + } + }; + } + + protected Comparator createNumberColumnCommparator(final Column column) { + return new Comparator() { + @SuppressWarnings({"rawtypes", "unchecked" }) + @Override + public int compare(T o1, T o2) { + return ((Comparable) column.getValue(o1)).compareTo((Comparable) column.getValue(o2)); + } + }; + } + + /** + * Add column definitions to the table. + * + * @param table the table. + * @param dataProvider the data provider associated with the table. + */ + protected abstract void createColumns(DefaultCellTable table, ListDataProvider dataProvider); + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/common/AlwaysFireSingleSelectionModel.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/AlwaysFireSingleSelectionModel.java new file mode 100644 index 000000000..bf3ecf41e --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/AlwaysFireSingleSelectionModel.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.common; + +import com.google.gwt.view.client.ProvidesKey; +import com.google.gwt.view.client.SelectionChangeEvent; +import com.google.gwt.view.client.SingleSelectionModel; + +/** + * AlwaysFireSingleSelectionModel + * + * A selection model similar to SingleSelectionModel except that a selection + * changed event is fired every time the selection is set. + * + * @param the data type of records in the list + * + * @author Rob Cernich + */ +public class AlwaysFireSingleSelectionModel extends SingleSelectionModel { + + private T _selection; + private boolean _selected; + + /** + * Create a new AlwaysFireSingleSelectionModel. + */ + public AlwaysFireSingleSelectionModel() { + super(null); + } + + /** + * Create a new AlwaysFireSingleSelectionModel. + * + * @param keyProvider the {@link ProvidesKey} to use. + */ + public AlwaysFireSingleSelectionModel(ProvidesKey keyProvider) { + super(keyProvider); + } + + @Override + public boolean isSelected(T object) { + Object objectKey = getKey(object); + Object selectedKey = getKey(_selection); + return objectKey == null ? selectedKey == null : objectKey.equals(selectedKey) && _selected; + } + + /** + * @return the current selection + */ + @Override + public T getSelectedObject() { + return _selected ? _selection : null; + } + + @Override + public void setSelected(T object, boolean selected) { + _selection = object; + _selected = selected; + scheduleSelectionChangeEvent(); + } + + @Override + protected void fireSelectionChangeEvent() { + if (isEventScheduled()) { + setEventCancelled(true); + } + SelectionChangeEvent.fire(this); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/common/GWTPTab.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/GWTPTab.java new file mode 100644 index 000000000..63b65cc34 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/GWTPTab.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.common; + +import com.google.gwt.user.client.ui.Widget; +import com.gwtplatform.mvp.client.Tab; +import com.gwtplatform.mvp.client.TabData; + +/** + * GWTPTab + * + *

+ * Tab implementation for use with GWT Platform tab presenters. + */ +public class GWTPTab implements Tab { + + private final TabData _tabData; + private String _historyToken; + + /** + * Create a new GWTPTab. + * + * @param tabData the tab data + * @param historyToken the history location + */ + public GWTPTab(TabData tabData, String historyToken) { + _tabData = tabData; + _historyToken = historyToken; + } + + @Override + public void activate() { + } + + @Override + public Widget asWidget() { + throw new UnsupportedOperationException( + "GWTPTab is intended to work with GWTPTabPanel, which does not support using custom widgets in the tab bar."); //$NON-NLS-1$ + } + + @Override + public void deactivate() { + } + + @Override + public float getPriority() { + return _tabData.getPriority(); + } + + @Override + public String getText() { + return _tabData.getLabel(); + } + + @Override + public void setTargetHistoryToken(String historyToken) { + _historyToken = historyToken; + } + + /** + * @return the history token associated with this tab's place. + */ + public String getTargetHistoryToken() { + return _historyToken; + } + + @Override + public void setText(String text) { + throw new UnsupportedOperationException("Cannot update label text for GWTPTab."); //$NON-NLS-1$ + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/common/GWTPTabPanel.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/GWTPTabPanel.java new file mode 100644 index 000000000..840689a3e --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/GWTPTabPanel.java @@ -0,0 +1,166 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.common; + +import java.util.ArrayList; + +import org.jboss.as.console.client.widgets.tabs.DefaultTabLayoutPanel; + +import com.google.gwt.dom.client.Style.Unit; +import com.google.gwt.event.logical.shared.SelectionEvent; +import com.google.gwt.event.logical.shared.SelectionHandler; +import com.google.gwt.user.client.ui.Label; +import com.google.gwt.user.client.ui.LayoutPanel; +import com.google.gwt.user.client.ui.Panel; +import com.google.gwt.user.client.ui.TabLayoutPanel; +import com.google.gwt.user.client.ui.Widget; +import com.gwtplatform.mvp.client.Tab; +import com.gwtplatform.mvp.client.TabData; +import com.gwtplatform.mvp.client.TabPanel; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import com.gwtplatform.mvp.client.proxy.PlaceRequest; + +/** + * GWTPTabPanel + * + * GWT Platform TabPanel functionality. + */ +public class GWTPTabPanel implements TabPanel { + + private Panel _layout; + private TabLayoutPanel _tabBar; + private Panel _content; + private boolean _modifyingTabs; + private ArrayList _tabs = new ArrayList(); + + /** + * Create a new GWTPTabPanel. + * + * @param placeManager the place manager to use when processing tab + * selections. + */ + public GWTPTabPanel(final PlaceManager placeManager) { + _layout = new LayoutPanel(); + _layout.addStyleName("fill-layout"); //$NON-NLS-1$ + + _tabBar = new DefaultTabLayoutPanel(40, Unit.PX); + // _tabBar = new TabBar(); + _tabBar.addSelectionHandler(new SelectionHandler() { + @Override + public void onSelection(SelectionEvent event) { + if (_modifyingTabs) { + // add/remove tab may change the selection + return; + } + if (event.getSelectedItem() < 0) { + // TODO: WHAT???? + return; + } + final PlaceRequest current = placeManager.getCurrentPlaceRequest(); + final String selectedToken = _tabs.get(event.getSelectedItem()).getTargetHistoryToken(); + final String currentToken = current == null ? null : current.getNameToken(); + if (!selectedToken.equals(currentToken)) { + placeManager.revealPlace(new PlaceRequest(selectedToken)); + } + } + }); + + _content = new LayoutPanel(); + _content.setStyleName("fill-layout"); //$NON-NLS-1$ + + _layout.add(_tabBar); + _layout.add(_content); + + ((LayoutPanel) _layout).setWidgetTopHeight(_tabBar, 0, Unit.PX, 40, Unit.PX); + ((LayoutPanel) _layout).setWidgetTopHeight(_content, 40, Unit.PX, 100, Unit.PCT); + } + + /** + * @return the widget associated with this tab panel. + */ + public Widget asWidget() { + return _layout; + } + + /** + * @param content set view content for tab place. + */ + public void setContent(Widget content) { + _content.clear(); + if (content != null) { + _content.add(content); + } + } + + @Override + public Tab addTab(TabData tabData, String historyToken) { + _modifyingTabs = true; + try { + final GWTPTab tab = new GWTPTab(tabData, historyToken); + final float priority = tabData.getPriority(); + int index = 0; + for (GWTPTab existing : _tabs) { + if (existing.getPriority() > priority) { + break; + } + ++index; + } + _tabs.add(index, tab); + _tabBar.insert(new Label(), tab.getText(), index); + return tab; + } finally { + _modifyingTabs = false; + } + } + + @Override + public void removeTab(Tab tab) { + _modifyingTabs = true; + try { + final int index = _tabs.indexOf(tab); + if (index < 0) { + return; + } + _tabs.remove(index); + _tabBar.remove(index); + } finally { + _modifyingTabs = false; + } + } + + @Override + public void removeTabs() { + _modifyingTabs = true; + try { + for (int index = 0, count = _tabBar.getWidgetCount(); index < count; ++index) { + _tabs.remove(index); + _tabBar.remove(0); + } + } finally { + _modifyingTabs = false; + } + } + + @Override + public void setActiveTab(Tab tab) { + _tabBar.selectTab(_tabs.indexOf(tab), false); + } + + @Override + public void changeTab(Tab tab, TabData tabData, String historyToken) { + // tab.setText(tabData.getLabel()); + // tab.setTargetHistoryToken(historyToken); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/common/PercentageBarCell.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/PercentageBarCell.java new file mode 100644 index 000000000..cc8957058 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/PercentageBarCell.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.common; + +import org.jboss.as.console.client.shared.runtime.charts.StackedBar; + +import com.google.gwt.cell.client.AbstractCell; +import com.google.gwt.safehtml.shared.SafeHtmlBuilder; +import com.google.gwt.user.client.ui.Widget; + +/** + * PercentageBarCell + * + *

+ * A cell that displays a fractional value as a bar, whose fill corresponds to + * the fractional amount. + * + * @author Rob Cernich + */ +public class PercentageBarCell extends AbstractCell { + + private StackedBar _barControl; + private Widget _widget; + + /** + * Create a new PercentageBarCell. + */ + public PercentageBarCell() { + super((String[]) null); + _barControl = new StackedBar(); + _widget = _barControl.asWidget(); + } + + @Override + public void render(com.google.gwt.cell.client.Cell.Context context, Double value, SafeHtmlBuilder sb) { + _barControl.setRatio(1.0, value); + sb.appendHtmlConstant(_widget.toString()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/common/PlainColumnView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/PlainColumnView.java new file mode 100644 index 000000000..a7c69d1d0 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/PlainColumnView.java @@ -0,0 +1,232 @@ +package org.switchyard.console.client.ui.common; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.jboss.as.console.client.shared.help.HelpSystem; +import org.jboss.as.console.client.shared.help.MetricHelpPanel; +import org.jboss.as.console.client.shared.help.StaticHelpPanel; +import org.jboss.as.console.client.shared.runtime.Metric; +import org.jboss.as.console.client.shared.runtime.Sampler; +import org.jboss.as.console.client.shared.runtime.charts.Column; +import org.jboss.as.console.client.shared.runtime.charts.StackedBar; +import org.switchyard.console.client.Singleton; + +import com.google.gwt.dom.client.Style; +import com.google.gwt.user.client.ui.FlexTable; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.HasHorizontalAlignment; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * Modified version from AS7 core. + * + * @author Heiko Braun + */ +public class PlainColumnView implements Sampler { + + private Column[] _columns = null; + private FlexTable _grid; + private String _title; + private int _rowOffset = 1; + + private List _stacks = new LinkedList(); + + // default width and height + private int _width = 100; + private Style.Unit _unit = Style.Unit.PCT; + private HelpSystem.AddressCallback _address = null; + private StaticHelpPanel _staticHelp; + private Map _columnIndexes = new HashMap(); + + /** + * Create a new PlainColumnView. + * + * @param title the title + */ + public PlainColumnView(String title) { + this._title = title; + } + + /** + * @param columns the columns to be displayed + * @return this + */ + public PlainColumnView setColumns(Column... columns) { + this._columns = columns; + return this; + } + + /** + * @param width the width of the view + * @param unit the units for the width + * @return this + */ + public PlainColumnView setWidth(int width, Style.Unit unit) { + this._width = width; + this._unit = unit; + return this; + } + + @Override + public Widget asWidget() { + + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + + layout.add(new HTML("

" + _title + "
")); //$NON-NLS-1$ //$NON-NLS-2$ + + _grid = new FlexTable(); + _grid.getElement().setAttribute("width", _width + _unit.getType() + ""); //$NON-NLS-1$ //$NON-NLS-2$ + + // header columns + _grid.setHTML(0, 0, Singleton.MESSAGES.label_metric()); + _grid.setHTML(0, 1, Singleton.MESSAGES.label_actual()); + _grid.setHTML(0, 2, " "); //$NON-NLS-1$ + + _grid.getCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT); + + // actual values + int row = _rowOffset; + for (Column c : _columns) { + _grid.setHTML(row, 0, "
" + c.getLabel() + ":
"); //$NON-NLS-1$ //$NON-NLS-2$ + _grid.setHTML(row, 1, ""); //$NON-NLS-1$ + + _stacks.add(new StackedBar()); + + if (c.getComparisonColumn() != null) { + StackedBar stack = _stacks.get(row - _rowOffset); + _grid.setWidget(row, 2, stack.asWidget()); + stack.setRatio(0, 0); + } else { + _grid.setText(row, 2, ""); //$NON-NLS-1$ + } + + _grid.getCellFormatter().setHorizontalAlignment(row, 1, HasHorizontalAlignment.ALIGN_RIGHT); + + if (!c.isVisible()) { + _grid.getRowFormatter().setVisible(row, false); + } + if (c.isBaseline()) { + _grid.getRowFormatter().addStyleName(row, "metric-table-baseline"); //$NON-NLS-1$ + } + + _columnIndexes.put(c, row - _rowOffset); + + row++; + } + + _grid.getCellFormatter().setStyleName(0, 0, "metric-table-header"); //$NON-NLS-1$ + _grid.getCellFormatter().setStyleName(0, 1, "metric-table-header"); //$NON-NLS-1$ + _grid.getCellFormatter().setStyleName(0, 2, "metric-table-header"); //$NON-NLS-1$ + _grid.getCellFormatter().setWidth(0, 2, "50%"); //$NON-NLS-1$ + + if (null == _staticHelp && _address != null) { + MetricHelpPanel helpPanel = new MetricHelpPanel(_address, this._columns); + // helpPanel.setAligned(true); + layout.add(helpPanel.asWidget()); + } else if (_staticHelp != null) { + layout.add(_staticHelp.asWidget()); + } + + layout.add(_grid); + + return layout; + } + + @Override + public void addSample(Metric metric) { + int row = _rowOffset; + int baselineIndex = getBaseLineIndex(); + + // check if they match + if (baselineIndex > metric.numSamples()) { + throw new RuntimeException( + Singleton.MESSAGES.error_illegalBaselineIndex(baselineIndex, metric.numSamples())); + } + + Long baseline = baselineIndex >= 0 ? Long.valueOf(metric.get(baselineIndex)) : -1; + + for (Column c : _columns) { + int dataIndex = row - _rowOffset; + String actualValue = metric.get(dataIndex); + + if (null == actualValue) { + throw new RuntimeException(Singleton.MESSAGES.error_metricIsNullAtIndex(dataIndex)); + } + + _grid.setText(row, 1, actualValue); + + if (c.getComparisonColumn() != null) { + _stacks.get(dataIndex).setRatio(getComparisonValue(metric, c.getComparisonColumn()), + Double.valueOf(actualValue)); + } + row++; + } + + } + + /** + * @return the baseline column index + */ + public int getBaseLineIndex() { + int i = 0; + boolean didMatch = false; + for (Column c : _columns) { + if (c.isBaseline()) { + didMatch = true; + break; + } + i++; + } + + return didMatch ? i : -1; + } + + @Override + public void clearSamples() { + int row = _rowOffset; + + for (Column c : _columns) { + int dataIndex = row - _rowOffset; + + // clear the 'Actual' value + _grid.setText(row, 1, ""); //$NON-NLS-1$ + + // cleanup stackbar if used + if (c.getComparisonColumn() != null) { + _stacks.get(dataIndex).setRatio(0, 0); + } else if (c.getComparisonColumn() != null) { + throw new RuntimeException(Singleton.MESSAGES.error_comparisonColumnWithoutBaseline()); + } + + row++; + } + } + + @Override + public long numSamples() { + return 1; + } + + @Override + public void recycle() { + + } + + /** + * @param helpPanel the help panel + * @return this + */ + public PlainColumnView setStaticHelp(StaticHelpPanel helpPanel) { + this._staticHelp = helpPanel; + return this; + } + + private long getComparisonValue(Metric metric, Column comparisonColumn) { + return Long.parseLong(metric.get(_columnIndexes.get(comparisonColumn))); + } +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/common/TransformersList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/TransformersList.java new file mode 100644 index 000000000..633f0554c --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/TransformersList.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.common; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Transformer; + +import com.google.gwt.dom.client.Style; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * TransformersList + * + * Wraps a table control for displaying transformers. + * + * @author Rob Cernich + */ +public class TransformersList extends AbstractDataTable { + + /** + * Create a new TransformersList. + */ + public TransformersList() { + super(Singleton.MESSAGES.label_transformers()); + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + TextColumn fromColumn = new TextColumn() { + @Override + public String getValue(Transformer transform) { + return transform.getFrom(); + } + }; + fromColumn.setSortable(true); + + TextColumn toColumn = new TextColumn() { + @Override + public String getValue(Transformer transform) { + return transform.getTo(); + } + }; + toColumn.setSortable(true); + + TextColumn typeColumn = new TextColumn() { + @Override + public String getValue(Transformer transform) { + return transform.getType(); + } + }; + typeColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(fromColumn, createColumnCommparator(fromColumn)); + sortHandler.setComparator(toColumn, createColumnCommparator(toColumn)); + sortHandler.setComparator(typeColumn, createColumnCommparator(typeColumn)); + + table.addColumn(fromColumn, Singleton.MESSAGES.label_from()); + table.addColumn(toColumn, Singleton.MESSAGES.label_to()); + table.addColumn(typeColumn, Singleton.MESSAGES.label_type()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(typeColumn); + table.getColumnSortList().push(toColumn); + table.getColumnSortList().push(fromColumn); + + table.setWidth("100%", false); //$NON-NLS-1$ + table.setColumnWidth(fromColumn, 45, Style.Unit.PCT); + table.setColumnWidth(toColumn, 45, Style.Unit.PCT); + table.setColumnWidth(typeColumn, 10, Style.Unit.PCT); + } + + @Override + protected ProvidesKey createKeyProvider() { + return new ProvidesKey() { + @Override + public Object getKey(Transformer item) { + return item.getType() + ":" + item.getFrom() + ":" + item.getTo(); //$NON-NLS-1$ //$NON-NLS-2$ + } + }; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/common/ValidatorsList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/ValidatorsList.java new file mode 100644 index 000000000..c99b502a7 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/common/ValidatorsList.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.common; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Validator; + +import com.google.gwt.dom.client.Style; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ValidatorsList + * + * Wraps a table control for displaying validators. + * + * @author Rob Cernich + */ +public class ValidatorsList extends AbstractDataTable { + + /** + * Create a new ValidatorsList. + */ + public ValidatorsList() { + super(Singleton.MESSAGES.label_validators()); + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(Validator validator) { + return validator.getName(); + } + }; + nameColumn.setSortable(true); + + TextColumn typeColumn = new TextColumn() { + @Override + public String getValue(Validator validator) { + return validator.getType(); + } + }; + typeColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(typeColumn, createColumnCommparator(typeColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(typeColumn, Singleton.MESSAGES.label_type()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(typeColumn); + table.getColumnSortList().push(nameColumn); + + table.setWidth("100%", false); //$NON-NLS-1$ + table.setColumnWidth(nameColumn, 70, Style.Unit.PCT); + table.setColumnWidth(typeColumn, 30, Style.Unit.PCT); + } + + @Override + protected ProvidesKey createKeyProvider() { + return new ProvidesKey() { + @Override + public Object getKey(Validator item) { + return "" + item.getName() + ":" + item.getType(); //$NON-NLS-1$ //$NON-NLS-2$ + } + }; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentConfigurationPresenterFactory.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentConfigurationPresenterFactory.java new file mode 100644 index 000000000..86ce4e9f8 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentConfigurationPresenterFactory.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.component; + +import java.util.HashMap; +import java.util.Map; + +import org.switchyard.console.client.ui.component.ComponentPresenter.PresenterFactory; +import org.switchyard.console.client.ui.component.ComponentPresenter.ViewFactory; +import org.switchyard.console.components.client.extension.ComponentProvider; +import org.switchyard.console.components.client.extension.ComponentProviders; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter; + +import com.google.inject.Inject; +import com.google.web.bindery.event.shared.EventBus; + +/** + * ComponentConfigurationPresenterFactory + * + * Factory which delegates creation of ComponentConfigurationPresenter objects + * to the extension providers. + * + * @author Rob Cernich + */ +public class ComponentConfigurationPresenterFactory implements PresenterFactory { + + private final EventBus _eventBus; + private final ViewFactory _viewFactory; + private final ComponentProviders _componentProviders; + private final Map _presentersCache = new HashMap(); + + /** + * Create a new ComponentConfigurationPresenterFactory. + * + * @param eventBus the EventBus + * @param viewFactory the ViewFactory + * @param componentProviders the ComponentProviders + */ + @Inject + public ComponentConfigurationPresenterFactory(EventBus eventBus, ViewFactory viewFactory, + ComponentProviders componentProviders) { + _eventBus = eventBus; + _viewFactory = viewFactory; + _componentProviders = componentProviders; + } + + @Override + public ComponentConfigurationPresenter create(String componentName) { + if (_presentersCache.containsKey(componentName)) { + return _presentersCache.get(componentName); + } + ComponentConfigurationPresenter presenter; + ComponentProvider provider = _componentProviders.getExtensionProviderByComponentName(componentName); + if (provider == null) { + provider = _componentProviders.getDefaultProvider(); + } + presenter = provider.createConfigurationPresenter(_eventBus, _viewFactory.create(componentName)); + _presentersCache.put(componentName, presenter); + return presenter; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentConfigurationViewFactory.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentConfigurationViewFactory.java new file mode 100644 index 000000000..a86460d07 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentConfigurationViewFactory.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.component; + +import org.switchyard.console.client.ui.component.ComponentPresenter.ViewFactory; +import org.switchyard.console.components.client.extension.ComponentProvider; +import org.switchyard.console.components.client.extension.ComponentProviders; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +import com.google.inject.Inject; + +/** + * ComponentConfigurationViewFactory + * + * Factory which delegates creation of ComponentConfigurationView objects to the + * extension providers. + * + * @author Rob Cernich + */ +public class ComponentConfigurationViewFactory implements ViewFactory { + + private final ComponentProviders _componentProviders; + + /** + * Create a new ComponentConfigurationViewFactory. + * + * @param componentProviders the ComponentProviders. + */ + @Inject + public ComponentConfigurationViewFactory(ComponentProviders componentProviders) { + _componentProviders = componentProviders; + } + + @Override + public ComponentConfigurationView create(String componentName) { + ComponentProvider provider = _componentProviders.getExtensionProviderByComponentName(componentName); + if (provider == null) { + provider = _componentProviders.getDefaultProvider(); + } + return provider.createConfigurationView(); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentPresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentPresenter.java new file mode 100644 index 000000000..4f0bfd5ca --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentPresenter.java @@ -0,0 +1,184 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.component; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.spi.AccessControl; +import org.jboss.as.console.spi.SubsystemExtension; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.SwitchYardStore; +import org.switchyard.console.client.ui.config.ConfigPresenter; +import org.switchyard.console.components.client.model.Component; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter.ComponentConfigurationView; + +import com.google.gwt.event.shared.EventBus; +import com.google.gwt.event.shared.GwtEvent; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.inject.Inject; +import com.gwtplatform.mvp.client.Presenter; +import com.gwtplatform.mvp.client.View; +import com.gwtplatform.mvp.client.annotations.ContentSlot; +import com.gwtplatform.mvp.client.annotations.NameToken; +import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; +import com.gwtplatform.mvp.client.proxy.Place; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import com.gwtplatform.mvp.client.proxy.Proxy; +import com.gwtplatform.mvp.client.proxy.RevealContentEvent; +import com.gwtplatform.mvp.client.proxy.RevealContentHandler; + +/** + * ComponentPresenter + * + * Presenter for SwitchYard component configuration. + * + * @author Rob Cernich + */ +public class ComponentPresenter extends Presenter { + + /** + * MyProxy + * + * The proxy type used by this presenter. + */ + @ProxyCodeSplit + @NameToken(NameTokens.SYSTEM_CONFIG_PRESENTER) + @SubsystemExtension(name = "Runtime Details", group = "SwitchYard", key = "switchyard") + @AccessControl(resources = {"{selected.profile}/subsystem=switchyard"}) + public interface MyProxy extends Proxy, Place { + } + + /** The main content slot for this presenter. */ + @ContentSlot + public static final GwtEvent.Type> TYPE_MAIN_CONTENT = new GwtEvent.Type>(); + + /** + * MyView + * + * The view type used by this presenter. + */ + public interface MyView extends View { + /** + * @param presenter the presenter associated with the view. + */ + void setPresenter(ComponentPresenter presenter); + } + + /** + * PresenterFactory + * + * A factory for creating ComponentConfigurationPresenter objects. + * + * @author Rob Cernich + */ + public interface PresenterFactory { + /** + * @param componentName the component. + * @return a ComponentConfigurationPresenter specific to the component. + */ + public ComponentConfigurationPresenter create(String componentName); + } + + /** + * ViewFactory + * + * A factory for creating ComponentConfigurationView objects. + * + * @author Rob Cernich + */ + public interface ViewFactory { + /** + * @param componentName the component. + * @return a ComponentConfigurationView specific to the component. + */ + public ComponentConfigurationView create(String componentName); + } + + private final PlaceManager _placeManager; + private final SwitchYardStore _switchYardStore; + private final PresenterFactory _factory; + private ComponentConfigurationPresenter _presenterWidget; + + /** + * Create a new ComponentPresenter. + * + * @param eventBus the injected EventBus. + * @param view the injected MyView. + * @param proxy the injected MyProxy. + * @param placeManager the injected PlaceManager. + * @param switchYardStore the injected SwitchYardStore. + * @param factory the PresenterFactory for specialized component presenters. + */ + @Inject + public ComponentPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, + SwitchYardStore switchYardStore, PresenterFactory factory) { + super(eventBus, view, proxy); + + _placeManager = placeManager; + _switchYardStore = switchYardStore; + _factory = factory; + } + + @Override + protected void onBind() { + super.onBind(); + getView().setPresenter(this); + } + + @Override + protected void onReset() { + super.onReset(); + + releasePresenterWidget(); + + loadComponent(_placeManager.getCurrentPlaceRequest().getParameter(NameTokens.COMPONENT_NAME_PARAM, null)); + } + + @Override + protected void revealInParent() { + RevealContentEvent.fire(this, ConfigPresenter.TYPE_COMPONENT_CONTENT, this); + } + + private void loadComponent(String componentName) { + if (componentName == null) { + return; + } + _switchYardStore.loadComponent(componentName, new AsyncCallback() { + + @Override + public void onSuccess(Component component) { + _presenterWidget = _factory.create(component.getName()); + _presenterWidget.bind(); + ComponentPresenter.this.setInSlot(TYPE_MAIN_CONTENT, _presenterWidget, false); + _presenterWidget.setComponent(component); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void releasePresenterWidget() { + if (_presenterWidget == null) { + return; + } + _presenterWidget.unbind(); + _presenterWidget = null; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentView.java new file mode 100644 index 000000000..ab081df61 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/component/ComponentView.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.component; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.client.core.DisposableViewImpl; + +import com.google.gwt.user.client.ui.IsWidget; +import com.google.gwt.user.client.ui.Panel; +import com.google.gwt.user.client.ui.SimplePanel; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * ComponentView + * + * View for SwitchYard module configuration. + * + * @author Rob Cernich + */ +public class ComponentView extends DisposableViewImpl implements ComponentPresenter.MyView { + + private ComponentPresenter _presenter; + private Panel _mainContentPanel; + + @Override + public Widget createWidget() { + VerticalPanel wrapper = new VerticalPanel(); + wrapper.setStyleName("fill-layout-width"); //$NON-NLS-1$ + _mainContentPanel = new SimplePanel(); + wrapper.add(_mainContentPanel); + + return wrapper; + } + + @Override + public void setPresenter(ComponentPresenter presenter) { + this._presenter = presenter; + } + + @Override + public void setInSlot(Object slot, IsWidget content) { + if (slot == ComponentPresenter.TYPE_MAIN_CONTENT) { + setMainContent(content == null ? null : content.asWidget()); + } else { + Console.error("Unknown slot requested:" + slot); //$NON-NLS-1$ + } + } + + private void setMainContent(Widget content) { + _mainContentPanel.clear(); + + if (content != null) { + _mainContentPanel.add(content); + } + } +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ComponentsList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ComponentsList.java new file mode 100644 index 000000000..db4cbdc54 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ComponentsList.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.config; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.ui.common.AbstractDataTable; +import org.switchyard.console.components.client.extension.ComponentProviders; +import org.switchyard.console.components.client.internal.ComponentExtensionManager.ComponentProviderProxy; +import org.switchyard.console.components.client.model.Component; + +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; +import com.google.inject.Inject; + +/** + * ComponentsList + * + * Wraps a table control for displaying components. + * + * @author Rob Cernich + */ +public class ComponentsList extends AbstractDataTable { + + private final ComponentProviders _componentProviders; + + /** + * Create a new ComponentsList. + * + * @param componentProviders the manager class for component type + * extensions. + */ + @Inject + public ComponentsList(ComponentProviders componentProviders) { + super(Singleton.MESSAGES.label_installedComponents()); + _componentProviders = componentProviders; + } + + @Override + protected ProvidesKey createKeyProvider() { + return new ProvidesKey() { + @Override + public Object getKey(Component item) { + return item.getName(); + } + }; + + } + + @SuppressWarnings("unchecked") + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + final TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(Component component) { + ComponentProviderProxy provider = _componentProviders.getExtensionProviderByComponentName(component + .getName()); + if (provider == null) { + return component.getName(); + } + return provider.getDisplayName(); + } + }; + nameColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(nameColumn); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigEditor.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigEditor.java new file mode 100644 index 000000000..cf7dabc69 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigEditor.java @@ -0,0 +1,123 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.config; + +import java.util.List; + +import org.jboss.ballroom.client.widgets.ContentGroupLabel; +import org.jboss.ballroom.client.widgets.forms.Form; +import org.jboss.ballroom.client.widgets.forms.TextItem; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.SystemDetails; +import org.switchyard.console.components.client.extension.ComponentProviders; +import org.switchyard.console.components.client.model.Component; + +import com.google.gwt.user.client.ui.Panel; +import com.google.gwt.user.client.ui.SimplePanel; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.SelectionChangeEvent; + +/** + * ConfigEditor + * + * Editor widget for SwitchYard system configuration. + * + * @author Rob Cernich + */ +public class ConfigEditor { + + private ConfigPresenter _presenter; + + private Form _systemDetailsForm; + private ComponentsList _componentsList; + private Panel _componentDetails; + private ComponentProviders _componentProviders; + + /** + * Create a new ConfigEditor. + * + * @param componentProviders the instance providing component type specific + * functionality. + */ + public ConfigEditor(ComponentProviders componentProviders) { + _componentProviders = componentProviders; + } + + /** + * @return this editor as a Widget. + */ + public Widget asWidget() { + + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + + TextItem versionItem = new TextItem("version", Singleton.MESSAGES.label_version()); //$NON-NLS-1$ + _systemDetailsForm = new Form(SystemDetails.class); + _systemDetailsForm.setFields(versionItem); + + _componentsList = new ComponentsList(_componentProviders); + _componentsList.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { + @Override + public void onSelectionChange(SelectionChangeEvent event) { + Component selected = _componentsList.getSelection(); + _presenter.onComponentSelected(selected); + } + }); + + _componentDetails = new SimplePanel(); + + layout.add(new ContentGroupLabel(Singleton.MESSAGES.label_coreRuntime())); //$NON-NLS-1$ + layout.add(_systemDetailsForm.asWidget()); + + layout.add(_componentsList.asWidget()); + + layout.add(new ContentGroupLabel(Singleton.MESSAGES.label_componentDetails())); + layout.add(_componentDetails); + + return layout; + } + + /** + * @param presenter the presenter managing the view. + */ + public void setPresenter(ConfigPresenter presenter) { + _presenter = presenter; + } + + /** + * @param systemDetails the new system details + */ + public void setSystemDetails(SystemDetails systemDetails) { + _systemDetailsForm.edit(systemDetails); + } + + /** + * @param components the components installed in the runtime. + */ + public void setComponents(List components) { + _componentsList.setData(components); + } + + /** + * @param content component specific content. + */ + public void setComponentContent(Widget content) { + _componentDetails.clear(); + if (content != null) { + _componentDetails.add(content); + } + } +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigPresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigPresenter.java new file mode 100644 index 000000000..66359220e --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigPresenter.java @@ -0,0 +1,251 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.config; + +import java.util.List; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.client.shared.subsys.RevealStrategy; +import org.jboss.as.console.spi.AccessControl; +import org.jboss.ballroom.client.layout.LHSHighlightEvent; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.SwitchYardStore; +import org.switchyard.console.client.model.SystemDetails; +import org.switchyard.console.client.ui.component.ComponentPresenter.PresenterFactory; +import org.switchyard.console.components.client.model.Component; +import org.switchyard.console.components.client.ui.ComponentConfigurationPresenter; + +import com.google.gwt.core.client.Scheduler; +import com.google.gwt.event.shared.GwtEvent; +import com.google.gwt.http.client.URL; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.inject.Inject; +import com.google.web.bindery.event.shared.EventBus; +import com.gwtplatform.mvp.client.Presenter; +import com.gwtplatform.mvp.client.View; +import com.gwtplatform.mvp.client.annotations.ContentSlot; +import com.gwtplatform.mvp.client.annotations.NameToken; +import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; +import com.gwtplatform.mvp.client.proxy.Place; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import com.gwtplatform.mvp.client.proxy.PlaceRequest; +import com.gwtplatform.mvp.client.proxy.PlaceRequest.Builder; +import com.gwtplatform.mvp.client.proxy.Proxy; +import com.gwtplatform.mvp.client.proxy.RevealContentHandler; + +/** + * ConfigPresenter + * + * Presenter for SwitchYard system configuration. + * + * @author Rob Cernich + */ +public class ConfigPresenter extends Presenter { + + /** + * MyProxy + * + * The proxy type associated with this presenter. + */ + @ProxyCodeSplit + @NameToken(NameTokens.SYSTEM_CONFIG_PRESENTER) + @AccessControl(resources = {"/{selected.host}/{selected.server}/subsystem=switchyard" }) + public interface MyProxy extends Proxy, Place { + } + + /** The slot where component specific details are displayed. */ + @ContentSlot + public static final GwtEvent.Type> TYPE_COMPONENT_CONTENT = new GwtEvent.Type>(); + + /** + * MyView + * + * The view type associated with this presenter. + */ + public interface MyView extends View { + /** + * @param presenter the presenter for the view. + */ + void setPresenter(ConfigPresenter presenter); + + /** + * @param systemDetails details of the SwitchYard system. + */ + void setSystemDetails(SystemDetails systemDetails); + + /** + * @param components the installed components. + */ + void setComponents(List components); + } + + private final PlaceManager _placeManager; + private final RevealStrategy _revealStrategy; + private final SwitchYardStore _switchYardStore; + private final PresenterFactory _factory; + private String _componentName; + private ComponentConfigurationPresenter _presenterWidget; + + /** + * Create a new ConfigPresenter. + * + * @param eventBus the injected EventBus. + * @param view the injected MyView. + * @param proxy the injected MyProxy. + * @param placeManager the injected PlaceManager. + * @param revealStrategy the RevealStrategy + * @param switchYardStore the injected SwitchYardStore. + * @param factory the PresenterFactory for specialized component presenters. + */ + @Inject + public ConfigPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, + RevealStrategy revealStrategy, SwitchYardStore switchYardStore, PresenterFactory factory) { + super(eventBus, view, proxy); + + _placeManager = placeManager; + _revealStrategy = revealStrategy; + _switchYardStore = switchYardStore; + _factory = factory; + } + + /** + * Notifies the presenter that the user wishes to view details about a + * specific component. The presenter will load the details and pass them + * back to the view to be displayed. + * + * @param component the selected component. + */ + public void onComponentSelected(Component component) { + clearComponentContent(); + + Builder requestBuilder = new Builder().nameToken(NameTokens.SYSTEM_CONFIG_PRESENTER); + if (component != null) { + requestBuilder.with(NameTokens.COMPONENT_NAME_PARAM, URL.encode(component.getName())); + } + _placeManager.revealRelativePlace(requestBuilder.build(), -1); + } + + @Override + protected void onBind() { + super.onBind(); + getView().setPresenter(this); + } + + @Override + public void prepareFromRequest(PlaceRequest request) { + super.prepareFromRequest(request); + _componentName = request.getParameter(NameTokens.COMPONENT_NAME_PARAM, null); + if (_componentName != null) { + _componentName = URL.decode(_componentName); + } + } + + @Override + protected void onReveal() { + super.onReveal(); + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + fireEvent(new LHSHighlightEvent("unused", NameTokens.SYSTEM_CONFIG_TEXT, //$NON-NLS-1$ + NameTokens.SUBSYSTEM_TREE_CATEGORY)); + } + }); + } + + @Override + protected void onReset() { + super.onReset(); + + loadSystemDetails(); + loadComponentsList(); + loadComponent(); + } + + @Override + protected void onHide() { + super.onHide(); + clearComponentContent(); + } + + @Override + protected void revealInParent() { + _revealStrategy.revealInParent(this); + } + + private void loadSystemDetails() { + _switchYardStore.loadSystemDetails(new AsyncCallback() { + + @Override + public void onSuccess(SystemDetails systemDetails) { + getView().setSystemDetails(systemDetails); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void loadComponentsList() { + _switchYardStore.loadComponents(new AsyncCallback>() { + @Override + public void onSuccess(List components) { + getView().setComponents(components); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void loadComponent() { + if (_componentName == null) { + clearComponentContent(); + return; + } + _switchYardStore.loadComponent(_componentName, new AsyncCallback() { + @Override + public void onSuccess(Component component) { + _presenterWidget = _factory.create(component.getName()); + _presenterWidget.bind(); + setInSlot(TYPE_COMPONENT_CONTENT, _presenterWidget, false); + _presenterWidget.setComponent(component); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void clearComponentContent() { + clearSlot(TYPE_COMPONENT_CONTENT); + releasePresenterWidget(); + } + + private void releasePresenterWidget() { + if (_presenterWidget == null) { + return; + } + _presenterWidget.unbind(); + _presenterWidget = null; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigView.java new file mode 100644 index 000000000..63a02b452 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/config/ConfigView.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.config; + +import java.util.List; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.client.core.DisposableViewImpl; +import org.jboss.as.console.client.layout.SimpleLayout; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.SystemDetails; +import org.switchyard.console.components.client.extension.ComponentProviders; +import org.switchyard.console.components.client.model.Component; + +import com.google.gwt.user.client.ui.IsWidget; +import com.google.gwt.user.client.ui.Widget; +import com.google.inject.Inject; + +/** + * ConfigView + * + * View implementation for SwitchYard system configuration. + * + * @author Rob Cernich + */ +public class ConfigView extends DisposableViewImpl implements ConfigPresenter.MyView { + + private ConfigPresenter _presenter; + private ConfigEditor _configEditor; + @Inject + private ComponentProviders _componentProviders; + + @Override + public Widget createWidget() { + _configEditor = new ConfigEditor(_componentProviders); + _configEditor.setPresenter(_presenter); + + SimpleLayout layout = new SimpleLayout().setTitle(Singleton.MESSAGES.label_switchYardRuntimeDetails()) + .setHeadline(Singleton.MESSAGES.label_switchYardRuntime()) + .setDescription(Singleton.MESSAGES.description_switchYardRuntime()) + .addContent(Singleton.MESSAGES.label_runtimeDetails(), _configEditor.asWidget()); + return layout.build(); + } + + @Override + public void setPresenter(ConfigPresenter presenter) { + _presenter = presenter; + if (_configEditor != null) { + _configEditor.setPresenter(presenter); + } + } + + @Override + public void setSystemDetails(SystemDetails systemDetails) { + _configEditor.setSystemDetails(systemDetails); + } + + @Override + public void setComponents(List components) { + _configEditor.setComponents(components); + } + + @Override + public void setInSlot(Object slot, IsWidget content) { + if (slot == ConfigPresenter.TYPE_COMPONENT_CONTENT) { + _configEditor.setComponentContent(content == null ? null : content.asWidget()); + } else { + Console.error("Unknown slot requested: " + slot); //$NON-NLS-1$ + } + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/GatewayMetricsList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/GatewayMetricsList.java new file mode 100644 index 000000000..4c682d90e --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/GatewayMetricsList.java @@ -0,0 +1,156 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.GatewayMetrics; +import org.switchyard.console.client.model.ServiceMetrics; +import org.switchyard.console.client.ui.common.AbstractDataTable; +import org.switchyard.console.client.ui.common.PercentageBarCell; + +import com.google.gwt.cell.client.NumberCell; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * GatewayMetricsList + * + * Wraps a table control for displaying metrics for gateways on a + * service/reference. + */ +public class GatewayMetricsList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(GatewayMetrics item) { + return item.getName(); + } + }; + + private ServiceMetrics _serviceMetrics; + + /** + * Create a new GatewayMetricsList. + */ + public GatewayMetricsList() { + super(Singleton.MESSAGES.label_gatewayMetrics()); + } + + @Override + protected void createColumns(DefaultCellTable table, + ListDataProvider dataProvider) { + final TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(GatewayMetrics metrics) { + return metrics.getName(); + } + }; + nameColumn.setSortable(true); + + final TextColumn typeColumn = new TextColumn() { + @Override + public String getValue(GatewayMetrics metrics) { + return metrics.getType(); + } + }; + typeColumn.setSortable(true); + + final Column countColumn = new Column(new NumberCell()) { + @Override + public Number getValue(GatewayMetrics metrics) { + return metrics.getTotalCount(); + } + }; + countColumn.setSortable(true); + + final Column averageTimeColumn = new Column( + new NumberCell()) { + @Override + public Number getValue(GatewayMetrics metrics) { + return metrics.getAverageProcessingTime(); + } + }; + averageTimeColumn.setSortable(true); + + final Column totalTimePercentageColumn = new Column( + new PercentageBarCell()) { + @Override + public Double getValue(GatewayMetrics metrics) { + if (_serviceMetrics == null || _serviceMetrics.getTotalProcessingTime() == 0) { + return 0.0; + } + return metrics.getTotalProcessingTime() / (double) _serviceMetrics.getTotalProcessingTime(); + } + }; + totalTimePercentageColumn.setSortable(true); + + final Column faultPercentageColumn = new Column( + new PercentageBarCell()) { + @Override + public Double getValue(GatewayMetrics metrics) { + if (metrics.getTotalCount() == 0) { + return 0.0; + } + return metrics.getFaultCount() / (double) metrics.getTotalCount(); + } + }; + faultPercentageColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(typeColumn, createColumnCommparator(typeColumn)); + sortHandler.setComparator(countColumn, createNumberColumnCommparator(countColumn)); + sortHandler.setComparator(averageTimeColumn, createNumberColumnCommparator(averageTimeColumn)); + sortHandler.setComparator(totalTimePercentageColumn, createNumberColumnCommparator(totalTimePercentageColumn)); + sortHandler.setComparator(faultPercentageColumn, createNumberColumnCommparator(faultPercentageColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(typeColumn, Singleton.MESSAGES.label_type()); + table.addColumn(countColumn, Singleton.MESSAGES.label_messageCount()); + table.addColumn(averageTimeColumn, Singleton.MESSAGES.label_averageTime()); + table.addColumn(totalTimePercentageColumn, Singleton.MESSAGES.label_timePercent()); + table.addColumn(faultPercentageColumn, Singleton.MESSAGES.label_faultPercent()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(averageTimeColumn); + table.getColumnSortList().push(countColumn); + table.getColumnSortList().push(totalTimePercentageColumn); + table.getColumnSortList().push(faultPercentageColumn); + table.getColumnSortList().push(nameColumn); + } + + /** + * @param serviceMetrics the parent service's metrics, containing a list of + * reference metrics. + */ + public void setServiceMetrics(ServiceMetrics serviceMetrics) { + _serviceMetrics = serviceMetrics; + if (serviceMetrics == null) { + setData(null); + } else { + setData(serviceMetrics.getGateways()); + } + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MessageMetricsViewer.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MessageMetricsViewer.java new file mode 100644 index 000000000..322bda45d --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MessageMetricsViewer.java @@ -0,0 +1,129 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import org.jboss.as.console.client.shared.runtime.Metric; +import org.jboss.as.console.client.shared.runtime.charts.Column; +import org.jboss.as.console.client.shared.runtime.charts.NumberColumn; +import org.jboss.as.console.client.shared.runtime.charts.TextColumn; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.MessageMetrics; +import org.switchyard.console.client.ui.common.PlainColumnView; + +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * MessageMetricsViewer + * + *

+ * Displays message metrics. + * + * @author Rob Cernich + */ +public class MessageMetricsViewer { + + private PlainColumnView _messageCounts; + private PlainColumnView _processingTimes; + private boolean _displaysChildMetrics; + + /** + * Create a new MessageMetricsViewer. + * + * @param displaysChildMetrics true if this viewer should display percentage + * bars for parent data. + */ + public MessageMetricsViewer(boolean displaysChildMetrics) { + _displaysChildMetrics = displaysChildMetrics; + } + + /** + * @return the control. + */ + public Widget asWidget() { + Column containerTotalCountItem = new NumberColumn("ContainerTotalCount", Singleton.MESSAGES.label_totalCount()).setVisible(false); //$NON-NLS-1$ + Column totalCountItem = new NumberColumn("TotalCount", Singleton.MESSAGES.label_totalCount()).setBaseline(true); //$NON-NLS-1$ + Column successCountItem = new NumberColumn("SuccessCount", Singleton.MESSAGES.label_successCount()) //$NON-NLS-1$ + .setComparisonColumn(totalCountItem); + Column faultCountItem = new NumberColumn("FaultCount", Singleton.MESSAGES.label_faultCount()).setComparisonColumn(totalCountItem); //$NON-NLS-1$ + if (_displaysChildMetrics) { + totalCountItem.setComparisonColumn(containerTotalCountItem); + } + + // XXX: these should really be "LongColumn" + Column containerTotalProcessingTime = new NumberColumn("ContainerTotalProcessingTime", //$NON-NLS-1$ + Singleton.MESSAGES.label_totalProcessingTime()).setVisible(false).setBaseline(true); + Column totalProcessingTimeItem = new NumberColumn("TotalProcessingTime", Singleton.MESSAGES.label_totalProcessingTime()); //$NON-NLS-1$ + if (_displaysChildMetrics) { + totalProcessingTimeItem.setComparisonColumn(containerTotalProcessingTime); + } + + // XXX: using TextColumn for long and double fields + Column averageProcessingTimeItem = new TextColumn("AverageProcessingTime", Singleton.MESSAGES.label_averageProcessingTime()); //$NON-NLS-1$ + Column minProcessingTimeItem = new TextColumn("MinProcessingTime", Singleton.MESSAGES.label_minProcessingTime()); //$NON-NLS-1$ + Column maxProcessingTimeItem = new TextColumn("MaxProcessingTime", Singleton.MESSAGES.label_maxProcessingTime()); //$NON-NLS-1$ + + _messageCounts = new PlainColumnView(Singleton.MESSAGES.label_messageCounts()); + _messageCounts.setColumns(containerTotalCountItem, totalCountItem, successCountItem, faultCountItem); + + _processingTimes = new PlainColumnView(Singleton.MESSAGES.label_processingTimes()); + _processingTimes.setColumns(containerTotalProcessingTime, totalProcessingTimeItem, averageProcessingTimeItem, + minProcessingTimeItem, maxProcessingTimeItem); + + VerticalPanel panel = new VerticalPanel(); + panel.setStyleName("fill-layout-width"); //$NON-NLS-1$ + + panel.add(_messageCounts.asWidget()); + panel.add(_processingTimes.asWidget()); + return panel; + } + + /** + * @param metrics the metrics to be displayed. + */ + public void setMessageMetrics(MessageMetrics metrics) { + Metric countMetric = new Metric("0", "" + metrics.getTotalCount(), "" + metrics.getSuccessCount(), "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + + metrics.getFaultCount()); + _messageCounts.addSample(countMetric); + + Metric timeMetric = new Metric("0", "" + metrics.getTotalProcessingTime(), "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + metrics.getAverageProcessingTime(), "" + metrics.getMinProcessingTime(), "" //$NON-NLS-1$ //$NON-NLS-2$ + + metrics.getMaxProcessingTime()); + _processingTimes.addSample(timeMetric); + } + + /** + * @param metrics the metrics to be displayed. + * @param totalCount the parent's total count. + * @param totalTime the parent's total time. + */ + public void setMessageMetrics(MessageMetrics metrics, int totalCount, long totalTime) { + Metric countMetric = new Metric(""+ totalCount, "" + metrics.getTotalCount(), "" + metrics.getSuccessCount(), "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + + metrics.getFaultCount()); + _messageCounts.addSample(countMetric); + + Metric timeMetric = new Metric("" + totalTime, "" + metrics.getTotalProcessingTime(), "" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + + metrics.getAverageProcessingTime(), "" + metrics.getMinProcessingTime(), "" //$NON-NLS-1$ //$NON-NLS-2$ + + metrics.getMaxProcessingTime()); + _processingTimes.addSample(timeMetric); + } + + /** + * Clear the display. + */ + public void clear() { + _messageCounts.clearSamples(); + _processingTimes.clearSamples(); + } +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsDetailsWidget.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsDetailsWidget.java new file mode 100644 index 000000000..99bfd6b30 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsDetailsWidget.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import org.switchyard.console.client.model.MessageMetrics; +import org.switchyard.console.client.model.ServiceMetrics; + +import com.google.gwt.user.client.ui.Widget; + +/** + * MetricsDetailsWidget + * + *

+ * Widget for displaying details for a set of metrics (specifically service or reference). + */ +public interface MetricsDetailsWidget { + + /** + * @param metrics the metrics being detailed + * @param systemMetrics parent metrics to be used for ratios + */ + public void setMetrics(ServiceMetrics metrics, MessageMetrics systemMetrics); + + /** + * @return the widget displaying the details + */ + public Widget asWidget(); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsPresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsPresenter.java new file mode 100644 index 000000000..f5c2f77d7 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsPresenter.java @@ -0,0 +1,256 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.metrics; + +import java.util.List; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.client.plugins.RuntimeGroup; +import org.jboss.as.console.client.shared.state.ServerSelectionChanged; +import org.jboss.as.console.client.shared.subsys.RevealStrategy; +import org.jboss.as.console.spi.AccessControl; +import org.jboss.as.console.spi.RuntimeExtension; +import org.jboss.ballroom.client.layout.LHSHighlightEvent; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.MessageMetrics; +import org.switchyard.console.client.model.ServiceMetrics; +import org.switchyard.console.client.model.SwitchYardStore; + +import com.google.gwt.core.client.Scheduler; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.inject.Inject; +import com.google.web.bindery.event.shared.EventBus; +import com.gwtplatform.mvp.client.Presenter; +import com.gwtplatform.mvp.client.View; +import com.gwtplatform.mvp.client.annotations.NameToken; +import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; +import com.gwtplatform.mvp.client.proxy.Place; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import com.gwtplatform.mvp.client.proxy.Proxy; +import com.gwtplatform.mvp.client.proxy.ResetPresentersEvent; + +/** + * RuntimePresenter + * + * Presenter for SwitchYard application. + * + * @author Rob Cernich + */ +public class MetricsPresenter extends Presenter implements + ServerSelectionChanged.ChangeListener { + + /** + * MyProxy + * + * The proxy type associated with this presenter. + */ + @ProxyCodeSplit + @NameToken(NameTokens.METRICS_PRESENTER) + @RuntimeExtension(name = NameTokens.RUNTIME_TEXT, group = RuntimeGroup.METRICS, key = NameTokens.SUBSYSTEM) + @AccessControl(resources = {"/{selected.host}/{selected.server}/subsystem=switchyard" }) + public interface MyProxy extends Proxy, Place { + } + + /** + * MyView + * + * The view type associated with this presenter. + */ + public interface MyView extends View { + /** + * @param presenter the associated presenter. + */ + void setPresenter(MetricsPresenter presenter); + + /** + * @param serviceMetrics metrics for all services deployed on the + * server. + */ + void setServices(List serviceMetrics); + + /** + * @param referenceMetrics metrics for all references deployed on the + * server. + */ + void setReferences(List referenceMetrics); + + /** + * @param systemMetrics the metrics for the system. + */ + void setSystemMetrics(MessageMetrics systemMetrics); + + /** + * Clear the view. + */ + void clearMetrics(); + } + + private final PlaceManager _placeManager; + private final RevealStrategy _revealStrategy; + private final SwitchYardStore _switchYardStore; + + /** + * Create a new RuntimePresenter. + * + * @param eventBus the injected EventBus. + * @param view the injected MyView. + * @param proxy the injected MyProxy. + * @param placeManager the injected PlaceManager. + * @param revealStrategy the RevealStrategy + * @param switchYardStore the injected SwitchYardStore. + */ + @Inject + public MetricsPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, + RevealStrategy revealStrategy, SwitchYardStore switchYardStore) { + super(eventBus, view, proxy); + + _placeManager = placeManager; + _revealStrategy = revealStrategy; + _switchYardStore = switchYardStore; + } + + /** + * Resets system metrics. + */ + public void resetSystemMetrics() { + _switchYardStore.resetSystemMetrics(new AsyncCallback() { + @Override + public void onSuccess(Void unused) { + getEventBus().fireEvent(new ResetPresentersEvent()); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + /** + * Resets metrics for the named service/reference. + * + * @param metrics the service/reference metrics. + */ + public void resetMetrics(ServiceMetrics metrics) { + _switchYardStore.resetMetrics(metrics.getName(), metrics.getApplication(), new AsyncCallback() { + @Override + public void onSuccess(Void unused) { + getEventBus().fireEvent(new ResetPresentersEvent()); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + @Override + public void onServerSelectionChanged(boolean isRunning) { + getView().clearMetrics(); + + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + if (isVisible()) { + loadMetrics(); + } + } + }); + } + + @Override + protected void onBind() { + super.onBind(); + getView().setPresenter(this); + getEventBus().addHandler(ServerSelectionChanged.TYPE, this); + } + + @Override + protected void onReveal() { + super.onReveal(); + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + fireEvent(new LHSHighlightEvent(NameTokens.METRICS_PRESENTER)); + } + }); + } + + @Override + protected void onReset() { + super.onReset(); + loadMetrics(); + } + + @Override + protected void revealInParent() { + _revealStrategy.revealInRuntimeParent(this); + } + + private void loadMetrics() { + getView().setServices(null); + getView().setReferences(null); + getView().clearMetrics(); + loadSystemMetrics(); + loadServicesList(); + loadReferencesList(); + } + + private void loadServicesList() { + _switchYardStore.loadAllServiceMetrics(new AsyncCallback>() { + @Override + public void onSuccess(List serviceMetrics) { + getView().setServices(serviceMetrics); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void loadReferencesList() { + _switchYardStore.loadAllReferenceMetrics(new AsyncCallback>() { + @Override + public void onSuccess(List referenceMetrics) { + getView().setReferences(referenceMetrics); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void loadSystemMetrics() { + _switchYardStore.loadSystemMetrics(new AsyncCallback() { + + @Override + public void onSuccess(MessageMetrics result) { + getView().setSystemMetrics(result); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsView.java new file mode 100644 index 000000000..5ffd778df --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/MetricsView.java @@ -0,0 +1,117 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import java.util.List; + +import org.jboss.as.console.client.core.DisposableViewImpl; +import org.jboss.as.console.client.layout.SimpleLayout; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.MessageMetrics; +import org.switchyard.console.client.model.ServiceMetrics; +import org.switchyard.console.client.ui.metrics.MetricsPresenter.MyView; + +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.user.client.ui.Button; +import com.google.gwt.user.client.ui.HTMLPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * RuntimeView + * + *

+ * View implementation for SwitchYard runtime metrics. + * + * @author Rob Cernich + */ +public class MetricsView extends DisposableViewImpl implements MyView { + + private MetricsPresenter _presenter; + private MessageMetricsViewer _systemMetricsViewer; + private ServiceMetricsList _servicesList; + private ServiceMetricsList _referencesList; + private MessageMetrics _systemMetrics; + + /** + * Create a new MetricsView. + */ + public MetricsView() { + _systemMetricsViewer = new MessageMetricsViewer(false); + _servicesList = new ServiceMetricsList(Singleton.MESSAGES.label_serviceMetrics()); + _referencesList = new ServiceMetricsList(Singleton.MESSAGES.label_referenceMetrics()) { + @Override + protected MetricsDetailsWidget createDetailsWidget() { + return new ReferenceDetailsWidget(); + } + }; + } + + @Override + public Widget createWidget() { + final Button resetButton = new Button(Singleton.MESSAGES.label_resetAllMetrics(), new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + _presenter.resetSystemMetrics(); + } + }); + SimpleLayout layout = new SimpleLayout().setTitle(Singleton.MESSAGES.label_switchYardMessageMetrics()).setHeadline(Singleton.MESSAGES.label_system()) + .setDescription(Singleton.MESSAGES.description_systemMetrics()) + .addContent(Singleton.MESSAGES.label_systemMessageMetrics(), _systemMetricsViewer.asWidget()) + .addContent("reset", resetButton) //$NON-NLS-1$ + .addContent("spacer", new HTMLPanel(" ")) //$NON-NLS-1$ //$NON-NLS-2$ + .addContent(Singleton.MESSAGES.label_serviceMessageMetrics(), _servicesList.asWidget()) + .addContent(Singleton.MESSAGES.label_referenceMessageMetrics(), _referencesList.asWidget()); + + final Widget result = layout.build(); + // hackery, prevent button from filling the row + resetButton.getElement().removeClassName("fill-layout-width"); //$NON-NLS-1$ + return result; + } + + @Override + public void setPresenter(MetricsPresenter presenter) { + _presenter = presenter; + _servicesList.setPresenter(presenter); + _referencesList.setPresenter(presenter); + } + + @Override + public void setServices(List serviceMetrics) { + _servicesList.setData(serviceMetrics); + } + + @Override + public void setReferences(List referenceMetrics) { + _referencesList.setData(referenceMetrics); + } + + @Override + public void setSystemMetrics(MessageMetrics systemMetrics) { + _systemMetrics = systemMetrics; + if (systemMetrics == null) { + _systemMetricsViewer.clear(); + return; + } + _systemMetricsViewer.setMessageMetrics(systemMetrics); + _servicesList.setSystemMetrics(systemMetrics); + _referencesList.setSystemMetrics(systemMetrics); + } + + @Override + public void clearMetrics() { + _systemMetricsViewer.clear(); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ReferenceDetailsWidget.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ReferenceDetailsWidget.java new file mode 100644 index 000000000..9dc1ba57b --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ReferenceDetailsWidget.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import org.jboss.as.console.client.layout.OneToOneLayout; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.MessageMetrics; +import org.switchyard.console.client.model.ServiceMetrics; + +import com.google.gwt.user.client.ui.Widget; + +/** + * ReferenceDetailsWidget + * + * Provides a widget for displaying a {@link ServiceMetrics}. + */ +public class ReferenceDetailsWidget implements MetricsDetailsWidget { + + private MessageMetricsViewer _referenceMetricsViewer; + private ServiceOperationMetricsList _referenceOperationMetricsList; + private GatewayMetricsList _gatewayMetricsList; + + /** + * Create a new ReferenceDetailsWidget. + */ + public ReferenceDetailsWidget() { + } + + /** + * @return the widget + */ + @Override + public Widget asWidget() { + _referenceMetricsViewer = new MessageMetricsViewer(true); + _referenceOperationMetricsList = new ServiceOperationMetricsList(); + _gatewayMetricsList = new GatewayMetricsList(); + + OneToOneLayout serviceMetricsLayout = new OneToOneLayout().setPlain(true).setHeadline(Singleton.MESSAGES.label_referenceMetrics()) + .setDescription(Singleton.MESSAGES.description_referenceMetrics()) + .setMaster(null, _referenceMetricsViewer.asWidget()) + .addDetail(Singleton.MESSAGES.label_gatewayMetrics(), _gatewayMetricsList.asWidget()) + .addDetail(Singleton.MESSAGES.label_operationMetrics(), _referenceOperationMetricsList.asWidget()); + return serviceMetricsLayout.build(); + } + + /** + * Updates the widget with the information for the specified service. + * + * @param metrics the metrics for the selected service. + * @param systemMetrics the metrics for the overall system. + */ + @Override + public void setMetrics(ServiceMetrics metrics, MessageMetrics systemMetrics) { + if (metrics == null) { + _referenceMetricsViewer.clear(); + _referenceOperationMetricsList.setServiceMetrics(null); + _gatewayMetricsList.setServiceMetrics(null); + return; + } + if (systemMetrics == null) { + _referenceMetricsViewer.setMessageMetrics(metrics); + } else { + _referenceMetricsViewer.setMessageMetrics(metrics, systemMetrics.getTotalCount(), + systemMetrics.getTotalProcessingTime()); + } + _referenceOperationMetricsList.setServiceMetrics(metrics); + _gatewayMetricsList.setServiceMetrics(metrics); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceDetailsWidget.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceDetailsWidget.java new file mode 100644 index 000000000..22fb71da3 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceDetailsWidget.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import org.jboss.as.console.client.layout.OneToOneLayout; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.MessageMetrics; +import org.switchyard.console.client.model.ServiceMetrics; + +import com.google.gwt.user.client.ui.Widget; + +/** + * ServiceDetailsWidget + * + * Provides a widget for displaying a {@link ServiceMetrics}. + */ +public class ServiceDetailsWidget implements MetricsDetailsWidget { + + private MessageMetricsViewer _serviceMetricsViewer; + private ServiceReferenceMetricsList _serviceReferenceMetricsList; + private ServiceOperationMetricsList _serviceOperationMetricsList; + private GatewayMetricsList _gatewayMetricsList; + + /** + * Create a new ServiceDetailsWidget. + */ + public ServiceDetailsWidget() { + } + + /** + * @return the widget + */ + @Override + public Widget asWidget() { + _serviceMetricsViewer = new MessageMetricsViewer(true); + _serviceOperationMetricsList = new ServiceOperationMetricsList(); + _serviceReferenceMetricsList = new ServiceReferenceMetricsList(); + _gatewayMetricsList = new GatewayMetricsList(); + + OneToOneLayout serviceMetricsLayout = new OneToOneLayout().setPlain(true).setHeadline(Singleton.MESSAGES.label_serviceMetrics()) + .setDescription(Singleton.MESSAGES.description_serviceMetrics()) + .setMaster(null, _serviceMetricsViewer.asWidget()) + .addDetail(Singleton.MESSAGES.label_gatewayMetrics(), _gatewayMetricsList.asWidget()) + .addDetail(Singleton.MESSAGES.label_operationMetrics(), _serviceOperationMetricsList.asWidget()) + .addDetail(Singleton.MESSAGES.label_referenceMetrics(), _serviceReferenceMetricsList.asWidget()); + return serviceMetricsLayout.build(); + } + + /** + * Updates the widget with the information for the specified service. + * + * @param metrics the metrics for the selected service. + * @param systemMetrics the metrics for the overall system. + */ + @Override + public void setMetrics(ServiceMetrics metrics, MessageMetrics systemMetrics) { + if (metrics == null) { + _serviceMetricsViewer.clear(); + _serviceReferenceMetricsList.setServiceMetrics(null); + _serviceOperationMetricsList.setServiceMetrics(null); + _gatewayMetricsList.setServiceMetrics(null); + return; + } + if (systemMetrics == null) { + _serviceMetricsViewer.setMessageMetrics(metrics); + } else { + _serviceMetricsViewer.setMessageMetrics(metrics, systemMetrics.getTotalCount(), + systemMetrics.getTotalProcessingTime()); + } + _serviceReferenceMetricsList.setServiceMetrics(metrics); + _serviceOperationMetricsList.setServiceMetrics(metrics); + _gatewayMetricsList.setServiceMetrics(metrics); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceMetricsList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceMetricsList.java new file mode 100644 index 000000000..399d48279 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceMetricsList.java @@ -0,0 +1,230 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.jboss.ballroom.client.widgets.window.DefaultWindow; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.MessageMetrics; +import org.switchyard.console.client.model.ServiceMetrics; +import org.switchyard.console.client.ui.common.AbstractDataTable; +import org.switchyard.console.client.ui.common.PercentageBarCell; + +import com.google.gwt.cell.client.ButtonCell; +import com.google.gwt.cell.client.FieldUpdater; +import com.google.gwt.cell.client.NumberCell; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ServiceReferenceMetricsList + * + * Wraps a table control for displaying metrics for services referenced by a + * service. + * + * @author Rob Cernich + */ +public class ServiceMetricsList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(ServiceMetrics item) { + return item.getName(); + } + }; + + private MessageMetrics _systemMetrics; + private MetricsPresenter _presenter; + private DefaultWindow _detailsWindow; + private MetricsDetailsWidget _detailsWidget; + private String _title; + + /** + * Create a new ServiceReferenceMetricsList. + * + * @param title for the list + */ + public ServiceMetricsList(String title) { + super(title); + _title = title; + } + + /** + * @param presenter the presenter. + */ + public void setPresenter(MetricsPresenter presenter) { + _presenter = presenter; + } + + @Override + public Widget asWidget() { + createDetailsWindow(); + return super.asWidget(); + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + final TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(ServiceMetrics metrics) { + return metrics.localName(); + } + }; + nameColumn.setSortable(true); + + final TextColumn namespaceColumn = new TextColumn() { + @Override + public String getValue(ServiceMetrics service) { + return service.namespace(); + } + }; + namespaceColumn.setSortable(true); + + final Column countColumn = new Column(new NumberCell()) { + @Override + public Number getValue(ServiceMetrics metrics) { + return metrics.getTotalCount(); + } + }; + countColumn.setSortable(true); + + final Column averageTimeColumn = new Column(new NumberCell()) { + @Override + public Number getValue(ServiceMetrics metrics) { + return metrics.getAverageProcessingTime(); + } + }; + averageTimeColumn.setSortable(true); + + final Column totalTimePercentageColumn = new Column( + new PercentageBarCell()) { + @Override + public Double getValue(ServiceMetrics metrics) { + if (_systemMetrics == null || _systemMetrics.getTotalProcessingTime() == 0) { + return 0.0; + } + return metrics.getTotalProcessingTime() / (double) _systemMetrics.getTotalProcessingTime(); + } + }; + totalTimePercentageColumn.setSortable(true); + + final Column faultPercentageColumn = new Column( + new PercentageBarCell()) { + @Override + public Double getValue(ServiceMetrics metrics) { + if (_systemMetrics == null || _systemMetrics.getFaultCount() == 0) { + return 0.0; + } + return metrics.getFaultCount() / (double) _systemMetrics.getFaultCount(); + } + }; + faultPercentageColumn.setSortable(true); + + + Column viewDetailsColumn = new Column(new ButtonCell()) { + @Override + public String getValue(ServiceMetrics dummy) { + return Singleton.MESSAGES.button_details(); + } + }; + viewDetailsColumn.setFieldUpdater(new FieldUpdater() { + @Override + public void update(int index, ServiceMetrics metrics, String value) { + showDetails(metrics); + } + }); + + Column clearColumn = new Column(new ButtonCell()) { + @Override + public String getValue(ServiceMetrics dummy) { + return Singleton.MESSAGES.label_resetMetrics(); + } + }; + clearColumn.setFieldUpdater(new FieldUpdater() { + @Override + public void update(int index, ServiceMetrics metrics, String value) { + _presenter.resetMetrics(metrics); + } + }); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(namespaceColumn, createColumnCommparator(namespaceColumn)); + sortHandler.setComparator(countColumn, createNumberColumnCommparator(countColumn)); + sortHandler.setComparator(averageTimeColumn, createNumberColumnCommparator(averageTimeColumn)); + sortHandler.setComparator(totalTimePercentageColumn, createNumberColumnCommparator(totalTimePercentageColumn)); + sortHandler.setComparator(faultPercentageColumn, createNumberColumnCommparator(faultPercentageColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(namespaceColumn, Singleton.MESSAGES.label_targetNamespace()); + table.addColumn(countColumn, Singleton.MESSAGES.label_messageCount()); + table.addColumn(averageTimeColumn, Singleton.MESSAGES.label_averageTime()); + table.addColumn(totalTimePercentageColumn, Singleton.MESSAGES.label_timePercent()); + table.addColumn(faultPercentageColumn, Singleton.MESSAGES.label_faultPercent()); + table.addColumn(viewDetailsColumn, Singleton.MESSAGES.label_details()); + table.addColumn(clearColumn, Singleton.MESSAGES.label_reset()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(averageTimeColumn); + table.getColumnSortList().push(countColumn); + table.getColumnSortList().push(faultPercentageColumn); + table.getColumnSortList().push(namespaceColumn); + table.getColumnSortList().push(nameColumn); + // insert twice for descending + table.getColumnSortList().push(totalTimePercentageColumn); + table.getColumnSortList().push(totalTimePercentageColumn); + } + + /** + * @param systemMetrics the system metrics. + */ + public void setSystemMetrics(MessageMetrics systemMetrics) { + _systemMetrics = systemMetrics; + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + + /** + * create the details widget + */ + protected MetricsDetailsWidget createDetailsWidget() { + return new ServiceDetailsWidget(); + } + + private void showDetails(ServiceMetrics metrics) { + _detailsWidget.setMetrics(metrics, _systemMetrics); + _detailsWindow.center(); + } + + private void createDetailsWindow() { + _detailsWindow = new DefaultWindow(_title); + _detailsWindow.setGlassEnabled(true); + _detailsWindow.setAutoHideEnabled(true); + _detailsWindow.setAutoHideOnHistoryEventsEnabled(true); + _detailsWindow.setWidth("80%"); //$NON-NLS-1$ + _detailsWindow.setHeight("80%"); //$NON-NLS-1$ + + _detailsWidget = createDetailsWidget(); + _detailsWindow.setWidget(_detailsWidget.asWidget()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceOperationMetricsList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceOperationMetricsList.java new file mode 100644 index 000000000..e7902695f --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceOperationMetricsList.java @@ -0,0 +1,148 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.OperationMetrics; +import org.switchyard.console.client.model.ServiceMetrics; +import org.switchyard.console.client.ui.common.AbstractDataTable; +import org.switchyard.console.client.ui.common.PercentageBarCell; + +import com.google.gwt.cell.client.NumberCell; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ServiceOperationMetricsList + * + * Wraps a table control for displaying metrics for services referenced by a + * service. + * + * @author Rob Cernich + */ +public class ServiceOperationMetricsList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(OperationMetrics item) { + return item.getName(); + } + }; + + private ServiceMetrics _serviceMetrics; + + /** + * Create a new ServiceReferenceMetricsList. + */ + public ServiceOperationMetricsList() { + super(Singleton.MESSAGES.label_serviceOperationMetrics()); + } + + @Override + protected void createColumns(DefaultCellTable table, + ListDataProvider dataProvider) { + final TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(OperationMetrics metrics) { + return metrics.getName(); + } + }; + nameColumn.setSortable(true); + + final Column countColumn = new Column(new NumberCell()) { + @Override + public Number getValue(OperationMetrics metrics) { + return metrics.getTotalCount(); + } + }; + countColumn.setSortable(true); + + final Column averageTimeColumn = new Column( + new NumberCell()) { + @Override + public Number getValue(OperationMetrics metrics) { + return metrics.getAverageProcessingTime(); + } + }; + averageTimeColumn.setSortable(true); + + final Column totalTimePercentageColumn = new Column( + new PercentageBarCell()) { + @Override + public Double getValue(OperationMetrics metrics) { + if (_serviceMetrics == null || _serviceMetrics.getTotalProcessingTime() == 0) { + return 0.0; + } + return metrics.getTotalProcessingTime() / (double) _serviceMetrics.getTotalProcessingTime(); + } + }; + totalTimePercentageColumn.setSortable(true); + + final Column faultPercentageColumn = new Column( + new PercentageBarCell()) { + @Override + public Double getValue(OperationMetrics metrics) { + if (metrics.getTotalCount() == 0) { + return 0.0; + } + return metrics.getFaultCount() / (double) metrics.getTotalCount(); + } + }; + faultPercentageColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(countColumn, createNumberColumnCommparator(countColumn)); + sortHandler.setComparator(averageTimeColumn, createNumberColumnCommparator(averageTimeColumn)); + sortHandler.setComparator(totalTimePercentageColumn, createNumberColumnCommparator(totalTimePercentageColumn)); + sortHandler.setComparator(faultPercentageColumn, createNumberColumnCommparator(faultPercentageColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(countColumn, Singleton.MESSAGES.label_messageCount()); + table.addColumn(averageTimeColumn, Singleton.MESSAGES.label_averageTime()); + table.addColumn(totalTimePercentageColumn, Singleton.MESSAGES.label_timePercent()); + table.addColumn(faultPercentageColumn, Singleton.MESSAGES.label_faultPercent()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(averageTimeColumn); + table.getColumnSortList().push(countColumn); + table.getColumnSortList().push(totalTimePercentageColumn); + table.getColumnSortList().push(faultPercentageColumn); + table.getColumnSortList().push(nameColumn); + } + + /** + * @param serviceMetrics the parent service's metrics, containing a list of + * reference metrics. + */ + public void setServiceMetrics(ServiceMetrics serviceMetrics) { + _serviceMetrics = serviceMetrics; + if (serviceMetrics == null) { + setData(null); + } else { + setData(serviceMetrics.getOperations()); + } + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceReferenceMetricsList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceReferenceMetricsList.java new file mode 100644 index 000000000..106aaf1c2 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/metrics/ServiceReferenceMetricsList.java @@ -0,0 +1,145 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.metrics; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.ServiceMetrics; +import org.switchyard.console.client.ui.common.AbstractDataTable; +import org.switchyard.console.client.ui.common.PercentageBarCell; + +import com.google.gwt.cell.client.NumberCell; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ServiceReferenceMetricsList + * + * Wraps a table control for displaying metrics for services referenced by a + * service. + * + * @author Rob Cernich + */ +public class ServiceReferenceMetricsList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(ServiceMetrics item) { + return item.getName(); + } + }; + + private ServiceMetrics _serviceMetrics; + + /** + * Create a new ServiceReferenceMetricsList. + */ + public ServiceReferenceMetricsList() { + super(Singleton.MESSAGES.label_referencedServiceMetrics()); + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + final TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(ServiceMetrics metrics) { + return metrics.localName(); + } + }; + nameColumn.setSortable(true); + + final Column countColumn = new Column(new NumberCell()) { + @Override + public Number getValue(ServiceMetrics metrics) { + return metrics.getTotalCount(); + } + }; + countColumn.setSortable(true); + + final Column averageTimeColumn = new Column(new NumberCell()) { + @Override + public Number getValue(ServiceMetrics metrics) { + return metrics.getAverageProcessingTime(); + } + }; + averageTimeColumn.setSortable(true); + + final Column totalTimePercentageColumn = new Column( + new PercentageBarCell()) { + @Override + public Double getValue(ServiceMetrics metrics) { + if (_serviceMetrics == null || _serviceMetrics.getTotalProcessingTime() == 0) { + return 0.0; + } + return metrics.getTotalProcessingTime() / (double) _serviceMetrics.getTotalProcessingTime(); + } + }; + totalTimePercentageColumn.setSortable(true); + + final Column faultPercentageColumn = new Column( + new PercentageBarCell()) { + @Override + public Double getValue(ServiceMetrics metrics) { + if (metrics.getTotalCount() == 0) { + return 0.0; + } + return metrics.getFaultCount() / (double) metrics.getTotalCount(); + } + }; + faultPercentageColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(countColumn, createNumberColumnCommparator(countColumn)); + sortHandler.setComparator(averageTimeColumn, createNumberColumnCommparator(averageTimeColumn)); + sortHandler.setComparator(totalTimePercentageColumn, createNumberColumnCommparator(totalTimePercentageColumn)); + sortHandler.setComparator(faultPercentageColumn, createNumberColumnCommparator(faultPercentageColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(countColumn, Singleton.MESSAGES.label_messageCount()); + table.addColumn(averageTimeColumn, Singleton.MESSAGES.label_averageTime()); + table.addColumn(totalTimePercentageColumn, Singleton.MESSAGES.label_timePercent()); + table.addColumn(faultPercentageColumn, Singleton.MESSAGES.label_faultPercent()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(averageTimeColumn); + table.getColumnSortList().push(countColumn); + table.getColumnSortList().push(totalTimePercentageColumn); + table.getColumnSortList().push(faultPercentageColumn); + table.getColumnSortList().push(nameColumn); + } + + /** + * @param serviceMetrics the parent service's metrics, containing a list of + * reference metrics. + */ + public void setServiceMetrics(ServiceMetrics serviceMetrics) { + _serviceMetrics = serviceMetrics; + if (serviceMetrics == null) { + setData(null); + } else { + setData(serviceMetrics.getReferences()); + } + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferenceEditor.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferenceEditor.java new file mode 100644 index 000000000..058078e85 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferenceEditor.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.reference; + +import org.jboss.ballroom.client.widgets.ContentGroupLabel; +import org.jboss.ballroom.client.widgets.forms.Form; +import org.jboss.ballroom.client.widgets.forms.TextItem; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Reference; +import org.switchyard.console.client.ui.service.GatewaysList; +import org.switchyard.console.client.ui.widgets.ClickableTextItem; +import org.switchyard.console.client.ui.widgets.ClickableTextItem.ValueAdapter; +import org.switchyard.console.client.ui.widgets.LocalNameFormItem; +import org.switchyard.console.client.ui.widgets.NamespaceFormItem; + +import com.google.gwt.http.client.URL; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import com.gwtplatform.mvp.client.proxy.PlaceRequest; + +/** + * ReferenceEditor + * + * Editor for SwitchYard reference configuration. + */ +public class ReferenceEditor { + + private ReferencePresenter _presenter; + + private Form _implementationDetailsForm; + private GatewaysList _gatewaysList; + + private Reference _reference; + + /** + * Create a new ReferenceEditor. + */ + public ReferenceEditor() { + _gatewaysList = new GatewaysList(); + } + + /** + * @param presenter the current presenter. + */ + public void setPresenter(ReferencePresenter presenter) { + _presenter = presenter; + _gatewaysList.setPresenter(_presenter); + } + + /** + * @return this editor as a Widget. + */ + public Widget asWidget() { + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + + layout.add(createImplementationDetailsPanel()); + layout.add(createGatewayDetailsPanel()); + + return layout; + } + + /** + * @param reference the reference to be edited. + */ + public void setReference(Reference reference) { + _reference = reference; + + if (reference.getInterface() == null) { + // XXX: workaround to ensure interface field in the form gets set. + reference.setInterface(""); //$NON-NLS-1$ + } + + _implementationDetailsForm.clearValues(); + _implementationDetailsForm.edit(reference); + _gatewaysList.setData(reference.getGateways()); + } + + private Widget createImplementationDetailsPanel() { + TextItem nameItem = new LocalNameFormItem("name_1", Singleton.MESSAGES.label_name()); //$NON-NLS-1$ + TextItem namespaceItem = new NamespaceFormItem("name_2", Singleton.MESSAGES.label_namespace()); //$NON-NLS-1$ + ClickableTextItem applicationItem = new ClickableTextItem("application", Singleton.MESSAGES.label_application(), //$NON-NLS-1$ + new ValueAdapter() { + @Override + public String getText(String value) { + return NameTokens.parseQName(value)[1]; + } + + @Override + public String getTargetHistoryToken(String value) { + return createApplicationLink(value); + } + }); + TextItem interfaceItem = new TextItem("interface", Singleton.MESSAGES.label_interface()) { //$NON-NLS-1$ + @Override + public void setValue(String value) { + if (value == null || value.length() == 0) { + value = Singleton.MESSAGES.constant_inherited(); + } + super.setValue(value); + } + }; + + _implementationDetailsForm = new Form(Reference.class); + _implementationDetailsForm.setNumColumns(2); + _implementationDetailsForm.setFields(nameItem, applicationItem, namespaceItem, interfaceItem); + + VerticalPanel implementationDetailsLayout = new VerticalPanel(); + implementationDetailsLayout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + implementationDetailsLayout.add(new ContentGroupLabel(Singleton.MESSAGES.label_referenceDetails())); + implementationDetailsLayout.add(_implementationDetailsForm.asWidget()); + + return implementationDetailsLayout; + } + + private String createApplicationLink(String applicationName) { + PlaceRequest request = new PlaceRequest(NameTokens.APPLICATIONS_PRESENTER); + if (applicationName != null) { + request = request.with(NameTokens.APPLICATION_NAME_PARAM, URL.encode(applicationName)); + } + return _presenter.getPlaceManager().buildRelativeHistoryToken(request, -1); + } + + private Widget createGatewayDetailsPanel() { + return _gatewaysList.asWidget(); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferencePresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferencePresenter.java new file mode 100644 index 000000000..648d67867 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferencePresenter.java @@ -0,0 +1,245 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.reference; + +import java.util.List; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.spi.AccessControl; +import org.jboss.ballroom.client.layout.LHSHighlightEvent; +import org.switchyard.console.client.Messages; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Binding; +import org.switchyard.console.client.model.Reference; +import org.switchyard.console.client.model.SwitchYardStore; +import org.switchyard.console.client.ui.runtime.RuntimePresenter; +import org.switchyard.console.client.ui.service.GatewayPresenter; + +import com.google.gwt.core.client.Scheduler; +import com.google.gwt.http.client.URL; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.inject.Inject; +import com.google.web.bindery.event.shared.EventBus; +import com.gwtplatform.mvp.client.Presenter; +import com.gwtplatform.mvp.client.View; +import com.gwtplatform.mvp.client.annotations.NameToken; +import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; +import com.gwtplatform.mvp.client.annotations.TabInfo; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import com.gwtplatform.mvp.client.proxy.PlaceRequest; +import com.gwtplatform.mvp.client.proxy.ResetPresentersEvent; +import com.gwtplatform.mvp.client.proxy.RevealContentEvent; +import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace; + +/** + * ReferencePresenter + * + * Presenter for SwitchYard component configuration. + */ +public class ReferencePresenter extends Presenter implements + GatewayPresenter { + + /** + * MyProxy + * + * The proxy type used by this presenter. + */ + @ProxyCodeSplit + @NameToken(NameTokens.REFERENCES_PRESENTER) + @AccessControl(resources = {"/{selected.host}/{selected.server}/subsystem=switchyard" }) + public interface MyProxy extends TabContentProxyPlace { + } + + @TabInfo(container = RuntimePresenter.class, priority = 3) + static String getLabel(Messages messages) { + return messages.label_references(); + } + + /** + * MyView + * + * The view type used by this presenter. + */ + public interface MyView extends View { + /** + * @param presenter the presenter associated with the view. + */ + void setPresenter(ReferencePresenter presenter); + + /** + * @param reference set the reference to be viewed/edited. + */ + void setReference(Reference reference); + + /** + * @param references the references deployed on the server. + */ + void setReferencesList(List references); + } + + private final PlaceManager _placeManager; + private final SwitchYardStore _switchYardStore; + private String _applicationName; + private String _referenceName; + + /** + * Create a new ReferencePresenter. + * + * @param eventBus the injected EventBus. + * @param view the injected MyView. + * @param proxy the injected MyProxy. + * @param placeManager the injected PlaceManager. + * @param switchYardStore the injected SwitchYardStore. + */ + @Inject + public ReferencePresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, + SwitchYardStore switchYardStore) { + super(eventBus, view, proxy); + + _placeManager = placeManager; + _switchYardStore = switchYardStore; + } + + @Override + public void startGateway(Binding binding) { + _switchYardStore.startGateway(binding.getName(), _referenceName, _applicationName, new AsyncCallback() { + @Override + public void onSuccess(Void dummy) { + getEventBus().fireEvent(new ResetPresentersEvent()); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + @Override + public void stopGateway(Binding binding) { + _switchYardStore.stopGateway(binding.getName(), _referenceName, _applicationName, new AsyncCallback() { + @Override + public void onSuccess(Void dummy) { + getEventBus().fireEvent(new ResetPresentersEvent()); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + /** + * Notifies the presenter that the user has selected a reference. The + * presenter will load the reference details and pass them back to the view + * to be displayed. + * + * @param reference the selected reference. + */ + public void onReferenceSelected(Reference reference) { + PlaceRequest request = new PlaceRequest(NameTokens.REFERENCES_PRESENTER); + if (reference != null && reference.getName() != null) { + request = request.with(NameTokens.REFERENCE_NAME_PARAM, URL.encode(reference.getName())); + if (reference.getApplication() != null) { + request = request.with(NameTokens.APPLICATION_NAME_PARAM, URL.encode(reference.getApplication())); + } + } + _placeManager.revealRelativePlace(request, -1); + } + + @Override + protected void onBind() { + super.onBind(); + getView().setPresenter(this); + } + + @Override + public void prepareFromRequest(PlaceRequest request) { + super.prepareFromRequest(request); + + _referenceName = _placeManager.getCurrentPlaceRequest().getParameter(NameTokens.REFERENCE_NAME_PARAM, null); + _applicationName = _placeManager.getCurrentPlaceRequest().getParameter(NameTokens.APPLICATION_NAME_PARAM, null); + + if (_referenceName != null) { + _referenceName = URL.decode(_referenceName); + } + if (_applicationName != null) { + _applicationName = URL.decode(_applicationName); + } + } + + @Override + protected void onReveal() { + super.onReveal(); + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + fireEvent(new LHSHighlightEvent(NameTokens.RUNTIME_OPERATIONS_PRESENTER)); + } + }); + } + + @Override + protected void onReset() { + super.onReset(); + + loadReferencesList(); + loadReference(); + } + + @Override + protected void revealInParent() { + RevealContentEvent.fire(this, RuntimePresenter.TYPE_SET_TAB_CONTENT, this); + } + + private void loadReferencesList() { + _switchYardStore.loadReferences(new AsyncCallback>() { + @Override + public void onSuccess(List references) { + getView().setReferencesList(references); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void loadReference() { + if (_referenceName == null || _applicationName == null) { + getView().setReference(_switchYardStore.getBeanFactory().reference().as()); + return; + } + _switchYardStore.loadReference(_referenceName, _applicationName, new AsyncCallback() { + @Override + public void onSuccess(Reference reference) { + getView().setReference(reference); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + protected PlaceManager getPlaceManager() { + return _placeManager; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferenceView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferenceView.java new file mode 100644 index 000000000..169574e52 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferenceView.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.reference; + +import java.util.List; + +import org.jboss.as.console.client.core.DisposableViewImpl; +import org.jboss.as.console.client.layout.SimpleLayout; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Reference; + +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.SelectionChangeEvent; + +/** + * ReferenceView + * + * View for SwitchYard reference configuration. + */ +public class ReferenceView extends DisposableViewImpl implements ReferencePresenter.MyView { + + private ReferencePresenter _presenter; + private ReferencesList _referencesList; + private ReferenceEditor _referenceEditor; + private Reference _selectedReference; + + /** + * Create a new ReferenceView. + */ + public ReferenceView() { + super(); + _referencesList = new ReferencesList(); + _referencesList.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { + @Override + public void onSelectionChange(SelectionChangeEvent event) { + // prevent infinite recursion + if (_referencesList.getSelection() != _selectedReference) { + _presenter.onReferenceSelected(_referencesList.getSelection()); + } + } + }); + + _referenceEditor = new ReferenceEditor(); + } + + @Override + public Widget createWidget() { + SimpleLayout layout = new SimpleLayout() + .setPlain(true) + .setTitle(Singleton.MESSAGES.label_switchYardReferences()) + .setHeadline(Singleton.MESSAGES.label_references()) + .setDescription( + Singleton.MESSAGES.description_switchYardReferences()) + .addContent(Singleton.MESSAGES.label_references(), _referencesList.asWidget()) + .addContent(Singleton.MESSAGES.label_referenceDetails(), _referenceEditor.asWidget()); + + return layout.build(); + } + + @Override + public void setPresenter(ReferencePresenter presenter) { + _presenter = presenter; + _referenceEditor.setPresenter(presenter); + } + + @Override + public void setReferencesList(List references) { + _referencesList.setData(references); + } + + @Override + public void setReference(Reference reference) { + _selectedReference = reference; + _referencesList.setSelection(reference); + _referenceEditor.setReference(reference); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferencesList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferencesList.java new file mode 100644 index 000000000..680855b6b --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/reference/ReferencesList.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.reference; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Reference; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.cell.client.ClickableTextCell; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ReferencesList + * + * Wraps a table control for displaying an application's references. + */ +public class ReferencesList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(Reference item) { + return item.getName(); + } + }; + + /** + * Create a new ReferencesList. + */ + public ReferencesList() { + super(Singleton.MESSAGES.label_references()); + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + Column nameColumn = new Column(new ClickableTextCell()) { + @Override + public String getValue(Reference reference) { + return reference.localName(); + } + }; + nameColumn.setSortable(true); + + final TextColumn namespaceColumn = new TextColumn() { + @Override + public String getValue(Reference reference) { + return reference.namespace(); + } + }; + namespaceColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(namespaceColumn, createColumnCommparator(namespaceColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(namespaceColumn, Singleton.MESSAGES.label_targetNamespace()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(namespaceColumn); + table.getColumnSortList().push(nameColumn); + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/runtime/RuntimePresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/runtime/RuntimePresenter.java new file mode 100644 index 000000000..9e7e7bc0e --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/runtime/RuntimePresenter.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.runtime; + +import org.jboss.as.console.client.plugins.RuntimeGroup; +import org.jboss.as.console.client.shared.state.ServerSelectionChanged; +import org.jboss.as.console.client.shared.subsys.RevealStrategy; +import org.jboss.as.console.spi.AccessControl; +import org.jboss.as.console.spi.RuntimeExtension; +import org.jboss.ballroom.client.layout.LHSHighlightEvent; +import org.switchyard.console.client.NameTokens; + +import com.google.gwt.core.client.Scheduler; +import com.google.gwt.event.shared.GwtEvent.Type; +import com.google.inject.Inject; +import com.google.web.bindery.event.shared.EventBus; +import com.gwtplatform.mvp.client.RequestTabsHandler; +import com.gwtplatform.mvp.client.TabContainerPresenter; +import com.gwtplatform.mvp.client.TabView; +import com.gwtplatform.mvp.client.annotations.ContentSlot; +import com.gwtplatform.mvp.client.annotations.NameToken; +import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; +import com.gwtplatform.mvp.client.annotations.RequestTabs; +import com.gwtplatform.mvp.client.proxy.Proxy; +import com.gwtplatform.mvp.client.proxy.RevealContentHandler; + +/** + * RuntimePresenter + * + * Presenter for SwitchYard application. + * + * @author Rob Cernich + */ +public class RuntimePresenter extends TabContainerPresenter + implements ServerSelectionChanged.ChangeListener { + + /** + * MyProxy + * + * The proxy type associated with this presenter. + */ + @ProxyCodeSplit + @NameToken(NameTokens.RUNTIME_OPERATIONS_PRESENTER) + @RuntimeExtension(name = NameTokens.RUNTIME_TEXT, group = RuntimeGroup.OPERATiONS, key = NameTokens.SUBSYSTEM) + @AccessControl(resources = {"/{selected.host}/{selected.server}/subsystem=switchyard" }) + public interface MyProxy extends Proxy { + } + + /** + * MyView + * + * The view type associated with this presenter. + */ + public interface MyView extends TabView { + /** + * Refresh the tab view. + */ + // public void refreshTabs(); + } + + /** + * This will be the event sent to our "unknown" child presenters, in order + * for them to register their tabs. + */ + @RequestTabs + public static final Type TYPE_REQUEST_TABS = new Type(); + + // XXX: gwtp 0.7+ + // /** + // * Fired by child proxie's when their tab content is changed. + // */ + // @ChangeTab + // public static final Type TYPE_ChangeTab = new + // Type(); + + /** + * Use this in leaf presenters, inside their {@link #revealInParent} method. + */ + @ContentSlot + public static final Type> TYPE_SET_TAB_CONTENT = new Type>(); + + private final RevealStrategy _revealStrategy; + + /** + * Create a new RuntimePresenter. + * + * @param eventBus the injected EventBus. + * @param view the injected MyView. + * @param proxy the injected MyProxy. + * @param revealStrategy the RevealStrategy + */ + @Inject + public RuntimePresenter(EventBus eventBus, MyView view, MyProxy proxy, RevealStrategy revealStrategy) { + super(eventBus, view, proxy, TYPE_SET_TAB_CONTENT, TYPE_REQUEST_TABS); + + _revealStrategy = revealStrategy; + } + + @Override + public void onServerSelectionChanged(boolean isRunning) { + // getView().refreshTabs(); + } + + @Override + protected void onBind() { + super.onBind(); + // getEventBus().addHandler(ServerSelectionEvent.TYPE, this); + } + + @Override + protected void onReveal() { + super.onReveal(); + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + fireEvent(new LHSHighlightEvent(NameTokens.RUNTIME_OPERATIONS_PRESENTER)); + } + }); + } + + @Override + protected void revealInParent() { + _revealStrategy.revealInRuntimeParent(this); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/runtime/RuntimeView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/runtime/RuntimeView.java new file mode 100644 index 000000000..2b8a46846 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/runtime/RuntimeView.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.runtime; + +import org.jboss.as.console.client.core.DisposableViewImpl; +import org.switchyard.console.client.ui.common.GWTPTabPanel; +import org.switchyard.console.client.ui.runtime.RuntimePresenter.MyView; + +import com.google.gwt.user.client.ui.IsWidget; +import com.google.gwt.user.client.ui.Widget; +import com.google.inject.Inject; +import com.gwtplatform.mvp.client.Tab; +import com.gwtplatform.mvp.client.TabData; +import com.gwtplatform.mvp.client.proxy.PlaceManager; + +/** + * RuntimeView + * + *

+ * View implementation for SwitchYard runtime metrics. + * + * @author Rob Cernich + */ +public class RuntimeView extends DisposableViewImpl implements MyView { + + private GWTPTabPanel _tabPanel; + + /** + * Create a new RuntimeView. + * + * @param placeManager the place manager. + */ + @Inject + public RuntimeView(PlaceManager placeManager) { + _tabPanel = new GWTPTabPanel(placeManager); + } + + @Override + public Widget asWidget() { + return _tabPanel.asWidget(); + } + + @Override + public Widget createWidget() { + return _tabPanel.asWidget(); + } + + @Override + public Tab addTab(TabData tabData, String historyToken) { + return _tabPanel.addTab(tabData, historyToken); + } + + @Override + public void removeTab(Tab tab) { + _tabPanel.removeTab(tab); + } + + @Override + public void removeTabs() { + _tabPanel.removeTabs(); + } + + @Override + public void setActiveTab(Tab tab) { + _tabPanel.setActiveTab(tab); + } + + @Override + public void changeTab(Tab tab, TabData tabData, String historyToken) { + _tabPanel.changeTab(tab, tabData, historyToken); + } + + @Override + public void setInSlot(Object slot, IsWidget content) { + if (slot == RuntimePresenter.TYPE_SET_TAB_CONTENT) { + _tabPanel.setContent(content == null ? null : content.asWidget()); + } else { + super.setInSlot(slot, content); + } + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/service/BindingDetailsWidget.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/BindingDetailsWidget.java new file mode 100644 index 000000000..9a461d448 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/BindingDetailsWidget.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.service; + +import org.switchyard.console.client.model.Binding; + +import com.google.gwt.dom.client.Element; +import com.google.gwt.user.client.DOM; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.ScrollPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * BindingDetailsWidget + * + * Provides a widget for displaying a {@link Binding}. + * + * @author Rob Cernich + */ +public class BindingDetailsWidget { + + private Element _bindingConfiguration; + + /** + * Create a new BindingDetailsWidget. + */ + public BindingDetailsWidget() { + } + + /** + * @return the widget + */ + public Widget asWidget() { + _bindingConfiguration = DOM.createElement("pre"); //$NON-NLS-1$ + + Element code = DOM.createElement("code"); //$NON-NLS-1$ + code.appendChild(_bindingConfiguration); + + HTML html = new HTML(); + html.getElement().appendChild(code); + html.setSize("100%", "100%"); //$NON-NLS-1$ //$NON-NLS-2$ + + ScrollPanel panel = new ScrollPanel(); + panel.setStyleName("fill-layout-width"); //$NON-NLS-1$ + panel.add(html); + panel.setSize("100%", "100%"); //$NON-NLS-1$ //$NON-NLS-2$ + + return panel; + } + + /** + * Updates the widget with the information from the specified binding. + * + * @param binding the binding + */ + public void setBinding(Binding binding) { + _bindingConfiguration.setInnerText(binding.getConfiguration()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/service/GatewayPresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/GatewayPresenter.java new file mode 100644 index 000000000..5e5493630 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/GatewayPresenter.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.service; + +import org.switchyard.console.client.model.Binding; + +/** + * GatewayPresenter + * + *

+ * Provides support for managing gateways/bindings. + */ +public interface GatewayPresenter { + + /** + * Tell the server to start the specified gateway. + * + * @param binding the gateway. + */ + void startGateway(Binding binding); + + /** + * Tell the server to stop the specified gateway. + * + * @param binding the gateway. + */ + void stopGateway(Binding binding); +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/service/GatewaysList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/GatewaysList.java new file mode 100644 index 000000000..ba690be74 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/GatewaysList.java @@ -0,0 +1,161 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.service; + +import java.util.EnumSet; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.jboss.ballroom.client.widgets.window.DefaultWindow; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Binding; +import org.switchyard.console.client.model.State; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.cell.client.ButtonCell; +import com.google.gwt.cell.client.FieldUpdater; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * GatewaysList + * + * Wraps a table control for displaying a service's gateways. + * + * @author Rob Cernich + */ +public class GatewaysList extends AbstractDataTable { + + private DefaultWindow _bindingDetailsWindow; + private BindingDetailsWidget _bindingDetailsWidget; + private GatewayPresenter _presenter; + + /** + * Create a new GatewaysList. + */ + public GatewaysList() { + super(Singleton.MESSAGES.label_gateways()); + } + + /** + * @param presenter the presenter. + */ + public void setPresenter(GatewayPresenter presenter) { + _presenter = presenter; + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + TextColumn nameColumn = new TextColumn() { + @Override + public String getValue(Binding binding) { + return binding.getName(); + } + }; + nameColumn.setSortable(true); + + TextColumn typeColumn = new TextColumn() { + @Override + public String getValue(Binding binding) { + return binding.getType(); + } + }; + typeColumn.setSortable(true); + + Column configColumn = new Column(new ButtonCell()) { + @Override + public String getValue(Binding dummy) { + return Singleton.MESSAGES.button_viewConfiguration(); + } + }; + configColumn.setFieldUpdater(new FieldUpdater() { + @Override + public void update(int index, Binding binding, String value) { + showDetails(binding); + } + }); + configColumn.setSortable(false); + + Column statusColumn = new TextColumn() { + @Override + public String getValue(Binding binding) { + return binding.getState() == null ? Singleton.MESSAGES.constant_unknown() : binding.getState().toString(); + } + }; + + Column startStopColumn = new Column(new ButtonCell()) { + @Override + public String getValue(Binding binding) { + return binding.getState() == null + || EnumSet. of(State.NONE, State.STOPPING).contains(binding.getState()) ? Singleton.MESSAGES.label_start() + : Singleton.MESSAGES.label_stop(); + } + }; + startStopColumn.setFieldUpdater(new FieldUpdater() { + @Override + public void update(int index, Binding binding, String value) { + if (EnumSet. of(State.STARTING, State.STARTED).contains(binding.getState())) { + _presenter.stopGateway(binding); + } else { + _presenter.startGateway(binding); + } + } + }); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(typeColumn, createColumnCommparator(typeColumn)); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(typeColumn, Singleton.MESSAGES.label_type()); + table.addColumn(statusColumn, Singleton.MESSAGES.label_status()); + table.addColumn(startStopColumn, Singleton.MESSAGES.label_startStop()); + table.addColumn(configColumn, Singleton.MESSAGES.label_configuration()); + + table.addColumnSortHandler(sortHandler); + + createBindingDetailsWindow(); + } + + @Override + protected ProvidesKey createKeyProvider() { + return new ProvidesKey() { + @Override + public Object getKey(Binding item) { + return item.getType() + ":" + item.getConfiguration(); + } + }; + } + + private void showDetails(Binding binding) { + _bindingDetailsWidget.setBinding(binding); + _bindingDetailsWindow.center(); + } + + private void createBindingDetailsWindow() { + _bindingDetailsWindow = new DefaultWindow(Singleton.MESSAGES.label_gatewayConfiguration()); + _bindingDetailsWindow.setGlassEnabled(true); + _bindingDetailsWindow.setAutoHideEnabled(true); + _bindingDetailsWindow.setAutoHideOnHistoryEventsEnabled(true); + _bindingDetailsWindow.setWidth(600); + _bindingDetailsWindow.setHeight(360); + + _bindingDetailsWidget = new BindingDetailsWidget(); + _bindingDetailsWindow.setWidget(_bindingDetailsWidget.asWidget()); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServiceEditor.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServiceEditor.java new file mode 100644 index 000000000..713855f0f --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServiceEditor.java @@ -0,0 +1,272 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.service; + +import java.util.Map; + +import org.jboss.as.console.client.widgets.ContentDescription; +import org.jboss.as.console.client.widgets.forms.BlankItem; +import org.jboss.as.console.client.widgets.forms.FormToolStrip; +import org.jboss.ballroom.client.widgets.ContentGroupLabel; +import org.jboss.ballroom.client.widgets.forms.CheckBoxItem; +import org.jboss.ballroom.client.widgets.forms.Form; +import org.jboss.ballroom.client.widgets.forms.FormItem; +import org.jboss.ballroom.client.widgets.forms.FormValidation; +import org.jboss.ballroom.client.widgets.forms.NumberBoxItem; +import org.jboss.ballroom.client.widgets.forms.TextItem; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Service; +import org.switchyard.console.client.model.Throttling; +import org.switchyard.console.client.ui.widgets.ClickableTextItem; +import org.switchyard.console.client.ui.widgets.ClickableTextItem.ValueAdapter; +import org.switchyard.console.client.ui.widgets.LocalNameFormItem; +import org.switchyard.console.client.ui.widgets.NamespaceFormItem; + +import com.google.gwt.event.logical.shared.BeforeSelectionEvent; +import com.google.gwt.event.logical.shared.BeforeSelectionHandler; +import com.google.gwt.http.client.URL; +import com.google.gwt.user.client.ui.TabPanel; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import com.gwtplatform.mvp.client.proxy.PlaceRequest; + +/** + * ServiceEditor + * + * Editor for SwitchYard service configuration. + * + * @author Rob Cernich + */ +public class ServiceEditor { + + private ServicePresenter _presenter; + + private Form _implementationDetailsForm; + private Form _throttlingDetailsForm; + private GatewaysList _gatewaysList; + private FormToolStrip _toolstrip; + + private Service _service; + + /** + * Create a new ServiceEditor. + */ + public ServiceEditor() { + _gatewaysList = new GatewaysList(); + } + + /** + * @param presenter the current presenter. + */ + public void setPresenter(ServicePresenter presenter) { + _presenter = presenter; + _gatewaysList.setPresenter(_presenter); + } + + /** + * @return this editor as a Widget. + */ + public Widget asWidget() { + VerticalPanel panel = new VerticalPanel(); + panel.add(new ContentGroupLabel(Singleton.MESSAGES.label_serviceDetails())); + panel.add(new ContentDescription(Singleton.MESSAGES.description_serviceDetails())); + panel.add(createImplementationDetailsPanel()); + + TabPanel tabs = new TabPanel(); + tabs.setStyleName("default-tabpanel"); //$NON-NLS-1$ + tabs.getElement().setAttribute("style", "margin-top:15px;"); //$NON-NLS-1$ //$NON-NLS-2$ + tabs.add(createGatewayDetailsPanel(), Singleton.MESSAGES.label_gateways()); + tabs.add(createThrottlingDetailsPanel(), Singleton.MESSAGES.label_throttling()); + tabs.addBeforeSelectionHandler(new BeforeSelectionHandler() { + @Override + public void onBeforeSelection(BeforeSelectionEvent event) { + _toolstrip.doCancel(); + } + }); + + panel.add(tabs); + tabs.selectTab(0); + + return panel; + } + + /** + * @param service the service to be edited. + */ + public void setService(Service service) { + _service = service; + + _toolstrip.doCancel(); + + _implementationDetailsForm.clearValues(); + _throttlingDetailsForm.clearValues(); + + if (service == null) { + _gatewaysList.setData(null); + } else { + if (service.getInterface() == null) { + // XXX: workaround to ensure interface field in the form gets + // set. + service.setInterface(""); //$NON-NLS-1$ + } + _implementationDetailsForm.edit(service); + if (service.getThrottling() != null) { + _throttlingDetailsForm.edit(service.getThrottling()); + } + _gatewaysList.setData(service.getGateways()); + } + } + + private Widget createImplementationDetailsPanel() { + TextItem nameItem = new LocalNameFormItem("name_1", Singleton.MESSAGES.label_name()); //$NON-NLS-1$ + TextItem namespaceItem = new NamespaceFormItem("name_2", Singleton.MESSAGES.label_namespace()); //$NON-NLS-1$ + ClickableTextItem applicationItem = new ClickableTextItem("application", Singleton.MESSAGES.label_application(), //$NON-NLS-1$ + new ValueAdapter() { + @Override + public String getText(String value) { + return NameTokens.parseQName(value)[1]; + } + + @Override + public String getTargetHistoryToken(String value) { + return createApplicationLink(value); + } + }); + TextItem interfaceItem = new TextItem("interface", Singleton.MESSAGES.label_interface()) { //$NON-NLS-1$ + @Override + public void setValue(String value) { + if (value == null || value.length() == 0) { + value = Singleton.MESSAGES.constant_inherited(); + } + super.setValue(value); + } + }; + ClickableTextItem implementationItem = new ClickableTextItem("promotedService", //$NON-NLS-1$ + Singleton.MESSAGES.label_promotedService(), new ValueAdapter() { + @Override + public String getText(String value) { + return NameTokens.parseQName(value)[1]; + } + + @Override + public String getTargetHistoryToken(String value) { + if (_service == null || _service.getApplication() == null) { + return createApplicationLink(null); + } + return createApplicationLink(_service.getApplication()); + } + }); + + _implementationDetailsForm = new Form(Service.class); + _implementationDetailsForm.setNumColumns(2); + _implementationDetailsForm.setFields(nameItem, applicationItem, namespaceItem); + _implementationDetailsForm.setFieldsInGroup(Singleton.MESSAGES.label_implementationDetails(), implementationItem, interfaceItem); + // don't disable as the fields won't display correctly + // _implementationDetailsForm.setEnabled(false); + + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + layout.add(_implementationDetailsForm.asWidget()); + return layout; + } + + private String createApplicationLink(String applicationName) { + PlaceRequest request = new PlaceRequest(NameTokens.APPLICATIONS_PRESENTER); + if (applicationName != null) { + request = request.with(NameTokens.APPLICATION_NAME_PARAM, URL.encode(applicationName)); + } + return _presenter.getPlaceManager().buildRelativeHistoryToken(request, -1); + } + + private Widget createGatewayDetailsPanel() { + _gatewaysList.setPresenter(_presenter); + return _gatewaysList.asWidget(); + } + + private Widget createThrottlingDetailsPanel() { + VerticalPanel layout = new VerticalPanel(); + layout.setStyleName("fill-layout-width"); //$NON-NLS-1$ + + CheckBoxItem enabledItem = new CheckBoxItem("enabled", Singleton.MESSAGES.label_enabled()); //$NON-NLS-1$ + NumberBoxItem maxRequestsItem = new NumberBoxItem("maxRequests", Singleton.MESSAGES.label_maximumRequests()) { //$NON-NLS-1$ + @Override + public boolean validate(Number value) { + return super.validate(value) && value.intValue() > 0; + } + }; + NumberBoxItem timePeriodItem = new NumberBoxItem("timePeriod", Singleton.MESSAGES.label_timePeriod()) { //$NON-NLS-1$ + @Override + public boolean validate(Number value) { + return super.validate(value) && value.intValue() > 0; + } + }; + timePeriodItem.setEnabled(false); + + _throttlingDetailsForm = new Form(Throttling.class) { + @SuppressWarnings("rawtypes") + public FormValidation validate() { + // copied from parent, but we always validate + FormValidation outcome = new FormValidation(); + for (Map groupItems : formItems.values()) { + for (FormItem item : groupItems.values()) { + Object value = item.getValue(); + // ascii or empty string are ok. the later will be + // checked in each form item implementation. + String stringValue = String.valueOf(value); + boolean ascii = stringValue.isEmpty() || stringValue.matches("^[\\u0020-\\u007e]+$"); //$NON-NLS-1$ + if (!ascii) { + outcome.addError(item.getName()); + item.setErroneous(true); + } else { + @SuppressWarnings("unchecked") + boolean validValue = item.validate(value); + if (validValue) { + item.setErroneous(false); + } else { + outcome.addError(item.getName()); + item.setErroneous(true); + } + } + } + } + return outcome; + } + }; + _throttlingDetailsForm.setNumColumns(2); + _throttlingDetailsForm.setFields(enabledItem, new BlankItem(), maxRequestsItem, timePeriodItem); + _throttlingDetailsForm.setEnabled(false); + + // toolstrip + _toolstrip = new FormToolStrip(_throttlingDetailsForm, + new FormToolStrip.FormCallback() { + @Override + public void onSave(Map changeset) { + _presenter.updateThrottling(_service, _throttlingDetailsForm.getEditedEntity(), changeset); + } + + @Override + public void onDelete(Throttling entity) { + } + }); + + _toolstrip.providesDeleteOp(false); // belongs to the top + + layout.add(_toolstrip.asWidget()); + layout.add(_throttlingDetailsForm.asWidget()); + + return layout; + } +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServicePresenter.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServicePresenter.java new file mode 100644 index 000000000..7b7f6dd7a --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServicePresenter.java @@ -0,0 +1,272 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.service; + +import java.util.List; +import java.util.Map; + +import org.jboss.as.console.client.Console; +import org.jboss.as.console.spi.AccessControl; +import org.jboss.ballroom.client.layout.LHSHighlightEvent; +import org.switchyard.console.client.Messages; +import org.switchyard.console.client.NameTokens; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Binding; +import org.switchyard.console.client.model.Service; +import org.switchyard.console.client.model.SwitchYardStore; +import org.switchyard.console.client.model.Throttling; +import org.switchyard.console.client.ui.runtime.RuntimePresenter; + +import com.google.gwt.core.client.Scheduler; +import com.google.gwt.http.client.URL; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.inject.Inject; +import com.google.web.bindery.event.shared.EventBus; +import com.gwtplatform.mvp.client.Presenter; +import com.gwtplatform.mvp.client.View; +import com.gwtplatform.mvp.client.annotations.NameToken; +import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; +import com.gwtplatform.mvp.client.annotations.TabInfo; +import com.gwtplatform.mvp.client.proxy.PlaceManager; +import com.gwtplatform.mvp.client.proxy.PlaceRequest; +import com.gwtplatform.mvp.client.proxy.ResetPresentersEvent; +import com.gwtplatform.mvp.client.proxy.RevealContentEvent; +import com.gwtplatform.mvp.client.proxy.TabContentProxyPlace; + +/** + * ServicePresenter + * + * Presenter for SwitchYard component configuration. + * + * @author Rob Cernich + */ +public class ServicePresenter extends Presenter implements + GatewayPresenter { + + /** + * MyProxy + * + * The proxy type used by this presenter. + */ + @ProxyCodeSplit + @NameToken(NameTokens.SERVICES_PRESENTER) + @AccessControl(resources = {"/{selected.host}/{selected.server}/subsystem=switchyard" }) + public interface MyProxy extends TabContentProxyPlace { + } + + @TabInfo(container = RuntimePresenter.class, priority = 2) + static String getLabel(Messages messages) { + return messages.label_services(); + } + + /** + * MyView + * + * The view type used by this presenter. + */ + public interface MyView extends View { + /** + * @param presenter the presenter associated with the view. + */ + void setPresenter(ServicePresenter presenter); + + /** + * @param service set the service to be viewed/edited. + */ + void setService(Service service); + + /** + * @param services the services deployed on the server. + */ + void setServicesList(List services); + } + + private final PlaceManager _placeManager; + private final SwitchYardStore _switchYardStore; + private String _applicationName; + private String _serviceName; + + /** + * Create a new ServicePresenter. + * + * @param eventBus the injected EventBus. + * @param view the injected MyView. + * @param proxy the injected MyProxy. + * @param placeManager the injected PlaceManager. + * @param switchYardStore the injected SwitchYardStore. + */ + @Inject + public ServicePresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager, + SwitchYardStore switchYardStore) { + super(eventBus, view, proxy); + + _placeManager = placeManager; + _switchYardStore = switchYardStore; + } + + @Override + public void startGateway(Binding binding) { + _switchYardStore.startGateway(binding.getName(), _serviceName, _applicationName, new AsyncCallback() { + @Override + public void onSuccess(Void dummy) { + getEventBus().fireEvent(new ResetPresentersEvent()); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + @Override + public void stopGateway(Binding binding) { + _switchYardStore.stopGateway(binding.getName(), _serviceName, _applicationName, new AsyncCallback() { + @Override + public void onSuccess(Void dummy) { + getEventBus().fireEvent(new ResetPresentersEvent()); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + /** + * Updates the throttling configuration for the specified service. + * + * @param service the service + * @param throttling the new throttling configuration + * @param changeset what changed from the original configuration + */ + public void updateThrottling(Service service, Throttling throttling, Map changeset) { + _switchYardStore.updateThrottling(service, + _switchYardStore.processChangeSet(Throttling.class, throttling, changeset, false), + new AsyncCallback() { + @Override + public void onSuccess(Void dummy) { + getEventBus().fireEvent(new ResetPresentersEvent()); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + /** + * Notifies the presenter that the user has selected a service. The + * presenter will load the service details and pass them back to the view to + * be displayed. + * + * @param service the selected service. + */ + public void onServiceSelected(Service service) { + PlaceRequest request = new PlaceRequest(NameTokens.SERVICES_PRESENTER); + if (service != null && service.getName() != null) { + request = request.with(NameTokens.SERVICE_NAME_PARAM, URL.encode(service.getName())); + if (service.getApplication() != null) { + request = request.with(NameTokens.APPLICATION_NAME_PARAM, URL.encode(service.getApplication())); + } + } + _placeManager.revealRelativePlace(request, -1); + } + + @Override + protected void onBind() { + super.onBind(); + getView().setPresenter(this); + } + + @Override + public void prepareFromRequest(PlaceRequest request) { + super.prepareFromRequest(request); + + _serviceName = _placeManager.getCurrentPlaceRequest().getParameter(NameTokens.SERVICE_NAME_PARAM, null); + _applicationName = _placeManager.getCurrentPlaceRequest().getParameter(NameTokens.APPLICATION_NAME_PARAM, null); + + if (_serviceName != null) { + _serviceName = URL.decode(_serviceName); + } + if (_applicationName != null) { + _applicationName = URL.decode(_applicationName); + } + } + + @Override + protected void onReveal() { + super.onReveal(); + Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { + @Override + public void execute() { + fireEvent(new LHSHighlightEvent(NameTokens.RUNTIME_OPERATIONS_PRESENTER)); + } + }); + } + + @Override + protected void onReset() { + super.onReset(); + + loadServicesList(); + loadService(); + } + + @Override + protected void revealInParent() { + RevealContentEvent.fire(this, RuntimePresenter.TYPE_SET_TAB_CONTENT, this); + } + + private void loadServicesList() { + _switchYardStore.loadServices(new AsyncCallback>() { + @Override + public void onSuccess(List services) { + getView().setServicesList(services); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + private void loadService() { + if (_serviceName == null || _applicationName == null) { + getView().setService(null); + return; + } + _switchYardStore.loadService(_serviceName, _applicationName, new AsyncCallback() { + + @Override + public void onSuccess(Service service) { + getView().setService(service); + } + + @Override + public void onFailure(Throwable caught) { + Console.error(Singleton.MESSAGES.error_unknown(), caught.getMessage()); + } + }); + } + + protected PlaceManager getPlaceManager() { + return _placeManager; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServiceView.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServiceView.java new file mode 100644 index 000000000..fa51f8493 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServiceView.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.service; + +import java.util.List; + +import org.jboss.as.console.client.core.DisposableViewImpl; +import org.jboss.as.console.client.layout.SimpleLayout; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Service; + +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.SelectionChangeEvent; + +/** + * ServiceView + * + * View for SwitchYard service configuration. + * + * @author Rob Cernich + */ +public class ServiceView extends DisposableViewImpl implements ServicePresenter.MyView { + + private ServicePresenter _presenter; + private ServicesList _servicesList; + private ServiceEditor _serviceEditor; + private Service _selectedService; + + /** + * Create a new ServiceView. + */ + public ServiceView() { + super(); + _servicesList = new ServicesList(); + _servicesList.addSelectionChangeHandler(new SelectionChangeEvent.Handler() { + @Override + public void onSelectionChange(SelectionChangeEvent event) { + // prevent infinite recursion + if (_servicesList.getSelection() != _selectedService) { + _presenter.onServiceSelected(_servicesList.getSelection()); + } + } + }); + + _serviceEditor = new ServiceEditor(); + + } + + @Override + public Widget createWidget() { + SimpleLayout layout = new SimpleLayout() + .setPlain(true) + .setTitle(Singleton.MESSAGES.label_switchYardServices()) + .setHeadline(Singleton.MESSAGES.label_services()) + .setDescription( + Singleton.MESSAGES.description_switchYardServices()) + .addContent(Singleton.MESSAGES.label_services(), _servicesList.asWidget()) + .addContent(Singleton.MESSAGES.label_serviceDetails(), _serviceEditor.asWidget()); + + return layout.build(); + } + + @Override + public void setPresenter(ServicePresenter presenter) { + _presenter = presenter; + _serviceEditor.setPresenter(presenter); + } + + @Override + public void setServicesList(List services) { + _servicesList.setData(services); + } + + @Override + public void setService(Service service) { + _selectedService = service; + _servicesList.setSelection(service); + _serviceEditor.setService(service); + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServicesList.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServicesList.java new file mode 100644 index 000000000..e2f2d07e3 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/service/ServicesList.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.service; + +import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; +import org.switchyard.console.client.Singleton; +import org.switchyard.console.client.model.Service; +import org.switchyard.console.client.ui.common.AbstractDataTable; + +import com.google.gwt.cell.client.ClickableTextCell; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.ProvidesKey; + +/** + * ServicesList + * + * Wraps a table control for displaying an application's services. + * + * @author Rob Cernich + */ +public class ServicesList extends AbstractDataTable { + + private static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { + @Override + public Object getKey(Service item) { + return item.getName(); + } + }; + + /** + * Create a new ServicesList. + */ + public ServicesList() { + super(Singleton.MESSAGES.label_services()); + } + + @Override + protected void createColumns(DefaultCellTable table, ListDataProvider dataProvider) { + Column nameColumn = new Column(new ClickableTextCell()) { + @Override + public String getValue(Service service) { + return service.localName(); + } + }; + nameColumn.setSortable(true); + + final TextColumn namespaceColumn = new TextColumn() { + @Override + public String getValue(Service service) { + return service.namespace(); + } + }; + namespaceColumn.setSortable(true); + + ColumnSortEvent.ListHandler sortHandler = new ColumnSortEvent.ListHandler( + dataProvider.getList()); + sortHandler.setComparator(nameColumn, createColumnCommparator(nameColumn)); + sortHandler.setComparator(namespaceColumn, createColumnCommparator(namespaceColumn)); + + table.addColumn(nameColumn, Singleton.MESSAGES.label_name()); + table.addColumn(namespaceColumn, Singleton.MESSAGES.label_targetNamespace()); + + table.addColumnSortHandler(sortHandler); + table.getColumnSortList().push(namespaceColumn); + table.getColumnSortList().push(nameColumn); + } + + @Override + protected ProvidesKey createKeyProvider() { + return KEY_PROVIDER; + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/ClickableTextItem.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/ClickableTextItem.java new file mode 100644 index 000000000..2c66ade04 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/ClickableTextItem.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.console.client.ui.widgets; + +import org.jboss.ballroom.client.widgets.forms.FormItem; + +import com.google.gwt.user.client.ui.Hyperlink; +import com.google.gwt.user.client.ui.Widget; + +/** + * ClickableTextItem + * + * Presents the text for the form field as a read-only hyperlink. + * + * @param the value type managed by this object. + * + * @author Rob Cernich + */ +public class ClickableTextItem extends FormItem { + + /** + * ValueAdapter + * + * Provides services for retrieving the display text and link token for the + * current field value. + * + * @author Rob Cernich + */ + public interface ValueAdapter { + /** + * @param value the field's current value. + * @return the text to display for the value. + */ + public String getText(T value); + + /** + * @param value the field's current value. + * @return the history token to use for the value. + */ + public String getTargetHistoryToken(T value); + } + + private T _value; + private ValueAdapter _valueAdapter; + private Hyperlink _link; + + /** + * Create a new ClickableTextItem. + * + * @param name the name of the bean member. + * @param title the label text. + * @param valueAdapter the adapter for the field value. + */ + public ClickableTextItem(String name, String title, ValueAdapter valueAdapter) { + super(name, title); + _link = new Hyperlink(); + _valueAdapter = valueAdapter; + + resetMetaData(); + } + + @Override + public T getValue() { + return _value; + } + + @Override + public void setValue(T value) { + _link.setText(_valueAdapter.getText(value)); + _link.setTargetHistoryToken(_valueAdapter.getTargetHistoryToken(value)); + } + + @Override + public Widget asWidget() { + return _link; + } + + @Override + public void setEnabled(boolean b) { + // it's not editable anyway + } + + @Override + public boolean validate(T value) { + return true; + } + + @Override + public void clearValue() { + setValue(null); + } +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/LocalNameFormItem.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/LocalNameFormItem.java new file mode 100644 index 000000000..94437f8b2 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/LocalNameFormItem.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.widgets; + +import org.jboss.ballroom.client.widgets.forms.TextItem; +import org.switchyard.console.client.NameTokens; + +/** + * LocalNameFormItem + * + * Unwraps the local value of a qname string. + * + * @author Rob Cernich + */ +public class LocalNameFormItem extends TextItem { + + private String _value; + + /** + * Create a new LocalNameFormItem. + * + * @param name the property name. + * @param title the display text. + */ + public LocalNameFormItem(String name, String title) { + super(name, title); + } + + @Override + public String getValue() { + return _value; + } + + @Override + public void clearValue() { + _value = null; + super.clearValue(); + } + + @Override + public void setValue(String value) { + _value = value; + super.setValue(NameTokens.parseQName(value)[1]); + } + + @Override + public void setEnabled(boolean b) { + // not editable + } + +} diff --git a/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/NamespaceFormItem.java b/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/NamespaceFormItem.java new file mode 100644 index 000000000..bf60c4039 --- /dev/null +++ b/console/gwt/src/main/java/org/switchyard/console/client/ui/widgets/NamespaceFormItem.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.console.client.ui.widgets; + +import org.jboss.ballroom.client.widgets.forms.TextItem; +import org.switchyard.console.client.NameTokens; + +/** + * NamespaceFormItem + * + * Unwraps the namespace value of a qname string. + * + * @author Rob Cernich + */ +public class NamespaceFormItem extends TextItem { + + private String _value; + + /** + * Create a new NamespaceFormItem. + * + * @param name the property name. + * @param title the display text. + */ + public NamespaceFormItem(String name, String title) { + super(name, title); + } + + @Override + public String getValue() { + return _value; + } + + @Override + public void clearValue() { + _value = null; + super.clearValue(); + } + + @Override + public void setValue(String value) { + _value = value; + super.setValue(NameTokens.parseQName(value)[0]); + } + + @Override + public void setEnabled(boolean b) { + // not editable + } + +} diff --git a/console/gwt/src/main/resources/org/switchyard/console/client/Messages.properties b/console/gwt/src/main/resources/org/switchyard/console/client/Messages.properties new file mode 100644 index 000000000..811f3442c --- /dev/null +++ b/console/gwt/src/main/resources/org/switchyard/console/client/Messages.properties @@ -0,0 +1,119 @@ +button_details=Details... +button_viewConfiguration=View Configuration... +button_viewDetails=View Details... +constant_inherited= +constant_unknown=Unknown +description_applicationDetails=Displays details for a specific application. Select an application to see its implementation details. +description_applications=Displays a list of deployed SwitchYard applications. Select an application to see more details. +description_artifactReferences=Displays all artifacts referenced throughout the system, along with the applications referencing a specific artifact. +description_referenceMetrics=Displays message metrics for a selected reference. +description_serviceDetails=Displays details for the selected service. +description_serviceMetrics=Displays message metrics for a selected service. +description_switchYardReferences=Displays a list of deployed SwitchYard references. Select a reference to see more details. +description_switchYardRuntime=Displays details about the SwitchYard runtime. +description_switchYardServices=Displays a list of deployed SwitchYard services. Select a service to see more details. +description_systemMetrics=Displays message metrics for the SwitchYard subsystem. +error_allReferenceMetricsLoad=Could not load all reference metrics. +error_allServiceMetricsLoad=Could not load all service metrics. +error_applicationLoad=Could not load information for application: {0} +error_artifactsLoad=Could not load artifact references. +error_comparisonColumnWithoutBaseline=Comparison column specified, but no baseline set\! +error_componentLoad=Could not load information for component: {0} +error_illegalBaselineIndex=Illegal baseline index {0,number} on number of samples {1,number}. +error_metricIsNullAtIndex=Metric value at index {0,number} is null +error_navigateToApplication=Cannot reveal application details. No application specified. +error_navigateToReference=Cannot reveal reference details. No reference or application specified. +error_navigateToService=Cannot reveal service details. No service or application specified. +error_referenceLoad=Could not load information for reference: {0} from application: {1} +error_resetObjectMetrics=Failure resetting metrics for {0}: {1} +error_resetSystemMetrics=Failure resetting system metrics: {0} +error_serviceLoad=Could not load information for service: {0} from application: {1} +error_serviceMetricsLoad=Could not load metrics for service: {0} +error_setProperty=Failure setting property: {0} +error_startGateway=Failure starting gateway for {0}: {1} +error_stopGateway=Failure stopping gateway for {0}: {1} +error_systemMetricsLoad=Could not load metrics for system +error_unknown=Unknown error +error_updateThrottling=Failure updating throttling details for {0}: {1} +label_actual=Actual +label_applicationDetails=Application Details +label_applicationName=Application Name +label_applicationNamespace=Application Namespace +label_application=Application +label_applications=Applications +label_applicationsUsingArtifacts=Applications Using Artifact +label_artifactReferences=Artifact References +label_artifacts=Artifacts +label_averageProcessingTime=Average Processing Time +label_averageTime=Average Time +label_componentDetails=Component Details +label_componentServices=Component Services +label_configuration=Configuration +label_coreRuntime=Core Runtime +label_details=Details +label_enabled=Enabled +label_faultCount=Fault Count +label_faultPercent=Fault % +label_from=From +label_gatewayConfiguration=Gateway Configuration +label_gatewayMetrics=Gateway Metrics +label_gateways=Gateways +label_implementation=Implementation +label_implementationDetails=Implementation Details +label_implementationInstance={0} implementation +label_installedComponents=Installed Components +label_interface=Interface +label_maximumRequests=Maximum Requests +label_maxProcessingTime=Max. Processing Time +label_messageCount=Message Count +label_messageCounts=Message Counts +label_metric=Metric +label_minProcessingTime=Min. Processing Time +label_name=Name +label_namespace=Namespace +label_operationMetrics=Operation Metrics +label_processingTimes=Processing Times +label_promotedService=Promoted Service +label_properties=Properties +label_rawConfiguration=Raw Configuration +label_referenceDetails=Reference Details +label_referencedServiceMetrics=Referenced Service Metrics +label_referenceMessageMetrics=Reference Message Metrics +label_referenceMetrics=Reference Metrics +label_references=References +label_referencingApplications=Referencing Applications +label_reset=Reset +label_resetAllMetrics=Reset All Metrics +label_resetMetrics=Reset Metrics +label_runtimeDetails=Runtime Details +label_serviceDetails=Service Details +label_serviceMessageMetrics=Service Message Metrics +label_serviceMetrics=Service Metrics +label_serviceOperationMetrics=Service Operation Metrics +label_services=Services +label_start=Start +label_startStop=Start/Stop +label_status=Status +label_stop=Stop +label_successCount=Success Count +label_switchYardApplications=SwitchYard Applications +label_switchYardArtifactReferences=SwitchYard Artifact References +label_switchYardMessageMetrics=SwitchYard Message Metrics +label_switchYardReferences=SwitchYard References +label_switchYardRuntime=SwitchYard Runtime +label_switchYardRuntimeDetails=SwitchYard Runtime Details +label_switchYardServices=SwitchYard Services +label_system=System +label_systemMessageMetrics=System Message Metrics +label_targetNamespace=Target Namespace +label_throttling=Throttling +label_timePercent=Time % +label_timePeriod=Time Period (millis) +label_to=To +label_totalCount=Total Count +label_totalProcessingTime=Total Processing Time +label_transformers=Transformers +label_type=Type +label_url=URL +label_validators=Validators +label_version=Version diff --git a/console/gwt/src/test/resources/org/switchyard/console/ApplicationJUnit.gwt.xml b/console/gwt/src/test/resources/org/switchyard/console/ApplicationJUnit.gwt.xml new file mode 100644 index 000000000..e88b3b9ae --- /dev/null +++ b/console/gwt/src/test/resources/org/switchyard/console/ApplicationJUnit.gwt.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/console/pom.xml b/console/pom.xml new file mode 100644 index 000000000..65fcb78c3 --- /dev/null +++ b/console/pom.xml @@ -0,0 +1,111 @@ + + + + + org.switchyard + switchyard-parent + 2.1.0-SNAPSHOT + .. + + 4.0.0 + org.switchyard.console + switchyard-console-parent + pom + SwitchYard: Console Parent + SwitchYard Management Console parent project. + + scm:git:https://github.com/jboss-switchyard/console.git + scm:git:ssh://git@github.com:jboss-switchyard/console.git + http://github.com/jboss-switchyard/console + + + 2.5.1 + 2.2.8.Final + + + component + gwt + app + + + + + org.jboss.as + jboss-as-console-bom + ${version.jbossas.console} + pom + import + + + org.bsc.maven + maven-processor-plugin + + + + + + + + + + org.codehaus.mojo + gwt-maven-plugin + ${version.com.google.gwt} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-versions + + enforce + + + + + 1.7 + + + + 3.1.0 + + + + + + + + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + https://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + + diff --git a/core/.gitignore b/core/.gitignore new file mode 100644 index 000000000..059d13efc --- /dev/null +++ b/core/.gitignore @@ -0,0 +1,16 @@ +.project +.classpath +.settings/ +target/ +bin/ +components-file/bin/ +core/bin/ +.checkstyle +*.iml +*.ipr +*.iws +.xml +.DS_Store +.idea +.fbExcludeFilterFile +.factorypath diff --git a/core/README.txt b/core/README.txt new file mode 100644 index 000000000..528f37862 --- /dev/null +++ b/core/README.txt @@ -0,0 +1,39 @@ +README +====== +Project instructions for developers below. + +Java: +----- +- Tested version = Sun JDK 1.6.0_20 +- export JAVA_HOME=/path/to/your/jdk +- export PATH=$JAVA_HOME/bin:$PATH + +Maven: +------ +- Tested version = 2.2.1 +- There are issues running the precommit checks with maven-3.0.1 - please use +the tested version specified above +- 'mvn clean install' to build +- 'mvn install -DskipTests=true' to skip tests +- 'mvn install findbugs:findbugs' to enable findbugs +- 'mvn install checkstyle:checkstyle' to enable checkstyle +- 'mvn javadoc:aggregate' to just run javadoc (see target/site/apidocs/index.html) + +Eclipse: +-------- +- Tested version = JBoss Developer Studio 3.0.0 + +[Using M2Eclipse] + - File -> Import... -> Maven -> Existing Maven Projects -> [Next >] -> + [Browse...] ->/path/to/core -> [OK] -> [Finish] + +[Using mvn eclipse:eclipse] +- 'mvn eclipse:clean; mvn eclipse:eclipse' (creates .project, .classpath, .settings/) + +- Window -> Preferences -> Java -> Build Path -> Classpath Variables -> [New...] + Name: M2_REPO + Path: /home//.m2/repository ( == jdoe, for example) + +- File -> Import... -> General -> Existing Projects into Workspace -> [Next >] -> + [Browse...] ->/path/to/core -> [OK] -> [Finish] + diff --git a/core/admin/pom.xml b/core/admin/pom.xml new file mode 100644 index 000000000..687141e60 --- /dev/null +++ b/core/admin/pom.xml @@ -0,0 +1,68 @@ + + + + 4.0.0 + switchyard-admin + bundle + SwitchYard: Admin + SwitchYard Administration + http://switchyard.org + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../pom.xml + + + + org.switchyard.admin.* + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-extensions-java + + + org.switchyard + switchyard-extensions-wsdl + + + org.switchyard + switchyard-runtime + + + org.mockito + mockito-all + test + + + diff --git a/core/admin/src/main/java/org/switchyard/admin/AdminLogger.java b/core/admin/src/main/java/org/switchyard/admin/AdminLogger.java new file mode 100644 index 000000000..2cd3615c8 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/AdminLogger.java @@ -0,0 +1,18 @@ +package org.switchyard.admin; + +import org.jboss.logging.Logger; + +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 10600-10799 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface AdminLogger { + /** + * A root logger with the category of the package name. + */ + AdminLogger ROOT_LOGGER = Logger.getMessageLogger(AdminLogger.class, AdminLogger.class.getPackage().getName()); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/AdminMessages.java b/core/admin/src/main/java/org/switchyard/admin/AdminMessages.java new file mode 100644 index 000000000..96b5553b4 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/AdminMessages.java @@ -0,0 +1,19 @@ +package org.switchyard.admin; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 10400-10599 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface AdminMessages { + /** + * The default messages. + */ + AdminMessages MESSAGES = Messages.getBundle(AdminMessages.class); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/Application.java b/core/admin/src/main/java/org/switchyard/admin/Application.java new file mode 100644 index 000000000..e5faada11 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/Application.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin; + +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Application + * + * Represents an application deployed within the SwitchYard runtime. + */ +public interface Application { + /** + * @return the services exported by this application. + */ + public List getServices(); + + /** + * @param serviceName the name of a service provided by this application. + * @return the requested service, may be null + */ + public Service getService(QName serviceName); + + /** + * @return the references consumed by this application. + */ + public List getReferences(); + + /** + * @param referenceName the name of a reference consumed by this application. + * @return the requested reference, may be null + */ + public Reference getReference(QName referenceName); + + /** + * @return the component services contained by this application. + */ + public List getComponentServices(); + + /** + * @param componentServiceName the name of a component service contained by + * this application. + * @return the requested service, may be null + */ + public ComponentService getComponentService(QName componentServiceName); + + /** + * @return the transformers provided by this application + */ + public List getTransformers(); + + /** + * @return the validators provided by this application + */ + public List getValidators(); + + /** + * Returns the name of the application. This will be the name specified + * within the switchyard.xml file, if one exists. If a name is not specified + * within the switchyard.xml file, the deployment archive name will be + * returned. + * + * @return the name of this application. + */ + public QName getName(); + + /** + * Return the application descriptor. + * @return the config model for the application descriptor + */ + public SwitchYardModel getConfig(); + + /** + * @return the properties defined for this application. + */ + public Map getProperties(); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/Binding.java b/core/admin/src/main/java/org/switchyard/admin/Binding.java new file mode 100644 index 000000000..2fd0d2b4c --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/Binding.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin; + +import org.switchyard.deploy.Lifecycle; + +/** + * Binding + * + * Represents a gateway binding defined on a {@link Service}. + * + * @author Rob Cernich + */ +public interface Binding extends MessageMetricsAware, Lifecycle { + + /** + * @return the type of binding (e.g. soap) + */ + public String getType(); + + /** + * Returns the name of the binding. + * @return binding name + */ + public String getName(); + + /** + * @return the raw configuration details + */ + public String getConfiguration(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/Component.java b/core/admin/src/main/java/org/switchyard/admin/Component.java new file mode 100644 index 000000000..71b9af040 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/Component.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin; + +import java.util.Map; +import java.util.Set; + +/** + * Component + * + * Represents a SwitchYard component registered with the SwitchYard runtime + * (e.g. camel). + */ +public interface Component { + /** + * @return the name of this component. + */ + String getName(); + + /** + * @return supported activation types, e.g. bean, soap, etc. + */ + Set getTypes(); + + /** + * @return component properties. + */ + Map getProperties(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/ComponentReference.java b/core/admin/src/main/java/org/switchyard/admin/ComponentReference.java new file mode 100644 index 000000000..cbeb7e650 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/ComponentReference.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin; + +import javax.xml.namespace.QName; + +/** + * ComponentReference + * + * Represents a referenced service required by a component. + * + * @author Rob Cernich + */ +public interface ComponentReference extends MessageMetricsAware { + + /** + * @return the name of this reference. + */ + QName getName(); + + /** + * @return the interface required for this reference. + */ + String getInterface(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/ComponentService.java b/core/admin/src/main/java/org/switchyard/admin/ComponentService.java new file mode 100644 index 000000000..5e4093269 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/ComponentService.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * ComponentService + * + * Represents a component service (i.e. implementation). + * + * @author Rob Cernich + */ +public interface ComponentService extends MessageMetricsAware { + + /** + * @return the name of this service. + */ + QName getName(); + + /** + * @return the implementation type used to implement this service. + */ + String getImplementation(); + + /** + * @return the raw configuration for the implementation defined for this + * service. + */ + String getImplementationConfiguration(); + + /** + * @return the interface implemented by this service. + */ + String getInterface(); + + /** + * @return the operations exposed by this service. + */ + List getServiceOperations(); + + /** + * Gets service operation by name. + * @param operation the name of a operation provided by this service. + * @return the requested operation, may be null + */ + ServiceOperation getServiceOperation(String operation); + + /** + * @return the references required by this service. + */ + List getReferences(); + + /** + * @return the application which exports this service. + */ + Application getApplication(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/ComponentType.java b/core/admin/src/main/java/org/switchyard/admin/ComponentType.java new file mode 100644 index 000000000..29b28fde5 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/ComponentType.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin; + +/** + * ComponentType + * + * Represents the type of a component. + */ +public enum ComponentType { + /** The component provides gateway services. */ + GATEWAY, + /** The component represents an implementation type. */ + IMPLEMENTATION; +} diff --git a/core/admin/src/main/java/org/switchyard/admin/MessageMetrics.java b/core/admin/src/main/java/org/switchyard/admin/MessageMetrics.java new file mode 100644 index 000000000..2fa536d97 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/MessageMetrics.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin; + +/** + * Reports messaging metrics for entities in a SwitchYard domain : service, + * reference, runtime, etc. + */ +public interface MessageMetrics { + + /** + * Return the number of successful messages. + * @return success count + */ + int getSuccessCount(); + /** + * Return the number of failed messages. + * @return fault count + */ + int getFaultCount(); + /** + * Return the total number of messages processed. This is equivalent to + * getSuccessCount() + getFaultCount(). + * @return total message count + */ + int getTotalCount(); + /** + * Total processing time for all messages in TimeUnit.MILLISECONDS. + * @return total processing time + */ + long getTotalProcessingTime(); + /** + * Average processing time for all messages in TimeUnit.MILLISECONDS. + * @return average processing time + */ + double getAverageProcessingTime(); + /** + * Minimum processing time for a message in TimeUnit.MILLISECONDS. + * @return min processing time + */ + int getMinProcessingTime(); + /** + * Maximum processing time for a message in TimeUnit.MILLISECONDS. + * @return max processing time + */ + int getMaxProcessingTime(); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/MessageMetricsAware.java b/core/admin/src/main/java/org/switchyard/admin/MessageMetricsAware.java new file mode 100644 index 000000000..13e8a8c87 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/MessageMetricsAware.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin; + +import org.switchyard.Exchange; + +/** + * Message metric aware element which is interested in collecting them from + * executed exchanges. + */ +public interface MessageMetricsAware { + + /** + * Gets related message metrics. + * @return Message metrics. + */ + MessageMetrics getMessageMetrics(); + + /** + * Reset all collected metrics. + */ + void resetMessageMetrics(); + + /** + * Collect metrics from given exchange. + * @param exchange Completed exchange. + */ + void recordMetrics(Exchange exchange); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/Reference.java b/core/admin/src/main/java/org/switchyard/admin/Reference.java new file mode 100644 index 000000000..287b090c2 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/Reference.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * Reference + * + * Represents an application dependency exported through the SwitchYard runtime. + */ +public interface Reference extends MessageMetricsAware { + + /** + * @return the name of this reference. + */ + QName getName(); + + /** + * @return the component reference promoted by this service. + */ + String getPromotedReference(); + + /** + * @return the gateway bindings for this reference. + */ + List getGateways(); + + /** + * @return the interface used by this reference. + */ + String getInterface(); + + /** + * @return the operations exposed by this service. + */ + List getServiceOperations(); + + /** + * Gets service operation by name. + * @param operation the name of a operation provided by this service. + * @return the requested operation, may be null + */ + ServiceOperation getServiceOperation(String operation); + + /** + * @return the application which exports this reference. + */ + Application getApplication(); + + /** + * @param gatewayName the name of a gateway on this service. + * @return the named gateway + */ + Binding getGateway(String gatewayName); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/Service.java b/core/admin/src/main/java/org/switchyard/admin/Service.java new file mode 100644 index 000000000..f9e61d31a --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/Service.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * Service + * + * Represents an application service exported through the SwitchYard runtime. + */ +public interface Service extends MessageMetricsAware { + + /** + * @return the name of this service. + */ + QName getName(); + + /** + * @return the component service promoted by this service. + */ + ComponentService getPromotedService(); + + /** + * @return the gateway bindings for this service. + */ + List getGateways(); + + /** + * @return the interface implemented by this service. + */ + String getInterface(); + + /** + * @return the application which exports this service. + */ + Application getApplication(); + + /** + * @param gatewayName the name of a gateway on this service. + * @return the named gateway + */ + Binding getGateway(String gatewayName); + + /** + * @return throttling details associated with this service. + */ + Throttling getThrottling(); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/ServiceOperation.java b/core/admin/src/main/java/org/switchyard/admin/ServiceOperation.java new file mode 100644 index 000000000..37035d271 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/ServiceOperation.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin; + +import javax.xml.namespace.QName; + +/** + * Represents an application service operation. + */ +public interface ServiceOperation extends MessageMetricsAware { + + /** + * The exchange pattern for the operation. + * @return exchange pattern + */ + String getExchangePattern(); + /** + * The name of the operation. + * @return operation name + */ + String getName(); + + /** + * The name of the input message type. + * @return input message type or null if no type information is available. + * @see org.switchyard.annotations.OperationTypes + */ + QName getInputType(); + /** + * The name of the output message type. + * @return output message name or null if no type information is available. + * @see org.switchyard.annotations.OperationTypes + */ + QName getOutputType(); + /** + * The name of the output message type. + * @return output message name or null if no type information is available. + * @see org.switchyard.annotations.OperationTypes + */ + QName getFaultType(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/SwitchYard.java b/core/admin/src/main/java/org/switchyard/admin/SwitchYard.java new file mode 100644 index 000000000..ba6c73842 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/SwitchYard.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +/** + * Top-level admin interface for SwitchYard runtime. + */ +public interface SwitchYard extends MessageMetricsAware { + + /** + * The SwitchYard version. + * + * @return the SwitchYard version + */ + String getVersion(); + + /** + * List of applications current deployed in SwitchYard runtime. + * + * @return list of SwitchYard applications + */ + List getApplications(); + + /** + * List of implementation and gateway components currently installed in + * SwitchYard runtime. + * + * @return list of SwitchYard components + */ + List getComponents(); + + /** + * List of services currently registered in the SwitchYard runtime. + * + * @return list of SwitchYard services + */ + List getServices(); + + /** + * List of references currently registered in the SwitchYard runtime. + * + * @return list of SwitchYard references + */ + List getReferences(); + + /** + * Find a component with the specified name. + * + * @param name + * the name of the component. + * @return the component with the specified name; may be null if a component + * with the specified name is not registered with the system. + */ + Component getComponent(String name); + + /** + * Find an application with the specified name. + * + * @param name + * the name of the application. + * @return the application with the specified name; may be null if an + * application with the specified name is not deployed on the + * system. + */ + Application getApplication(QName name); + + /** + * @return the socket binding names configured for SwitchYard. + */ + Set getSocketBindingNames(); + + /** + * @return the SwitchYard system configuration properties. + */ + Map getProperties(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/Throttling.java b/core/admin/src/main/java/org/switchyard/admin/Throttling.java new file mode 100644 index 000000000..cbb035633 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/Throttling.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin; + +/** + * Throttling + *

+ * Throttling details associated with a management object. + */ +public interface Throttling { + + /** + * @return true if throttling is enabled. + */ + boolean isEnabled(); + + /** + * enable throttling for the associated object. + */ + void enable(); + + /** + * disable throttling for the associated object. + */ + void disable(); + + /** + * @return the maximum number of requests per time period. + */ + int getMaxRequests(); + + /** + * @param maxRequests the maximumn number of requests per time period. + */ + void setMaxRequests(int maxRequests); + + /** + * @return the time period, in milliseconds, over which requests are + * counted. + */ + long getTimePeriod(); + + /** + * Update the throttling details. + * + * @param enabled true to enable, false to disable, null for no change. + * @param maxRequests maxRequests; null for no change. + */ + void update(Boolean enabled, Integer maxRequests); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/Transformer.java b/core/admin/src/main/java/org/switchyard/admin/Transformer.java new file mode 100644 index 000000000..642d001c4 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/Transformer.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin; + +import javax.xml.namespace.QName; + +/** + * Transformer + * + * Represents a data transformer provided by an application. + * + * @author Rob Cernich + */ +public interface Transformer { + + /** + * @return the "from" type upon which the transformer acts + */ + public QName getFrom(); + + /** + * @return the "to" type produced by the transformer + */ + public QName getTo(); + + /** + * @return the transformer type (e.g. java, smooks, etc.) + */ + public String getType(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/Validator.java b/core/admin/src/main/java/org/switchyard/admin/Validator.java new file mode 100644 index 000000000..dc6bd0aa3 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/Validator.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin; + +import javax.xml.namespace.QName; + +/** + * Validator + * + * Represents a data validator provided by an application. + * + * @author Tomohisa Igarashi + */ +public interface Validator { + + /** + * @return the name of type upon which the validator acts + */ + public QName getName(); + + /** + * @return the validator type (e.g. java, xml, etc.) + */ + public String getType(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseApplication.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseApplication.java new file mode 100644 index 000000000..2788705a2 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseApplication.java @@ -0,0 +1,229 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.base; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.Transformer; +import org.switchyard.admin.Validator; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.switchyard.EsbInterfaceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.deploy.internal.AbstractDeployment; + +/** + * Base implementation of Application. + */ +public class BaseApplication implements Application { + + private final QName _name; + private Map _services; + private Map _references; + private Map _componentServices; + private List _transformers; + private List _validators; + private AbstractDeployment _deployment; + private Map _properties; + + /** + * Create a new BaseApplication. + * @param deployment the deployment representing this application + */ + public BaseApplication(AbstractDeployment deployment) { + _name = deployment.getName(); + _deployment = deployment; + + addTransformers(); + addValidators(); + addComponents(); + addServices(); + addReferences(); + addProperties(); + } + + @Override + public QName getName() { + return _name; + } + + @Override + public List getServices() { + if (_services == null) { + return Collections.emptyList(); + } + return new ArrayList(_services.values()); + } + + @Override + public List getReferences() { + if (_references == null) { + return Collections.emptyList(); + } + return new ArrayList(_references.values()); + } + + @Override + public Service getService(QName serviceName) { + if (_services == null) { + return null; + } + return _services.get(serviceName); + } + + @Override + public Reference getReference(QName referenceName) { + if (_references == null) { + return null; + } + return _references.get(referenceName); + } + + @Override + public SwitchYardModel getConfig() { + return _deployment.getConfig(); + } + + @Override + public List getComponentServices() { + if (_componentServices == null) { + return Collections.emptyList(); + } + return new ArrayList(_componentServices.values()); + } + + @Override + public ComponentService getComponentService(QName componentServiceName) { + if (_componentServices == null) { + return null; + } + return _componentServices.get(componentServiceName); + } + + @Override + public List getTransformers() { + return Collections.unmodifiableList(_transformers); + } + + @Override + public List getValidators() { + return Collections.unmodifiableList(_validators); + } + + + @Override + public Map getProperties() { + return Collections.unmodifiableMap(_properties); + } + + /** + * @return the deployment associated with this application. + */ + public AbstractDeployment getDeployment() { + return _deployment; + } + + private void addServices() { + _services = new LinkedHashMap(); + if (getConfig().getComposite().getServices() == null) { + return; + } + + for (CompositeServiceModel service : getConfig().getComposite().getServices()) { + _services.put(service.getQName(), new BaseService(service, this)); + } + } + + private void addReferences() { + _references = new LinkedHashMap(); + if (getConfig().getComposite().getReferences() == null) { + return; + } + + for (CompositeReferenceModel ref : getConfig().getComposite().getReferences()) { + _references.put(ref.getQName(), new BaseReference(ref, this)); + } + } + + private void addTransformers() { + _transformers = new LinkedList(); + if (getConfig().getTransforms() == null) { + return; + } + for (TransformModel transformModel : getConfig().getTransforms().getTransforms()) { + _transformers.add(new BaseTransformer(transformModel)); + } + } + + private void addValidators() { + _validators = new LinkedList(); + if (getConfig().getValidates() == null) { + return; + } + for (ValidateModel validateModel : getConfig().getValidates().getValidates()) { + _validators.add(new BaseValidator(validateModel)); + } + } + + private void addComponents() { + _componentServices = new LinkedHashMap(); + if (getConfig().getComposite().getComponents() == null) { + return; + } + for (ComponentModel component : getConfig().getComposite().getComponents()) { + // TODO: we need a separate node for components, to support cases + // where the component implements no services. Should also consider + // multiple services per component. + if (component.getServices().size() > 0) { + ComponentServiceModel service = component.getServices().get(0); + if (service.getInterface() == null || EsbInterfaceModel.ESB.equals(service.getInterface().getType())) { + _componentServices.put(service.getQName(), new BaseNoopComponentService(service, component, this)); + } else if (InterfaceModel.JAVA.equals(service.getInterface().getType())) { + _componentServices.put(service.getQName(), new BaseJavaComponentService(service, component, this)); + } else if (InterfaceModel.WSDL.equals(service.getInterface().getType())) { + _componentServices.put(service.getQName(), new BaseWsdlComponentService(service, component, this)); + } + } + } + } + + private void addProperties() { + _properties = new LinkedHashMap(); + if (getConfig().getComposite() == null) { + return; + } + for (PropertyModel property : getConfig().getComposite().getProperties().values()) { + _properties.put(property.getName(), property.getValue()); + } + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseBinding.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseBinding.java new file mode 100644 index 000000000..18d944a00 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseBinding.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import javax.xml.namespace.QName; + +import org.switchyard.admin.Binding; +import org.switchyard.deploy.Lifecycle; + +/** + * BaseBinding + * + * Base implementation for {@link Binding}. + * + * @author Rob Cernich + */ +public class BaseBinding extends BaseMessageMetricsAware implements Binding { + + private final BaseApplication _application; + private final QName _serviceName; + private final String _type; + private final String _name; + private final String _configuration; + + /** + * Create a new BaseBinding. + * + * @param application the containing application + * @param serviceName the name of the service or reference providing this + * binding + * @param type the binding's type (e.g. soap) + * @param name the binding's name + * @param configuration the binding's raw configuration + */ + public BaseBinding(BaseApplication application, QName serviceName, String type, String name, String configuration) { + _application = application; + _serviceName = serviceName; + _type = type; + _name = name; + _configuration = configuration; + } + + @Override + public String getType() { + return _type; + } + + @Override + public String getConfiguration() { + return _configuration; + } + + @Override + public String getName() { + return _name; + } + + @Override + public void start() { + /* + * TODO: should we verify that we could retrieve the service handler? + * should we check the state first? + */ + getGatewayLifecycle().start(); + } + + @Override + public void stop() { + /* + * TODO: should we verify that we could retrieve the service handler? + * should we check the state first? + */ + getGatewayLifecycle().stop(); + } + + @Override + public State getState() { + final Lifecycle lifecycle = getGatewayLifecycle(); + return lifecycle == null ? State.NONE : lifecycle.getState(); + } + + private Lifecycle getGatewayLifecycle() { + return _application.getDeployment().getGatwayLifecycle(_serviceName, _name); + } +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseComponent.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseComponent.java new file mode 100644 index 000000000..bd13efc77 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseComponent.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.base; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.switchyard.admin.Component; + +/** + * BaseComponent + * + * Basic implementation for Component. + */ +public class BaseComponent implements Component { + + private Map _properties; + private String _name; + private Set _types; + + /** + * Create a new BaseComponent. + * + * @param name the name of the component. + * @param types the type of the component. + * @param properties the configuration properties of this component. + */ + public BaseComponent(String name, Collection types, Map properties) { + _name = name; + _types = new HashSet(); + if (types != null) { + _types.addAll(types); + } + _properties = new HashMap(); + if (properties != null) { + _properties.putAll(properties); + } + } + + @Override + public Map getProperties() { + return _properties; + } + + @Override + public String getName() { + return _name; + } + + @Override + public Set getTypes() { + return _types; + } +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseComponentReference.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseComponentReference.java new file mode 100644 index 000000000..3ca28b3f8 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseComponentReference.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import javax.xml.namespace.QName; + +import org.switchyard.admin.ComponentReference; + +/** + * BaseComponentReference + * + * Base implementation for {@link ComponentReference}. + * + * @author Rob Cernich + */ +public class BaseComponentReference extends BaseMessageMetricsAware implements ComponentReference { + + private final QName _name; + private final String _interface; + + /** + * Create a new BaseComponentReference. + * + * @param name the name of the reference + * @param interfaceName the required interface + */ + public BaseComponentReference(QName name, String interfaceName) { + _name = name; + _interface = interfaceName; + } + + @Override + public QName getName() { + return _name; + } + + @Override + public String getInterface() { + return _interface; + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseComponentService.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseComponentService.java new file mode 100644 index 000000000..3fbc11815 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseComponentService.java @@ -0,0 +1,129 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentReference; +import org.switchyard.admin.ComponentService; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.InterfaceModel; + +/** + * BaseComponentService + * + * Base implementation for {@link ComponentService}. + * + * @author Rob Cernich + */ +public abstract class BaseComponentService extends BaseMessageMetricsAware implements ComponentService { + + private final QName _name; + private final String _implementation; + private final String _interface; + private final Application _application; + private List _references; + private final String _implementationConfiguration; + + /** + * Create a new BaseComponentService from a config model. + * + * @param serviceConfig the component service configuration + * @param componentConfig the component configuration + * @param application the switchyard application + */ + public BaseComponentService(ComponentServiceModel serviceConfig, ComponentModel componentConfig, Application application) { + _name = serviceConfig.getQName(); + _implementation = getComponentImplementationType(componentConfig); + _interface = getInterfaceName(serviceConfig.getInterface()); + _application = application; + _references = new LinkedList(); + _implementationConfiguration = getComponentImplementationConfiguration(componentConfig); + + for (ComponentReferenceModel referenceModel : componentConfig.getReferences()) { + _references.add(new BaseComponentReference(referenceModel.getQName(), + getInterfaceName(referenceModel.getInterface()))); + } + } + + @Override + public QName getName() { + return _name; + } + + @Override + public String getImplementation() { + return _implementation; + } + + @Override + public String getInterface() { + return _interface; + } + + @Override + public List getReferences() { + if (_references == null) { + return Collections.emptyList(); + } + return Collections.unmodifiableList(_references); + } + + @Override + public Application getApplication() { + return _application; + } + + @Override + public String getImplementationConfiguration() { + return _implementationConfiguration; + } + + @Override + public void resetMessageMetrics() { + for (final ComponentReference reference : _references) { + reference.resetMessageMetrics(); + } + super.resetMessageMetrics(); + } + + private String getInterfaceName(InterfaceModel interfaceModel) { + if (interfaceModel == null) { + return null; + } + return interfaceModel.getInterface(); + } + + private String getComponentImplementationType(ComponentModel componentModel) { + ComponentImplementationModel implementationModel = componentModel.getImplementation(); + if (implementationModel == null) { + return null; + } + return implementationModel.getType(); + } + + private String getComponentImplementationConfiguration(ComponentModel componentModel) { + return componentModel.getImplementation() != null + ? componentModel.getImplementation().toString() : null; + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseJavaComponentService.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseJavaComponentService.java new file mode 100644 index 000000000..5625ad307 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseJavaComponentService.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import java.util.Collection; + +import org.switchyard.admin.Application; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.extensions.java.JavaService; + +/** + * Represents service with java contract. + */ +public class BaseJavaComponentService extends ComponentServiceWithOperations { + + /** + * Create a new BaseComponentService from a config model. + * + * @param serviceConfig the component service configuration + * @param componentConfig the component configuration + * @param application the switchyard application + */ + public BaseJavaComponentService(ComponentServiceModel serviceConfig, ComponentModel componentConfig, Application application) { + super(serviceConfig, componentConfig, application); + } + + @Override + protected Collection getInterfaceOperations(InterfaceModel interfaceModel) { + return JavaService.fromClass(Classes.forName(interfaceModel.getInterface())).getOperations(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseMessageMetricsAware.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseMessageMetricsAware.java new file mode 100644 index 000000000..39fd4993d --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseMessageMetricsAware.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import org.switchyard.Exchange; +import org.switchyard.admin.MessageMetrics; +import org.switchyard.admin.MessageMetricsAware; + +/** + * Simple base class for elements which supports message metrics. + */ +public class BaseMessageMetricsAware implements MessageMetricsAware { + + private MessageMetricsSupport _messageMetrics = new MessageMetricsSupport(); + + @Override + public MessageMetrics getMessageMetrics() { + return _messageMetrics; + } + + @Override + public void resetMessageMetrics() { + _messageMetrics.reset(); + } + + @Override + public void recordMetrics(Exchange exchange) { + _messageMetrics.recordMetrics(exchange); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseNoopComponentService.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseNoopComponentService.java new file mode 100644 index 000000000..563076b29 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseNoopComponentService.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import java.util.Collections; +import java.util.List; + +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.ServiceOperation; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; + +/** + * Service without interface definition/operations. + */ +public class BaseNoopComponentService extends BaseComponentService implements ComponentService { + + /** + * Create a new BaseComponentService from a config model. + * + * @param serviceConfig the component service configuration + * @param componentConfig the component configuration + * @param application the switchyard application + */ + public BaseNoopComponentService(ComponentServiceModel serviceConfig, ComponentModel componentConfig, Application application) { + super(serviceConfig, componentConfig, application); + } + + @Override + public List getServiceOperations() { + return Collections.emptyList(); + } + + @Override + public ServiceOperation getServiceOperation(String operation) { + return null; + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseReference.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseReference.java new file mode 100644 index 000000000..7060725a2 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseReference.java @@ -0,0 +1,198 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.base; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.Reference; +import org.switchyard.admin.ServiceOperation; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.switchyard.EsbInterfaceModel; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.extensions.wsdl.WSDLReaderException; +import org.switchyard.extensions.wsdl.WSDLService; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * Base implementation for Reference. + */ +public class BaseReference extends BaseMessageMetricsAware implements Reference { + + private QName _name; + private String _referenceInterface; + private BaseApplication _application; + private String _promotedReference; + private Map _gateways = new LinkedHashMap(); + private List _operations = new LinkedList();; + + /** + * Create a new BaseReference. + * + * @param name the name of the reference. + * @param referenceInterface the interface implemented by the reference. + * @param application the application containing the reference. + * @param reference the component reference. + * @param gateways the gateway types exposing the reference. + */ + public BaseReference(QName name, + String referenceInterface, + BaseApplication application, + String reference, + Map gateways) { + + _name = name; + _referenceInterface = referenceInterface; + _application = application; + _promotedReference = reference; + _gateways = gateways; + } + + /** + * Create a new BaseReference from the specified config model. + * + * @param referenceConfig the composite reference config. + * @param application the application containing the service. + */ + public BaseReference(CompositeReferenceModel referenceConfig, BaseApplication application) { + _name = referenceConfig.getQName(); + _application = application; + if (referenceConfig.getInterface() != null) { + _referenceInterface = referenceConfig.getInterface().getInterface(); + } + _promotedReference = referenceConfig.getPromote(); + _gateways = new LinkedHashMap(); + + int idx = 0; + for (BindingModel bindingModel : referenceConfig.getBindings()) { + // Generate binding name for now until tooling and config are updated to expose it + ++idx; + String name = bindingModel.getName() == null ? "_" + _name.getLocalPart() + "_" + bindingModel.getType() + + "_" + idx : bindingModel.getName(); + _gateways.put(name, new BaseBinding(_application, _name, bindingModel.getType(), name, bindingModel.toString())); + } + _operations = new LinkedList(); + for (org.switchyard.metadata.ServiceOperation so : getInterfaceOperations(referenceConfig.getInterface())) { + _operations.add(new BaseServiceOperation(so.getName(), so.getExchangePattern().name(), so.getInputType(), so.getOutputType(), so.getFaultType())); + } + } + + private Collection getInterfaceOperations(InterfaceModel interfaceModel) { + if (interfaceModel == null || EsbInterfaceModel.ESB.equals(interfaceModel.getType())) { + return Collections.emptySet(); + } else if (InterfaceModel.JAVA.equals(interfaceModel.getType())) { + return JavaService.fromClass(Classes.forName(interfaceModel.getInterface())).getOperations(); + } else if (InterfaceModel.WSDL.equals(interfaceModel.getType())) { + try { + return WSDLService.fromWSDL(interfaceModel.getInterface()).getOperations(); + } catch (WSDLReaderException e) { + // not sure what should do here.. - service should not be deployed + // so we won't collect metrics for it anyway + return Collections.emptySet(); + } + } + return Collections.emptySet(); + } + + @Override + public Application getApplication() { + return _application; + } + + @Override + public List getGateways() { + return new ArrayList(_gateways.values()); + } + + @Override + public Binding getGateway(String gatewayName) { + if (_gateways.containsKey(gatewayName)) { + return _gateways.get(gatewayName); + } + return null; + } + + @Override + public String getPromotedReference() { + return _promotedReference; + } + + @Override + public String getInterface() { + return _referenceInterface; + } + + @Override + public QName getName() { + return _name; + } + + @Override + public List getServiceOperations() { + return Collections.unmodifiableList(_operations); + } + + @Override + public ServiceOperation getServiceOperation(String operation) { + for (ServiceOperation serviceOperation : _operations) { + if (serviceOperation.getName().equals(operation)) { + return serviceOperation; + } + } + return null; + } + + @Override + public void resetMessageMetrics() { + for (final Binding binding : _gateways.values()) { + binding.resetMessageMetrics(); + } + for (final ServiceOperation operation : _operations) { + operation.resetMessageMetrics(); + } + super.resetMessageMetrics(); + } + + @Override + public void recordMetrics(Exchange exchange) { + final String gatewayName = exchange.getContext().getPropertyValue(ExchangeCompletionEvent.GATEWAY_NAME); + if (gatewayName != null && _gateways.containsKey(gatewayName)) { + _gateways.get(gatewayName).recordMetrics(exchange); + } + final String operationName = exchange.getContract().getProviderOperation().getName(); + if (operationName != null) { + for (final ServiceOperation operation : _operations) { + if (operationName.equals(operation.getName())) { + operation.recordMetrics(exchange); + break; + } + } + } + super.recordMetrics(exchange); + } +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseService.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseService.java new file mode 100644 index 000000000..03a401afa --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseService.java @@ -0,0 +1,164 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.base; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.MessageMetrics; +import org.switchyard.admin.Service; +import org.switchyard.admin.Throttling; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * Base implementation for Service. + */ +public class BaseService implements Service { + + private QName _name; + private String _serviceInterface; + private BaseApplication _application; + private ComponentService _promotedService; + private Map _gateways = new LinkedHashMap(); + private Throttling _throttling; + + /** + * Create a new BaseService. + * + * @param name the name of the service. + * @param serviceInterface the interface implemented by the service. + * @param application the application containing the service. + * @param implementation the implementation type of the service. + * @param gateways the gateway types exposing the service. + */ + public BaseService(QName name, + String serviceInterface, + BaseApplication application, + ComponentService implementation, + Map gateways) { + + _name = name; + _serviceInterface = serviceInterface; + _application = application; + _promotedService = implementation; + _gateways = gateways; + _throttling = new ServiceThrottling(this, null); + } + + /** + * Create a new BaseService from the specified config model. + * + * @param serviceConfig the composite service config. + * @param application the application containing the service. + */ + public BaseService(CompositeServiceModel serviceConfig, BaseApplication application) { + _name = serviceConfig.getQName(); + _application = application; + if (serviceConfig.getInterface() != null) { + _serviceInterface = serviceConfig.getInterface().getInterface(); + } + _promotedService = getPromotedService(application, serviceConfig); + _gateways = new LinkedHashMap(); + + int idx = 0; + for (BindingModel bindingModel : serviceConfig.getBindings()) { + // Generate binding name for now until tooling and config are updated to expose it + ++idx; + String name = bindingModel.getName() == null ? "_" + _name.getLocalPart() + "_" + bindingModel.getType() + + "_" + idx : bindingModel.getName(); + _gateways.put(name, new BaseBinding(_application, _name, bindingModel.getType(), name, bindingModel.toString())); + } + _throttling = new ServiceThrottling(this, serviceConfig.getExtensions()); + } + + @Override + public Application getApplication() { + return _application; + } + + @Override + public List getGateways() { + return new ArrayList(_gateways.values()); + } + + @Override + public Binding getGateway(String gatewayName) { + if (_gateways.containsKey(gatewayName)) { + return _gateways.get(gatewayName); + } + return null; + } + + @Override + public ComponentService getPromotedService() { + return _promotedService; + } + + @Override + public String getInterface() { + return _serviceInterface; + } + + @Override + public QName getName() { + return _name; + } + + @Override + public Throttling getThrottling() { + return _throttling; + } + + private ComponentService getPromotedService(Application application, CompositeServiceModel compositeService) { + ComponentServiceModel componentServiceModel = compositeService.getComponentService(); + if (componentServiceModel == null) { + return null; + } + return application.getComponentService(componentServiceModel.getQName()); + } + + @Override + public MessageMetrics getMessageMetrics() { + return _promotedService.getMessageMetrics(); + } + + @Override + public void resetMessageMetrics() { + for (final Binding binding : _gateways.values()) { + binding.resetMessageMetrics(); + } + _promotedService.resetMessageMetrics(); + } + + @Override + public void recordMetrics(Exchange exchange) { + final String gatewayName = exchange.getContext().getPropertyValue(ExchangeCompletionEvent.GATEWAY_NAME); + if (gatewayName != null && _gateways.containsKey(gatewayName)) { + _gateways.get(gatewayName).recordMetrics(exchange); + } + _promotedService.recordMetrics(exchange); + } +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseServiceOperation.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseServiceOperation.java new file mode 100644 index 000000000..def7090ed --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseServiceOperation.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import javax.xml.namespace.QName; + +import org.switchyard.admin.ServiceOperation; + +/** + * Implementation of service operation. + */ +public class BaseServiceOperation extends BaseMessageMetricsAware implements ServiceOperation { + + private String _name; + private String _exchangePattern; + private QName _inputType; + private QName _outputType; + private QName _faultType; + + /** + * Creates new service operation. + * @param name Operation name. + * @param exchangePattern Operation exchange pattern. + * @param inputType Input type for operation. + * @param outputType Output type for operation. + * @param faultType Fault type returned by operation in case of failures. + */ + public BaseServiceOperation(String name, String exchangePattern, QName inputType, QName outputType, QName faultType) { + this._name = name; + this._exchangePattern = exchangePattern; + this._inputType = inputType; + this._outputType = outputType; + this._faultType = faultType; + } + + @Override + public String getExchangePattern() { + return _exchangePattern; + } + + @Override + public String getName() { + return _name; + } + + @Override + public QName getInputType() { + return _inputType; + } + + @Override + public QName getOutputType() { + return _outputType; + } + + @Override + public QName getFaultType() { + return _faultType; + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseSwitchYard.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseSwitchYard.java new file mode 100644 index 000000000..14fede9a7 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseSwitchYard.java @@ -0,0 +1,298 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.base; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import javax.xml.namespace.QName; + +import org.switchyard.admin.Application; +import org.switchyard.admin.Component; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.common.version.Versions; + +/** + * In-memory representation of System admin contract. Note that Service objects + * are stored in a list and that removals are based on object identity and not + * object value. This is to support multiple services registered with the same + * name. + */ +public class BaseSwitchYard extends BaseMessageMetricsAware implements SwitchYard { + + private final String _version; + private ConcurrentMap _applications = new ConcurrentHashMap(); + private ConcurrentMap _components = new ConcurrentHashMap(); + private List _services = Collections.synchronizedList(new LinkedList()); + private List _references = Collections.synchronizedList(new LinkedList()); + private Set _socketBindingNames = Collections.synchronizedSet(new HashSet()); + private ConcurrentMap _properties = new ConcurrentHashMap(); + + /** + * Create a new BaseSwitchYard. + */ + public BaseSwitchYard() { + _version = Versions.getSwitchYardVersion(); + } + + @Override + public List getApplications() { + return new ArrayList(_applications.values()); + } + + /** + * Add an application. + * + * @param application application to add + * @return reference to this admin object + */ + public BaseSwitchYard addApplication(Application application) { + Application existing = _applications.putIfAbsent(application.getName(), application); + if (existing == null) { + _services.addAll(application.getServices()); + _references.addAll(application.getReferences()); + } + return this; + } + + /** + * Remove an application. + * + * @param application application to remove + * @return reference to this admin object + */ + public BaseSwitchYard removeApplication(Application application) { + return removeApplication(application.getName()); + } + + /** + * Remove an application. + * + * @param name name of the application to remove. + * @return reference to this admin object + */ + public BaseSwitchYard removeApplication(QName name) { + Application application = _applications.remove(name); + if (application != null) { + _references.removeAll(application.getReferences()); + _services.removeAll(application.getServices()); + } + return this; + } + + @Override + public List getComponents() { + return new ArrayList(_components.values()); + } + + /** + * Add a component. + * + * @param component component to add + * @return reference to this admin object + */ + public BaseSwitchYard addComponent(Component component) { + _components.putIfAbsent(component.getName(), component); + return this; + } + + /** + * Remove a component. + * + * @param component component to remove + * @return reference to this admin object + */ + public BaseSwitchYard removeComponent(Component component) { + _components.remove(component.getName()); + return this; + } + + @Override + public List getServices() { + return new ArrayList(_services); + } + + /** + * Add a service. + * + * @param service service to add + * @return reference to this admin object + */ + public BaseSwitchYard addService(Service service) { + _services.add(service); + return this; + } + + /** + * Remove a service. + * + * @param service service to remove + * @return reference to this admin object + */ + public BaseSwitchYard removeService(Service service) { + _services.remove(service); + return this; + } + + @Override + public List getReferences() { + return new ArrayList(_references); + } + + /** + * Add a reference. + * + * @param reference reference to add + * @return reference to this admin object + */ + public BaseSwitchYard addReference(Reference reference) { + _references.add(reference); + return this; + } + + /** + * Remove a reference. + * + * @param reference reference to remove + * @return reference to this admin object + */ + public BaseSwitchYard removeReference(Reference reference) { + _references.remove(reference); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVersion() { + return _version; + } + + @Override + public Component getComponent(String name) { + return _components.get(name); + } + + @Override + public Application getApplication(QName name) { + return _applications.get(name); + } + + /** + * Add a set of names to the set of socket binding names. + * + * @param names the names to add. + * + */ + public void addSocketBindingNames(Set names) { + _socketBindingNames.addAll(names); + } + + /** + * Add a name to the set of socket binding names. + * + * @param name the name to add. + */ + public void addSocketBindingName(String name) { + _socketBindingNames.add(name); + } + + /** + * Remove the specified name from the set of socket bindings. + * + * @param name the name to remove. + */ + public void removeSocketBindingName(String name) { + _socketBindingNames.remove(name); + } + + /** + * Removes the specified names from the set of socket bindings. + * + * @param names the names to remove. + */ + public void removeSocketBindingNames(Set names) { + _socketBindingNames.removeAll(names); + } + + @Override + public Set getSocketBindingNames() { + return Collections.unmodifiableSet(_socketBindingNames); + } + + @Override + public Map getProperties() { + return Collections.unmodifiableMap(_properties); + } + + /** + * Adds a set of properties to the set of system properties. + * + * @param properties the properties to add. + */ + public void addProperties(Map properties) { + _properties.putAll(properties); + } + + /** + * Adds a property to the set of system properties. + * + * @param name the name of the property. + * @param value the value of the property. + */ + public void addProperty(String name, String value) { + _properties.put(name, value); + } + + /** + * Removes the properties from the set of system properties. + * + * @param properties the properties to remove. + */ + public void removeProperties(Map properties) { + _properties.keySet().removeAll(properties.keySet()); + } + + /** + * Removes a property from the set of system properties. + * + * @param name the name of the property to remove. + */ + public void removeProperty(String name) { + _properties.remove(name); + } + + @Override + public void resetMessageMetrics() { + for (final Service service : _services) { + service.resetMessageMetrics(); + } + for (final Reference reference : _references) { + reference.resetMessageMetrics(); + } + super.resetMessageMetrics(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseTransformer.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseTransformer.java new file mode 100644 index 000000000..da1d3e405 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseTransformer.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import javax.xml.namespace.QName; + +import org.switchyard.admin.Transformer; +import org.switchyard.config.model.TypedModel; +import org.switchyard.config.model.transform.TransformModel; + +/** + * BaseTransformer + * + * Base implementation for {@link Transformer}. + * + * @author Rob Cernich + */ +public class BaseTransformer implements Transformer { + + private final QName _from; + private final QName _to; + private String _type; + + /** + * Create a new BaseTransformer. + * + * @param from the from type + * @param to the to type + * @param type the implementation type (e.g. java) + */ + public BaseTransformer(QName from, QName to, String type) { + _from = from; + _to = to; + _type = type; + } + + /** + * Create a new BaseTransformer from a config model. + * @param config the transformer confing model + */ + public BaseTransformer(TransformModel config) { + _from = config.getFrom(); + _to = config.getTo(); + if (config instanceof TypedModel) { + _type = ((TypedModel)config).getType(); + } + } + + @Override + public QName getFrom() { + return _from; + } + + @Override + public QName getTo() { + return _to; + } + + @Override + public String getType() { + return _type; + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseValidator.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseValidator.java new file mode 100644 index 000000000..b399ca656 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseValidator.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import javax.xml.namespace.QName; + +import org.switchyard.admin.Validator; +import org.switchyard.config.model.TypedModel; +import org.switchyard.config.model.validate.ValidateModel; + +/** + * BaseValidator + * + * Base implementation for {@link Validator}. + * + * @author Tomohisa Igarashi + */ +public class BaseValidator implements Validator { + + private final QName _name; + private String _type; + + /** + * Create a new BaseTransformer. + * + * @param name the name of type + * @param type the implementation type (e.g. java) + */ + public BaseValidator(QName name, String type) { + _name = name; + _type = type; + } + + /** + * Create a new BaseValidator from a config model. + * @param config the the validator config model + */ + public BaseValidator(ValidateModel config) { + _name = config.getName(); + if (config instanceof TypedModel) { + _type = ((TypedModel)config).getType(); + } + } + + @Override + public QName getName() { + return _name; + } + + @Override + public String getType() { + return _type; + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/BaseWsdlComponentService.java b/core/admin/src/main/java/org/switchyard/admin/base/BaseWsdlComponentService.java new file mode 100644 index 000000000..55f13cd89 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/BaseWsdlComponentService.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import java.util.Collection; +import java.util.Collections; + +import org.switchyard.admin.Application; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.extensions.wsdl.WSDLReaderException; +import org.switchyard.extensions.wsdl.WSDLService; +import org.switchyard.metadata.ServiceOperation; + +/** + * Base class for services with WSDL contract. + */ +public class BaseWsdlComponentService extends ComponentServiceWithOperations { + + /** + * Create a new BaseComponentService from a config model. + * + * @param serviceConfig the component service configuration + * @param componentConfig the component configuration + * @param application the switchyard application + */ + public BaseWsdlComponentService(ComponentServiceModel serviceConfig, ComponentModel componentConfig, Application application) { + super(serviceConfig, componentConfig, application); + } + + @Override + protected Collection getInterfaceOperations(InterfaceModel interfaceModel) { + try { + return WSDLService.fromWSDL(interfaceModel.getInterface()).getOperations(); + } catch (WSDLReaderException e) { + // not sure what should do here.. - service should not be deployed + // so we won't collect metrics for it anyway + return Collections.emptyList(); + } + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/ComponentServiceWithOperations.java b/core/admin/src/main/java/org/switchyard/admin/base/ComponentServiceWithOperations.java new file mode 100644 index 000000000..29f37fe24 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/ComponentServiceWithOperations.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.switchyard.Exchange; +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.ServiceOperation; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.InterfaceModel; + +/** + * BaseComponentService + * + * Base implementation for {@link ComponentService}. + * + * @author Rob Cernich + */ +public abstract class ComponentServiceWithOperations extends BaseComponentService implements ComponentService { + + private List _operations; + + /** + * Create a new BaseComponentService from a config model. + * + * @param serviceConfig the component service configuration + * @param componentConfig the component configuration + * @param application the switchyard application + */ + public ComponentServiceWithOperations(ComponentServiceModel serviceConfig, ComponentModel componentConfig, Application application) { + super(serviceConfig, componentConfig, application); + + _operations = new LinkedList(); + for (org.switchyard.metadata.ServiceOperation so : getInterfaceOperations(serviceConfig.getInterface())) { + _operations.add(new BaseServiceOperation(so.getName(), so.getExchangePattern().name(), so.getInputType(), so.getOutputType(), so.getFaultType())); + } + } + + @Override + public List getServiceOperations() { + return Collections.unmodifiableList(_operations); + } + + @Override + public ServiceOperation getServiceOperation(String operation) { + for (ServiceOperation serviceOperation : _operations) { + if (serviceOperation.getName().equals(operation)) { + return serviceOperation; + } + } + return null; + } + + /** + * Template method for children, should return list of operations supported + * by interface model. + * + * @param interfaceModel Interface definition for this service. + * @return Supported operations. + */ + protected abstract Collection getInterfaceOperations(InterfaceModel interfaceModel); + + @Override + public void resetMessageMetrics() { + for (final ServiceOperation operation : _operations) { + operation.resetMessageMetrics(); + } + super.resetMessageMetrics(); + } + + @Override + public void recordMetrics(Exchange exchange) { + final String operationName = exchange.getContract().getProviderOperation().getName(); + if (operationName != null) { + for (final ServiceOperation operation : _operations) { + if (operationName.equals(operation.getName())) { + operation.recordMetrics(exchange); + break; + } + } + } + super.recordMetrics(exchange); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/MessageMetricsSupport.java b/core/admin/src/main/java/org/switchyard/admin/base/MessageMetricsSupport.java new file mode 100644 index 000000000..d950da7bc --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/MessageMetricsSupport.java @@ -0,0 +1,127 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.base; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeState; +import org.switchyard.Property; +import org.switchyard.admin.MessageMetrics; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * Message metric collection support. Holds the values of message metrics + * and provides a method recording metric data from an exchange. + */ +public class MessageMetricsSupport implements MessageMetrics { + + private static final String NL = System.getProperty("line.separator"); + private AtomicInteger _successCount = new AtomicInteger(); + private AtomicInteger _faultCount = new AtomicInteger(); + private AtomicInteger _minTimeMS = new AtomicInteger(); + private AtomicInteger _maxTimeMS = new AtomicInteger(); + private AtomicLong _totalTimeMS = new AtomicLong(); + + /** + * Update metric data based on the specified exchange. + * @param exchange an exchange with metrics info + */ + public synchronized void recordMetrics(Exchange exchange) { + if (exchange.getState().equals(ExchangeState.FAULT)) { + _faultCount.incrementAndGet(); + } else { + _successCount.incrementAndGet(); + } + + Property prop = exchange.getContext().getProperty(ExchangeCompletionEvent.EXCHANGE_DURATION); + if (prop != null) { + Long duration = (Long)prop.getValue(); + _totalTimeMS.addAndGet(duration); + // check minTime + if (_minTimeMS.intValue() == 0 || duration < _minTimeMS.intValue()) { + _minTimeMS.set(duration.intValue()); + } + // check maxTime + if (_maxTimeMS.intValue() == 0 || duration > _maxTimeMS.intValue()) { + _maxTimeMS.set(duration.intValue()); + } + } + } + + /** + * Reset all message metrics. + */ + public synchronized void reset() { + _successCount.set(0); + _faultCount.set(0); + _minTimeMS.set(0); + _maxTimeMS.set(0); + _totalTimeMS.set(0); + } + + @Override + public int getTotalCount() { + return _successCount.get() + _faultCount.get(); + } + + @Override + public int getFaultCount() { + return _faultCount.get(); + } + + @Override + public int getSuccessCount() { + return _successCount.get(); + } + + @Override + public long getTotalProcessingTime() { + return _totalTimeMS.get(); + } + + @Override + public synchronized double getAverageProcessingTime() { + if (getTotalCount() == 0) { + return 0.0; + } + return (double)getTotalProcessingTime() / getTotalCount(); + } + + @Override + public int getMaxProcessingTime() { + return _maxTimeMS.get(); + } + + @Override + public int getMinProcessingTime() { + return _minTimeMS.get(); + } + + @Override + public String toString() { + return String.format("Success Count : %s%n" + + "Fault Count : %s%n" + + "Total Count : %s%n" + + "Avg Time MS : %s%n" + + "Min Time MS : %s%n" + + "Max Time MS : %s%n" + + "Total Time MS : %s%n", getSuccessCount(), + getFaultCount(), getTotalCount(), getAverageProcessingTime(), + getMinProcessingTime(), getMaxProcessingTime(), + getTotalProcessingTime()); + } +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/ServiceThrottling.java b/core/admin/src/main/java/org/switchyard/admin/base/ServiceThrottling.java new file mode 100644 index 000000000..d0a3881ad --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/ServiceThrottling.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import org.switchyard.ServiceReference; +import org.switchyard.admin.Throttling; +import org.switchyard.config.model.composite.ExtensionsModel; +import org.switchyard.config.model.switchyard.ThrottlingModel; +import org.switchyard.metadata.ServiceMetadataBuilder; + +/** + * ServiceThrottling + *

+ * Throttling details for Service objects. + */ +public class ServiceThrottling implements Throttling { + + private final BaseService _service; + private boolean _enabled = false; + private int _maxRequests; + private long _timePeriod = org.switchyard.metadata.qos.Throttling.DEFAULT_TIME_PERIOD; + + /** + * Create a new ServiceThrottling. + * + * @param service the service being throttled + * @param extensions configuration details + */ + public ServiceThrottling(final BaseService service, final ExtensionsModel extensions) { + _service = service; + + if (extensions == null) { + return; + } + final ThrottlingModel throttling = extensions.getThrottling(); + if (throttling == null) { + return; + } + _maxRequests = throttling.getMaxRequests(); + _enabled = true; + final Long timePeriod = throttling.getTimePeriod(); + if (timePeriod != null) { + _timePeriod = timePeriod; + } + } + + @Override + public boolean isEnabled() { + return _enabled; + } + + @Override + public void enable() { + update(true, null); + } + + @Override + public void disable() { + update(false, null); + } + + @Override + public int getMaxRequests() { + return _maxRequests; + } + + @Override + public void setMaxRequests(int maxRequests) { + update(null, maxRequests); + } + + @Override + public long getTimePeriod() { + return _timePeriod; + } + + @Override + public void update(Boolean enabled, Integer maxRequests) { + boolean doUpdate = false; + if (maxRequests != null && maxRequests != _maxRequests) { + _maxRequests = maxRequests; + // only update if enabled + doUpdate = _enabled; + } + if (enabled != null && enabled != _enabled) { + _enabled = enabled; + // always update + doUpdate = true; + } + if (doUpdate) { + updateThrottler(); + } + } + + private void updateThrottler() { + final org.switchyard.metadata.qos.Throttling throttling; + if (_enabled) { + throttling = new org.switchyard.metadata.qos.Throttling(); + throttling.setMaxRequests(_maxRequests); + throttling.setTimePeriod(_timePeriod); + } else { + throttling = null; + } + final BaseApplication application = (BaseApplication) _service.getApplication(); + final ServiceReference serviceReference = application.getDeployment().getDomain().getServiceReference(_service.getName()); + ServiceMetadataBuilder.update(serviceReference.getServiceMetadata()).throttling(throttling); + } +} diff --git a/core/admin/src/main/java/org/switchyard/admin/base/SwitchYardBuilder.java b/core/admin/src/main/java/org/switchyard/admin/base/SwitchYardBuilder.java new file mode 100644 index 000000000..3e4ed4fe2 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/base/SwitchYardBuilder.java @@ -0,0 +1,164 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import java.util.EventObject; + +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentReference; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.admin.mbean.internal.LocalManagement; +import org.switchyard.admin.mbean.internal.MBeans; +import org.switchyard.deploy.ComponentNames; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.event.ApplicationDeployedEvent; +import org.switchyard.deploy.event.ApplicationUndeployedEvent; +import org.switchyard.deploy.internal.AbstractDeployment; +import org.switchyard.event.EventObserver; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * SwitchYardBuilder + * + * {@link EventObserver} implementation which builds a + * {@link org.switchyard.admin.SwitchYard} model using notifications from + * {@link AbstractDeployment} events. + * + * @author Rob Cernich + */ +public class SwitchYardBuilder implements EventObserver { + + private BaseSwitchYard _switchYard; + private ServiceDomainManager _domainManager; + + /** + * Create a new SwitchYardBuilder. + */ + public SwitchYardBuilder() { + _switchYard = new BaseSwitchYard(); + } + + /** + * Initializes the SwitchBuilder which includes registering the local management MBean + * and registering as an EventObserver within SwitchYard. + * @param domainManager the SY ServiceDomainManager + */ + public void init(ServiceDomainManager domainManager) { + _domainManager = domainManager; + + // Register local management MBeans + LocalManagement lm = new LocalManagement(_domainManager); + MBeans.registerLocalManagement(lm); + + // Register event hooks + _domainManager.getEventManager() + .addObserver(this, ExchangeCompletionEvent.class) + .addObserver(this, ApplicationDeployedEvent.class) + .addObserver(this, ApplicationUndeployedEvent.class); + } + + /** + * Tears down registered MBeans and event subscriptions. Call this during system shutdown + * to clean up. + */ + public void destroy() { + // Unregister event hooks + _domainManager.getEventManager().removeObserver(this); + // Unregister management mbeans + MBeans.unregisterLocalManagement(); + } + + /** + * Returns the SwitchYard admin object. + * @return SwitchYard interface representing the SY runtime + */ + public SwitchYard getSwitchYard() { + return _switchYard; + } + + /** + * Returns the ServiceDomainManager instance in use for this builder. + * @return ServiceDomainManager used by this builder instance. + */ + public ServiceDomainManager getDomainManager() { + return _domainManager; + } + + @Override + public void notify(EventObject event) { + if (event instanceof ApplicationDeployedEvent) { + applicationDeployed((ApplicationDeployedEvent)event); + } else if (event instanceof ApplicationUndeployedEvent) { + applicationUndeployed((ApplicationUndeployedEvent)event); + } else if (event instanceof ExchangeCompletionEvent) { + exchangeCompleted((ExchangeCompletionEvent)event); + } + } + + void applicationDeployed(ApplicationDeployedEvent event) { + AbstractDeployment deployment = event.getDeployment(); + if (deployment.getName() != null) { + BaseApplication app = new BaseApplication(deployment); + _switchYard.addApplication(app); + MBeans.registerApplication(app); + } + } + + void applicationUndeployed(ApplicationUndeployedEvent event) { + AbstractDeployment deployment = event.getDeployment(); + if (deployment.getName() != null) { + Application app = _switchYard.getApplication(deployment.getName()); + if (app != null) { + MBeans.unregisterApplication(app); + _switchYard.removeApplication(deployment.getName()); + } + } + } + + void exchangeCompleted(ExchangeCompletionEvent event) { + // Recording metrics at multiple levels at this point instead of + // aggregating them. + Exchange exchange = event.getExchange(); + QName serviceName = exchange.getProvider().getName(); + QName referenceName = ComponentNames.unqualify(exchange.getConsumer().getName()); + for (Service service : _switchYard.getServices()) { + if (service.getName().equals(serviceName)) { + // 1 - the aggregate switchyard stats + _switchYard.recordMetrics(exchange); + + // 2 - service stats + service.recordMetrics(exchange); + } + // 3 - reference stats + // XXX: this looks like it lumps the stats into every component reference with a matching name + for (ComponentReference reference : service.getPromotedService().getReferences()) { + if (reference.getName().equals(referenceName)) { + ((BaseComponentReference)reference).recordMetrics(exchange); + } + } + } + // 4 - reference stats + for (Reference reference : _switchYard.getReferences()) { + if (reference.getName().equals(referenceName)) { + reference.recordMetrics(exchange); + break; + } + } + } +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/ApplicationMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/ApplicationMXBean.java new file mode 100644 index 000000000..d29934bd3 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/ApplicationMXBean.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.mbean; + +import java.util.List; + +import javax.management.ObjectName; + +/** + * Management interface for a SwitchYard application. + */ +public interface ApplicationMXBean { + /** + * Returns a list of composite services provided by the application. + * @return composite services provided by the application. + */ + public List getServices(); + + /** + * Provides the ObjectName for the management interface of a composite service in this application. + * @param serviceName the name of a service provided by this application. + * @return the object name for the service's management interface, may be null + */ + public ObjectName getService(String serviceName); + + /** + * Returns a list of composite references consumed by the application. + * @return composite references consumed by the application. + */ + public List getReferences(); + + /** + * Provides the ObjectName for the management interface of a composite reference in this application. + * @param referenceName the name of a reference consumed by this application. + * @return the object name for the reference's management interface, may be null + */ + public ObjectName getReference(String referenceName); + + /** + * Returns a list of names of component services for this application. + * @return names of component services contained by this application. + */ + public List getComponentServices(); + + /** + * Provides the ObjectName for the management interface of a component service in this application. + * @param componentServiceName the name of a component service contained in this application. + * @return the object name for the component service's management interface, may be null + */ + public ObjectName getComponentService(String componentServiceName); + + /** + * Provides a list of ObjectNames for the management interfaces for all transformers in this + * application. + * @return list of ObjectNames + */ + public List getTransformers(); + + /** + * Provides a list of ObjectNames for the management interfaces for all validators in this + * application. + * @return list of ObjectNames + */ + public List getValidators(); + + /** + * Returns the name of the application. + * @return the name of this application. + */ + public String getName(); + + /** + * Return the application descriptor. + * @return the config model for the application descriptor + */ + public String getConfig(); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/BindingMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/BindingMXBean.java new file mode 100644 index 000000000..b3d942298 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/BindingMXBean.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean; + +/** + * Management interface for a gateway binding defined on a service or reference. + */ +public interface BindingMXBean extends LifecycleMXBean, MessageMetricsMXBean { + + /** + * The binding type. + * @return the type of binding (e.g. soap) + */ + public String getType(); + + /** + * The binding's name. + * @return binding name. + */ + public String getName(); + + + /** + * The config descriptor for the binding as a string. + * @return the raw configuration details + */ + public String getConfiguration(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/ComponentReferenceMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/ComponentReferenceMXBean.java new file mode 100644 index 000000000..278f448d4 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/ComponentReferenceMXBean.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean; + +/** + * Management interface for a component reference contained in a SwitchYard application. + */ +public interface ComponentReferenceMXBean extends MessageMetricsMXBean { + + /** + * Component reference name. + * @return the name of this reference. + */ + String getName(); + + /** + * Interface used by component reference. + * @return the interface required for this reference. + */ + String getInterface(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/ComponentServiceMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/ComponentServiceMXBean.java new file mode 100644 index 000000000..9b7dfa9cf --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/ComponentServiceMXBean.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean; + +import java.util.List; + +/** + * Management interface for a component service provided in a SwitchYard application. + */ +public interface ComponentServiceMXBean extends MessageMetricsMXBean { + + /** + * The component service name. + * @return the name of this service. + */ + String getName(); + + /** + * The implementation type used for the component service. + * @return the implementation type used to implement this service. + */ + String getImplementation(); + + /** + * The configuration descriptor for the service implementation. + * @return implementation configuration as a string + */ + String getImplementationConfiguration(); + + /** + * The component service interface. + * @return the interface implemented by this service. + */ + String getInterface(); + + /** + * List of operation names provided by this service. + * @return the operations exposed by this service. + */ + List getServiceOperations(); + + /** + * List of reference names consumed by this service. + * @return the references required by this service. + */ + List getReferences(); + + /** + * The application which contains this component service. + * @return the application which exports this service. + */ + ApplicationMXBean getApplication(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/LifecycleMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/LifecycleMXBean.java new file mode 100644 index 000000000..5052eeb89 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/LifecycleMXBean.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean; + +/** + * LifecycleMXBean + *

+ * Common operations for manipulating object lifecycle. + */ +public interface LifecycleMXBean { + + /** + * Represents the current state of a Lifecycle object. + */ + public enum State { + /** No state. */ + NONE, + /** + * In the process of starting, i.e. start() has been invoked, but has + * not yet completed. + */ + STARTING, + /** + * The object has been started and is running, i.e. start() has been + * invoked and has successfully completed. + */ + STARTED, + /** + * In the process of stopping, i.e. stop() has been invoked, but has not + * yet completed. + */ + STOPPING; + } + + /** + * Start processing. + */ + void start(); + + /** + * Stop processing. + */ + void stop(); + + /** + * @return the current state of this object. + */ + State getState(); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/MessageMetricsMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/MessageMetricsMXBean.java new file mode 100644 index 000000000..aab64a60f --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/MessageMetricsMXBean.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.mbean; + +/** + * Reports messaging metrics for entities in a SwitchYard domain : service, + * reference, runtime, etc. + */ +public interface MessageMetricsMXBean { + + /** + * Return the number of successful messages. + * @return success count + */ + int getSuccessCount(); + /** + * Return the number of failed messages. + * @return fault count + */ + int getFaultCount(); + /** + * Return the total number of messages processed. This is equivalent to + * getSuccessCount() + getFaultCount(). + * @return total message count + */ + int getTotalCount(); + /** + * Total processing time for all messages in TimeUnit.MILLISECONDS. + * @return total processing time + */ + long getTotalProcessingTime(); + /** + * Average processing time for all messages in TimeUnit.MILLISECONDS. + * @return average processing time + */ + double getAverageProcessingTime(); + /** + * Minimum processing time for a message in TimeUnit.MILLISECONDS. + * @return min processing time + */ + int getMinProcessingTime(); + /** + * Maximum processing time for a message in TimeUnit.MILLISECONDS. + * @return max processing time + */ + int getMaxProcessingTime(); + + /** + * Reset all collected metrics. + */ + void reset(); + + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/ReferenceMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/ReferenceMXBean.java new file mode 100644 index 000000000..ae5356bfd --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/ReferenceMXBean.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.mbean; + +import java.util.List; + +/** + * Management interface for a composite reference consumed by a SwitchYard application. + */ +public interface ReferenceMXBean extends MessageMetricsMXBean { + + /** + * Reference name. + * @return the name of this reference. + */ + String getName(); + + /** + * The component reference that this composite reference promotes. + * @return the component reference promoted by this reference. + */ + String getPromotedReference(); + + /** + * List of managed bindings used by this reference. + * @return management interfaces for gateway bindings on this reference. + */ + List getBindings(); + + /** + * The composite reference interface. + * @return the interface used by this reference. + */ + String getInterface(); + + /** + * The application which uses this reference. + * @return the application which exports this reference. + */ + ApplicationMXBean getApplication(); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/ServiceMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/ServiceMXBean.java new file mode 100644 index 000000000..7de70c7d2 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/ServiceMXBean.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.mbean; + +import java.util.List; + +/** + * Management interface for a composite service provided by a SwitchYard application. + */ +public interface ServiceMXBean { + + /** + * The service name. + * @return the name of this service. + */ + String getName(); + + /** + * The component service promoted by this composite service. + * @return the component service promoted by this service. + */ + String getPromotedService(); + + /** + * List of managed bindings used by this service. + * @return management interfaces for gateway bindings on this service. + */ + List getBindings(); + + /** + * Composite service interface. + * @return the interface implemented by this service. + */ + String getInterface(); + + /** + * The application which uses this reference. + * @return the application which exports this reference. + */ + ApplicationMXBean getApplication(); + + /** + * @return throttling details associated with this service. + */ + ThrottlingMXBean getThrottling(); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/ThrottlingMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/ThrottlingMXBean.java new file mode 100644 index 000000000..12d051f01 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/ThrottlingMXBean.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean; + +/** + * ThrottlingMXBean + *

+ * Throttling details associated with a management object. + */ +public interface ThrottlingMXBean { + + /** + * @return true if throttling is enabled. + */ + boolean isEnabled(); + + /** + * enable throttling for the associated object. + */ + void enable(); + + /** + * disable throttling for the associated object. + */ + void disable(); + + /** + * @return the maximum number of requests per time period. + */ + int getMaxRequests(); + + /** + * @param maxRequests the maximumn number of requests per time period. + */ + void setMaxRequests(int maxRequests); + + /** + * @return the time period, in milliseconds, over which requests are + * counted. + */ + long getTimePeriod(); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/TransformerMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/TransformerMXBean.java new file mode 100644 index 000000000..756c8a6f1 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/TransformerMXBean.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean; + +/** + * Management interface for a SwitchYard transformer. + */ +public interface TransformerMXBean { + + /** + * Transformer "from" type name. + * @return the "from" type upon which the transformer acts + */ + public String getFrom(); + + /** + * Transformer "to" type name. + * @return the "to" type produced by the transformer + */ + public String getTo(); + + /** + * The implementation type of the transformer. + * @return the transformer type (e.g. java, smooks, etc.) + */ + public String getType(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/ValidatorMXBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/ValidatorMXBean.java new file mode 100644 index 000000000..47bc29934 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/ValidatorMXBean.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean; + +/** + * Management interface for a SwitchYard validator. + */ +public interface ValidatorMXBean { + + /** + * The name of the data type validated by this validator. + * @return the name of type upon which the validator acts + */ + public String getName(); + + /** + * The implementation type of this validator. + * @return the validator type (e.g. java, xml, etc.) + */ + public String getType(); + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/LocalManagement.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/LocalManagement.java new file mode 100644 index 000000000..689f4b254 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/LocalManagement.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import java.util.EventObject; +import java.util.List; + +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.event.EventObserver; + +/** + * This is a local, in-memory management interface for a SwitchYard runtime. The methods on + * this management interface are not intended for use by remote JMX clients outside the VM. + */ +public class LocalManagement implements LocalManagementMBean { + + private ServiceDomainManager _domainManager; + + /** + * Create a new LocalManagement instance. + * @param domainManager the SY ServiceDomainManager + */ + public LocalManagement(ServiceDomainManager domainManager) { + _domainManager = domainManager; + } + + @Override + public void addObserver(EventObserver observer, Class event) { + _domainManager.getEventManager().addObserver(observer, event); + } + + @Override + public void addObserver(EventObserver observer, List> events) { + if (events != null) { + for (Class event : events) { + addObserver(observer, event); + } + } + } + + @Override + public void removeObserver(EventObserver observer) { + _domainManager.getEventManager().removeObserver(observer); + } + + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/LocalManagementMBean.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/LocalManagementMBean.java new file mode 100644 index 000000000..a939b9e8c --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/LocalManagementMBean.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import java.util.EventObject; + +import org.switchyard.event.EventObserver; + +/** + * This is a local, in-memory management interface for a SwitchYard runtime. The methods on + * this management interface are not intended for use by remote JMX clients outside the VM. + */ +public interface LocalManagementMBean { + + /** + * Add an event observer associated with the supplied event type. + * @param observer observer instance to add + * @param event the event to subscribe to + */ + public void addObserver(EventObserver observer, Class event); + + /** + * Add an event observer associated with the supplied event type. + * @param observer observer instance to add + * @param events the list of events to register against + */ + public void addObserver(EventObserver observer, java.util.List> events); + + /** + * Remove all event registrations for a given EventObserver instance. + * @param observer the observer to unregister + */ + public void removeObserver(EventObserver observer); +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/MBeans.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/MBeans.java new file mode 100644 index 000000000..004e305af --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/MBeans.java @@ -0,0 +1,247 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import java.lang.management.ManagementFactory; + +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.jboss.logging.Logger; + +import org.switchyard.SwitchYardException; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.ComponentReference; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.Throttling; +import org.switchyard.admin.Transformer; +import org.switchyard.admin.Validator; + +/** + * Utility class for JMX-related functions in admin API. + */ +public final class MBeans { + + /** + * Domain name used for SwitchYard MBean ObjectNames. + */ + public static final String DOMAIN = "org.switchyard.admin"; + + static final String APPLICATION = "type=Application,name="; + static final String SERVICE = "type=Service,name="; + static final String REFERENCE = "type=Reference,name="; + static final String BINDING = "type=Binding,name="; + static final String TRANSFORMER = "type=Transformer,name="; + static final String VALIDATOR = "type=Validator,name="; + static final String COMPONENT_SERVICE = "type=ComponentService,name="; + static final String COMPONENT_REFERENCE = "type=ComponentReference,name="; + static final String LOCAL_MANAGEMENT = "type=Management.Local"; + static final String THROTTLING = "type=Throttling,service="; + + private static MBeanServer _server = ManagementFactory.getPlatformMBeanServer(); + private static Logger _log = Logger.getLogger(MBeans.class); + + private MBeans() { + // Not for public use + } + + /** + * Register an instance of the local management MBean. + * @param localManage local management MBean + */ + public static void registerLocalManagement(LocalManagement localManage) { + registerMBean(localManage, toName(DOMAIN + ":" + LOCAL_MANAGEMENT)); + } + + /** + * Unregister local management MBean. + */ + public static void unregisterLocalManagement() { + unregisterMBean(toName(DOMAIN + ":" + LOCAL_MANAGEMENT)); + } + + /** + * Creates MBeans for all manageable aspects of a SY application and registers them with + * the platform MBean server. + * @param application the application to manage + */ + public static void registerApplication(Application application) { + ManagedApplication mApp = new ManagedApplication(application); + registerMBean(mApp, getObjectName(application)); + + // register composite services + for (Service service : application.getServices()) { + ManagedService mSvc = new ManagedService(service, mApp); + registerMBean(mSvc, getObjectName(service)); + registerMBean(mSvc.getThrottling(), getObjectName(service, service.getThrottling())); + // register service bindings + for (Binding binding : service.getGateways()) { + ManagedBinding mBind = new ManagedBinding(binding); + registerMBean(mBind, getObjectName(service, binding)); + mSvc.addBinding(mBind); + } + } + + // register composite references + for (Reference reference : application.getReferences()) { + ManagedReference mRef = new ManagedReference(reference, mApp); + registerMBean(mRef, getObjectName(reference)); + // register service bindings + for (Binding binding : reference.getGateways()) { + ManagedBinding mBind = new ManagedBinding(binding); + registerMBean(mBind, getObjectName(reference, binding)); + mRef.addBinding(mBind); + } + } + + // register transformers + for (Transformer trans : application.getTransformers()) { + ManagedTransformer mTrans = new ManagedTransformer(trans); + registerMBean(mTrans, getObjectName(trans)); + } + + // register validators + for (Validator val : application.getValidators()) { + ManagedValidator mVal = new ManagedValidator(val); + registerMBean(mVal, getObjectName(val)); + } + + // register component services + for (ComponentService cs : application.getComponentServices()) { + ManagedComponentService mCS = new ManagedComponentService(cs, mApp); + registerMBean(mCS, getObjectName(cs)); + for (ComponentReference cr : cs.getReferences()) { + ManagedComponentReference mCR = new ManagedComponentReference(cr); + registerMBean(mCR, getObjectName(cs, cr)); + } + } + } + + /** + * Unregisters all MBeans for a SwitchYard application. + * @param application all associated MBeans for this application will be unregistered. + */ + public static void unregisterApplication(Application application) { + // Unregister application + unregisterMBean(getObjectName(application)); + + // Unregister composite services + for (Service service : application.getServices()) { + unregisterMBean(getObjectName(service)); + unregisterMBean(getObjectName(service, service.getThrottling())); + for (Binding binding : service.getGateways()) { + unregisterMBean(getObjectName(service, binding)); + } + } + // Unregister composite references + for (Reference reference : application.getReferences()) { + unregisterMBean(getObjectName(reference)); + for (Binding binding : reference.getGateways()) { + unregisterMBean(getObjectName(reference, binding)); + } + } + + // Unregister transformers + for (Transformer trans : application.getTransformers()) { + unregisterMBean(getObjectName(trans)); + } + + // Unregister validators + for (Validator val : application.getValidators()) { + unregisterMBean(getObjectName(val)); + } + + // Unregister component services + for (ComponentService cs : application.getComponentServices()) { + unregisterMBean(getObjectName(cs)); + for (ComponentReference cr : cs.getReferences()) { + unregisterMBean(getObjectName(cs, cr)); + } + } + } + + private static void registerMBean(Object obj, ObjectName name) { + try { + _server.registerMBean(obj, name); + } catch (Exception ex) { + _log.debug("Failed to register SwitchYard MBean: " + name, ex); + } + } + + private static void unregisterMBean(ObjectName name) throws SwitchYardException { + try { + _server.unregisterMBean(name); + } catch (Exception ex) { + _log.debug("Failed to unregister SwitchYard MBean: " + name, ex); + } + } + + static ObjectName getObjectName(Application application) { + return toName(DOMAIN + ":" + APPLICATION + ObjectName.quote(application.getName().toString())); + } + + static ObjectName getObjectName(Service service) { + return toName(DOMAIN + ":" + SERVICE + ObjectName.quote(service.getName().toString())); + } + + static ObjectName getObjectName(Reference reference) { + return toName(DOMAIN + ":" + REFERENCE + ObjectName.quote(reference.getName().toString())); + } + + static ObjectName getObjectName(ComponentService compSvc) { + return toName(DOMAIN + ":" + COMPONENT_SERVICE + ObjectName.quote(compSvc.getName().toString())); + } + + static ObjectName getObjectName(Transformer transformer) { + return toName(DOMAIN + ":" + TRANSFORMER + ObjectName.quote(transformer.getFrom() + " => " + transformer.getTo())); + } + + static ObjectName getObjectName(Validator validator) { + return toName(DOMAIN + ":" + VALIDATOR + ObjectName.quote(validator.getName().toString())); + } + + static ObjectName getObjectName(ComponentService service, ComponentReference reference) { + return toName(DOMAIN + ":" + + COMPONENT_REFERENCE + ObjectName.quote(reference.getName().toString()) + + ",service=" + ObjectName.quote(service.getName().toString())); + } + + static ObjectName getObjectName(Service service, Binding binding) { + return toName(DOMAIN + ":" + + BINDING + ObjectName.quote(binding.getName()) + + ",service=" + ObjectName.quote(service.getName().toString())); + } + + static ObjectName getObjectName(Reference reference, Binding binding) { + return toName(DOMAIN + ":" + + BINDING + ObjectName.quote(binding.getName()) + + ",reference=" + ObjectName.quote(reference.getName().toString())); + } + + static ObjectName getObjectName(Service service, Throttling throttling) { + return toName(DOMAIN + ":" + + THROTTLING + ObjectName.quote(service.getName().toString())); + } + + private static ObjectName toName(String nameStr) { + try { + return new ObjectName(nameStr); + } catch (javax.management.MalformedObjectNameException badNameEx) { + throw new IllegalArgumentException(badNameEx); + } + } +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedApplication.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedApplication.java new file mode 100644 index 000000000..6e80ba90b --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedApplication.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import java.util.ArrayList; +import java.util.List; + +import javax.management.ObjectName; +import javax.xml.namespace.QName; + +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.Transformer; +import org.switchyard.admin.Validator; +import org.switchyard.admin.mbean.ApplicationMXBean; + +/** + * Implementation of ApplicationMXBean. + */ +public class ManagedApplication implements ApplicationMXBean { + + private Application _application; + + /** + * Create a new managed application. + * @param application the Application delegate from the admin API + */ + public ManagedApplication(Application application) { + _application = application; + } + + @Override + public List getServices() { + List services = new ArrayList(); + for (Service s : _application.getServices()) { + services.add(s.getName().toString()); + } + return services; + } + + @Override + public List getReferences() { + List references = new ArrayList(); + for (Reference ref : _application.getReferences()) { + references.add(ref.getName().toString()); + } + return references; + } + + @Override + public ObjectName getService(String serviceName) { + ObjectName name = null; + if (serviceName != null) { + Service service = _application.getService(QName.valueOf(serviceName)); + if (service != null) { + name = MBeans.getObjectName(service); + } + } + return name; + } + + @Override + public ObjectName getReference(String referenceName) { + ObjectName name = null; + if (referenceName != null) { + Reference reference = _application.getReference(QName.valueOf(referenceName)); + if (reference != null) { + name = MBeans.getObjectName(reference); + } + } + return name; + } + + @Override + public List getComponentServices() { + List services = new ArrayList(); + for (ComponentService cs : _application.getComponentServices()) { + services.add(cs.getName().toString()); + } + return services; + } + + @Override + public ObjectName getComponentService(String componentServiceName) { + ObjectName name = null; + if (componentServiceName != null) { + ComponentService service = _application.getComponentService(QName.valueOf(componentServiceName)); + if (service != null) { + name = MBeans.getObjectName(service); + } + } + return name; + } + + @Override + public List getTransformers() { + List transformers = new ArrayList(); + for (Transformer t : _application.getTransformers()) { + transformers.add(MBeans.getObjectName(t)); + } + + return transformers; + } + + @Override + public List getValidators() { + List validators = new ArrayList(); + for (Validator v : _application.getValidators()) { + validators.add(MBeans.getObjectName(v)); + } + + return validators; + } + + @Override + public String getName() { + return _application.getName().toString(); + } + + @Override + public String getConfig() { + return _application.getConfig().toString(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedBinding.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedBinding.java new file mode 100644 index 000000000..9a71d7674 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedBinding.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import org.switchyard.admin.Binding; +import org.switchyard.admin.mbean.BindingMXBean; + +/** + * Implementation of BindingMXBean. + */ +public class ManagedBinding implements BindingMXBean { + + private Binding _binding; + + /** + * Create a new ManagedBinding. + * @param binding delegate to admin Binding instance + */ + public ManagedBinding(Binding binding) { + _binding = binding; + } + + @Override + public String getType() { + return _binding.getType(); + } + + @Override + public String getConfiguration() { + return _binding.getConfiguration(); + } + + @Override + public String getName() { + return _binding.getName(); + } + + @Override + public void start() { + _binding.start(); + } + + @Override + public void stop() { + _binding.stop(); + } + + @Override + public State getState() { + return State.valueOf(_binding.getState().toString()); + } + + @Override + public int getSuccessCount() { + return _binding.getMessageMetrics().getSuccessCount(); + } + + @Override + public int getFaultCount() { + return _binding.getMessageMetrics().getFaultCount(); + } + + @Override + public int getTotalCount() { + return _binding.getMessageMetrics().getTotalCount(); + } + + @Override + public long getTotalProcessingTime() { + return _binding.getMessageMetrics().getTotalProcessingTime(); + } + + @Override + public double getAverageProcessingTime() { + return _binding.getMessageMetrics().getAverageProcessingTime(); + } + + @Override + public int getMinProcessingTime() { + return _binding.getMessageMetrics().getMinProcessingTime(); + } + + @Override + public int getMaxProcessingTime() { + return _binding.getMessageMetrics().getMaxProcessingTime(); + } + + @Override + public void reset() { + _binding.resetMessageMetrics(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedComponentReference.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedComponentReference.java new file mode 100644 index 000000000..fc1e0ffe7 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedComponentReference.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import org.switchyard.admin.ComponentReference; +import org.switchyard.admin.mbean.ComponentReferenceMXBean; + +/** + * Implementation of ComponentReferenceMXBean. + */ +public class ManagedComponentReference implements ComponentReferenceMXBean { + + private ComponentReference _reference; + + /** + * Create a new ManagedComponentReference. + * @param reference delegate reference to admin ComponentReference + */ + public ManagedComponentReference(ComponentReference reference) { + _reference = reference; + } + + @Override + public String getName() { + return _reference.getName().toString(); + } + + @Override + public String getInterface() { + return _reference.getInterface(); + } + + @Override + public int getSuccessCount() { + return _reference.getMessageMetrics().getSuccessCount(); + } + + @Override + public int getFaultCount() { + return _reference.getMessageMetrics().getFaultCount(); + } + + @Override + public int getTotalCount() { + return _reference.getMessageMetrics().getTotalCount(); + } + + @Override + public long getTotalProcessingTime() { + return _reference.getMessageMetrics().getTotalProcessingTime(); + } + + @Override + public double getAverageProcessingTime() { + return _reference.getMessageMetrics().getAverageProcessingTime(); + } + + @Override + public int getMinProcessingTime() { + return _reference.getMessageMetrics().getMinProcessingTime(); + } + + @Override + public int getMaxProcessingTime() { + return _reference.getMessageMetrics().getMaxProcessingTime(); + } + + @Override + public void reset() { + _reference.resetMessageMetrics(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedComponentService.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedComponentService.java new file mode 100644 index 000000000..9e7585798 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedComponentService.java @@ -0,0 +1,126 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import java.util.ArrayList; +import java.util.List; + +import org.switchyard.admin.ComponentReference; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.ServiceOperation; +import org.switchyard.admin.mbean.ApplicationMXBean; +import org.switchyard.admin.mbean.ComponentServiceMXBean; + +/** + * Implementation of ComponentService. + */ +public class ManagedComponentService implements ComponentServiceMXBean { + + private ComponentService _service; + private ManagedApplication _parent; + + /** + * Create a new ManagedComponentService. + * @param service delegate reference to admin ComponentService + * @param parent pointer to parent application + */ + public ManagedComponentService(ComponentService service, ManagedApplication parent) { + _service = service; + _parent = parent; + } + + @Override + public String getName() { + return _service.getName().toString(); + } + + @Override + public String getInterface() { + return _service.getInterface(); + } + + @Override + public ApplicationMXBean getApplication() { + return _parent; + } + + @Override + public String getImplementation() { + return _service.getImplementation(); + } + + @Override + public String getImplementationConfiguration() { + return _service.getImplementationConfiguration(); + } + + @Override + public List getServiceOperations() { + List ops = new ArrayList(); + for (ServiceOperation op : _service.getServiceOperations()) { + ops.add(op.getName()); + } + return ops; + } + + @Override + public List getReferences() { + List refs = new ArrayList(); + for (ComponentReference ref : _service.getReferences()) { + refs.add(ref.getName().toString()); + } + return refs; + } + + @Override + public int getSuccessCount() { + return _service.getMessageMetrics().getSuccessCount(); + } + + @Override + public int getFaultCount() { + return _service.getMessageMetrics().getFaultCount(); + } + + @Override + public int getTotalCount() { + return _service.getMessageMetrics().getTotalCount(); + } + + @Override + public long getTotalProcessingTime() { + return _service.getMessageMetrics().getTotalProcessingTime(); + } + + @Override + public double getAverageProcessingTime() { + return _service.getMessageMetrics().getAverageProcessingTime(); + } + + @Override + public int getMinProcessingTime() { + return _service.getMessageMetrics().getMinProcessingTime(); + } + + @Override + public int getMaxProcessingTime() { + return _service.getMessageMetrics().getMaxProcessingTime(); + } + + @Override + public void reset() { + _service.resetMessageMetrics(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedReference.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedReference.java new file mode 100644 index 000000000..8f1c4ef9f --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedReference.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import java.util.ArrayList; +import java.util.List; + +import org.switchyard.admin.Reference; +import org.switchyard.admin.mbean.ApplicationMXBean; +import org.switchyard.admin.mbean.BindingMXBean; +import org.switchyard.admin.mbean.ReferenceMXBean; + +/** + * Implementation of ReferenceMXBean. + */ +public class ManagedReference implements ReferenceMXBean { + + private Reference _reference; + private ManagedApplication _application; + private List _bindings = new ArrayList(); + + /** + * Create a new ManagedReference. + * @param reference delegate reference to admin Reference + * @param application pointer to parent application + */ + public ManagedReference(Reference reference, ManagedApplication application) { + _reference = reference; + _application = application; + } + + @Override + public String getName() { + return _reference.getName().toString(); + } + + @Override + public String getPromotedReference() { + return _reference.getPromotedReference(); + } + + @Override + public List getBindings() { + return _bindings; + } + + /** + * Adds a managed binding to this reference. + * @param binding managed binding + */ + public void addBinding(BindingMXBean binding) { + _bindings.add(binding); + } + + @Override + public String getInterface() { + return _reference.getInterface(); + } + + @Override + public ApplicationMXBean getApplication() { + return _application; + } + + @Override + public int getSuccessCount() { + return _reference.getMessageMetrics().getSuccessCount(); + } + + @Override + public int getFaultCount() { + return _reference.getMessageMetrics().getFaultCount(); + } + + @Override + public int getTotalCount() { + return _reference.getMessageMetrics().getTotalCount(); + } + + @Override + public long getTotalProcessingTime() { + return _reference.getMessageMetrics().getTotalProcessingTime(); + } + + @Override + public double getAverageProcessingTime() { + return _reference.getMessageMetrics().getAverageProcessingTime(); + } + + @Override + public int getMinProcessingTime() { + return _reference.getMessageMetrics().getMinProcessingTime(); + } + + @Override + public int getMaxProcessingTime() { + return _reference.getMessageMetrics().getMaxProcessingTime(); + } + + @Override + public void reset() { + _reference.resetMessageMetrics(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedService.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedService.java new file mode 100644 index 000000000..4fc3c38f9 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedService.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import java.util.ArrayList; +import java.util.List; + +import org.switchyard.admin.Service; +import org.switchyard.admin.mbean.ApplicationMXBean; +import org.switchyard.admin.mbean.BindingMXBean; +import org.switchyard.admin.mbean.ServiceMXBean; +import org.switchyard.admin.mbean.ThrottlingMXBean; + +/** + * Implementation of ServiceMXBean. + */ +public class ManagedService implements ServiceMXBean { + + private Service _service; + private ManagedApplication _parent; + private List _bindings = new ArrayList(); + private ThrottlingMXBean _throttling; + + /** + * Creates a new ManagedService. + * @param service delegate reference to admin Service + * @param parent pointer to parent application. + */ + public ManagedService(Service service, ManagedApplication parent) { + _service = service; + _parent = parent; + _throttling = new ManagedThrottling(service.getThrottling()); + } + + @Override + public String getName() { + return _service.getName().toString(); + } + + @Override + public String getPromotedService() { + return _service.getPromotedService().getName().toString(); + } + + @Override + public List getBindings() { + return _bindings; + } + + /** + * Adds a managed binding to this service. + * @param binding managed binding + */ + public void addBinding(BindingMXBean binding) { + _bindings.add(binding); + } + + @Override + public String getInterface() { + return _service.getInterface(); + } + + @Override + public ApplicationMXBean getApplication() { + return _parent; + } + + @Override + public ThrottlingMXBean getThrottling() { + return _throttling; + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedThrottling.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedThrottling.java new file mode 100644 index 000000000..939620fd6 --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedThrottling.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import org.switchyard.admin.Throttling; +import org.switchyard.admin.mbean.ThrottlingMXBean; + +/** + * ManagedThrottling + *

+ * Implementation for {@link ThrottlingMXBean}. + */ +public class ManagedThrottling implements ThrottlingMXBean { + + private final Throttling _delegate; + /** + * Create a new ManagedThrottling. + * + * @param delegate the delegate admin object. + */ + public ManagedThrottling(Throttling delegate) { + _delegate = delegate; + } + + @Override + public boolean isEnabled() { + return _delegate.isEnabled(); + } + + @Override + public void enable() { + _delegate.enable(); + } + + @Override + public void disable() { + _delegate.disable(); + } + + @Override + public int getMaxRequests() { + return _delegate.getMaxRequests(); + } + + @Override + public void setMaxRequests(int maxRequests) { + _delegate.setMaxRequests(maxRequests); + } + + @Override + public long getTimePeriod() { + return _delegate.getTimePeriod(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedTransformer.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedTransformer.java new file mode 100644 index 000000000..89ff567fc --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedTransformer.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import org.switchyard.admin.Transformer; +import org.switchyard.admin.mbean.TransformerMXBean; + +/** + * Implementation of TransformerMXBean. + */ +public class ManagedTransformer implements TransformerMXBean { + + private Transformer _transformer; + + /** + * Create a new ManagedTransformer instance. + * @param transformer delegate reference to admin Transformer. + */ + public ManagedTransformer(Transformer transformer) { + _transformer = transformer; + } + + @Override + public String getFrom() { + return _transformer.getFrom().toString(); + } + + @Override + public String getTo() { + return _transformer.getTo().toString(); + } + + @Override + public String getType() { + return _transformer.getType(); + } + +} diff --git a/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedValidator.java b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedValidator.java new file mode 100644 index 000000000..b904c16fd --- /dev/null +++ b/core/admin/src/main/java/org/switchyard/admin/mbean/internal/ManagedValidator.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import org.switchyard.admin.Validator; +import org.switchyard.admin.mbean.ValidatorMXBean; + +/** + * Implementation of ValidatorMXBean. + */ +public class ManagedValidator implements ValidatorMXBean { + + private Validator _validator; + + /** + * Create new instance of ManagedValidator. + * @param validator delegate reference to admin Validator. + */ + public ManagedValidator(Validator validator) { + _validator = validator; + } + + @Override + public String getName() { + return _validator.getName().toString(); + } + + @Override + public String getType() { + return _validator.getType(); + } +} diff --git a/core/admin/src/test/java/org/switchyard/admin/base/MessageMetricsCollectionTest.java b/core/admin/src/test/java/org/switchyard/admin/base/MessageMetricsCollectionTest.java new file mode 100644 index 000000000..7da35102d --- /dev/null +++ b/core/admin/src/test/java/org/switchyard/admin/base/MessageMetricsCollectionTest.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.base; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.xml.namespace.QName; + +import org.junit.Test; +import org.mockito.Mockito; +import org.switchyard.Exchange; +import org.switchyard.ExchangeState; +import org.switchyard.Property; +import org.switchyard.admin.ComponentService; +import org.switchyard.deploy.ComponentNames; +import org.switchyard.runtime.event.ExchangeCompletionEvent; + +/** + * Test of message metrics collection on various levels. + */ +public class MessageMetricsCollectionTest extends SwitchYardBuilderTestBase { + + private static final String OPERATION_NAME = "greet"; + private static final QName TEST_SERVICE = new QName("urn:m1app:example:1.0", "M1AppService"); + private static final QName TEST_PROMOTED_SERVICE = new QName("urn:m1app:example:1.0", "SimpleService"); + private static final QName TEST_REFERENCE = ComponentNames.qualify(TEST_PROMOTED_SERVICE, new QName("urn:m1app:example:1.0", "anotherService")); + private static final String TEST_GATEWAY = "_M1AppService_sca_1"; + + public MessageMetricsCollectionTest() throws Exception { + super(); + } + + @Test + public void testSwitchyardLevelCollection() { + Exchange ex = createMock(); + defaultExpectations(ex); + + _builder.notify(new ExchangeCompletionEvent(ex)); + + assertEquals(1, _switchYard.getMessageMetrics().getSuccessCount()); + assertEquals(10.0, _switchYard.getMessageMetrics().getAverageProcessingTime(), 0); + } + + @Test + public void testOperationLevelCollection() { + Exchange ex = createMock(); + defaultExpectations(ex); + + Mockito.when(ex.getContract().getProviderOperation().getName()).thenReturn(OPERATION_NAME); + + _builder.notify(new ExchangeCompletionEvent(ex)); + + assertEquals(1, _switchYard.getMessageMetrics().getSuccessCount()); + assertEquals(10.0, _switchYard.getMessageMetrics().getAverageProcessingTime(), 0); + ComponentService componentService = _switchYard.getApplication(TEST_APP).getComponentService(TEST_PROMOTED_SERVICE); + assertEquals(10.0, componentService.getMessageMetrics().getAverageProcessingTime(), 0); + assertEquals(10.0, componentService.getServiceOperation(OPERATION_NAME).getMessageMetrics().getAverageProcessingTime(), 0); + assertEquals(10.0, _switchYard.getApplication(TEST_APP).getService(TEST_SERVICE).getGateway(TEST_GATEWAY).getMessageMetrics().getAverageProcessingTime(), 0); + } + + private Exchange createMock() { + return mock(Exchange.class, Mockito.RETURNS_DEEP_STUBS); + } + + private void defaultExpectations(Exchange ex) { + when(ex.getProvider().getName()).thenReturn(TEST_SERVICE); + when(ex.getConsumer().getName()).thenReturn(TEST_REFERENCE); + when(ex.getState()).thenReturn(ExchangeState.OK); + Property property = mock(Property.class); + when(property.getValue()).thenReturn(new Long(10)); + when(ex.getContext().getProperty(ExchangeCompletionEvent.EXCHANGE_DURATION)).thenReturn(property); + when(ex.getContext().getPropertyValue(ExchangeCompletionEvent.GATEWAY_NAME)).thenReturn(TEST_GATEWAY); + } +} diff --git a/core/admin/src/test/java/org/switchyard/admin/base/SwitchYardBuilderTest.java b/core/admin/src/test/java/org/switchyard/admin/base/SwitchYardBuilderTest.java new file mode 100644 index 000000000..707bc98f4 --- /dev/null +++ b/core/admin/src/test/java/org/switchyard/admin/base/SwitchYardBuilderTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.admin.base; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.event.ApplicationDeployedEvent; +import org.switchyard.deploy.internal.Deployment; + +public class SwitchYardBuilderTest extends SwitchYardBuilderTestBase { + + public SwitchYardBuilderTest() throws Exception { + super(); + } + + @Test + public void testApplication() { + Assert.assertEquals(1, _switchYard.getApplications().size()); + } + + @Test + public void testService() { + Assert.assertEquals(1, _switchYard.getApplication(TEST_APP).getServices().size()); + } + + @Test + public void testComponent() { + Assert.assertEquals(2, _switchYard.getApplication(TEST_APP).getComponentServices().size()); + } + + @Test + public void testNoComponentService() throws Exception{ + Deployment testDeployment = new MockDeployment( + new ModelPuller().pull("switchyard_multiappweb.xml", getClass()), + QName.valueOf("{urn:switchyard-quickstart-demo:multiapp:0.1.0}web")); + SwitchYardBuilder builder = new SwitchYardBuilder(); + builder.notify(new ApplicationDeployedEvent(testDeployment)); + + Assert.assertEquals(1, builder.getSwitchYard().getApplications().size()); + } + +} + +class MockDeployment extends Deployment { + private QName _name; + + MockDeployment(SwitchYardModel config, QName name) { + super(config); + _name = name; + } + + @Override + public QName getName() { + return _name; + } +} diff --git a/core/admin/src/test/java/org/switchyard/admin/base/SwitchYardBuilderTestBase.java b/core/admin/src/test/java/org/switchyard/admin/base/SwitchYardBuilderTestBase.java new file mode 100644 index 000000000..6b42ef8f8 --- /dev/null +++ b/core/admin/src/test/java/org/switchyard/admin/base/SwitchYardBuilderTestBase.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +import javax.xml.namespace.QName; + +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.switchyard.admin.SwitchYard; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.event.ApplicationDeployedEvent; +import org.switchyard.deploy.event.ApplicationUndeployedEvent; +import org.switchyard.deploy.internal.Deployment; + +/** + * Base class for builder tests. + */ +@Ignore +public class SwitchYardBuilderTestBase { + + protected static final QName TEST_APP = new QName("test-app"); + protected SwitchYard _switchYard; + protected Deployment _deployment; + protected SwitchYardBuilder _builder; + + public SwitchYardBuilderTestBase() throws Exception { + _deployment = new MockDeployment(new ModelPuller().pull("switchyard.xml", getClass()), + TEST_APP); + } + + @Before + public void setUp() throws Exception { + _builder = new SwitchYardBuilder(); + _switchYard = _builder.getSwitchYard(); + _builder.notify(new ApplicationDeployedEvent(_deployment)); + //Thread.sleep(300 * 1000); + } + + @After + public void tearDown() { + _builder.notify(new ApplicationUndeployedEvent(_deployment)); + } + +} \ No newline at end of file diff --git a/core/admin/src/test/java/org/switchyard/admin/base/TestInterface.java b/core/admin/src/test/java/org/switchyard/admin/base/TestInterface.java new file mode 100644 index 000000000..197f569c2 --- /dev/null +++ b/core/admin/src/test/java/org/switchyard/admin/base/TestInterface.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.base; + +/** + * Test interface. + */ +public interface TestInterface { + + /** + * First dummy operation. + * @param args Dummy argument. + */ + void invoke(String args); + + /** + * Second dummy operation. + * @param name Dummy argument. + * @return Dummy return value. + */ + String greet(String name); + +} diff --git a/core/admin/src/test/java/org/switchyard/admin/mbean/internal/MBeansTest.java b/core/admin/src/test/java/org/switchyard/admin/mbean/internal/MBeansTest.java new file mode 100644 index 000000000..ce9407bb4 --- /dev/null +++ b/core/admin/src/test/java/org/switchyard/admin/mbean/internal/MBeansTest.java @@ -0,0 +1,238 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.admin.mbean.internal; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.lang.management.ManagementFactory; +import java.util.ArrayList; +import java.util.EventObject; +import java.util.List; + +import javax.management.MBeanServer; +import javax.management.ObjectName; +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.ComponentReference; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.Transformer; +import org.switchyard.admin.Validator; +import org.switchyard.admin.base.BaseApplication; +import org.switchyard.admin.base.BaseService; +import org.switchyard.admin.base.SwitchYardBuilder; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.event.EventObserver; + +public class MBeansTest { + + private static final QName TEST_APP = + new QName("test-application"); + private static final QName TEST_COMPOSITE_SERVICE = + new QName("test-composite-service"); + private static final QName TEST_COMPOSITE_REFERENCE = + new QName("test-composite-reference"); + private static final QName TEST_COMPONENT_SERVICE = + new QName("test-component-service"); + private static final QName TEST_COMPONENT_REFERENCE = + new QName("test-component-reference"); + + private MBeanServer _mbs; + private ServiceDomainManager _domainManager; + private SwitchYardBuilder _builder; + + @Before + public void setUp() throws Exception { + _mbs = ManagementFactory.getPlatformMBeanServer(); + _domainManager = new ServiceDomainManager(); + _builder = new SwitchYardBuilder(); + _builder.init(_domainManager); + } + + @After + public void tearDown() { + _builder.destroy(); + } + + @Test + public void localManagementRegistration() throws Exception { + ObjectName lmName = new ObjectName(MBeans.DOMAIN + ":" + MBeans.LOCAL_MANAGEMENT); + Assert.assertTrue(_mbs.isRegistered(lmName)); + } + + @Test + public void eventNotification() throws Exception { + EventSink sink = new EventSink(); + ObjectName lmName = new ObjectName(MBeans.DOMAIN + ":" + MBeans.LOCAL_MANAGEMENT); + + // Register our event listener via JMX + _mbs.invoke(lmName, "addObserver", + new Object[] {sink, DummyEvent.class}, + new String[] {EventObserver.class.getName(), "java.lang.Class"}); + + // Generate an event + _domainManager.getEventManager().publish(new DummyEvent()); + + // Verify we received the event + Assert.assertNotNull(sink.lastEvent); + Assert.assertTrue(sink.lastEvent instanceof DummyEvent); + } + + @Test + public void testApplicationMBeans() { + Application app = createApplication(); + MBeans.registerApplication(app); + Assert.assertTrue(_mbs.isRegistered(MBeans.getObjectName(app))); + MBeans.unregisterApplication(app); + Assert.assertFalse(_mbs.isRegistered(MBeans.getObjectName(app))); + } + + @Test + public void testServiceMBeans() { + Application app = createApplication(); + MBeans.registerApplication(app); + Assert.assertTrue(_mbs.isRegistered(MBeans.getObjectName(app.getServices().get(0)))); + MBeans.unregisterApplication(app); + Assert.assertFalse(_mbs.isRegistered(MBeans.getObjectName(app.getServices().get(0)))); + } + + @Test + public void testReferenceMBeans() { + Application app = createApplication(); + MBeans.registerApplication(app); + Assert.assertTrue(_mbs.isRegistered(MBeans.getObjectName(app.getReferences().get(0)))); + MBeans.unregisterApplication(app); + Assert.assertFalse(_mbs.isRegistered(MBeans.getObjectName(app.getReferences().get(0)))); + } + + @Test + public void testTransformerMBeans() { + Application app = createApplication(); + MBeans.registerApplication(app); + Assert.assertTrue(_mbs.isRegistered(MBeans.getObjectName(app.getTransformers().get(0)))); + MBeans.unregisterApplication(app); + Assert.assertFalse(_mbs.isRegistered(MBeans.getObjectName(app.getTransformers().get(0)))); + } + + @Test + public void testValidatorMBeans() { + Application app = createApplication(); + MBeans.registerApplication(app); + Assert.assertTrue(_mbs.isRegistered(MBeans.getObjectName(app.getValidators().get(0)))); + MBeans.unregisterApplication(app); + Assert.assertFalse(_mbs.isRegistered(MBeans.getObjectName(app.getValidators().get(0)))); + } + + @Test + public void testBindingMBeans() { + Application app = createApplication(); + MBeans.registerApplication(app); + Service service = app.getServices().get(0); + Assert.assertTrue(_mbs.isRegistered(MBeans.getObjectName(service, service.getGateways().get(0)))); + MBeans.unregisterApplication(app); + Assert.assertFalse(_mbs.isRegistered(MBeans.getObjectName(app.getValidators().get(0)))); + } + + @Test + public void testComponentServiceMBeans() { + Application app = createApplication(); + MBeans.registerApplication(app); + ComponentService cs = app.getComponentServices().get(0); + Assert.assertTrue(_mbs.isRegistered(MBeans.getObjectName(cs))); + Assert.assertTrue(_mbs.isRegistered(MBeans.getObjectName(cs, cs.getReferences().get(0)))); + MBeans.unregisterApplication(app); + Assert.assertFalse(_mbs.isRegistered(MBeans.getObjectName(cs))); + Assert.assertFalse(_mbs.isRegistered(MBeans.getObjectName(cs, cs.getReferences().get(0)))); + } + + private Application createApplication() { + Application app = mock(BaseApplication.class); + when(app.getName()).thenReturn(TEST_APP); + + // Services + List services = new ArrayList(); + Service service = mock(BaseService.class); + when (service.getName()).thenReturn(TEST_COMPOSITE_SERVICE); + services.add(service); + when(app.getServices()).thenReturn(services); + + // References + List references = new ArrayList(); + Reference ref = mock(Reference.class); + when(ref.getName()).thenReturn(TEST_COMPOSITE_REFERENCE); + references.add(ref); + when(app.getReferences()).thenReturn(references); + + // Bindings + Binding bind = mock(Binding.class); + List bindings = new ArrayList(); + bindings.add(bind); + when(bind.getName()).thenReturn("xyz"); + when(service.getGateways()).thenReturn(bindings); + + // Transformers + List transformers = new ArrayList(); + Transformer t = mock(Transformer.class); + transformers.add(t); + when(app.getTransformers()).thenReturn(transformers); + + // Validators + List validators = new ArrayList(); + Validator v = mock(Validator.class); + when(v.getName()).thenReturn(new QName("foo")); + validators.add(v); + when(app.getValidators()).thenReturn(validators); + + // Components + List compSvcs = new ArrayList(); + List compRefs = new ArrayList(); + ComponentService compSvc = mock(ComponentService.class); + ComponentReference compRef = mock(ComponentReference.class); + when(compSvc.getName()).thenReturn(TEST_COMPONENT_SERVICE); + when(compRef.getName()).thenReturn(TEST_COMPONENT_REFERENCE); + compSvcs.add(compSvc); + compRefs.add(compRef); + when(app.getComponentServices()).thenReturn(compSvcs); + when(compSvc.getReferences()).thenReturn(compRefs); + + return app; + } +} + +class EventSink implements EventObserver { + EventObject lastEvent; + + @Override + public void notify(EventObject event) { + lastEvent = event; + } + +} + +class DummyEvent extends EventObject { + private static final long serialVersionUID = 1L; + + DummyEvent() { + super(""); + } +} diff --git a/core/admin/src/test/resources/switchyard.xml b/core/admin/src/test/resources/switchyard.xml new file mode 100644 index 000000000..383509f81 --- /dev/null +++ b/core/admin/src/test/resources/switchyard.xml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + stuff + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/admin/src/test/resources/switchyard_multiappweb.xml b/core/admin/src/test/resources/switchyard_multiappweb.xml new file mode 100644 index 000000000..4c0d26623 --- /dev/null +++ b/core/admin/src/test/resources/switchyard_multiappweb.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/core/api/pom.xml b/core/api/pom.xml new file mode 100644 index 000000000..5971d9b4a --- /dev/null +++ b/core/api/pom.xml @@ -0,0 +1,35 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-api + bundle + SwitchYard: API + The Core API. + http://switchyard.org + + + !org.switchyard.common.*; + org.switchyard.* + + + + diff --git a/core/api/src/main/java/org/switchyard/APILogger.java b/core/api/src/main/java/org/switchyard/APILogger.java new file mode 100644 index 000000000..bb493d07a --- /dev/null +++ b/core/api/src/main/java/org/switchyard/APILogger.java @@ -0,0 +1,36 @@ +package org.switchyard; + +import static org.jboss.logging.Logger.Level.WARN; + +import org.jboss.logging.BasicLogger; +import org.jboss.logging.Logger; + +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +import javax.xml.namespace.QName; + +/** + *

+ * This file is using the subset 10200-10399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface APILogger extends BasicLogger { + /** + * Basic root logger. + */ + APILogger ROOT_LOGGER = Logger.getMessageLogger(APILogger.class, APILogger.class.getPackage().getName()); + + /** + * nullTransformResult method definition. + * @param className class name + * @param fromType from type + * @param toType to type + */ + @LogMessage(level = WARN) + @Message(id = 10200, value= "Transformer '%s' returned a null transformation result when transforming from type " + + "'%s' to type '%s'. Check input payload matches requirements of the Transformer implementation.") + void nullTransformResult(String className, QName fromType, QName toType); +} diff --git a/core/api/src/main/java/org/switchyard/APIMessages.java b/core/api/src/main/java/org/switchyard/APIMessages.java new file mode 100644 index 000000000..bdd095bd6 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/APIMessages.java @@ -0,0 +1,73 @@ +package org.switchyard; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 10000-10199 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface APIMessages { + /** + * The default messages. + */ + APIMessages MESSAGES = Messages.getBundle(APIMessages.class); + + /** + * unexpectedInterrupt method definition. + * @return IllegalStateException + */ + @Message(id = 10003, value = "Unexpected Interrupt exception.") + IllegalStateException unexpectedInterrupt(); + + /** + * serviceOpNeedOneParamater method definition. + * @return RuntimeException + */ + @Message(id = 10004, value = "Service operations on a Java interface must have exactly one parameter.") + RuntimeException serviceOpNeedOneParamater(); + + /** + * serviceOpOnlyOneParameter method definition. + * @return SwitchYardException + */ + @Message(id = 10005, value = "Service operations on a Java interface can only throw one type of exception.") + SwitchYardException serviceOpOnlyOneParameter(); + + /** + * invalidPolicyName method definition. + * @param name name + * @return Exception + */ + @Message(id = 10006, value = "Invalid policy name: %s doesn't exist.") + Exception invalidPolicyName(String name); + + /** + * nullTypeNamePassed method definition. + * @return IllegalArgumentException + */ + @Message(id = 10009, value = "null 'typeName' arg passed.") + IllegalArgumentException nullTypeNamePassed(); + + /** + * unrecognizedURI method definition. + * @param uri uri + * @return IllegalArgumentException + */ + @Message(id = 10010, value = "Unrecognized URI: %s") + IllegalArgumentException unrecognizedURI(String uri); + + + /** + * unableUpdateMetadataType method definition. + * @param klass klass + * @return IllegalArgumentException + */ + @Message(id = 10011, value = "Unable to update metadata type %s") + IllegalArgumentException unableUpdateMetadataType(String klass); + +} diff --git a/core/api/src/main/java/org/switchyard/BaseHandler.java b/core/api/src/main/java/org/switchyard/BaseHandler.java new file mode 100644 index 000000000..0c70ba5cf --- /dev/null +++ b/core/api/src/main/java/org/switchyard/BaseHandler.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +/** + * Empty implementation of the ExchangeHandler interface that can be used to + * selectively override fault or message handling logic. + */ +public class BaseHandler implements ExchangeHandler { + + /** + * @param exchange the exchange + * @see ExchangeHandler#handleFault(Exchange) + */ + public void handleFault(final Exchange exchange) { + // Default implementation does nothing for now + } + + /** + * @param exchange the exchange + * @throws HandlerException handler exception + * @see ExchangeHandler#handleMessage(Exchange) + */ + public void handleMessage(final Exchange exchange) throws HandlerException { + // Default implementation does nothing for now + } +} diff --git a/core/api/src/main/java/org/switchyard/Context.java b/core/api/src/main/java/org/switchyard/Context.java new file mode 100644 index 000000000..fea033360 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/Context.java @@ -0,0 +1,144 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import java.util.Set; + +/** + * Holds contextual information around the exchange of messages between a + * service consumer and provider. + */ +public interface Context { + + /** + * Merges the properties in this Context instance into the specified Context instance, + * adding missing values and overwriting existing values. A shallow copy of + * context property values is performed, so values that are references will be shared + * between the two contexts. + *

+ * Properties with a label of Labels.TRANSIENT are not included in the merge. + * @param context context properties are copied from this context + */ + void mergeInto(Context context); + + /** + * Retrieves the named property within this context, regardless + * of the scope. + * @param name property name + * @return value of the property in this context or null if the property + * does not exist + */ + Property getProperty(String name); + + /** + * Retrieves the value of the named property with the given scope in this + * context. + * @param name property name + * @param scope property scope + * @return value of the property in this context or null if the property + * does not exist + */ + Property getProperty(String name, Scope scope); + + /** + * Retrieves the value of the named property within this context, regardless + * of the scope. This is a convenience method equivalent to + * getProperty(name).getValue() . + * @param name property name + * @return value of the property in this context or null if the property + * does not exist + * @param Expected type of property. + */ + T getPropertyValue(String name); + + /** + * Returns the set of all properties in this context. The returned + * set is a shallow copy of the properties set in this context, so + * modifications to the map are not reflected in the underlying context. + * @return set containing all properties in this context. If there are no + * properties in this context, an empty set is returned. + */ + Set getProperties(); + + /** + * Returns the set of all properties in this context in the specified scope. The + * returned set is a shallow copy of the properties set in this context, so + * modifications to the map are not reflected in the underlying context. + * @param scope scope from which properties will be retrieved + * @return set containing all properties in this context for the specified + * scope. If there are no properties in the scope, an empty set is returned. + */ + Set getProperties(Scope scope); + + /** + * Get all properties with a given label. + * @param label the label each property must have + * @return set of properties with the specified label + */ + Set getProperties(String label); + + /** + * Removes the named property from this context. + * @param property property to remove + * not exist + */ + void removeProperty(Property property); + + /** + * Removes all properties from this context. + */ + void removeProperties(); + + /** + * Removes properties from the specified scope from this context. + * @param scope scope of the properties to remove + */ + void removeProperties(Scope scope); + + /** + * Remove all properties with a given label. + * @param label the label each property must have + */ + void removeProperties(String label); + + /** + * Sets the named context property with the specified value. If the context + * property does not exist already, it is added. If the property already + * exists, the value of the property is replaced. + * @param name name of the property to set + * @param val the value to set for the property + * @return a reference to the set Property + */ + Property setProperty(String name, Object val); + + /** + * Sets the named context property with the specified value in a specific + * scope. If the context property does not exist already, it is added. + * If the property already exists, the value of the property is replaced. + * If the specified value is null, the property is removed from the context. + * @param name name of the property to set + * @param val the value to set for the property + * @param scope scope of the property to add + * @return a reference to the set Property + */ + Property setProperty(String name, Object val, Scope scope); + + /** + * Adds the set of properties to this context. + * @param properties set of properties to add + * @return a reference to the updated Context + */ + Context setProperties(Set properties); +} diff --git a/core/api/src/main/java/org/switchyard/ErrorListener.java b/core/api/src/main/java/org/switchyard/ErrorListener.java new file mode 100644 index 000000000..6808364ce --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ErrorListener.java @@ -0,0 +1,29 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard; + +/** + * Interface for elements intent to be aware about exceptions during mediation. + */ +public interface ErrorListener { + + /** + * Process exception thrown during handling of given exchange. + * + * @param exchange Exchange instance. + * @param throwable Exception thrown during mediation. + */ + void notify(Exchange exchange, Throwable throwable); + +} diff --git a/core/api/src/main/java/org/switchyard/Exchange.java b/core/api/src/main/java/org/switchyard/Exchange.java new file mode 100644 index 000000000..47f746967 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/Exchange.java @@ -0,0 +1,184 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard; + +import org.switchyard.metadata.ExchangeContract; +import org.switchyard.metadata.ServiceOperation; + +/** + * An Exchange represents an instance of a service invocation with a specific + * message exchange pattern (e.g. InOnly, InOut). Exchange provides a conduit + * for the messages that flow into and out of a service as part of a service + * invocation. Unlike messages, an exchange cannot be copied and reused across + * service invocations. State associated with an invocation (i.e. context) is + * maintained at the exchange level. + */ +public interface Exchange { + + /** + * Context property name used for Message ID. + */ + String MESSAGE_ID = "org.switchyard.messageId"; + + /** + * Context property name used for Relates To. + */ + String RELATES_TO = "org.switchyard.relatesTo"; + + /** + * Context property name used for Message Content Type. + */ + String CONTENT_TYPE = "org.switchyard.contentType"; + + /** + * Context property name used for Operation Name. + */ + String OPERATION_NAME = "org.switchyard.operationName"; + + /** + * Context property name used for Fault Type. + */ + String FAULT_TYPE = "org.switchyard.faultType"; + + /** + * Context property name used for Service Name. + */ + String SERVICE_NAME = "org.switchyard.serviceName"; + + /** + * Context property name used for A boolean flag which indicates if the transaction should + * be rolled back or not on fault. + * */ + String ROLLBACK_ON_FAULT = "org.switchyard.rollbackOnFault"; + + /** + * Domain property name used for a boolean flag which indicates if the exception should + * be propagate back to the service consumer. + */ + String PROPAGATE_EXCEPTION_ON_IN_ONLY = "org.switchyard.propagateExceptionOnInOnly"; + + /** + * Retrieves the exchange context. + * @return the exchange context + */ + Context getContext(); + + /** + * Retrieves context available for passed message. If message is same as + * message available on this exchange it will return same context as {@link #getContext()} + * method, otherwise another instance of Context will be returned. + * + * @param message Message instance. + * @return Context for message. + */ + Context getContext(Message message); + + /** + * Get the service reference representing the consumer. + * @return The consumer service reference instance. + */ + ServiceReference getConsumer(); + + /** + * Get the service representing the provider. This method will return + * null before an exchange is sent for the first time. + * @return the provider's service + */ + Service getProvider(); + + /** + * The contract between consumer and provider for this exchange. + * @return exchange contract + */ + ExchangeContract getContract(); + + /** + * Set service consumer info for this exchange. + * @param consumer the service reference used by the exchange + * @param operation the operation being invoked + * @return this Exchange instance + */ + Exchange consumer(ServiceReference consumer, ServiceOperation operation); + + /** + * Set service provider info for this exchange. + * @param provider the service provider used by the exchange + * @param operation the operation being invoked + * @return this Exchange instance + */ + Exchange provider(Service provider, ServiceOperation operation); + + /** + * Returns the current message for the exchange. On new exchanges, this + * method will always return null. The current message reference is updated + * with each call to send(). + * @return the current message for the exchange + */ + Message getMessage(); + + /** + * Create a message to be used with this exchange. + * @return new message + */ + Message createMessage(); + + /** + * Sends the specified message as part of this message exchange. + *

+ * Implementations must throw an {@link IllegalStateException} if this method is + * called when the Exchange {@link #getState() state} is in {@link ExchangeState#FAULT}. + * @param message message to send + */ + void send(Message message); + + /** + * Sends the specified message as part of this message exchange. + *

+ * Also sets the Exchange {@link #getState() state} to {@link ExchangeState#FAULT}. + * @param message message to send + */ + void sendFault(Message message); + + /** + * Get the exchange state. + * @return The exchange State. + */ + ExchangeState getState(); + + /** + * Get the exchange phase. + * @return the exchange phase + */ + ExchangePhase getPhase(); + + /** + * Get the reply handler for this exchange. + * @return reply handler + */ + ExchangeHandler getReplyHandler(); + + /** + * Provides the consumer's view of the message exchange pattern. This + * method is equivalent to getContract().getConsumerOperation().getExchangePattern(). + * Note that if consumer information has not been set, this method will return null! + * @return the consumer's exchange pattern or null if no consumer info is set on the exchange + */ + ExchangePattern getPattern(); + + /** + * Get the exchange security. + * @return the exchange security + */ + ExchangeSecurity getSecurity(); +} diff --git a/core/api/src/main/java/org/switchyard/ExchangeHandler.java b/core/api/src/main/java/org/switchyard/ExchangeHandler.java new file mode 100644 index 000000000..42ba75cea --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ExchangeHandler.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +/** + * The role of a Handler is to handle messages and fault events during the + * course of a service invocation. When consuming a service, a handler can be + * registered during Exchange creation to handle consumer events (e.g. fault + * or reply message). When providing a service, a handler is specified while + * registering the service to process invocations of that service. + */ +public interface ExchangeHandler { + /** + * Called when a message is sent through an exchange. + * @param exchange an {@code Exchange} instance containing a message to be + * processed + * @throws HandlerException when handling of the message event fails (e.g. + * invalid request message). + */ + void handleMessage(Exchange exchange) throws HandlerException; + /** + * Called when a fault is generated while processing an exchange. + * @param exchange an {@code Exchange} instance containing a message to be + * processed + */ + void handleFault(Exchange exchange); +} diff --git a/core/api/src/main/java/org/switchyard/ExchangeInterceptor.java b/core/api/src/main/java/org/switchyard/ExchangeInterceptor.java new file mode 100644 index 000000000..129bc3c19 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ExchangeInterceptor.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import java.util.List; + +/** + * ExchangeInterceptors allow code to be injected around specific interactions + * in the core exchange bus via a target definition. Valid targets are documented + * as constant fields in this interface. + */ +public interface ExchangeInterceptor { + + /** + * Intercepts an exchange before a message is passed into the processing pipeline + * and after all processing steps have completed. + */ + String CONSUMER = "Consumer"; + + /** + * Intercepts an exchange immediately before the provider is invoked and again + * immediately after the provider returns. + */ + String PROVIDER = "Provider"; + + /** + * Invoked immediately before the specified target scope in a message exchange. + * @param target interception point + * @param exchange message exchange + * @throws HandlerException in order to fail a message exchange + */ + void before(String target, Exchange exchange) throws HandlerException; + + /** + * Invoked immediately after the specified target scope in a message exchange. + * @param target interception point + * @param exchange message exchange + * @throws HandlerException in order to fail a message exchange + */ + void after(String target, Exchange exchange) throws HandlerException; + + /** + * The list of targets, or interception points, where this interceptor should be invoked. + * @return list of targets where this interceptor applies. + */ + List getTargets(); +} diff --git a/core/api/src/main/java/org/switchyard/ExchangePattern.java b/core/api/src/main/java/org/switchyard/ExchangePattern.java new file mode 100644 index 000000000..d1f8254a9 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ExchangePattern.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +/** + * The list of supported exchange patterns within SwitchYard. + */ +public enum ExchangePattern { + + /** + * A message exchange consisting of a single request message. + */ + IN_ONLY ("http://www.w3.org/ns/wsdl/in-only"), + /** + * A message exchange consisting of a single request message and a single + * response message. + */ + IN_OUT ("http://www.w3.org/ns/wsdl/in-out"); + + /** + * String representation of the pattern URI. + */ + private String _patternURI; + + /** + * Creates a new ExchangePattern instance with the specified URI string. + * @param uri a URI uniquely identifying the exchange pattern + */ + ExchangePattern(final String uri) { + _patternURI = uri; + } + + /** + * Returns the string representation of the ExchangePattern instance. + * @return exchange pattern URI + */ + public String getURI() { + return _patternURI; + } + + /** + * Converts an exchange pattern URI string into an instance of this enum. + * @param uri exchange pattern URI + * @return an instane of ExchangePattern corresponding to the specified + * pattern URI. + */ + public static ExchangePattern fromURI(final String uri) { + if (IN_ONLY.getURI().equals(uri)) { + return IN_ONLY; + } else if (IN_OUT.getURI().equals(uri)) { + return IN_OUT; + } else { + throw APIMessages.MESSAGES.unrecognizedURI(uri); + } + } +} diff --git a/core/api/src/main/java/org/switchyard/ExchangePhase.java b/core/api/src/main/java/org/switchyard/ExchangePhase.java new file mode 100644 index 000000000..8174f1509 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ExchangePhase.java @@ -0,0 +1,29 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +/** + * Represents the phase of an exchange. + */ +public enum ExchangePhase { + /** + * The input phase of an exchange. + */ + IN, + /** + * The output phase of an exchange. + */ + OUT +} diff --git a/core/api/src/main/java/org/switchyard/ExchangeSecurity.java b/core/api/src/main/java/org/switchyard/ExchangeSecurity.java new file mode 100644 index 000000000..1494d4ca6 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ExchangeSecurity.java @@ -0,0 +1,38 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard; + +import java.security.Principal; + +/** + * ExchangeSecurity. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public interface ExchangeSecurity { + + /** + * Gets the caller Principal. + * @return the caller Principal + */ + public Principal getCallerPrincipal(); + + /** + * Is the caller in the role name. + * @param roleName the role name + * @return successful check + */ + public boolean isCallerInRole(String roleName); + +} diff --git a/core/api/src/main/java/org/switchyard/ExchangeState.java b/core/api/src/main/java/org/switchyard/ExchangeState.java new file mode 100644 index 000000000..80f92b10d --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ExchangeState.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +/** + * Exchange State. + * @author tom.fennelly@gmail.com + */ +public enum ExchangeState { + /** + * Exchange OK (default). + */ + OK, + /** + * Exchange in fault. + */ + FAULT +} diff --git a/core/api/src/main/java/org/switchyard/HandlerException.java b/core/api/src/main/java/org/switchyard/HandlerException.java new file mode 100644 index 000000000..f0d71b175 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/HandlerException.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import org.switchyard.annotations.DefaultType; + +/** + * Represents a runtime processing error when handling an exchange. + */ +@DefaultType(HandlerException.MESSAGE_TYPE) +public class HandlerException extends Exception { + + /** + * Base fault Message type. + */ + public static final String MESSAGE_TYPE = "java:org.switchyard.HandlerException"; + + /** + * Generated serial version UID. + */ + private static final long serialVersionUID = -4026111208898030754L; + + private boolean _wrapper; + + /** + * Create a new HandlerException with the specified error message. + * @param message error text + */ + public HandlerException(final String message) { + super(message); + } + + /** + * Create a new HandlerException with the specified cause. + * @param cause error causing the handler to fail processing + */ + public HandlerException(final Throwable cause) { + super(cause); + _wrapper = true; + } + + /** + * Create a new HandlerException with the specified error message and cause. + * @param message error text + * @param cause error causing the handler to fail processing + */ + public HandlerException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Indicates whether this HandlerException is simply a wrapper for another + * exception type - i.e. it contains no independent error message or stack + * trace detail. + * @return true if this is a wrapper exception, false otherwise + */ + public boolean isWrapper() { + return _wrapper; + } +} diff --git a/core/api/src/main/java/org/switchyard/Message.java b/core/api/src/main/java/org/switchyard/Message.java new file mode 100644 index 000000000..baa4cbea7 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/Message.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import java.util.Map; + +import javax.activation.DataSource; + +/** + * A {@code Message} represents an individual input or output of a service, the + * content of which is interpreted by service implementation logic. A Message + * does not carry context specific to a service invocation, which means that it + * can be copied and reused across service invocations. + *

+ * There are two distinct parts to a message: + *

    + *
  • Content : the main body, or payload, of the message. There is + * only one body per message instance. The message body is mutable, so message + * processing logic can access the content, change it (transform, enrich, etc.), + * and then set it back on the message. + *

    + *

  • Attachments : provide the ability to associate content with a + * message separate from the main body, allowing it to be parsed independently. + * One example would be a binary image that is referenced by the main body of + * the message. The attachment may be too large to be processed in certain + * services or the service implementation may not be able to parse/interpret + * it. + *
+ */ +public interface Message { + + /** + * Retrieves the message context. + * @return the message context + */ + Context getContext(); + + /** + * Assigns the specified content to the body of this message. + * + * @param content message body content + * @return {@code this} message instance. + */ + Message setContent(Object content); + /** + * Returns the content from the body of the message. + * @return body content or null if the body has not been set + */ + Object getContent(); + /** + * Convenience method used to retrieve a typed instance of the message body. + * @param type + * @param type body content type + * @return body content or null if the body has not been set + */ + T getContent(Class type); + + /** + * Adds an attachment to the message with the specified name. + * @param name attachment name + * @param attachment attachment content + * @return {@code this} message instance. + */ + Message addAttachment(String name, DataSource attachment); + /** + * Retrieves the named attachment from the message. + * @param name name of the attachment + * @return the named attachment or null if the attachment does not exist + */ + DataSource getAttachment(String name); + /** + * Removes the named attachment from this message. + * @param name the attachment name + */ + void removeAttachment(String name); + + /** + * Returns a map containing all attachments to this message. The returned + * map is not a live reference to the underlying attachment map in the + * Message so changes to the returned map will not be reflected in the + * Message instance. + * @return a map containing all message attachments + */ + Map getAttachmentMap(); + + /** + * Return copy of message. The copy will contain clean context and point + * to same payload object. In other words contents of message is not cloned + * nor copied. + * + * @return copy of message. + */ + Message copy(); + +} diff --git a/core/api/src/main/java/org/switchyard/Property.java b/core/api/src/main/java/org/switchyard/Property.java new file mode 100644 index 000000000..20b59305c --- /dev/null +++ b/core/api/src/main/java/org/switchyard/Property.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import java.util.Set; + +/** + * Represents a context property consisting of a name, scope, and value. + */ +public interface Property { + + /** + * The scope of the property. + * @return property scope + */ + Scope getScope(); + + /** + * The name of the property. + * @return property name + */ + String getName(); + + /** + * The value of the property. + * @return property value + */ + Object getValue(); + + /** + * The labels of the property. + * @return the labels + */ + Set getLabels(); + + /** + * Adds labels to the property. + * @param labels the labels to add + * @return this property (useful for chaining) + */ + Property addLabels(String... labels); + + /** + * Adds a set of labels to the property. + * @param labels the labels to add + * @return this property (useful for chaining) + */ + Property addLabels(Set labels); + + /** + * Removes labels from the property. + * @param labels the labels to remove + * @return this property (useful for chaining) + */ + Property removeLabels(String... labels); + + /** + * If the property has the specified label. + * @param label the specified label + * @return this property (useful for chaining) + */ + boolean hasLabel(String label); + +} diff --git a/core/api/src/main/java/org/switchyard/Scope.java b/core/api/src/main/java/org/switchyard/Scope.java new file mode 100644 index 000000000..43b9322b8 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/Scope.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +/** + * Defines the scope of a context property. + */ +public enum Scope { + + /** + * Properties available for the duration of an exchange. + */ + EXCHANGE, + + /** + * Properties available as part of message. + */ + MESSAGE; + +} diff --git a/core/api/src/main/java/org/switchyard/Service.java b/core/api/src/main/java/org/switchyard/Service.java new file mode 100644 index 000000000..a3bba9344 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/Service.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import javax.xml.namespace.QName; + +import org.switchyard.metadata.ServiceInterface; + +/** + * A service registered with the SwitchYard runtime. + */ +public interface Service { + + /** + * Qualified name of the service. + * @return service name + */ + QName getName(); + + /** + * Interface metadata for the registered service. + * @return the service interface + */ + ServiceInterface getInterface(); + + /** + * Unregisters this service from the domain it's registered in. + */ + void unregister(); + + /** + * The domain in which this service is registered. + * @return service domain which created this service + */ + ServiceDomain getDomain(); + + /** + * Return the exchange handler representing the provider. + * @return provider's exchange handler + */ + ExchangeHandler getProviderHandler(); + + /** + * Return runtime metadata associated with this service. + * @return runtime service metadata + */ + ServiceMetadata getServiceMetadata(); +} diff --git a/core/api/src/main/java/org/switchyard/ServiceDomain.java b/core/api/src/main/java/org/switchyard/ServiceDomain.java new file mode 100644 index 000000000..923eba39b --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ServiceDomain.java @@ -0,0 +1,199 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import java.util.EventObject; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.event.EventObserver; +import org.switchyard.event.EventPublisher; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.validate.ValidatorRegistry; + +/** + * A ServiceDomain represents a collection of services with a shared set of + * resources, configuration, and policy definitions. The ServiceDomain + * interface is used by software components to provide and/or consume + * services. These software components include protocol gateways, service + * containers, translation engines, adapters, orchestration and routing + * engines. + */ +public interface ServiceDomain { + + /** + * Initialize the service domain. This method exists to allow additional + * properties and resources to be associated with the service domain before + * it is started. + */ + void init(); + + /** + * Name of the ServiceDomain. This is unique within a runtime. + * @return name name of the ServiceDomain. + */ + QName getName(); + + /** + * Register a service with the domain. + * @param serviceName the name of the service + * @param handler the handler to use to process exchanges directed at this + * service + * @param contract service interface details + * @return the registered service + */ + Service registerService(QName serviceName, + ServiceInterface contract, + ExchangeHandler handler); + + /** + * Register a service with the domain. + * @param serviceName the name of the service + * @param handler the handler to use to process exchanges directed at this + * service + * @param contract service interface details + * @param metadata runtime metadata associated with the service + * @return the registered service + */ + Service registerService(QName serviceName, + ServiceInterface contract, + ExchangeHandler handler, + ServiceMetadata metadata); + + /** + * Register a service reference with the domain. + * @param serviceName the name of the reference + * @param metadata service consumer contract + * @return a reference to the registered service that can be used to + * unregister when required + */ + ServiceReference registerServiceReference(QName serviceName, ServiceInterface metadata); + + /** + * Register a service reference with the domain. + * @param serviceName the name of the reference + * @param contract service consumer contract + * @param handler the handler to use to process replies from the service + * @return a reference to the registered service that can be used to + * unregister when required + */ + ServiceReference registerServiceReference(QName serviceName, + ServiceInterface contract, + ExchangeHandler handler); + + /** + * Register a service reference with the domain. + * @param serviceName the name of the reference + * @param contract service consumer contract + * @param handler the handler to use to process replies from the service + * @param metadata runtime metadata associated with the service + * @return a reference to the registered service that can be used to + * unregister when required + */ + ServiceReference registerServiceReference(QName serviceName, + ServiceInterface contract, + ExchangeHandler handler, + ServiceMetadata metadata); + + /** + * Fetches a registered service reference for the specified name. + * @param serviceName name of the service reference + * @return registered service reference, or null if no references have + * been registered with the specified name. + */ + ServiceReference getServiceReference(QName serviceName); + + /** + * Return the list of services. + * @return services + */ + List getServices(); + + /** + * Get the list of services for the specified service name. + * @param serviceName service name + * @return services + */ + List getServices(QName serviceName); + + /** + * Returns a reference to the transformer registry for this domain. + * @return transformer registry instance + */ + TransformerRegistry getTransformerRegistry(); + + /** + * Returns a reference to the validator registry for this domain. + * @return validator registry instance + */ + ValidatorRegistry getValidatorRegistry(); + + /** + * Add an EventObserver for the specified event type. A single instance + * of EventObserver can be registered to receive multiple event types. + * @param observer the event observer to add + * @param eventType the event type to receive notifications on + * @return a reference to this ServiceDomain for chaining multiple addEventObserver() calls + */ + ServiceDomain addEventObserver(EventObserver observer, Class eventType); + + /** + * Returns the EventPublisher for this domain, which can be used to notify + * event observers of activity. + * @return event publisher + */ + EventPublisher getEventPublisher(); + + /** + * Gets a ServiceSecurity by name. + * @param name the name + * @return the ServiceSecurity + */ + ServiceSecurity getServiceSecurity(String name); + + /** + * Sets the specified property on this domain. + * @param name property name + * @param value property value + * @return this ServiceDomain instance + */ + public ServiceDomain setProperty(String name, Object value); + + /** + * Returns the value of the specified domain property. + * @param name property name + * @return the value associated with this property, or null if no such property exists. + */ + public Object getProperty(String name); + + /** + * Shared properties/POJOs for this service domain. The returned map does not permit + * updates to domain properties. The setProperty() method should be used for + * setting/updating properties + * @return unmodifiable map of all domain properties + */ + Map getProperties(); + + /** + * Cleans up all resources associated with a ServiceDomain instance including + * the transformer/validator/service registry and exchange bus. ServiceDomain + * instances can not be used after they are destroyed. + */ + void destroy(); + +} diff --git a/core/api/src/main/java/org/switchyard/ServiceMetadata.java b/core/api/src/main/java/org/switchyard/ServiceMetadata.java new file mode 100644 index 000000000..3f61e8333 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ServiceMetadata.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import java.util.List; + +import org.switchyard.metadata.Registrant; +import org.switchyard.metadata.qos.Throttling; +import org.switchyard.policy.Policy; + +/** + * Contains runtime details on services and service references registered + * in SwitchYard. Instances of ServiceMetadata can be created and updated + * using the ServiceMetadataBuilder class. + */ +public interface ServiceMetadata { + + /** + * Gets the security. + * @return the security + */ + ServiceSecurity getSecurity(); + + /** + * Returns a list of required policies for this service reference. + * @return list of required policy + */ + List getRequiredPolicies(); + + /** + * Returns a list of policies provided by this service reference. + * @return list of provided policy + */ + List getProvidedPolicies(); + + /** + * Return the consumer metadata associated with this service. + * @return consumer metadata + */ + Registrant getRegistrant(); + + /** + * Return the throttling configuration associated with a service reference. Throttling + * config only applies to consumers via service references. + * @return throttling config + */ + Throttling getThrottling(); +} diff --git a/core/api/src/main/java/org/switchyard/ServiceReference.java b/core/api/src/main/java/org/switchyard/ServiceReference.java new file mode 100644 index 000000000..4775e1881 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ServiceReference.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import javax.xml.namespace.QName; + +import org.switchyard.metadata.ServiceInterface; + +/** + * A service registered with the SwitchYard runtime. + */ +public interface ServiceReference { + /** + * Qualified name of the service. + * @return service name + */ + QName getName(); + + /** + * The domain in which this service reference is registered. + * @return service domain which created this service reference + */ + ServiceDomain getDomain(); + + /** + * Interface metadata for the registered service. + * @return the service interface + */ + ServiceInterface getInterface(); + + /** + * Creates a new Exchange to invoke this service. Since this method does + * not accept an operation name, it should only be used when the service + * interface contains a single operation. + * @return a new Exchange instance + */ + Exchange createExchange(); + + /** + * Creates a new Exchange to invoke this service, with replies handled by + * the specified ExchangeHandler. Since this method does + * not accept an operation name, it should only be used when the service + * interface contains a single operation. + * @param handler used to process reply messages + * @return a new Exchange instance + */ + Exchange createExchange(ExchangeHandler handler); + + /** + * Creates a new Exchange to invoke this service with the specified exchange + * pattern. + * @param operation the operation to invoke + * @return a new Exchange instance + */ + Exchange createExchange(String operation); + + /** + * Creates a new Exchange to invoke this service with the specified exchange + * pattern. The supplied ExchangeHandler is used to handle any faults or + * reply messages that are generated as part of the message exchange. + * @param operation the operation to invoke + * @param handler used to process response and fault messages + * @return a new Exchange instance + */ + Exchange createExchange(String operation, ExchangeHandler handler); + + /** + * Unregisters this service reference from the domain it's registered in. + */ + void unregister(); + + /** + * Wire this service reference to a registered service. The default wiring + * of a reference maps it to a service with the same name. This method + * can be used to map references to services with a different name. + * @param serviceName service name to wire + */ + void wire(QName serviceName); + + /** + * Returns the name of a service which is wired from this reference. + * @return wired service name + */ + QName getTargetServiceName(); + + /** + * Return runtime metadata associated with this service reference. + * @return runtime service reference metadata + */ + ServiceMetadata getServiceMetadata(); + +} diff --git a/core/api/src/main/java/org/switchyard/ServiceSecurity.java b/core/api/src/main/java/org/switchyard/ServiceSecurity.java new file mode 100644 index 000000000..ca69e96a9 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/ServiceSecurity.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard; + +import java.util.Map; +import java.util.Set; + +/** + * ServiceSecurity. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface ServiceSecurity { + + /** + * The default name ("default"). + */ + public static final String DEFAULT_NAME = "default"; + + /** + * The default security domain ("other"). + */ + public static final String DEFAULT_SECURITY_DOMAIN = "other"; + + /** + * Gets the name. + * @return the name + */ + public String getName(); + + /** + * Gets the CallbackHandler class. + * @return the CallbackHandler class + */ + public Class getCallbackHandler(); + + /** + * Gets the properties. + * @return the properties + */ + public Map getProperties(); + + /** + * Gets the roles allowed. + * @return the roles allowed + */ + public Set getRolesAllowed(); + + /** + * Gets the run as. + * @return the run as + */ + public String getRunAs(); + + /** + * Gets the security domain. + * @return the security domain + */ + public String getSecurityDomain(); + +} diff --git a/core/api/src/main/java/org/switchyard/SwitchYardException.java b/core/api/src/main/java/org/switchyard/SwitchYardException.java new file mode 100644 index 000000000..5a6a29163 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/SwitchYardException.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard; + +/** + * SwitchYard base exception class. + * + * @author Tom Cunningham <tcunning@redhat.com> (C) 2011 Red Hat Inc. + */ +public class SwitchYardException extends RuntimeException { + + /** + * Serial UID. + */ + private static final long serialVersionUID = -5932547061290094335L; + + /** + * Public constructor. + * @param message Exception message. + */ + public SwitchYardException(String message) { + super(message); + } + + /** + * Public constructor. + * @param cause Throwable cause. + */ + public SwitchYardException(Throwable cause) { + super(cause); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Throwable cause. + */ + public SwitchYardException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/core/api/src/main/java/org/switchyard/annotations/DefaultType.java b/core/api/src/main/java/org/switchyard/annotations/DefaultType.java new file mode 100644 index 000000000..5a93c8dca --- /dev/null +++ b/core/api/src/main/java/org/switchyard/annotations/DefaultType.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Default payload type name. + *

+ * For Java Service implementations, SwitchYard uses the Java class name as the + * default {@link org.switchyard.metadata.InvocationContract invocation operation} + * input, output and fault type. This annotation allows you to set the default + * type name for a class hierarchy (note the annotation is inherited). This is + * very useful for setting the default type for e.g. a family of Exception types. + * + * @author tom.fennelly@gmail.com + * @see OperationTypes + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +public @interface DefaultType { + + /** + * Value. + */ + String value(); +} diff --git a/core/api/src/main/java/org/switchyard/annotations/OperationTypes.java b/core/api/src/main/java/org/switchyard/annotations/OperationTypes.java new file mode 100644 index 000000000..5f11fe9b7 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/annotations/OperationTypes.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Service operation type names. + *

+ * This annotation allows you to override the {@link DefaultType default type naming + * strategy used by SwitchYard}. + * + * @author tom.fennelly@gmail.com + * @see DefaultType + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +public @interface OperationTypes { + + /** + * Operation Input Type. + */ + String in() default ""; + + /** + * Operation Output Type. + */ + String out() default ""; + + /** + * Operation Fault Type. + */ + String fault() default ""; +} diff --git a/core/api/src/main/java/org/switchyard/annotations/Requires.java b/core/api/src/main/java/org/switchyard/annotations/Requires.java new file mode 100644 index 000000000..bc1185ecd --- /dev/null +++ b/core/api/src/main/java/org/switchyard/annotations/Requires.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.switchyard.policy.SecurityPolicy; +import org.switchyard.policy.TransactionPolicy; + +/** + * Specifies the types of policies that are required. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE,ElementType.FIELD}) +@Inherited +public @interface Requires { + + /** + * The security policies. + */ + SecurityPolicy[] security() default {}; + + /** + * The transaction policy. + */ + TransactionPolicy[] transaction() default {}; + +} diff --git a/core/api/src/main/java/org/switchyard/annotations/Transformer.java b/core/api/src/main/java/org/switchyard/annotations/Transformer.java new file mode 100644 index 000000000..58b9eb50b --- /dev/null +++ b/core/api/src/main/java/org/switchyard/annotations/Transformer.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.annotations; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * @author tom.fennelly@gmail.com + */ +@Target({METHOD }) +@Retention(RUNTIME) +@Documented +public @interface Transformer { + + /** + * Transform from (QName). + */ + String from() default ""; + + /** + * Transform to (QName). + */ + String to() default ""; +} diff --git a/core/api/src/main/java/org/switchyard/annotations/Validator.java b/core/api/src/main/java/org/switchyard/annotations/Validator.java new file mode 100644 index 000000000..fe10d5ef6 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/annotations/Validator.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.annotations; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * @author Tomohisa Igarashi + */ +@Target({METHOD }) +@Retention(RUNTIME) +@Documented +public @interface Validator { + + /** + * Validate for (QName). + */ + String name() default ""; + +} diff --git a/core/api/src/main/java/org/switchyard/event/DomainShutdownEvent.java b/core/api/src/main/java/org/switchyard/event/DomainShutdownEvent.java new file mode 100644 index 000000000..3456782f9 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/DomainShutdownEvent.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.event; + +import java.util.EventObject; + +import org.switchyard.ServiceDomain; + +/** + * Fired when domain is going to be shut down. + */ +public class DomainShutdownEvent extends EventObject { + + private static final long serialVersionUID = 8880993695548773898L; + + /** + * Creates new event object. + * + * @param source Service domain which will be stopped. + */ + public DomainShutdownEvent(ServiceDomain source) { + super(source); + } + + /** + * Gets domain associated with this event. + * + * @return Domain. + */ + public ServiceDomain getDomain() { + return (ServiceDomain) super.getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/event/DomainStartupEvent.java b/core/api/src/main/java/org/switchyard/event/DomainStartupEvent.java new file mode 100644 index 000000000..ab1b9a8b9 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/DomainStartupEvent.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.event; + +import java.util.EventObject; + +import org.switchyard.ServiceDomain; + +/** + * Fired when {@link ServiceDomain} is starting. + */ +public class DomainStartupEvent extends EventObject { + + private static final long serialVersionUID = -1146561635652637083L; + + /** + * Creates a new event object. + * + * @param source Domain which just started. + */ + public DomainStartupEvent(ServiceDomain source) { + super(source); + } + + /** + * Gets domain associated with event. + * + * @return Domain. + */ + public ServiceDomain getDomain() { + return (ServiceDomain) super.getSource(); + } + +} diff --git a/core/api/src/main/java/org/switchyard/event/EventObserver.java b/core/api/src/main/java/org/switchyard/event/EventObserver.java new file mode 100644 index 000000000..760d657bb --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/EventObserver.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; + +/** + * Used to observe SwitchYard events. An instance of EventObserver can be + * registered to handle multiple event types through ServiceDomain.addEventObserver() . + * Event notification can be synchronous or asynchronous, so Observer implementations + * should not rely on specific behavior. + */ +public interface EventObserver { + + /** + * Notification that an event has occurred. + * @param event event notification + */ + void notify(EventObject event); +} diff --git a/core/api/src/main/java/org/switchyard/event/EventPublisher.java b/core/api/src/main/java/org/switchyard/event/EventPublisher.java new file mode 100644 index 000000000..253f4eedd --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/EventPublisher.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; + +/** + * Used to publish events in a ServiceDomain. Event notification can be + * synchronous or asynchronous, so client code publishing events should + * not rely on specific behavior. + */ +public interface EventPublisher { + + /** + * Publish an event. + * @param event the event to publish + */ + void publish(EventObject event); +} diff --git a/core/api/src/main/java/org/switchyard/event/ReferenceRegistrationEvent.java b/core/api/src/main/java/org/switchyard/event/ReferenceRegistrationEvent.java new file mode 100644 index 000000000..41c4e79bb --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/ReferenceRegistrationEvent.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; +import org.switchyard.ServiceReference; + +/** + * Fired when a ServiceReference has been registered in the domain. + */ +public class ReferenceRegistrationEvent extends EventObject { + + private static final long serialVersionUID = 6157615236549484485L; + + /** + * Create a new ReferenceRegistrationEvent. + * @param reference the reference that was registered + */ + public ReferenceRegistrationEvent(ServiceReference reference) { + super(reference); + } + + /** + * Get the registered reference associated with this event. + * @return registered service reference + */ + public ServiceReference getReference() { + return (ServiceReference)getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/event/ReferenceUnregistrationEvent.java b/core/api/src/main/java/org/switchyard/event/ReferenceUnregistrationEvent.java new file mode 100644 index 000000000..54b1c999d --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/ReferenceUnregistrationEvent.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; +import org.switchyard.ServiceReference; + + +/** + * Fired when a ServiceReference has been unregistered in the domain. + */ +public class ReferenceUnregistrationEvent extends EventObject { + + private static final long serialVersionUID = 1052600470255473448L; + + /** + * Create a new ReferenceUnregistrationEvent. + * @param reference the reference that was unregistered + */ + public ReferenceUnregistrationEvent(ServiceReference reference) { + super(reference); + } + + /** + * Get the unregistered reference associated with this event. + * @return unregistered service reference + */ + public ServiceReference getReference() { + return (ServiceReference)getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/event/ServiceRegistrationEvent.java b/core/api/src/main/java/org/switchyard/event/ServiceRegistrationEvent.java new file mode 100644 index 000000000..be8f66ab0 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/ServiceRegistrationEvent.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; +import org.switchyard.Service; + +/** + * Fired when a Service has been registered in the domain. + */ +public class ServiceRegistrationEvent extends EventObject { + + private static final long serialVersionUID = -5100785646126159088L; + + /** + * Create a new ServiceRegistrationEvent. + * @param service the service that was registered + */ + public ServiceRegistrationEvent(Service service) { + super(service); + } + + /** + * Get the registered service associated with this event. + * @return registered service + */ + public Service getService() { + return (Service)getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/event/ServiceUnregistrationEvent.java b/core/api/src/main/java/org/switchyard/event/ServiceUnregistrationEvent.java new file mode 100644 index 000000000..6f84daf61 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/ServiceUnregistrationEvent.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; +import org.switchyard.Service; + +/** + * Fired when a Service has been unregistered in the domain. + */ +public class ServiceUnregistrationEvent extends EventObject { + + private static final long serialVersionUID = -2443169814086096894L; + + /** + * Create a new ServiceUnregistrationEvent. + * @param service the service that was unregistered + */ + public ServiceUnregistrationEvent(Service service) { + super(service); + } + + /** + * Get the unregistered reference associated with this event. + * @return unregistered service reference + */ + public Service getService() { + return (Service)getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/event/TransformerAddedEvent.java b/core/api/src/main/java/org/switchyard/event/TransformerAddedEvent.java new file mode 100644 index 000000000..8c11e7f84 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/TransformerAddedEvent.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; + +import org.switchyard.transform.Transformer; + +/** + * Fired when a transformer is added to the domain. + */ +public class TransformerAddedEvent extends EventObject { + + private static final long serialVersionUID = -8936714042650010616L; + + /** + * Creates a new TransformerAddedEvent. + * @param transformer the transformer that was added + */ + public TransformerAddedEvent(Transformer transformer) { + super(transformer); + } + + /** + * Get the added transformer. + * @return added transformer + */ + public Transformer getTransformer() { + return (Transformer)getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/event/TransformerRemovedEvent.java b/core/api/src/main/java/org/switchyard/event/TransformerRemovedEvent.java new file mode 100644 index 000000000..d42226161 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/TransformerRemovedEvent.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; + +import org.switchyard.transform.Transformer; + +/** + * Fired when a transformer is removed from the domain. + */ +public class TransformerRemovedEvent extends EventObject { + + private static final long serialVersionUID = -4987595062503824361L; + + /** + * Creates a new TransformerRemovedEvent. + * @param transformer the transformer that was removed + */ + public TransformerRemovedEvent(Transformer transformer) { + super(transformer); + } + + /** + * Get the removed transformer. + * @return removed transformer + */ + public Transformer getTransformer() { + return (Transformer)getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/event/ValidatorAddedEvent.java b/core/api/src/main/java/org/switchyard/event/ValidatorAddedEvent.java new file mode 100644 index 000000000..6ad26f3d2 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/ValidatorAddedEvent.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; + +import org.switchyard.validate.Validator; + +/** + * Fired when a validator is added to the domain. + */ +public class ValidatorAddedEvent extends EventObject { + + private static final long serialVersionUID = -715600806592716257L; + + /** + * Creates a new ValidatorAddedEvent. + * @param validator the validator that was added + */ + public ValidatorAddedEvent(Validator validator) { + super(validator); + } + + /** + * Get the added validator. + * @return added validator + */ + public Validator getTransformer() { + return (Validator)getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/event/ValidatorRemovedEvent.java b/core/api/src/main/java/org/switchyard/event/ValidatorRemovedEvent.java new file mode 100644 index 000000000..244f277b8 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/event/ValidatorRemovedEvent.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.event; + +import java.util.EventObject; + +import org.switchyard.validate.Validator; + +/** + * Fired when a validator is removed from the domain. + */ +public class ValidatorRemovedEvent extends EventObject { + + private static final long serialVersionUID = 7248520803400556118L; + + /** + * Creates a new ValidatorRemovedEvent. + * @param validator the validator that was removed + */ + public ValidatorRemovedEvent(Validator validator) { + super(validator); + } + + /** + * Get the removed validator. + * @return removed validator + */ + public Validator getTransformer() { + return (Validator)getSource(); + } +} diff --git a/core/api/src/main/java/org/switchyard/label/BehaviorLabel.java b/core/api/src/main/java/org/switchyard/label/BehaviorLabel.java new file mode 100644 index 000000000..526fe2292 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/label/BehaviorLabel.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.label; + +/** + * Represents behavior labels. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum BehaviorLabel implements Label { + + /** Behavior labels. */ + TRANSIENT; // the property will not be preserved in a copy of the Exchange via Context.copy() + + private final String _label; + + private BehaviorLabel() { + _label = Label.Util.toSwitchYardLabel("behavior", name()); + } + + /** + * {@inheritDoc} + */ + @Override + public String label() { + return _label; + } + + /** + * Gets the BehaviorLabel enum via case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the BehaviorLabel enum + */ + public static final BehaviorLabel ofName(String name) { + return Label.Util.ofName(BehaviorLabel.class, name); + } + + /** + * Gets the full-form behavior label from the case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the full-form behavior label + */ + public static final String toLabel(String name) { + BehaviorLabel label = ofName(name); + return label != null ? label.label() : null; + } + + /** + * Prints all known behavior labels. + * @param args ignored + */ + public static void main(String... args) { + Label.Util.print(values()); + } + +} diff --git a/core/api/src/main/java/org/switchyard/label/Label.java b/core/api/src/main/java/org/switchyard/label/Label.java new file mode 100644 index 000000000..d2915412d --- /dev/null +++ b/core/api/src/main/java/org/switchyard/label/Label.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.label; + + +/** + * Labels mark context properties, in their String form. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface Label { + + /** + * Gets the label name. + * @return the label name + */ + public String name(); + + /** + * Gets the full-form label String. + * @return the full-form label String + */ + public String label(); + + /** Util. */ + public static class Util { + + private static final String PREFIX = "org.switchyard.label."; + + /** + * Builds a label String given the specified label type and name. + * @param labelType the type + * @param name the name + * @return the full label String + */ + public static final String toSwitchYardLabel(String labelType, String name) { + labelType = labelType.trim().toLowerCase(); + name = name.trim().toLowerCase(); + return new StringBuilder(PREFIX).append(labelType).append('.').append(name).toString(); + } + + /** + * Retrieves a Label enum given the specified enum type and name. + * @param the enum class type + * @param enumType the enum type + * @param name the name + * @return the Label enum + */ + public static final > T ofName(Class enumType, String name) { + name = trimToNull(name); + if (name != null) { + name = name.toUpperCase(); + try { + return Enum.valueOf(enumType, name); + } catch (IllegalArgumentException iae) { + return null; + } + } + return null; + } + + /** + * Trims the specified String, and if after it is zero-length, return null. + * @param str the specified String + * @return the trim-to-null'd String + */ + public static String trimToNull(String str) { + if (str != null) { + str = str.trim(); + if (str.length() == 0) { + str = null; + } + } + return str; + } + + /** + * Prints the labels. + * @param labels the labels + */ + public static final void print(Label... labels) { + for (Label label : labels) { + System.out.println(String.format("%s: %s = %s", label.getClass().getName(), label.name(), label.label())); + } + } + + } + +} diff --git a/core/api/src/main/java/org/switchyard/metadata/BaseExchangeContract.java b/core/api/src/main/java/org/switchyard/metadata/BaseExchangeContract.java new file mode 100644 index 000000000..8eba6865c --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/BaseExchangeContract.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.metadata; + +/** + * Base implementation of ExchangeContract. + */ +public class BaseExchangeContract implements ExchangeContract { + + private ServiceOperation _consumer; + private ServiceOperation _provider; + + /** + * Create a new, empty BaseExchangeContract. + */ + public BaseExchangeContract() { + + } + + /** + * Create a new BaseExchangeContract with the specified consumer info. + * @param consumer consumer contract + */ + public BaseExchangeContract(ServiceOperation consumer) { + _consumer = consumer; + } + + /** + * Create a new BaseExchangeContract with the specified consumer and provider info. + * @param consumer consumer contract + * @param provider provider contract + */ + public BaseExchangeContract(ServiceOperation consumer, ServiceOperation provider) { + _consumer = consumer; + _provider = provider; + } + + @Override + public ServiceOperation getConsumerOperation() { + return _consumer; + } + + @Override + public ServiceOperation getProviderOperation() { + return _provider; + } + + /** + * Specify the consumer contract. + * @param consumer consumer contract + * @return this BaseExchangeContract instance + */ + public BaseExchangeContract setConsumerOperation(ServiceOperation consumer) { + _consumer = consumer; + return this; + } + + /** + * Specify the provider contract. + * @param provider provider contract + * @return this BaseExchangeContract instance + */ + public BaseExchangeContract setProviderOperation(ServiceOperation provider) { + _provider = provider; + return this; + } + +} diff --git a/core/api/src/main/java/org/switchyard/metadata/BaseService.java b/core/api/src/main/java/org/switchyard/metadata/BaseService.java new file mode 100644 index 000000000..10a274b99 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/BaseService.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +import java.util.HashSet; +import java.util.Set; + +/** + * Base implementation of ServiceInterface. Specific interface types such as + * Java and WSDL will extend this class or provide their own implementation of + * ServiceInterface. + */ +public class BaseService implements ServiceInterface { + + // The interface type + private String _type; + // The interface operations + private Set _operations; + + /** + * Create a new ServiceInterface with the specified operation. The default + * interface type, ServiceInterface.DEFAULT_TYPE, is assumed. + * @param operation interface operation + */ + public BaseService(ServiceOperation operation) { + this(operation, ServiceInterface.DEFAULT_TYPE); + } + + /** + * Create a new ServiceInterface with the specified operations. The default + * interface type, ServiceInterface.DEFAULT_TYPE, is assumed. + * @param operations interface operations + */ + public BaseService(Set operations) { + this(operations, ServiceInterface.DEFAULT_TYPE); + } + + /** + * Create a new ServiceInterface with the specified operation and type. + * @param operation interface operation + * @param type interface type + */ + public BaseService(ServiceOperation operation, String type) { + _operations = new HashSet(1); + _operations.add(operation); + _type = type; + } + + /** + * Create a new ServiceInterface with the specified operations and type. + * @param operations interface operations + * @param type interface type + */ + public BaseService(Set operations, String type) { + _operations = operations; + _type = type; + } + + /** + * @param name operation name + * @return service operation + * @see ServiceInterface + */ + @Override + public ServiceOperation getOperation(String name) { + ServiceOperation operation = null; + for (ServiceOperation op : _operations) { + // the '==' covers null equality + if (op.getName() == name || op.getName().equals(name)) { + operation = op; + break; + } + } + return operation; + } + + /** + * @return set of service operations + * @see ServiceInterface + */ + @Override + public Set getOperations() { + return new HashSet(_operations); + } + + /** + * @return interface type + * @see ServiceInterface + */ + @Override + public String getType() { + return _type; + } + + @Override + public String toString() { + return String.format("BaseServiceInterface [type=%s, operations=%s]", _type, _operations); + } + + protected void setType(String type) { + _type = type; + } + + protected void setOperations(Set operations) { + _operations = operations; + } +} diff --git a/core/api/src/main/java/org/switchyard/metadata/BaseServiceOperation.java b/core/api/src/main/java/org/switchyard/metadata/BaseServiceOperation.java new file mode 100644 index 000000000..689f90f3d --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/BaseServiceOperation.java @@ -0,0 +1,133 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +import javax.xml.namespace.QName; + +import org.switchyard.ExchangePattern; + +/** + * Base invocation contract. + * + * @author tom.fennelly@gmail.com + */ +public class BaseServiceOperation implements ServiceOperation { + + private QName _inputType; + private QName _outputType; + private QName _faultType; + private String _name; + private ExchangePattern _pattern; + + protected BaseServiceOperation(ExchangePattern pattern) { + _pattern = pattern; + } + + /** + * Constructor. + * @param pattern the exchange pattern + * @param name the operation name + * @param inputType Input type associated with the invocation instance. + * @param outputType Output type associated with the invocation instance. + * @param faultType Fault type associated with the invocation instance. + */ + public BaseServiceOperation( + ExchangePattern pattern, + String name, + QName inputType, + QName outputType, + QName faultType) { + _pattern = pattern; + _name = name; + _inputType = inputType; + _outputType = outputType; + _faultType = faultType; + } + + /** + * Set the input type associated with the invocation instance. + * @param inputType Input type associated with the invocation instance. + * @return {@link this} instance. + */ + public BaseServiceOperation setInputType(QName inputType) { + _inputType = inputType; + return this; + } + + @Override + public QName getInputType() { + return _inputType; + } + + /** + * Set the output type associated with the invocation instance. + * @param outputType Output type associated with the invocation instance. + * @return {@link this} instance. + */ + public BaseServiceOperation setOutputType(QName outputType) { + _outputType = outputType; + return this; + } + + @Override + public QName getOutputType() { + return _outputType; + } + + /** + * Set the fault type associated with the invocation instance. + * @param faultType Fault type associated with the invocation instance. + * @return {@link this} instance. + */ + public BaseServiceOperation setFaultType(QName faultType) { + _faultType = faultType; + return this; + } + + @Override + public QName getFaultType() { + return _faultType; + } + + @Override + public ExchangePattern getExchangePattern() { + return _pattern; + } + + @Override + public String getName() { + return _name; + } + + @Override + public String toString() { + return String.format("%s : %s : [%s, %s, %s]", _name, _pattern, getInputType(), + getOutputType(), getFaultType()); + } + + // Protected methods provide deserialization access for fields + + protected void setPattern(ExchangePattern pattern) { + _pattern = pattern; + } + + protected void setName(String name) { + _name = name; + } + + protected void setExchangePattern(ExchangePattern pattern) { + _pattern = pattern; + } +} diff --git a/core/api/src/main/java/org/switchyard/metadata/ExchangeContract.java b/core/api/src/main/java/org/switchyard/metadata/ExchangeContract.java new file mode 100644 index 000000000..60880adb3 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/ExchangeContract.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +/** + * Exchange Contract. + *

+ * Two-way Exchange contract, detailing the requirements of both the consumer + * and provider {@link ServiceOperation} being invoked. + * + * @author tom.fennelly@gmail.com + */ +public interface ExchangeContract { + + /** + * Returns the consumer contract for a message exchange. + * @return consumer contract + */ + ServiceOperation getConsumerOperation(); + + /** + * Returns the provider contract for a message exchange. + * @return provider contract + */ + ServiceOperation getProviderOperation(); + +} diff --git a/core/api/src/main/java/org/switchyard/metadata/InOnlyOperation.java b/core/api/src/main/java/org/switchyard/metadata/InOnlyOperation.java new file mode 100644 index 000000000..aee4b509f --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/InOnlyOperation.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +import javax.xml.namespace.QName; + +import org.switchyard.ExchangePattern; + +/** + * Default implementation of ServiceOperation for ExchangePattern.IN_ONLY + * operations. + */ +public class InOnlyOperation extends BaseServiceOperation { + + protected InOnlyOperation() { + super(ExchangePattern.IN_OUT); + } + + /** + * Create a new instance of an InOnly operation with a default message name. + * @param operationName the name of the operation + */ + public InOnlyOperation(String operationName) { + super(ExchangePattern.IN_ONLY, operationName, null, null, null); + } + + /** + * Create a new instance of an InOnly operation with a specific message name. + * @param operationName the name of the operation + * @param inputName the name of the input message + */ + public InOnlyOperation(String operationName, QName inputName) { + super(ExchangePattern.IN_ONLY, operationName, inputName, null, null); + } + +} diff --git a/core/api/src/main/java/org/switchyard/metadata/InOnlyService.java b/core/api/src/main/java/org/switchyard/metadata/InOnlyService.java new file mode 100644 index 000000000..835e35911 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/InOnlyService.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +/** + * Implementation of ServiceInterface with a single ExchangePattern.IN_ONLY + * operation. + */ +public class InOnlyService extends BaseService { + + /** + * Creates a new InOnlyService with a ServiceInterface.DEFAULT_OPERATION + * operation. + */ + public InOnlyService() { + this(DEFAULT_OPERATION); + } + + /** + * Creates a new InOnlyService with the specified operation name. + * @param operationName name of the operation + */ + public InOnlyService(String operationName) { + super(new InOnlyOperation(operationName)); + } + + /** + * Creates a new InOnlyService with the specified operation metadata. + * @param operation operation metadata + */ + public InOnlyService(InOnlyOperation operation) { + super(operation); + } +} diff --git a/core/api/src/main/java/org/switchyard/metadata/InOutOperation.java b/core/api/src/main/java/org/switchyard/metadata/InOutOperation.java new file mode 100644 index 000000000..f6aec968a --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/InOutOperation.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +import javax.xml.namespace.QName; + +import org.switchyard.ExchangePattern; + +/** + * Default implementation of ServiceOperation for ExchangePattern.IN_OUT + * operations. + */ +public class InOutOperation extends BaseServiceOperation { + + protected InOutOperation() { + super(ExchangePattern.IN_OUT); + } + + /** + * Create a new instance of an InOut operation with a default message name. + * @param operationName the name of the operation + */ + public InOutOperation(String operationName) { + super(ExchangePattern.IN_OUT, operationName, null, null, null); + } + + /** + * Create a new instance of an InOut operation with the specified message name. + * @param operationName the name of the operation + * @param inputType input message name + * @param outputType output message name + */ + public InOutOperation(String operationName, QName inputType, QName outputType) { + super(ExchangePattern.IN_OUT, operationName, inputType, outputType, null); + } + + /** + * Create a new instance of an InOut operation with the specified message name. + * @param operationName the name of the operation + * @param inputType input message name + * @param outputType output message name + * @param faultType fault message name + */ + public InOutOperation(String operationName, QName inputType, QName outputType, QName faultType) { + super(ExchangePattern.IN_OUT, operationName, inputType, outputType, faultType); + } +} diff --git a/core/api/src/main/java/org/switchyard/metadata/InOutService.java b/core/api/src/main/java/org/switchyard/metadata/InOutService.java new file mode 100644 index 000000000..b6868986b --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/InOutService.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +/** + * Implementation of ServiceInterface with a single ExchangePattern.IN_OUT + * operation. + */ +public class InOutService extends BaseService { + + /** + * Creates a new InOutService with a ServiceInterface.DEFAULT_OPERATION + * operation. + */ + public InOutService() { + this(DEFAULT_OPERATION); + } + + /** + * Creates a new InOutService with the specified operation name. + * @param operationName name of the operation + */ + public InOutService(String operationName) { + super(new InOutOperation(operationName)); + } + + /** + * Creates a new InOutService with the specified operation metadata. + * @param operation operation metadata + */ + public InOutService(InOutOperation operation) { + super(operation); + } +} diff --git a/core/api/src/main/java/org/switchyard/metadata/JavaTypes.java b/core/api/src/main/java/org/switchyard/metadata/JavaTypes.java new file mode 100644 index 000000000..70a84dc3c --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/JavaTypes.java @@ -0,0 +1,57 @@ +package org.switchyard.metadata; + +import javax.xml.namespace.QName; + +import org.switchyard.annotations.DefaultType; + +/** + * Provides utility methods for converting a Java class to it's corresponding + * data type name in SwitchYard. + */ +public final class JavaTypes { + + /** + * Type prefix. + */ + private static final String TYPE_PREFIX = "java:"; + + private JavaTypes() { + + } + + /** + * Equivalent to toMessageType(javaType, null). + *
+ * Checks for a {@link org.switchyard.annotations.DefaultType} on the type. If not found, + * the type name is derived from the Java Class name. + * + * @param javaType The Java type. + * @return The payload type. + */ + public static QName toMessageType(Class javaType) { + return QName.valueOf(toMessageTypeString(javaType)); + } + + /** + * Convert the supplied java type to a payload type name. + *

+ * Checks for a {@link org.switchyard.annotations.DefaultType} on the type. If not found, + * the type name is derived from the Java Class name. + * + * @param javaType The Java type. + * @return The payload type. + */ + public static String toMessageTypeString(Class javaType) { + DefaultType defaultType = javaType.getAnnotation(DefaultType.class); + + if (defaultType != null) { + return defaultType.value(); + } else { + if (javaType.isMemberClass()) { + return TYPE_PREFIX + javaType.getName(); + } else { + return TYPE_PREFIX + javaType.getCanonicalName(); + } + } + } +} diff --git a/core/api/src/main/java/org/switchyard/metadata/Registrant.java b/core/api/src/main/java/org/switchyard/metadata/Registrant.java new file mode 100644 index 000000000..c0a1754f7 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/Registrant.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +/** + * Represents a component which registers a service and/or reference within a + * service domain. + */ +public interface Registrant { + + /** + * Indicates whether the registrant is a binding or implementation. + * @return true if binding, false otherwise + */ + boolean isBinding(); + + /** + * Indicates whether the registrant is a binding or implementation. + * @return true if implementation, false otherwise + */ + boolean isImplementation(); + + /** + * Returns a config representation based on the type of registrant. + * @param Implementations will return ComponentImplementationModel, while + * bindings will return List. + * @return type-specific configuration model + */ + T getConfig(); +} diff --git a/core/api/src/main/java/org/switchyard/metadata/ServiceInterface.java b/core/api/src/main/java/org/switchyard/metadata/ServiceInterface.java new file mode 100644 index 000000000..1fee780ec --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/ServiceInterface.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +import java.util.Set; + +/** + * The canonical representation of a service interface in SwitchYard. Every + * service in SwitchYard is registered with exactly one ServiceInterface, + * providing information on the type, operations, and input/output messages + * for the service. The SwitchYard runtime provides concrete implementations + * of ServiceInterface for Java and WSDL interface types. There is also + * a default type of ServiceInterface.DEFAULT_TYPE which is used + * to represent services which do not publish a formal contract. + */ +public interface ServiceInterface { + + /** + * Default interface type used when a concrete interface (Java, WSDL) is + * not provided by the service. + */ + String DEFAULT_TYPE = "esb"; + /** + * Empty string is the default operation name for service interface. + */ + String DEFAULT_OPERATION = ""; + + /** + * The type of the interface - e.g. java, wsdl, esb, etc. + * @return the interface type + */ + String getType(); + + /** + * The set of operations available on this service. + * @return A Set containing operations available on this service. If the + * interface contains no operations, the returned Set will be empty and not + * null. + */ + Set getOperations(); + + /** + * Returns operation details for the specified name from the service interface. + * @param name operation name + * @return operation details or null if the named operation is not present + * on this interface + */ + ServiceOperation getOperation(String name); +} diff --git a/core/api/src/main/java/org/switchyard/metadata/ServiceMetadataBuilder.java b/core/api/src/main/java/org/switchyard/metadata/ServiceMetadataBuilder.java new file mode 100644 index 000000000..685223c22 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/ServiceMetadataBuilder.java @@ -0,0 +1,172 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +import java.util.Collections; +import java.util.List; + +import org.switchyard.APIMessages; +import org.switchyard.ServiceMetadata; +import org.switchyard.ServiceSecurity; +import org.switchyard.metadata.qos.Throttling; +import org.switchyard.policy.Policy; + +/** + * Fluent builder for ServiceMetadata instances. This class can be used + * to create new ServiceMetadata objects or update existing instances of + * ServiceMetadata associated with a service or service reference. + */ +public final class ServiceMetadataBuilder { + + private ServiceMetadataImpl _metadata; + + private ServiceMetadataBuilder() { + _metadata = new ServiceMetadataImpl(); + } + + private ServiceMetadataBuilder(ServiceMetadataImpl metadata) { + _metadata = metadata; + } + + /** + * Specifies service security for service metadata. + * @param security service security + * @return this builder + */ + public ServiceMetadataBuilder security(ServiceSecurity security) { + _metadata._security = security; + return this; + } + + /** + * Specifies required policies for service metadata. + * @param requiredPolicies required policies + * @return this builder + */ + public ServiceMetadataBuilder requiredPolicies(List requiredPolicies) { + _metadata._requiredPolicies = requiredPolicies; + return this; + } + + /** + * Specifies provided policies for service metadata. + * @param providedPolicies provided policies + * @return this builder + */ + public ServiceMetadataBuilder providedPolicies(List providedPolicies) { + _metadata._providedPolicies = providedPolicies; + return this; + } + + /** + * Specifies the registrant of a service or service reference associated with this metadata. + * @param registrant the registrant of a service or reference + * @return this builder + */ + public ServiceMetadataBuilder registrant(Registrant registrant) { + _metadata._registrant = registrant; + return this; + } + + /** + * Specifies throttling for service references. NOTE : this setting is ignored + * for services at present. + * @param throttling throttling setting + * @return this builder + */ + public ServiceMetadataBuilder throttling(Throttling throttling) { + _metadata._throttling = throttling; + return this; + } + + /** + * Returns a configured ServiceMetadata instance. + * @return ServiceMetadata + */ + public ServiceMetadata build() { + return _metadata; + } + + /** + * Creates a new ServiceMetadata instance. This method is called first when building + * a new ServiceMetadata instance. + * @return a reference to this builder to configure the ServiceMetadata + */ + public static ServiceMetadataBuilder create() { + return new ServiceMetadataBuilder(); + } + + /** + * Used to update an existing instance of ServiceMetadata by chaining additional + * calls after the call to update(). + * @param metadata the ServiceMetadata to update + * @return a reference to this builder to configure the ServiceMetadata + */ + public static ServiceMetadataBuilder update(ServiceMetadata metadata) { + if (!ServiceMetadataImpl.class.isInstance(metadata)) { + throw APIMessages.MESSAGES.unableUpdateMetadataType(metadata.getClass().toString()); + } + return new ServiceMetadataBuilder((ServiceMetadataImpl)metadata); + } + + /** + * A copy operation which is compatible with the fluent builder API in case changes + * are necessary. + * @param metadata the ServiceMetadata to copy + * @return a reference to this builder to configure the ServiceMetadata + */ + public static ServiceMetadataBuilder createFrom(ServiceMetadata metadata) { + return create() + .security(metadata.getSecurity()) + .registrant(metadata.getRegistrant()) + .requiredPolicies(metadata.getRequiredPolicies()) + .providedPolicies(metadata.getProvidedPolicies()); + } + + private class ServiceMetadataImpl implements ServiceMetadata { + + private ServiceSecurity _security; + private List _requiredPolicies = Collections.emptyList(); + private List _providedPolicies = Collections.emptyList(); + private Registrant _registrant; + private Throttling _throttling; + + @Override + public ServiceSecurity getSecurity() { + return _security; + } + + @Override + public List getRequiredPolicies() { + return _requiredPolicies; + } + + @Override + public List getProvidedPolicies() { + return _providedPolicies; + } + + @Override + public Registrant getRegistrant() { + return _registrant; + } + + @Override + public Throttling getThrottling() { + return _throttling; + } + + } +} diff --git a/core/api/src/main/java/org/switchyard/metadata/ServiceOperation.java b/core/api/src/main/java/org/switchyard/metadata/ServiceOperation.java new file mode 100644 index 000000000..1541f1faf --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/ServiceOperation.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +import javax.xml.namespace.QName; + +import org.switchyard.ExchangePattern; + +/** + * Representation of an operation on a ServiceInterface. + *

+ * Each operation has: + *

    + *
  • an exchange pattern (IN_OUT, IN_ONLY) + *
  • a name + *
  • an input message referenced type + *
  • an (optional) output message type + *
  • an (optional) fault message type + *
+ *
+ * The mapping of operation and message names is defined by the concrete + * implementation of ServiceInterface. For example, the expected mapping of + * a Java interface would be Java method name to ServiceInterface operation name. + */ +public interface ServiceOperation { + + /** + * The exchange pattern for the operation. + * @return exchange pattern + */ + ExchangePattern getExchangePattern(); + /** + * The name of the operation. + * @return operation name + */ + String getName(); + + /** + * The name of the input message type. + * @return input message type or null if no type information is available. + * @see org.switchyard.annotations.OperationTypes + */ + QName getInputType(); + + /** + * The name of the output message type. + * @return output message name or null if no type information is available. + * @see org.switchyard.annotations.OperationTypes + */ + QName getOutputType(); + + /** + * The name of the output message type. + * @return output message name or null if no type information is available. + * @see org.switchyard.annotations.OperationTypes + */ + QName getFaultType(); +} diff --git a/core/api/src/main/java/org/switchyard/metadata/qos/Throttling.java b/core/api/src/main/java/org/switchyard/metadata/qos/Throttling.java new file mode 100644 index 000000000..e9cf82f19 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/metadata/qos/Throttling.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata.qos; + +/** + * Represents configuration for throttling of service references. + */ +public class Throttling { + + /** + * Message header used to specify the max requests used by the throttler in a given + * time period. + */ + public static final String MAX_REQUESTS = "org.switchyard.qos.throttling.maxRequests"; + + /** + * Default time period is one second. + */ + public static final long DEFAULT_TIME_PERIOD = 1000; + + + private int _maxRequests; + private long _timePeriod = DEFAULT_TIME_PERIOD; + + /** + * Returns the maximum number of requests allowed in a given time period. + * @return max requests + */ + public int getMaxRequests() { + return _maxRequests; + } + + /** + * Returns the time period in milliseconds used to calculate the max request window. + * @return time period in milliseconds + */ + public long getTimePeriod() { + return _timePeriod; + } + + /** + * Specifies the maximum number of requests allowed in a given time period. + * @param max maximum number of requests + * @return a reference to this Throttling instance + */ + public Throttling setMaxRequests(int max) { + _maxRequests = max; + return this; + } + + /** + * Specifies the time period in milliseconds used to calculate the max request window. + * @param timeMS time period in milliseconds + * @return a reference to this Throttling instance + */ + public Throttling setTimePeriod(long timeMS) { + _timePeriod = timeMS; + return this; + } +} diff --git a/core/api/src/main/java/org/switchyard/policy/Policy.java b/core/api/src/main/java/org/switchyard/policy/Policy.java new file mode 100644 index 000000000..83c8763f3 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/policy/Policy.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.policy; + +import javax.xml.namespace.QName; + +/** + * Base contract for all policy types. Every policy has a string literal + * representation which is used to identify the policy in application + * configuration (e.g. "suspendsTransaction"). + * + * @author Keith Babo © 2011 Red Hat Inc. + */ +public interface Policy { + + /** policy type. */ + public enum PolicyType {INTERACTION, IMPLEMENTATION}; + + /** + * Returns the qualified identifier for the policy. + * @return policy qualified name + */ + public QName getQName(); + + /** + * Returns the string identifier for the policy. + * @return policy name + * @deprecated use {@link #getQName()} instead + */ + @Deprecated + public String getName(); + + /** + * Returns whether the policy type passed in parameter is supported by this policy. + * @param type policy type + * @return policy type + */ + public boolean supports(PolicyType type); + + /** + * Returns whether the policy passed in parameter is compatible with this or not. + * @param target policy to check compatibility + * @return true if compatible + */ + public boolean isCompatibleWith(Policy target); + + /** + * Returns a policy which is a dependency of this Policy. + * @return a policy dependency + */ + public Policy getPolicyDependency(); +} diff --git a/core/api/src/main/java/org/switchyard/policy/PolicyFactory.java b/core/api/src/main/java/org/switchyard/policy/PolicyFactory.java new file mode 100644 index 000000000..c7d7d4f66 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/policy/PolicyFactory.java @@ -0,0 +1,134 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.policy; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; + +import org.switchyard.policy.Policy.PolicyType; + +/** + * A factory class for the policies. + */ +public final class PolicyFactory { + + private PolicyFactory() {} + + private static Set _policies; + + static { + _policies = new HashSet(); + _policies.addAll(Arrays.asList(TransactionPolicy.values())); + _policies.addAll(Arrays.asList(SecurityPolicy.values())); + } + + /** + * Returns policy object from name. + * @param name policy name to get + * @return Policy object + * @throws Exception failed to create Policy object + * @deprecated use {@link #getPolicy(QName)} instead + */ + @Deprecated + public static Policy getPolicy(String name) throws Exception { + return getPolicy(new QName(name)); + } + + /** + * Returns policy object from qualified name. + * @param qname policy qualified name to get + * @return Policy object + * @throws Exception failed to create Policy object + */ + public static Policy getPolicy(final QName qname) throws Exception { + for (Policy p : _policies) { + // 1. look for an exact match first + if (p.getQName().equals(qname)) { + return p; + } + // 2. look for a localName match second for backwards compatibility + // NOTE: similar logic found in: + // - core/api: org.switchyard.policy.PolicyUtil.containsPolicy(Set, Policy):boolean + // - core/config: org.switchyard.config.model.composite.v1.PolicyConfig.hasRequirement(Model, QName):boolean + // NOTE: NULL_NS_URI works because of no default namespace assumption from parent element made in: + // - core/config: org.switchyard.config.BaseConfiguration.createAttributeQName(String value):QName + if (XMLConstants.NULL_NS_URI.equals(qname.getNamespaceURI()) && qname.getLocalPart().equals(p.getQName().getLocalPart())) { + return p; + } + } + + // return Generic Policy instance for the non-built-in policy + return new Policy() { + public QName getQName() { + return qname; + } + public String getName() { + return getQName().getLocalPart(); + } + public String toString() { + return getQName().toString(); + } + public boolean supports(PolicyType type) { + return true; + } + public boolean isCompatibleWith(Policy target) { + return true; + } + public Policy getPolicyDependency() { + return null; + } + }; + } + + /** + * Returns a set of all available policies. + * @return policies + */ + public static Set getAllAvailablePolicies() { + return Collections.unmodifiableSet(_policies); + } + + /** + * Returns a set of available interaction policies. + * @return policies + */ + public static Set getAvailableInteractionPolicies() { + Set interactions = new HashSet(); + for (Policy p : _policies) { + if (p.supports(PolicyType.INTERACTION)) { + interactions.add(p); + } + } + return Collections.unmodifiableSet(interactions); + } + + /** + * Returns a set of available implementation policies. + * @return policies + */ + public static Set getAvailableImplementationPolicies() { + Set implementations = new HashSet(); + for (Policy p : _policies) { + if (p.supports(PolicyType.IMPLEMENTATION)) { + implementations.add(p); + } + } + return Collections.unmodifiableSet(implementations); + } +} diff --git a/core/api/src/main/java/org/switchyard/policy/PolicyUtil.java b/core/api/src/main/java/org/switchyard/policy/PolicyUtil.java new file mode 100644 index 000000000..04d1f8b93 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/policy/PolicyUtil.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.policy; + +import java.util.HashSet; +import java.util.Set; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.label.BehaviorLabel; + +/** + * Used to set policy details on a message exchange. Provided policy represents + * an assertion that a given policy is satisfied. Required policy represents a + * requirement that a specific policy must be provided. The set of required and + * provided policies is carried as an exchange-scoped context property. + */ +public final class PolicyUtil { + + /** + * Exchange property name where provided policies are kept. + */ + public final static String PROVIDED_PROPERTY = "org.switchyard.policy.provided"; + + /** + * Exchange property name where required policies are kept. + */ + public final static String REQUIRED_PROPERTY = "org.switchyard.policy.required"; + + private PolicyUtil() {} + + /** + * Indicate that a given policy is satisfied for the exchange. + * @param exchange assert policy on this exchange + * @param policy the policy to assert + */ + public static void provide(Exchange exchange, Policy policy) { + Set provided = getPolicies(exchange, PROVIDED_PROPERTY); + provided.add(policy); + exchange.getContext().setProperty(PROVIDED_PROPERTY, provided, Scope.EXCHANGE).addLabels(BehaviorLabel.TRANSIENT.label()); + } + + /** + * Returns the set of policies provided for this exchange. + * @param exchange check policy on this exchange + * @return set of policies provided; empty set if no policies are provided + */ + public static Set getProvided(Exchange exchange) { + return getPolicies(exchange, PROVIDED_PROPERTY); + } + + /** + * Indicates whether a given policy is provided on the exchange. + * @param exchange check policy on this exchange + * @param policy the policy to check + * @return true if the policy is provided, false otherwise + */ + public static boolean isProvided(Exchange exchange, Policy policy) { + return containsPolicy(getProvided(exchange), policy); + } + + /** + * Indicate that a given policy is required for the exchange. + * @param exchange require policy on this exchange + * @param policy the policy to require + */ + public static void require(Exchange exchange, Policy policy) { + Set required = getPolicies(exchange, REQUIRED_PROPERTY); + required.add(policy); + exchange.getContext().setProperty(REQUIRED_PROPERTY, required, Scope.EXCHANGE).addLabels(BehaviorLabel.TRANSIENT.label()); + } + + /** + * Returns the set of policies required for this exchange. + * @param exchange check policy on this exchange + * @return set of policies required; empty set if no policies are required + */ + public static Set getRequired(Exchange exchange) { + return getPolicies(exchange, REQUIRED_PROPERTY); + } + + /** + * Indicates whether a given policy is required on the exchange. + * @param exchange check policy on this exchange + * @param policy the policy to check + * @return true if the policy is required, false otherwise + */ + public static boolean isRequired(Exchange exchange, Policy policy) { + return containsPolicy(getRequired(exchange), policy); + } + + @SuppressWarnings("unchecked") + private static Set getPolicies(Exchange exchange, String propertyName) { + Property intentsProperty = exchange.getContext().getProperty(propertyName, Scope.EXCHANGE); + Set intents = new HashSet(); + if (intentsProperty != null) { + intents.addAll((Set)intentsProperty.getValue()); + } + return intents; + } + + // Compares policies by qualified name vs. object identity/hashCode + private static boolean containsPolicy(Set list, Policy target) { + QName qname = target.getQName(); + for (Policy p : list) { + // 1. look for an exact match first + if (p.getQName().equals(qname)) { + return true; + } + // 2. look for a localName match second for backwards compatibility + // NOTE: similar logic found in: + // - core/api: org.switchyard.policy.PolicyFactory.getPolicy(QName):Policy + // - core/config: org.switchyard.config.model.composite.v1.PolicyConfig.hasRequirement(Model, QName):boolean + // NOTE: NULL_NS_URI works because of no default namespace assumption from parent element made in: + // - core/config: org.switchyard.config.BaseConfiguration.createAttributeQName(String value):QName + if (XMLConstants.NULL_NS_URI.equals(qname.getNamespaceURI()) && qname.getLocalPart().equals(p.getQName().getLocalPart())) { + return true; + } + } + return false; + } +} diff --git a/core/api/src/main/java/org/switchyard/policy/SecurityPolicy.java b/core/api/src/main/java/org/switchyard/policy/SecurityPolicy.java new file mode 100644 index 000000000..88dde310f --- /dev/null +++ b/core/api/src/main/java/org/switchyard/policy/SecurityPolicy.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.policy; + +import javax.xml.namespace.QName; + +/** + * Supported types for Security Policy. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum SecurityPolicy implements Policy { + + /** + * Ensure that the client is authorized to use the service. + */ + AUTHORIZATION("authorization") { + @Override + public boolean supports(PolicyType type) { + // "The SCA Security specification defines the authorization intent to specify implementation policy." + // NOTE: We also still support interaction policy for backwards-compatibility with SwitchYard 1.0. + return type == PolicyType.IMPLEMENTATION || type == PolicyType.INTERACTION; + } + }, + + /** + * Ensure that the client is authenticated by the server. + */ + CLIENT_AUTHENTICATION("clientAuthentication") { + @Override + public boolean supports(PolicyType type) { + // "The SCA security specification defines the following intents to specify interaction policy: ..., clientAuthentication, ..." + return type == PolicyType.INTERACTION; + } + }, + + /** + * Ensure that only authorized entities can view the contents of a message. + */ + CONFIDENTIALITY("confidentiality") { + @Override + public boolean supports(PolicyType type) { + // "The SCA security specification defines the following intents to specify interaction policy: ..., confidentiality, ..." + return type == PolicyType.INTERACTION; + } + }; + + private final QName _qname; + + private SecurityPolicy(String name) { + _qname = new QName("http://docs.oasis-open.org/ns/opencsa/sca/200912", name, "sca"); + } + + /** + * {@inheritDoc} + */ + @Override + public QName getQName() { + return _qname; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return getQName().getLocalPart(); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return getQName().toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isCompatibleWith(Policy target) { + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public Policy getPolicyDependency() { + return null; + } + +} diff --git a/core/api/src/main/java/org/switchyard/policy/TransactionPolicy.java b/core/api/src/main/java/org/switchyard/policy/TransactionPolicy.java new file mode 100644 index 000000000..a50c19628 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/policy/TransactionPolicy.java @@ -0,0 +1,159 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.policy; + +import javax.xml.namespace.QName; + +/** + * Supported types for Transaction Policy. + * + * @author Keith Babo © 2011 Red Hat Inc. + */ +public enum TransactionPolicy implements Policy { + + /** Transaction implementation policies */ + /** + * Uses any existing global transaction propagated from the client + * or else begins and complete a new global transaction. + */ + MANAGED_TRANSACTION_GLOBAL("managedTransaction.Global") { + @Override + public boolean supports(PolicyType type) { + return type == PolicyType.IMPLEMENTATION; + } + @Override + public boolean isCompatibleWith(Policy target) { + if (target == MANAGED_TRANSACTION_LOCAL + || target == NO_MANAGED_TRANSACTION) { + return false; + } + return true; + } + }, + + /** + * SwitchYard runtime begins and complete a Local Transaction Containment for each Exchange. + */ + MANAGED_TRANSACTION_LOCAL("managedTransaction.Local") { + @Override + public boolean supports(PolicyType type) { + return type == PolicyType.IMPLEMENTATION; + } + @Override + public boolean isCompatibleWith(Policy target) { + if (target == MANAGED_TRANSACTION_GLOBAL + || target == NO_MANAGED_TRANSACTION + || target == PROPAGATES_TRANSACTION) { + return false; + } + return true; + } + @Override + public Policy getPolicyDependency() { + return SUSPENDS_TRANSACTION; + } + }, + + /** + * SwitchYard runtime doesn't start any transaction. Application has a responsibility + * to manage the transaction boundaries. + */ + NO_MANAGED_TRANSACTION("noManagedTransaction") { + @Override + public boolean supports(PolicyType type) { + return type == PolicyType.IMPLEMENTATION; + } + @Override + public boolean isCompatibleWith(Policy target) { + if (target == MANAGED_TRANSACTION_GLOBAL + || target == MANAGED_TRANSACTION_LOCAL + || target == PROPAGATES_TRANSACTION) { + return false; + } + return true; + } + }, + + /** Transaction interaction policies */ + /** + * Any existing transaction should continue and be used during the invocation. + */ + PROPAGATES_TRANSACTION("propagatesTransaction") { + @Override + public boolean supports(PolicyType type) { + return type == PolicyType.INTERACTION; + } + @Override + public boolean isCompatibleWith(Policy target) { + if (target == MANAGED_TRANSACTION_LOCAL + || target == NO_MANAGED_TRANSACTION + || target == SUSPENDS_TRANSACTION) { + return false; + } + return true; + } + }, + + /** + * Any existing transaction should be suspended before the invocation takes place. + */ + SUSPENDS_TRANSACTION("suspendsTransaction") { + @Override + public boolean supports(PolicyType type) { + return type == PolicyType.INTERACTION; + } + @Override + public boolean isCompatibleWith(Policy target) { + if (target == PROPAGATES_TRANSACTION) { + return false; + } + return true; + } + }; + + private final QName _qname; + + private TransactionPolicy(String name) { + _qname = new QName("http://docs.oasis-open.org/ns/opencsa/sca/200912", name, "sca"); + } + + /** + * {@inheritDoc} + */ + @Override + public QName getQName() { + return _qname; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return getQName().getLocalPart(); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return getQName().toString(); + } + + @Override + public Policy getPolicyDependency() { + return null; + } +} diff --git a/core/api/src/main/java/org/switchyard/selector/OperationSelector.java b/core/api/src/main/java/org/switchyard/selector/OperationSelector.java new file mode 100644 index 000000000..f85d9e6cb --- /dev/null +++ b/core/api/src/main/java/org/switchyard/selector/OperationSelector.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.selector; + +import javax.xml.namespace.QName; + +/** + * OperationSelector which determine the operation to be mapped to the binding. + * + * @param the type of source object + */ +public interface OperationSelector { + + /** + * Select a operation. + * + * @param content message content to search for operation + * @return operation QName + * @throws Exception if failed to determine the operation + */ + public QName selectOperation(T content) throws Exception; + + /** + * Sets default namespace. + * @param namespace namespace + * @return this instance for chaining + */ + public OperationSelector setDefaultNamespace(String namespace); + + /** + * Gets default namespace. + * @return namespace + */ + public String getDefaultNamespace(); + +} diff --git a/core/api/src/main/java/org/switchyard/transform/BaseTransformer.java b/core/api/src/main/java/org/switchyard/transform/BaseTransformer.java new file mode 100644 index 000000000..60b184569 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/transform/BaseTransformer.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import java.lang.reflect.ParameterizedType; + +import javax.xml.namespace.QName; + +import org.switchyard.metadata.JavaTypes; + + +/** + * Base transformer implementation. + * + * @param From Type + * @param To Type. + */ +public abstract class BaseTransformer implements Transformer { + + private enum Types { F, T }; + private QName _from; + private QName _to; + + /** + * Constructor. + */ + public BaseTransformer() { + _to = JavaTypes.toMessageType(getType(Types.T)); + _from = JavaTypes.toMessageType(getType(Types.F)); + } + + /** + * Constructor. + * @param from from + * @param to to + */ + public BaseTransformer(QName from, QName to) { + _from = from; + _to = to; + } + + @Override + public Transformer setFrom(QName fromType) { + _from = fromType; + return this; + } + + @Override + public QName getFrom() { + return _from; + } + + @Override + public Transformer setTo(QName toType) { + _to = toType; + return this; + } + + @Override + public QName getTo() { + return _to; + } + + @SuppressWarnings("unchecked") + @Override + public Class getFromType() { + return (Class) getType(Types.F); + } + + @SuppressWarnings("unchecked") + @Override + public Class getToType() { + return (Class) getType(Types.T); + } + + @Override + public abstract T transform(F from); + + /** + * Get the type QName for the specified Java type. + *

+ * + * @param type The Java type. + * @return The QName type. + */ + protected static QName toMessageType(Class type) { + return JavaTypes.toMessageType(type); + } + + private Class getType(Types type) { + try { + ParameterizedType pt = + (ParameterizedType) getClass().getGenericSuperclass(); + + return (Class) pt.getActualTypeArguments()[type.ordinal()]; + } catch (Exception e) { + // Generics not specified... + return Object.class; + } + } +} diff --git a/core/api/src/main/java/org/switchyard/transform/TransformResolver.java b/core/api/src/main/java/org/switchyard/transform/TransformResolver.java new file mode 100644 index 000000000..affeb1800 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/transform/TransformResolver.java @@ -0,0 +1,17 @@ +package org.switchyard.transform; + +import javax.xml.namespace.QName; + +/** + * Transform resolver operations for the Transformer Registry. + */ +public interface TransformResolver { + + /** + * Resolve a transform sequence wiring transformers. + * @param from from + * @param to to + * @return transformer + */ + TransformSequence resolveSequence(QName from, QName to); +} diff --git a/core/api/src/main/java/org/switchyard/transform/TransformSequence.java b/core/api/src/main/java/org/switchyard/transform/TransformSequence.java new file mode 100644 index 000000000..fcd90dc8f --- /dev/null +++ b/core/api/src/main/java/org/switchyard/transform/TransformSequence.java @@ -0,0 +1,224 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.APILogger; +import org.switchyard.APIMessages; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.label.BehaviorLabel; + +/** + * Transformation sequence/pipeline. + *

+ * Allows the stringing together of a sequence of transformers and then associating that + * with a Message context e.g. + *

+ * TransformSequence.from("a").to("b").to("c').associateWith(messageContext);
+ * 
+ * + * @author tom.fennelly@gmail.com + */ +public final class TransformSequence implements Serializable { + + /** + * Serial UID + */ + static final long serialVersionUID = -1; + /** + * Logger. + */ + private static final Logger LOGGER = Logger.getLogger(TransformSequence.class); + + /** + * Transform Sequence. + */ + private List _sequence = new ArrayList(); + + /** + * Create an unassociated sequence. + */ + private TransformSequence() { + } + + /** + * Associate this instance with the supplied message context. + * @param message associate the transform to this message + */ + public void associateWith(Message message) { + message.getContext().setProperty(TransformSequence.class.getName(), this) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } + + /** + * Start the transformation sequence. + * + * @param typeName The from type. + * @return The sequence. + */ + public static TransformSequence from(final QName typeName) { + TransformSequence newSequence = new TransformSequence(); + newSequence.add(typeName); + return newSequence; + } + + /** + * Add to the transformation sequence. + * + * @param typeName The from type. + * @return The sequence. + */ + public TransformSequence to(final QName typeName) { + add(typeName); + return this; + } + + /** + * Apply this {@link TransformSequence} to the supplied {@link Message} instance. + * @param message Message instance. + * @param registry Transformation Registry. + */ + public void apply(Message message, TransformerRegistry registry) { + + while (_sequence.size() > 1) { + QName from = _sequence.get(0); + QName to = _sequence.get(1); + Transformer transformer = registry.getTransformer(from, to); + + if (transformer == null) { + break; + } + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Transforming Message (" + System.identityHashCode(message) + ") from '" + transformer.getFrom() + "' to '" + + transformer.getTo() + "' using transformer type '" + transformer.getClass().getName() + "'."); + } + + Object result; + if (Message.class.isAssignableFrom(transformer.getFromType())) { + // A returned object just indicates that the transformation took place. + result = transformer.transform(message); + } else { + // A returned object indicates that the transformation took place and is + // used as the new Message payload. + result = transformer.transform(message.getContent(transformer.getFromType())); + message.setContent(result); + } + + // We can now remove the 1st element in the sequence. 2nd element will become the + // "from" for the next transformation in the sequence, if one is required... + _sequence.remove(0); + + if (result == null) { + APILogger.ROOT_LOGGER.nullTransformResult(transformer.getClass().getName(), from, to); + } + } + } + + /** + * Get the current message type for the specified exchange. + * + * @param exchange The exchange. + * @return The current exchange message type, or null if + * no TransformSequence is set on the exchange. + */ + public static QName getCurrentMessageType(final Exchange exchange) { + TransformSequence transformSequence = get(exchange); + + if (transformSequence != null && !transformSequence._sequence.isEmpty()) { + return transformSequence._sequence.get(0); + } + + return null; + } + + /** + * Get the target message type for the specified exchange phase. + * + * @param exchange The exchange. + * @return The target exchange message type, or null if + * no TransformSequence is set on the exchange. + */ + public static QName getTargetMessageType(final Exchange exchange) { + TransformSequence transformSequence = get(exchange); + + if (transformSequence != null && !transformSequence._sequence.isEmpty()) { + // Return the last entry in the sequence... + return transformSequence._sequence.get(transformSequence._sequence.size() - 1); + } + + return null; + } + + /** + * Utility assertion method for checking if the source to destination transformations + * have been applied to the Exchange. + * + * @param exchange The exchange instance. + * @return True if the transformations have been applied (or are not specified), otherwise false. + */ + public static boolean assertTransformsApplied(final Exchange exchange) { + QName fromName = getCurrentMessageType(exchange); + QName toName = getTargetMessageType(exchange); + + if (fromName != null && toName != null && !fromName.equals(toName)) { + return false; + } + + return true; + } + + /** + * Apply the active exchange transformation sequence to the supplied + * Exchange Message. + * + * @param exchange The Exchange instance. + * @param registry The transformation registry. + */ + public static void applySequence(final Exchange exchange, final TransformerRegistry registry) { + Message message = exchange.getMessage(); + TransformSequence transformSequence = get(exchange); + + if (transformSequence == null) { + return; + } + + transformSequence.apply(message, registry); + } + + private void add(final QName typeName) { + if (typeName == null) { + throw APIMessages.MESSAGES.nullTypeNamePassed(); + } + _sequence.add(typeName); + } + + private static TransformSequence get(final Exchange exchange) { + Property sequenceProperty = exchange.getContext().getProperty(TransformSequence.class.getName()); + if (sequenceProperty != null) { + return (TransformSequence)sequenceProperty.getValue(); + } else { + return null; + } + } +} diff --git a/core/api/src/main/java/org/switchyard/transform/Transformer.java b/core/api/src/main/java/org/switchyard/transform/Transformer.java new file mode 100644 index 000000000..528ec7e89 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/transform/Transformer.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import javax.xml.namespace.QName; + +/** + * Handles transformation between message content types (e.g. Object -> XML) to + * reconcile the type systems used by a service consumer and provider. A + * Transformer instance can be directly attached to an exchange or it can be + * registered in the TransformerRegistry and loaded dynamically based on the + * from and to message names. + * + * @param Java type representing the from, or source, format + * @param Java type representing the to, or target, format + */ +public interface Transformer { + + /** + * Transforms the source format F to the target format + * T. + * @param from the object to be transformed + * @return object in target format + */ + T transform(F from); + + /** + * Set the name of the from, or source, message type. + * @param fromType From type. + * @return a reference to the current Transformer. + */ + Transformer setFrom(QName fromType); + + /** + * The name of the from, or source, message. + * @return from message + */ + QName getFrom(); + + /** + * Set the name of the to, or target, message type. + * @param toType To type. + * @return a reference to the current Transformer. + */ + Transformer setTo(QName toType); + + /** + * The name of the to, or target, message. + * @return to message + */ + QName getTo(); + + /** + * The Java type of the source format. + * @return class representing the Java type for the from format. + */ + Class getFromType(); + + /** + * The Java type of the target format. + * @return class representing the Java type for the from format. + */ + Class getToType(); +} diff --git a/core/api/src/main/java/org/switchyard/transform/TransformerRegistry.java b/core/api/src/main/java/org/switchyard/transform/TransformerRegistry.java new file mode 100644 index 000000000..ef61b85a1 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/transform/TransformerRegistry.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import java.util.List; +import javax.xml.namespace.QName; + +/** + * Registry for transformers. + */ +public interface TransformerRegistry { + + /** + * Add a transformer. + * @param transformer transformer + * @return {@code this} TransformRegistry instance. + */ + TransformerRegistry addTransformer(Transformer transformer); + + /** + * Add a transformer. + * @param transformer transformer + * @param from from + * @param to to + * @return {@code this} TransformRegistry instance. + */ + TransformerRegistry addTransformer(Transformer transformer, QName from, QName to); + + /** + * Remove a transformer. + * @param transformer transformer + * @return status of removal + */ + boolean removeTransformer(Transformer transformer); + + /** + * Does the registry have a transformer for the specified types. + * @param from from + * @param to to + * @return True if it has a transformer, otherwise false. + */ + boolean hasTransformer(QName from, QName to); + + /** + * Get a transformer. + * @param from from + * @param to to + * @return transformer + */ + Transformer getTransformer(QName from, QName to); + + /** + * Get a list of currently registered Transformers. + * @return ArrayList> list of currently registered transformers. + */ + List> getRegisteredTransformers(); + + /** + * Returns a list of transformers that transform from the specified type. + * @param type the type transformed from + * @return list of transformers + */ + public List> getTransformersFrom(QName type); + + /** + * Returns a list of transformers that transform to the specified type. + * @param type the type transformed to + * @return list of transformers + */ + public List> getTransformersTo(QName type); + + /** + * Get a transform sequence wiring transformers. + * @param from from + * @param to to + * @return transformer + */ + TransformSequence getTransformSequence(QName from, QName to); + + /** + * Set an instance of a TransformResolver. + * @param resolver resolver + * @return + */ + void setTransfomResolver(TransformResolver resolver); + +} diff --git a/core/api/src/main/java/org/switchyard/validate/BaseValidator.java b/core/api/src/main/java/org/switchyard/validate/BaseValidator.java new file mode 100644 index 000000000..9394c2266 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/validate/BaseValidator.java @@ -0,0 +1,126 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +import java.lang.reflect.ParameterizedType; + +import javax.xml.namespace.QName; + +import org.switchyard.metadata.JavaTypes; + +/** + * Base validator implementation. + * + * @param Type + */ +public abstract class BaseValidator implements Validator { + + private QName _name; + + /** + * Constructor. + */ + public BaseValidator() { + _name = JavaTypes.toMessageType(getType()); + } + + /** + * Constructor. + * @param name name + */ + public BaseValidator(QName name) { + _name = name; + } + + @Override + public Validator setName(QName name) { + _name = name; + return this; + } + + @Override + public QName getName() { + return _name; + } + + @SuppressWarnings("unchecked") + @Override + public Class getType() { + try { + ParameterizedType pt = + (ParameterizedType) getClass().getGenericSuperclass(); + + return (Class) pt.getActualTypeArguments()[0]; + } catch (Exception e) { + // Generics not specified... + return (Class) Object.class; + } + } + + /** + * Create validation result which indicates valid result. + * @return valid result + */ + public static ValidationResult validResult() { + return new DefaultValidationResult(true, null); + } + + /** + * Create validation result which indicates invalid result. + * @param error error message + * @return invalid result + */ + public static ValidationResult invalidResult(String error) { + return new DefaultValidationResult(false, error); + } + + /** + * Create validation result which indicates invalid result. + * @return invalid result + */ + public static ValidationResult invalidResult() { + return invalidResult(null); + } + + /** + * Get the type QName for the specified Java type. + *

+ * + * @param type The Java type. + * @return The QName type. + */ + protected static QName toMessageType(Class type) { + return JavaTypes.toMessageType(type); + } + + protected static class DefaultValidationResult implements ValidationResult { + private boolean _valid; + private String _detail; + + public DefaultValidationResult(boolean valid, String detail) { + _valid = valid; + _detail = detail; + } + + public boolean isValid() { + return _valid; + } + + public String getDetail() { + return _detail; + } + } + +} diff --git a/core/api/src/main/java/org/switchyard/validate/ValidationResult.java b/core/api/src/main/java/org/switchyard/validate/ValidationResult.java new file mode 100644 index 000000000..162a191c0 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/validate/ValidationResult.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +/** + * Represents message validation result which contains error details if it failed. + */ +public interface ValidationResult { + + /** + * Return whether the validation succeeded or not. + * @return true if it succeeded + */ + boolean isValid(); + + /** + * Return error details if it failed. + * @return error message + */ + String getDetail(); +} diff --git a/core/api/src/main/java/org/switchyard/validate/Validator.java b/core/api/src/main/java/org/switchyard/validate/Validator.java new file mode 100644 index 000000000..dff18ada7 --- /dev/null +++ b/core/api/src/main/java/org/switchyard/validate/Validator.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +import javax.xml.namespace.QName; + +/** + * Handles validation for message content to ensure type and structure is + * suitable for consumer. A Validator instance can be directly attached to + * an exchange or it can be registered in the ValidatorRegistry and loaded + * dynamically based on the message name. + * + * @param Java type representing the content to be validated + */ +public interface Validator { + + /** + * Validates the content. + * T. + * @param content the content to be validated + * @return true if the content is valid, otherwise false + */ + ValidationResult validate(T content); + + /** + * Set the name of the subject for validation. + * @param name name of the subject for validation. + * @return a reference to the current Validator. + */ + Validator setName(QName name); + + /** + * Return the name of the subject for validation. + * @return from message + */ + QName getName(); + + /** + * Return the Java type of the content to be validated. + * @return class representing the Java type for the content to be validated + */ + Class getType(); +} diff --git a/core/api/src/main/java/org/switchyard/validate/ValidatorRegistry.java b/core/api/src/main/java/org/switchyard/validate/ValidatorRegistry.java new file mode 100644 index 000000000..c88bb5d9e --- /dev/null +++ b/core/api/src/main/java/org/switchyard/validate/ValidatorRegistry.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +import javax.xml.namespace.QName; + +/** + * Registry for validators. + */ +public interface ValidatorRegistry { + + /** + * Add a validator. + * @param validator validator + * @return {@code this} ValidatorRegistry instance. + */ + ValidatorRegistry addValidator(Validator validator); + + /** + * Add a validator. + * @param validator validator + * @param name name + * @return {@code this} ValidatorRegistry instance. + */ + ValidatorRegistry addValidator(Validator validator, QName name); + + /** + * Remove a validator. + * @param validator validatort + * @return status of removal + */ + boolean removeValidator(Validator validator); + + /** + * Does the registry have a validator for the specified types. + * @param name name + * @return True if it has a validator, otherwise false. + */ + boolean hasValidator(QName name); + + /** + * Get a validator. + * @param name name + * @return validator + */ + Validator getValidator(QName name); +} diff --git a/core/api/src/test/java/org/switchyard/MockContext.java b/core/api/src/test/java/org/switchyard/MockContext.java new file mode 100644 index 000000000..a4e969ce2 --- /dev/null +++ b/core/api/src/test/java/org/switchyard/MockContext.java @@ -0,0 +1,180 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * MockContext. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class MockContext implements Context { + + private final Map _exchangeProperties = Collections.synchronizedMap(new HashMap()); + private final Map _messageProperties = Collections.synchronizedMap(new HashMap()); + + public MockContext() {} + + private Map getPropertiesMap(Scope scope) { + switch (scope) { + case MESSAGE: + return _messageProperties; + case EXCHANGE: + default: + return _exchangeProperties; + } + } + + /** + * {@inheritDoc} + */ + @Override + public Property getProperty(String name) { + return getProperty(name, Scope.EXCHANGE); + } + + /** + * {@inheritDoc} + */ + @Override + public Property getProperty(String name, Scope scope) { + return getPropertiesMap(scope).get(name); + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public T getPropertyValue(String name) { + Property property = getProperty(name); + return property != null ? (T) property.getValue() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public Set getProperties() { + return getProperties(Scope.EXCHANGE); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getProperties(Scope scope) { + Set properties = new HashSet(); + for (Property property : getPropertiesMap(scope).values()) { + properties.add(property); + } + return properties; + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperty(Property property) { + getPropertiesMap(Scope.EXCHANGE).remove(property.getName()); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperties() { + removeProperties(Scope.EXCHANGE); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeProperties(Scope scope) { + getPropertiesMap(scope).clear(); + } + + /** + * {@inheritDoc} + */ + @Override + public Property setProperty(String name, Object val) { + return setProperty(name, val, Scope.EXCHANGE); + } + + /** + * {@inheritDoc} + */ + @Override + public Property setProperty(String name, Object val, Scope scope) { + Map properties = getPropertiesMap(scope); + if (val != null) { + Property p = new MockProperty(name, val, scope); + properties.put(name, p); + return p; + } else { + properties.remove(name); + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + public Context setProperties(Set properties) { + for (Property property : properties) { + setProperty(property.getName(), property.getValue(), property.getScope()); + } + return this; + } + + @Override + public void mergeInto(Context context) { + // brute force with no bells since this is only a mock object + for (Property property : _exchangeProperties.values()) { + context.setProperty(property.getName(), property.getValue(), Scope.EXCHANGE); + } + for (Property property : _messageProperties.values()) { + context.setProperty(property.getName(), property.getValue(), Scope.MESSAGE); + } + } + + @Override + public Set getProperties(String label) { + Set props = new HashSet(); + for (Property p : getProperties()) { + if (p.hasLabel(label)) { + props.add(p); + } + } + return props; + } + + @Override + public void removeProperties(String label) { + for (Property p : getProperties()) { + if (p.hasLabel(label)) { + removeProperty(p); + } + } + } + +} diff --git a/core/api/src/test/java/org/switchyard/MockExchange.java b/core/api/src/test/java/org/switchyard/MockExchange.java new file mode 100644 index 000000000..f440a85aa --- /dev/null +++ b/core/api/src/test/java/org/switchyard/MockExchange.java @@ -0,0 +1,146 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import org.switchyard.metadata.ExchangeContract; +import org.switchyard.metadata.ServiceOperation; + +/** + * Dumb implementation of Exchange meant for unit testing. + */ +public class MockExchange implements Exchange { + + private ExchangeState _state; + private ExchangePhase _phase; + private ExchangeContract _contract; + private Message _message; + private Context _context; + private ServiceReference _consumer; + private Service _provider; + + public MockExchange() { + } + + @Override + public Message createMessage() { + return _message; + } + + @Override + public Context getContext() { + return _context; + } + + @Override + public Context getContext(Message message) { + return message.getContext(); + } + + @Override + public ExchangeContract getContract() { + return _contract; + } + + @Override + public Message getMessage() { + return _message; + } + + @Override + public ExchangePhase getPhase() { + return _phase; + } + + @Override + public ExchangeState getState() { + return _state; + } + + @Override + public void send(Message message) { + // NOP + } + + @Override + public void sendFault(Message message) { + // NOP + } + + public MockExchange setPhase(ExchangePhase phase) { + _phase = phase; + return this; + } + + public MockExchange setState(ExchangeState state) { + _state = state; + return this; + } + + public MockExchange setMessage(Message message) { + _message = message; + return this; + } + + public MockExchange setContext(Context context) { + _context = context; + return this; + } + + public MockExchange setContract(ExchangeContract contract) { + _contract = contract; + return this; + } + + @Override + public ServiceReference getConsumer() { + return _consumer; + } + + @Override + public Service getProvider() { + return _provider; + } + + @Override + public MockExchange consumer(ServiceReference consumer, ServiceOperation operations) { + _consumer = consumer; + return this; + } + + @Override + public MockExchange provider(Service provider, ServiceOperation operations) { + _provider = provider; + return this; + } + + @Override + public ExchangeHandler getReplyHandler() { + return null; + } + + @Override + public ExchangePattern getPattern() { + ExchangePattern pattern = null; + if (getContract() != null) { + pattern = getContract().getConsumerOperation().getExchangePattern(); + } + return pattern; + } + + @Override + public ExchangeSecurity getSecurity() { + return null; + } +} diff --git a/core/api/src/test/java/org/switchyard/MockProperty.java b/core/api/src/test/java/org/switchyard/MockProperty.java new file mode 100644 index 000000000..3961cc131 --- /dev/null +++ b/core/api/src/test/java/org/switchyard/MockProperty.java @@ -0,0 +1,130 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard; + +import java.util.Collections; +import java.util.Set; +import java.util.TreeSet; + + +/** + * MockProperty. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class MockProperty implements Property { + + private final String _name; + private final Object _value; + private final Scope _scope; + private Set _labels = Collections.synchronizedSet(new TreeSet()); + + public MockProperty(String name, Object value, Scope scope) { + _name = name; + _value = value; + _scope = scope; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public Object getValue() { + return _value; + } + + /** + * {@inheritDoc} + */ + @Override + public Scope getScope() { + return _scope; + } + + /** + * {@inheritDoc} + */ + @Override + public Set getLabels() { + return Collections.unmodifiableSet(_labels); + } + + /** + * {@inheritDoc} + */ + @Override + public Property addLabels(String... labels) { + for (String label : labels) { + label = normalizeLabel(label); + if (label != null) { + _labels.add(label); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Property addLabels(Set labels) { + for (String label : labels) { + label = normalizeLabel(label); + if (label != null) { + _labels.add(label); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Property removeLabels(String... labels) { + for (String label : labels) { + label = normalizeLabel(label); + if (label != null) { + _labels.remove(label); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasLabel(String label) { + label = normalizeLabel(label); + return label != null && _labels.contains(label); + } + + private String normalizeLabel(String label) { + if (label != null) { + label.trim(); + label = label.toLowerCase(); + } + return label; + } + +} diff --git a/core/api/src/test/java/org/switchyard/metadata/ServiceMetadataBuilderTest.java b/core/api/src/test/java/org/switchyard/metadata/ServiceMetadataBuilderTest.java new file mode 100644 index 000000000..b7aa03265 --- /dev/null +++ b/core/api/src/test/java/org/switchyard/metadata/ServiceMetadataBuilderTest.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.metadata; + +import java.util.LinkedList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.ServiceMetadata; +import org.switchyard.metadata.qos.Throttling; +import org.switchyard.policy.Policy; +import org.switchyard.policy.TransactionPolicy; + +public class ServiceMetadataBuilderTest { + + @Test + public void buildMetadata() { + // build metadata pieces + Registrant registrant = new MockRegistrant(); + List required = new LinkedList(); + required.add(TransactionPolicy.SUSPENDS_TRANSACTION); + List provided = new LinkedList(); + provided.add(TransactionPolicy.PROPAGATES_TRANSACTION); + Throttling throttling = new Throttling(); + + // add them to service metadata + ServiceMetadata metadata = ServiceMetadataBuilder.create() + .providedPolicies(provided) + .requiredPolicies(required) + .registrant(registrant) + .throttling(throttling) + .build(); + + // verify + Assert.assertEquals(registrant, metadata.getRegistrant()); + Assert.assertEquals(throttling, metadata.getThrottling()); + Assert.assertEquals(required.get(0), metadata.getRequiredPolicies().get(0)); + Assert.assertEquals(provided.get(0), metadata.getProvidedPolicies().get(0)); + } + + @Test + public void testUpdate() { + Throttling throttling1 = new Throttling().setMaxRequests(50); + ServiceMetadata metadata = ServiceMetadataBuilder.create() + .throttling(throttling1) + .build(); + + Assert.assertEquals(50, metadata.getThrottling().getMaxRequests()); + + Throttling throttling2 = new Throttling().setMaxRequests(150); + ServiceMetadataBuilder.update(metadata).throttling(throttling2); + Assert.assertEquals(150, metadata.getThrottling().getMaxRequests()); + } +} + + +class MockRegistrant implements Registrant { + + @Override + public boolean isBinding() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isImplementation() { + // TODO Auto-generated method stub + return false; + } + + @Override + public T getConfig() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/core/api/src/test/java/org/switchyard/policy/PolicyFactoryTest.java b/core/api/src/test/java/org/switchyard/policy/PolicyFactoryTest.java new file mode 100644 index 000000000..a5d1c5dd0 --- /dev/null +++ b/core/api/src/test/java/org/switchyard/policy/PolicyFactoryTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.policy; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.policy.Policy.PolicyType; + +public class PolicyFactoryTest { + + @Test + @SuppressWarnings("deprecation") + public void testFactory() throws Exception { + // TransactionPolicy + Policy p = PolicyFactory.getPolicy("managedTransaction.Global"); + Assert.assertEquals(TransactionPolicy.MANAGED_TRANSACTION_GLOBAL, p); + Assert.assertTrue(p.supports(PolicyType.IMPLEMENTATION)); + p = PolicyFactory.getPolicy("managedTransaction.Local"); + Assert.assertEquals(TransactionPolicy.MANAGED_TRANSACTION_LOCAL, p); + Assert.assertTrue(p.supports(PolicyType.IMPLEMENTATION)); + p = PolicyFactory.getPolicy("noManagedTransaction"); + Assert.assertEquals(TransactionPolicy.NO_MANAGED_TRANSACTION, p); + Assert.assertTrue(p.supports(PolicyType.IMPLEMENTATION)); + p = PolicyFactory.getPolicy("propagatesTransaction"); + Assert.assertEquals(TransactionPolicy.PROPAGATES_TRANSACTION, p); + Assert.assertTrue(p.supports(PolicyType.INTERACTION)); + p = PolicyFactory.getPolicy("suspendsTransaction"); + Assert.assertEquals(TransactionPolicy.SUSPENDS_TRANSACTION, p); + Assert.assertTrue(p.supports(PolicyType.INTERACTION)); + // SecurityPolicy + p = PolicyFactory.getPolicy("authorization"); + Assert.assertEquals(SecurityPolicy.AUTHORIZATION, p); + Assert.assertTrue(p.supports(PolicyType.IMPLEMENTATION)); + Assert.assertTrue(p.supports(PolicyType.INTERACTION)); + p = PolicyFactory.getPolicy("clientAuthentication"); + Assert.assertEquals(SecurityPolicy.CLIENT_AUTHENTICATION, p); + Assert.assertTrue(p.supports(PolicyType.INTERACTION)); + p = PolicyFactory.getPolicy("confidentiality"); + Assert.assertEquals(SecurityPolicy.CONFIDENTIALITY, p); + Assert.assertTrue(p.supports(PolicyType.INTERACTION)); + // Generic Policy + p = PolicyFactory.getPolicy("myGenericPolicy"); + Assert.assertEquals("myGenericPolicy", p.getName()); + Assert.assertTrue(p.supports(PolicyType.IMPLEMENTATION)); + Assert.assertTrue(p.supports(PolicyType.INTERACTION)); + } + +} diff --git a/core/api/src/test/java/org/switchyard/policy/PolicyUtilTest.java b/core/api/src/test/java/org/switchyard/policy/PolicyUtilTest.java new file mode 100644 index 000000000..20e62cd89 --- /dev/null +++ b/core/api/src/test/java/org/switchyard/policy/PolicyUtilTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.policy; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.Exchange; +import org.switchyard.MockContext; +import org.switchyard.MockExchange; + +public class PolicyUtilTest { + + @Test + public void testProvidePolicy() { + Exchange ex = new MockExchange().setContext(new MockContext()); + PolicyUtil.provide(ex, DummyPolicy.A); + Assert.assertTrue(PolicyUtil.isProvided(ex, DummyPolicy.A)); + Assert.assertFalse(PolicyUtil.isProvided(ex, DummyPolicy.B)); + Assert.assertFalse(PolicyUtil.isRequired(ex, DummyPolicy.B)); + Assert.assertEquals(1, PolicyUtil.getProvided(ex).size()); + } + + @Test + public void testRequirePolicy() { + Exchange ex = new MockExchange().setContext(new MockContext()); + PolicyUtil.require(ex, DummyPolicy.A); + Assert.assertTrue(PolicyUtil.isRequired(ex, DummyPolicy.A)); + Assert.assertFalse(PolicyUtil.isRequired(ex, DummyPolicy.B)); + Assert.assertFalse(PolicyUtil.isProvided(ex, DummyPolicy.A)); + Assert.assertEquals(1, PolicyUtil.getRequired(ex).size()); + } +} + +enum DummyPolicy implements Policy { + + A("A"), B("B"); + + private final QName _qname; + + private DummyPolicy(String name) { + _qname = new QName(name); + } + + @Override + public QName getQName() { + return _qname; + } + + @Override + public String getName() { + return getQName().getLocalPart(); + } + + @Override + public String toString() { + return getQName().toString(); + } + + @Override + public boolean supports(PolicyType type) { + return type == PolicyType.INTERACTION; + } + + @Override + public boolean isCompatibleWith(Policy target) { + return true; + } + + @Override + public Policy getPolicyDependency() { + return null; + } +} diff --git a/core/api/src/test/java/org/switchyard/transform/BaseTransformerTest.java b/core/api/src/test/java/org/switchyard/transform/BaseTransformerTest.java new file mode 100644 index 000000000..7fb0b165b --- /dev/null +++ b/core/api/src/test/java/org/switchyard/transform/BaseTransformerTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; + +public class BaseTransformerTest { + + @Test + public void testTypedTransformer() throws Exception { + Transformer t = new StringToIntegerTransformer(); + Assert.assertEquals(String.class, t.getFromType()); + Assert.assertEquals(Integer.class, t.getToType()); + } + + @Test + public void testUntypedTransformer() throws Exception { + Transformer t = new UntypedTransformer(); + Assert.assertEquals(Object.class, t.getFromType()); + Assert.assertEquals(Object.class, t.getToType()); + } + + @Test + public void testImplementsTransformer() throws Exception { + Transformer t = new ImplementsTransfomer(); + Assert.assertEquals(String.class, t.getFromType()); + Assert.assertEquals(Boolean.class, t.getToType()); + } +} + +class StringToIntegerTransformer extends BaseTransformer { + public Integer transform(String num) { + return 5; + } +} + +class UntypedTransformer extends BaseTransformer { + public Object transform(Object obj) { + return null; + } +} + +class ImplementsTransfomer implements Transformer { + + @Override + public QName getFrom() { + return null; + } + + @Override + public Class getFromType() { + return String.class; + } + + @Override + public QName getTo() { + return null; + } + + @Override + public Class getToType() { + return Boolean.class; + } + + @Override + public Transformer setFrom(QName fromType) { + return null; + } + + @Override + public Transformer setTo(QName toType) { + return null; + } + + @Override + public Object transform(Object from) { + return null; + } + +} diff --git a/core/api/src/test/java/org/switchyard/validate/BaseValidatorTest.java b/core/api/src/test/java/org/switchyard/validate/BaseValidatorTest.java new file mode 100644 index 000000000..fb4a0fd53 --- /dev/null +++ b/core/api/src/test/java/org/switchyard/validate/BaseValidatorTest.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; + +public class BaseValidatorTest { + + @Test + public void testTypedValidator() throws Exception { + Validator t = new StringValidator(); + Assert.assertEquals(String.class, t.getType()); + } + + @Test + public void testUntypedValidator() throws Exception { + Validator t = new UntypedValidator(); + Assert.assertEquals(Object.class, t.getType()); + } + + @Test + public void testImplementsValidator() throws Exception { + Validator t = new ImplementsValidator(); + Assert.assertEquals(String.class, t.getType()); + } +} + +class StringValidator extends BaseValidator { + public ValidationResult validate(String num) { + return new ValidationResult() { + public boolean isValid() { + return false; + } + public String getDetail() { + return "error"; + } + }; + } +} + +class UntypedValidator extends BaseValidator { + public ValidationResult validate(Object obj) { + return new ValidationResult() { + public boolean isValid() { + return false; + } + public String getDetail() { + return "error"; + } + }; + } +} + +class ImplementsValidator implements Validator { + + @Override + public QName getName() { + return null; + } + + @Override + public Class getType() { + return String.class; + } + + @Override + public Validator setName(QName name) { + return null; + } + + @Override + public ValidationResult validate(Object name) { + return new ValidationResult() { + public boolean isValid() { + return false; + } + public String getDetail() { + return "error"; + } + }; + } + +} + diff --git a/core/build/pom.xml b/core/build/pom.xml new file mode 100644 index 000000000..4de6bccdc --- /dev/null +++ b/core/build/pom.xml @@ -0,0 +1,61 @@ + + + + 4.0.0 + + UTF-8 + + org.switchyard + switchyard-build + SwitchYard: Build + 2.1.0-SNAPSHOT + The SwitchYard Build Module + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + jira + http://jira.jboss.org/browse/SWITCHYARD + + + + SwitchYard committers + + + + + GNU Lesser General Public License + http://www.gnu.org/copyleft/lesser.html + repo + + + + http://github.com/switchyard/core + + + + jboss-releases-repository + JBoss Releases Repository + https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/ + + + jboss-snapshots-repository + JBoss Snapshots Repository + https://repository.jboss.org/nexus/content/repositories/snapshots/ + + + diff --git a/core/build/src/main/resources/checkstyle/checkstyle.xml b/core/build/src/main/resources/checkstyle/checkstyle.xml new file mode 100644 index 000000000..9c25c4b81 --- /dev/null +++ b/core/build/src/main/resources/checkstyle/checkstyle.xml @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/build/src/main/resources/checkstyle/suppressions.xml b/core/build/src/main/resources/checkstyle/suppressions.xml new file mode 100644 index 000000000..417395f6e --- /dev/null +++ b/core/build/src/main/resources/checkstyle/suppressions.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/core/build/src/main/resources/findbugs/findbugs-exclude.xml b/core/build/src/main/resources/findbugs/findbugs-exclude.xml new file mode 100644 index 000000000..6ef10581a --- /dev/null +++ b/core/build/src/main/resources/findbugs/findbugs-exclude.xml @@ -0,0 +1,185 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/build/src/site/site.xml b/core/build/src/site/site.xml new file mode 100644 index 000000000..dfe033aa5 --- /dev/null +++ b/core/build/src/site/site.xml @@ -0,0 +1,11 @@ + + + + + org.apache.maven.skins + maven-default-skin + 1.0 + + + + diff --git a/core/bus/camel/pom.xml b/core/bus/camel/pom.xml new file mode 100644 index 000000000..68ab5ef84 --- /dev/null +++ b/core/bus/camel/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-bus-camel + bundle + SwitchYard: Camel Exchange Bus + Bus provider using Camel Core + http://switchyard.org + + + org.switchyard.bus.camel.* + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-runtime + test-jar + test + + + org.switchyard + switchyard-security + + + + org.apache.camel + camel-core + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + test + + + diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/BusLogger.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/BusLogger.java new file mode 100644 index 000000000..dccc37d94 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/BusLogger.java @@ -0,0 +1,70 @@ +package org.switchyard.bus.camel; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.INFO; + +import org.jboss.logging.Logger; + +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 11000-11199 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface BusLogger { + /** + * Basic root logger. + */ + BusLogger ROOT_LOGGER = Logger.getMessageLogger(BusLogger.class, BusLogger.class.getPackage().getName()); + + /** + * exceptionDuringFaultResponse method definition. + * @param t t + */ + @LogMessage(level = ERROR) + @Message(id = 11000, value="Unexpected exception thrown during handling FAULT response. " + + "This exception can not be handled, thus it's marked as handled and only logged. " + + "If you don't want see messages like this consider handling " + + "exceptions in your handler logic") + void exceptionDuringFaultResponse(@Cause Throwable t); + + /** + * listenerFailedHandleException method definition. + * @param key key + * @param klass klass + */ + @LogMessage(level = ERROR) + @Message(id = 11001, value="Error listener %s failed to handle exception %s") + void listenerFailedHandleException(String key, Class klass); + + /** + * removeRoute method definition. + * @param endpoint endpoint + */ + @LogMessage(level = INFO) + @Message(id = 11002, value="Removing route %s") + void removeRoute(String endpoint); + + /** + * alreadyInFaultState method definition. + * @param error error + */ + @LogMessage(level = ERROR) + @Message(id = 11003, value="Interceptor threw an exception while exchange is already in fault state %s") + void alreadyInFaultState(Exception error); + + /** + * failedToHandlException method definition. + * @param listenerKey listenerKey + * @param exceptionClass exceptionClass + */ + @LogMessage(level = ERROR) + @Message(id = 11004, value="Error listener %s failed to handle exception %s") + void failedToHandlException(String listenerKey, Class exceptionClass); + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/BusMessages.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/BusMessages.java new file mode 100644 index 000000000..0ce042b7d --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/BusMessages.java @@ -0,0 +1,144 @@ +package org.switchyard.bus.camel; + +import java.util.Set; +import javax.xml.namespace.QName; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 10800-10999 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface BusMessages { + /** + * Default messages. + */ + BusMessages MESSAGES = Messages.getBundle(BusMessages.class); + + /** + * maxOneExceptionHandler method definition. + * @param set set + * @return SwitchYardException + */ + @Message(id = 10800, value = "Only one exception handler can be defined. Found %s") + SwitchYardException maxOneExceptionHandler(Set set); + + /** + * failedToStartBus method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id = 10801, value = "Failed to start Camel Exchange Bus") + SwitchYardException failedToStartBus(@Cause Exception e); + + /** + * failedToStopBus method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id = 10802, value = "Failed to stop Camel Exchange Bus") + SwitchYardException failedToStopBus(@Cause Exception e); + + /** + * failedToCreateRoute method definition. + * @param name name + * @param e e + * @return SwitchYardException + */ + @Message(id = 10803, value = "Failed to create Camel route for service %s") + SwitchYardException failedToCreateRoute(QName name, @Cause Exception e); + + /** + * methodMustBeOverridden method definition. + * @return AbstractMethodError + */ + @Message(id = 10807, value = "Method must be overriden") + AbstractMethodError methodMustBeOverridden(); + + /** + * cannontChangeProviderMetadata method definition. + * @return IllegalStateException + */ + @Message(id = 10808, value = "Cannot change provider metadata after provider has been invoked!") + IllegalStateException cannotChangeProviderMetadata(); + + /** + * cannotSendMessageTwice method definition. + * @return IllegalStateException + */ + @Message(id = 10809, value = "Can not send same message twice. Use Message.copy() instead") + IllegalStateException cannotSendMessageTwice(); + + /** + * cannotSendMesageTwice method definition. + * @return IllegalStateException + */ + @Message(id = 10810, value = "CamelExchange accepts only CamelMessages") + IllegalStateException camelExchangeOnlyCamelMessages(); + + /** + * nullTypeArgument method definition. + * @return IllegalStateException + */ + @Message(id = 10811, value = "null 'type' argument.") + IllegalStateException nullTypeArgument(); + + /** + * cannotConvertNoTransformRegistry method definition. + * @param className className + * @param typeName typeName + * @return SwitchYardException + */ + @Message(id = 10812, value = "Cannot convert from '%s' to '%s'. No TransformRegistry available.") + SwitchYardException cannotConvertNoTransformRegistry(String className, String typeName); + + + /** + * transformerMustBeRegistered method definition. + * @param className className + * @param typeName typeName + * @param fromType fromType + * @param toType toType + * @return SwitchYardException + */ + @Message(id = 10813, value = "Cannot convert from '%s' to '%s'. No registered Transformer available for transforming from '%s' to '%s'. A Transformer must be registered.") + SwitchYardException transformerMustBeRegistered(String className, String typeName, String fromType, String toType); + + + /** + * transformerReturnedNull method definition. + * @param className className + * @param typeName typeName + * @param transformerName transformerName + * @return SwitchYardException + */ + @Message(id = 10814, value = "Error converting from '%s' to '%s'. Transformer '%s' returned null.") + SwitchYardException transformerReturnedNull(String className, String typeName, String transformerName); + + /** + * transformerReturnedIncompatibleType method definition. + * @param className className + * @param typeName typeName + * @param transformerName transformerName + * @param transformedContentName transformedContentName + * @return SwitchYardException + */ + @Message(id = 10815, value = "Error converting from '%s' to '%s'. Transformer '%s' returned incompatible type '%s'.") + SwitchYardException transformerReturnedIncompatibleType(String className, String typeName, String transformerName, String transformedContentName); + + /** + * transformerReturnedIncompatibleType method definition. + * @return IllegalArgumentException + */ + @Message(id = 10816, value = "Camel Bus accepts only CamelExchanges") + IllegalArgumentException onlyCamelExchanges(); + + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelCompositeContext.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelCompositeContext.java new file mode 100644 index 000000000..b16de787a --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelCompositeContext.java @@ -0,0 +1,213 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.common.camel.ContextPropertyUtil; +import org.switchyard.label.BehaviorLabel; + +/** + * Implementation of {@link Context} specific to Camel Exchange Bus. + */ +public class CamelCompositeContext implements Context { + + private final Exchange _exchange; + private final Message _message; + + /** + * Creates new Context with {@link Scope#EXCHANGE} as default scope. + * + * In addition the current IN message of exchange will be used to map {@link Scope#MESSAGE} scope. + * + * @param exchange Exchange to use. + */ + public CamelCompositeContext(Exchange exchange) { + this(exchange, exchange.getIn()); + } + + /** + * Creates new Context with given as default scope. + * + * {@link Scope#MESSAGE} scope will be mapped to passed message instance. + * + * @param exchange Exchange to use. + * @param message Message to use. + */ + public CamelCompositeContext(Exchange exchange, Message message) { + this._exchange = exchange; + this._message = message; + } + + @Override + public void mergeInto(Context context) { + for (Property property : getProperties()) { + if (ContextPropertyUtil.isReservedProperty(property.getName(), property.getScope()) + || property.hasLabel(BehaviorLabel.TRANSIENT.label())) { + continue; + } + + context.setProperty(property.getName(), property.getValue(), property.getScope()) + .addLabels(property.getLabels()); + } + } + + @Override + public Property getProperty(String name) { + Property property = getProperty(name, Scope.MESSAGE); + return property == null ? getProperty(name, Scope.EXCHANGE) : property; + } + + @Override + public Property getProperty(String name, Scope scope) { + switch (scope) { + case EXCHANGE: + return getExchangeProperty(name); + default: + return getMessageProperty(name); + } + } + + private Property getMessageProperty(String name) { + if (_message.hasHeaders() && _message.getHeaders().containsKey(name)) { + return new CamelMessageProperty(_message, name); + } + return null; + } + + private Property getExchangeProperty(String name) { + if (_exchange.hasProperties() && _exchange.getProperties().containsKey(name)) { + return new CamelExchangeProperty(_exchange, name); + } + return null; + } + + @Override + @SuppressWarnings("unchecked") + public T getPropertyValue(String name) { + Property property = getProperty(name); + return property == null ? null : (T) property.getValue(); + } + + @Override + public Set getProperties() { + Set properties = new HashSet(); + properties.addAll(getProperties(Scope.EXCHANGE)); + properties.addAll(getProperties(Scope.MESSAGE)); + return properties; + } + + @Override + public Set getProperties(Scope scope) { + Set properties = new HashSet(); + switch (scope) { + case EXCHANGE: + if (_exchange.hasProperties()) { + for (String prop : _exchange.getProperties().keySet()) { + properties.add(new CamelExchangeProperty(_exchange, prop)); + } + } + break; + default: + if (_message.hasHeaders()) { + for (String prop : _message.getHeaders().keySet()) { + properties.add(new CamelMessageProperty(_message, prop)); + } + } + break; + } + return properties; + } + + @Override + public Set getProperties(String label) { + Set properties = new HashSet(); + for (Property property : getProperties()) { + if (property.hasLabel(label)) { + properties.add(property); + } + } + return properties; + } + + @Override + public void removeProperty(Property property) { + switch (property.getScope()) { + case EXCHANGE: + _exchange.removeProperty(property.getName()); + break; + default: + _message.removeHeader(property.getName()); + break; + } + } + + @Override + public void removeProperties() { + for (Property property : getProperties()) { + removeProperty(property); + } + } + + @Override + public void removeProperties(Scope scope) { + for (Property property : getProperties(scope)) { + removeProperty(property); + } + } + + @Override + public void removeProperties(String label) { + for (Property property : getProperties()) { + if (property.hasLabel(label)) { + removeProperty(property); + } + } + } + + @Override + public Property setProperty(String name, Object val) { + return setProperty(name, val, Scope.MESSAGE); + } + + @Override + public Property setProperty(String name, Object val, Scope scope) { + switch (scope) { + case EXCHANGE: + _exchange.setProperty(name, val); + break; + default: + _message.setHeader(name, val); + break; + } + return getProperty(name, scope); + } + + @Override + public Context setProperties(Set properties) { + for (Property property : properties) { + Set labels = property.getLabels(); + setProperty(property.getName(), property.getValue(), property.getScope()) + .addLabels(labels.toArray(new String[labels.size()])); + } + return this; + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchange.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchange.java new file mode 100644 index 000000000..fe8ef741b --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchange.java @@ -0,0 +1,305 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import javax.xml.namespace.QName; + +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangePhase; +import org.switchyard.ExchangeSecurity; +import org.switchyard.ExchangeState; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.BaseExchangeContract; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.runtime.event.ExchangeInitiatedEvent; +import org.switchyard.security.context.DefaultExchangeSecurity; + +/** + * Exchange implementation which wraps Camel {@link org.apache.camel.Exchange} interface. + */ +public class CamelExchange implements Exchange { + + private static final String DISPATCHER = "org.switchyard.bus.camel.dispatcher"; + private static final String CONSUMER = "org.switchyard.bus.camel.consumer"; + private static final String PROVIDER = "org.switchyard.bus.camel.provider"; + private static final String CONTRACT = "org.switchyard.bus.camel.contract"; + private static final String REPLY_HANDLER = "org.switchyard.bus.camel.replyHandler"; + private static final String PHASE = "org.switchyard.bus.camel.phase"; + private static final String FAULT = "org.switchyard.bus.camel.fault"; + + /** + * Property/header name used to store property labels bag. + */ + public static final String LABELS = "org.switchyard.bus.camel.labels"; + + /** + * Header name used to mark message as sent. + */ + public static final String MESSAGE_SENT = "org.switchyard.bus.camel.messageSent"; + + private org.apache.camel.Exchange _exchange; + + private transient ExchangeSecurity _security = null; + + /** + * Creates new CamelExchange. + * + * @param dispatch Exchange dispatcher. + * @param exchange Camel exchange instance. + * @param replyHandler Reply handler. + */ + public CamelExchange(ExchangeDispatcher dispatch, org.apache.camel.Exchange exchange, ExchangeHandler replyHandler) { + _exchange = exchange; + + Map properties = exchange.getProperties(); + if (!properties.containsKey(DISPATCHER)) { + _exchange.setProperty(DISPATCHER, dispatch); + } + if (!properties.containsKey(REPLY_HANDLER)) { + _exchange.setProperty(REPLY_HANDLER, replyHandler); + } + } + + /** + * Creates new CamelExchange. + * + * This is some kind of "copy" constructor which allows to create {@link CamelExchange} + * only from camel Exchange. + * + * @param exchange Exchange instance. + */ + public CamelExchange(org.apache.camel.Exchange exchange) { + this(exchange.getProperty(DISPATCHER, ExchangeDispatcher.class), exchange, exchange.getProperty(REPLY_HANDLER, ExchangeHandler.class)); + } + + @Override + public Context getContext() { + return new CamelCompositeContext(_exchange, getMessage()); + } + + @Override + public Context getContext(Message message) { + if (_exchange.getIn() == message) { + return getContext(); + } + return message.getContext(); + } + + @Override + public ServiceReference getConsumer() { + return _exchange.getProperty(CONSUMER, ServiceReference.class); + } + + @Override + public Service getProvider() { + return _exchange.getProperty(PROVIDER, Service.class); + } + + @Override + public BaseExchangeContract getContract() { + if (_exchange.getProperty(CONTRACT) == null) { + _exchange.setProperty(CONTRACT, new BaseExchangeContract()); + } + return _exchange.getProperty(CONTRACT, BaseExchangeContract.class); + } + + @Override + public Exchange consumer(ServiceReference consumer, ServiceOperation operation) { + _exchange.setProperty(CONSUMER, consumer); + getContract().setConsumerOperation(operation); + return this; + } + + @Override + public Exchange provider(Service provider, ServiceOperation operation) { + if (getPhase() == ExchangePhase.OUT) { + throw BusMessages.MESSAGES.cannotChangeProviderMetadata(); + } + _exchange.setProperty(PROVIDER, provider); + getContract().setProviderOperation(operation); + return this; + } + + @Override + public CamelMessage getMessage() { + return (CamelMessage) _exchange.getIn(); + } + + @Override + public CamelMessage createMessage() { + return new CamelMessage(_exchange); + } + + @Override + public void send(Message message) { + org.apache.camel.Message camelMsg = extract(message); + + if (getPhase() == null) { + _exchange.setProperty(PHASE, ExchangePhase.IN); + _exchange.setIn(camelMsg); + getContext().setProperty(Exchange.MESSAGE_ID, camelMsg.getMessageId()); + initInContentType(); + } else { + _exchange.setProperty(PHASE, ExchangePhase.OUT); + String id = getContext().getPropertyValue(MESSAGE_ID); + _exchange.setIn(camelMsg); + getContext().setProperty(Exchange.RELATES_TO, id); + getContext().setProperty(Exchange.MESSAGE_ID, camelMsg.getMessageId()); + initOutContentType(); + } + + sendInternal(); + } + + private org.apache.camel.Message extract(Message message) { + if (message instanceof CamelMessage) { + CamelMessage msg = (CamelMessage) message; + if (msg.isSent()) { + throw BusMessages.MESSAGES.cannotSendMessageTwice(); + } + msg.sent(); // mark as sent + return msg; + } + throw BusMessages.MESSAGES.camelExchangeOnlyCamelMessages(); + } + + @Override + public void sendFault(Message message) { + org.apache.camel.Message extract = extract(message); + + _exchange.setProperty(PHASE, ExchangePhase.OUT); + String id = getContext().getPropertyValue(MESSAGE_ID); + _exchange.setIn(extract); + _exchange.setProperty(FAULT, true); + getContext().setProperty(Exchange.RELATES_TO, id); + getContext().setProperty(Exchange.MESSAGE_ID, extract.getMessageId()); + + org.switchyard.Property rollbackOnFaultProperty = getContext().getProperty(org.switchyard.Exchange.ROLLBACK_ON_FAULT); + if (rollbackOnFaultProperty == null || rollbackOnFaultProperty.getValue() == null) { + getContext().setProperty(org.switchyard.Exchange.ROLLBACK_ON_FAULT, Boolean.FALSE, Scope.EXCHANGE); + } + + sendInternal(); + } + + private void initInContentType() { + QName exchangeInputType = getContract().getConsumerOperation().getInputType(); + + if (exchangeInputType != null) { + getContext().setProperty(Exchange.CONTENT_TYPE, exchangeInputType) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } + } + + private void initOutContentType() { + QName exchangeOutputType = getContract().getProviderOperation().getOutputType(); + + if (exchangeOutputType != null) { + getContext().setProperty(Exchange.CONTENT_TYPE, exchangeOutputType) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } + } + + private void sendInternal() { + ServiceDomain domain = ((SwitchYardCamelContext) _exchange.getContext()).getServiceDomain(); + ExchangePhase sendPhase = getPhase(); + + // Publish exchange initiation event + if (ExchangePhase.IN.equals(getPhase())) { + getContext().setProperty(ExchangeInitiatedEvent.EXCHANGE_INITIATED_TIME, Long.toString(System.nanoTime()), Scope.EXCHANGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + domain.getEventPublisher().publish(new ExchangeInitiatedEvent(this)); + } + + _exchange.getProperty(DISPATCHER, ExchangeDispatcher.class).dispatch(this); + + if (isDone(sendPhase)) { + // Publish exchange completion event + long duration = System.nanoTime() - _exchange.getProperty(ExchangeInitiatedEvent.EXCHANGE_INITIATED_TIME, 0, Long.class); + getContext().setProperty(ExchangeCompletionEvent.EXCHANGE_DURATION, TimeUnit.NANOSECONDS.toMillis(duration)) + .addLabels(BehaviorLabel.TRANSIENT.label()); + domain.getEventPublisher().publish(new ExchangeCompletionEvent(this)); + } + } + + @Override + public ExchangeState getState() { + return isFault(_exchange) ? ExchangeState.FAULT : ExchangeState.OK; + } + + @Override + public ExchangePhase getPhase() { + return _exchange.getProperty(PHASE, ExchangePhase.class); + } + + /** + * Returns wrapped exchange. + * @return Camel exchange. + */ + public org.apache.camel.Exchange getExchange() { + return _exchange; + } + + @Override + public ExchangeHandler getReplyHandler() { + return _exchange.getProperty(REPLY_HANDLER, ExchangeHandler.class); + } + + private boolean isDone(ExchangePhase phase) { + ExchangePattern mep = getContract().getConsumerOperation().getExchangePattern(); + return (ExchangePhase.IN.equals(phase) && ExchangePattern.IN_ONLY.equals(mep)) + || (ExchangePhase.OUT.equals(phase) && ExchangePattern.IN_OUT.equals(mep)); + } + + /** + * Utility method which checks state of camel exchange used to implement + * switchyard flow. + * + * @param exchange Camel exchange. + * @return True if exchange state is fault. + */ + public static boolean isFault(org.apache.camel.Exchange exchange) { + return exchange.getProperty(FAULT, false, Boolean.class); + } + + @Override + public ExchangePattern getPattern() { + ExchangePattern pattern = null; + if (getContract() != null) { + pattern = getContract().getConsumerOperation().getExchangePattern(); + } + return pattern; + } + + @Override + public ExchangeSecurity getSecurity() { + if (_security == null) { + _security = new DefaultExchangeSecurity(this); + } + return _security; + } +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeBus.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeBus.java new file mode 100644 index 000000000..095ee9626 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeBus.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.bus.camel; + +import java.util.HashMap; + +import javax.xml.namespace.QName; + +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.impl.SimpleRegistry; +import org.apache.camel.model.ModelHelper; +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.bus.camel.processors.Processors; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.spi.Dispatcher; +import org.switchyard.spi.ExchangeBus; + +/** + * Exchange bus implemented on to of Apache Camel mediation engine. SwitchYard + * handlers are wrapped into camel Exchange processors. + */ +public class CamelExchangeBus implements ExchangeBus { + + private Logger _logger = Logger.getLogger(CamelExchangeBus.class); + + private HashMap _dispatchers = + new HashMap(); + + private SwitchYardCamelContext _camelContext; + + /** + * Create a new Camel exchange bus provider. + * @param context the CamelContext instance used by this provider + */ + public CamelExchangeBus(SwitchYardCamelContext context) { + _camelContext = context; + } + + @Override + public void init(ServiceDomain domain) { + if (_logger.isDebugEnabled()) { + _logger.debug("Initialization of CamelExchangeBus for domain " + domain.getName()); + } + + SimpleRegistry registry = _camelContext.getWritebleRegistry(); + for (Processors processor : Processors.values()) { + registry.put(processor.name(), processor.create(domain)); + } + + // CAMEL-7728 introduces an issue on finding BeanManager due to the fact that default + // applicationContextClassLoader in the CamelContext is not a bundle deployment class loader. + // We need to ensure the applicationContextClassLoader is the bundle deployment class loader + // for now. This will be unnecessary once CAMEL-7759 is merged. + _camelContext.setApplicationContextClassLoader(Thread.currentThread().getContextClassLoader()); + } + + /** + * Start the bus provider. + */ + @Override + public synchronized void start() { + try { + _camelContext.start(); + } catch (Exception ex) { + throw BusMessages.MESSAGES.failedToStartBus(ex); + } + } + + /** + * Stop the provider. + */ + @Override + public synchronized void stop() { + try { + _dispatchers.clear(); + _camelContext.stop(); + } catch (Exception ex) { + throw BusMessages.MESSAGES.failedToStopBus(ex); + } + } + + @Override + public Dispatcher getDispatcher(ServiceReference reference) { + return _dispatchers.get(reference.getName()); + } + + @Override + public ExchangeDispatcher createDispatcher(final ServiceReference reference) { + if (_logger.isDebugEnabled()) { + _logger.debug("Creating Camel dispatcher for " + reference.getName()); + } + + String endpoint = "direct:" + reference.getName(); + RouteBuilder rb = new CamelExchangeBusRouteBuilder(endpoint, reference); + + try { + // TODO - remove this logic once the test framework is able + // to hot-replace a service endpoint. + if (_camelContext.getRoute(endpoint) != null) { + _camelContext.removeRoute(endpoint); + if (_logger.isInfoEnabled()) { + BusLogger.ROOT_LOGGER.removeRoute(endpoint); + } + } + + _camelContext.addRoutes(rb); + + if (_logger.isDebugEnabled()) { + _logger.debug("Created route for " + endpoint + ", definition is: " + ModelHelper.dumpModelAsXml(rb.getRouteCollection())); + } + } catch (Exception ex) { + throw BusMessages.MESSAGES.failedToCreateRoute(reference.getName(), ex); + } + + ExchangeDispatcher dispatcher = new ExchangeDispatcher(_camelContext, reference); + _dispatchers.put(reference.getName(), dispatcher); + return dispatcher; + } + +} + diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeBusRouteBuilder.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeBusRouteBuilder.java new file mode 100644 index 000000000..eca209785 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeBusRouteBuilder.java @@ -0,0 +1,197 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import static org.switchyard.bus.camel.processors.Processors.ADDRESSING; +import static org.switchyard.bus.camel.processors.Processors.CONSUMER_CALLBACK; +import static org.switchyard.bus.camel.processors.Processors.CONSUMER_INTERCEPT; +import static org.switchyard.bus.camel.processors.Processors.ERROR_HANDLING; +import static org.switchyard.bus.camel.processors.Processors.GENERIC_POLICY; +import static org.switchyard.bus.camel.processors.Processors.PROVIDER_CALLBACK; +import static org.switchyard.bus.camel.processors.Processors.PROVIDER_INTERCEPT; +import static org.switchyard.bus.camel.processors.Processors.SECURITY_CLEANUP; +import static org.switchyard.bus.camel.processors.Processors.SECURITY_PROCESS; +import static org.switchyard.bus.camel.processors.Processors.TRANSACTION_HANDLER; +import static org.switchyard.bus.camel.processors.Processors.TRANSFORMATION; +import static org.switchyard.bus.camel.processors.Processors.VALIDATION; + +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.camel.Exchange; +import org.apache.camel.Predicate; +import org.apache.camel.builder.ErrorHandlerBuilder; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.model.ExpressionNode; +import org.apache.camel.model.FilterDefinition; +import org.apache.camel.model.RouteDefinition; +import org.apache.camel.model.TryDefinition; +import org.apache.camel.spi.InterceptStrategy; +import org.switchyard.ErrorListener; +import org.switchyard.ExchangePattern; +import org.switchyard.ServiceReference; +import org.switchyard.bus.camel.audit.AuditInterceptStrategy; +import org.switchyard.bus.camel.audit.FaultInterceptStrategy; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.metadata.qos.Throttling; + +/** + * Route builder which creates mediation necessary to handle communication inside SwitchYard. + */ +public class CamelExchangeBusRouteBuilder extends RouteBuilder { + + private static final Predicate IN_OUT_CHECK = new Predicate() { + @Override + public boolean matches(Exchange exchange) { + ServiceOperation operation = new CamelExchange(exchange).getContract().getConsumerOperation(); + return operation.getExchangePattern() == ExchangePattern.IN_OUT; + } + + public String toString() { + return "IN_OUT_CHECK"; + } + }; + + private static final Predicate THROTTLE_CHECK = new Predicate() { + @Override + public boolean matches(Exchange exchange) { + return exchange.getIn().getHeader(Throttling.MAX_REQUESTS) != null; + } + + public String toString() { + return "THROTTLE_CHECK"; + } + }; + + private String _endpoint; + private ServiceReference _reference; + + /** + * Dedicated route builder which dynamically creates SwitchYard mediation + * from given endpoint. + * + * @param reference ServiceReference representing the consumer + * @param endpoint Endpoint address. + */ + public CamelExchangeBusRouteBuilder(String endpoint, ServiceReference reference) { + _endpoint = endpoint; + _reference = reference; + } + + @Override + public SwitchYardCamelContext getContext() { + return (SwitchYardCamelContext) super.getContext(); + } + + @Override + public void configure() throws Exception { + RouteDefinition definition = from(_endpoint); + definition.routeId(_endpoint); + + Map handlers = lookup(ErrorHandlerBuilder.class); + if (handlers.isEmpty()) { + definition.errorHandler(loggingErrorHandler()); + } else if (handlers.size() == 1) { + definition.errorHandler(handlers.values().iterator().next()); + } else { + throw BusMessages.MESSAGES.maxOneExceptionHandler(handlers.keySet()); + } + + // add default intercept strategy using @Audit annotation + definition.addInterceptStrategy(new FaultInterceptStrategy()); + definition.addInterceptStrategy(new AuditInterceptStrategy()); + + for (Entry interceptEntry : lookup(InterceptStrategy.class).entrySet()) { + if (log.isDebugEnabled()) { + log.debug("Adding intercept strategy {} to route {}", interceptEntry.getKey(), _endpoint); + } + definition.addInterceptStrategy(interceptEntry.getValue()); + } + + Map errorListeners = lookup(ErrorListener.class); + if (errorListeners.isEmpty()) { + getContext().getWritebleRegistry().put("defaultErrorListener", new DefaultErrorListener()); + } + + // Since camel doesn't support onException closures together with doCatch/doFinal + // code below is commented because it doesn't work as expected + // definition.onException(Throwable.class).processRef(FATAL_ERROR.name()); + + TryDefinition tryDefinition = definition.doTry(); + addThrottling(tryDefinition); + + tryDefinition + .processRef(CONSUMER_INTERCEPT.name()) + .processRef(ADDRESSING.name()) + .processRef(TRANSACTION_HANDLER.name()) + .processRef(SECURITY_PROCESS.name()) + .processRef(GENERIC_POLICY.name()) + .processRef(VALIDATION.name()) + .processRef(TRANSFORMATION.name()) + .processRef(VALIDATION.name()) + .processRef(PROVIDER_INTERCEPT.name()) + .processRef(PROVIDER_CALLBACK.name()) + .processRef(PROVIDER_INTERCEPT.name()) + .processRef(SECURITY_CLEANUP.name()) + .processRef(TRANSACTION_HANDLER.name()) + .addOutput(createFilterDefinition()); + + tryDefinition + .doCatch(Exception.class) + .processRef(ERROR_HANDLING.name()) + .processRef(PROVIDER_INTERCEPT.name()) + .processRef(SECURITY_CLEANUP.name()) + .processRef(TRANSACTION_HANDLER.name()) + .addOutput(createFilterDefinition()); + + tryDefinition.doFinally() + .processRef(CONSUMER_INTERCEPT.name()) + .processRef(CONSUMER_CALLBACK.name()); + } + + private ExpressionNode createFilterDefinition() { + return new FilterDefinition(IN_OUT_CHECK) + .processRef(VALIDATION.name()) + .processRef(TRANSFORMATION.name()) + .processRef(VALIDATION.name()); + } + + /** + * Lookup in camel context given type of beans. + * + * @param type Type of bean. + * @return Map of beans where key is name. + */ + private Map lookup(Class type) { + Map result = getContext().getRegistry().lookupByType(type); + if (result == null) { + return Collections.emptyMap(); + } + return result; + } + + private void addThrottling(TryDefinition route) { + Throttling throttling = _reference.getServiceMetadata().getThrottling(); + long timePeriodMS = throttling != null ? throttling.getTimePeriod() : Throttling.DEFAULT_TIME_PERIOD; + route.filter(THROTTLE_CHECK) + .throttle(header(Throttling.MAX_REQUESTS)).timePeriodMillis(timePeriodMS) + // throttle needs a child process, so we'll just remove the header + // using an empty process definition causes some of the interceptors + // to blow chunks, specifically audit interceptors + .removeHeader(Throttling.MAX_REQUESTS) + .end().end(); + } +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeProperty.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeProperty.java new file mode 100644 index 000000000..43288295c --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelExchangeProperty.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.camel.Exchange; +import org.switchyard.Scope; + +/** + * Property implementation to handle {@link Scope#EXCHANGE}. + */ +public class CamelExchangeProperty extends CamelPropertyBase { + + private final Exchange _exchange; + private final String _name; + + /** + * Creates new exchange property. + * + * @param exchange Exchange instance. + * @param name Property name. + */ + public CamelExchangeProperty(Exchange exchange, String name) { + this._exchange = exchange; + this._name = name; + } + + @Override + @SuppressWarnings("unchecked") + protected Map> getLabelsBag() { + if (!_exchange.getProperties().containsKey(CamelExchange.LABELS)) { + _exchange.setProperty(CamelExchange.LABELS, new HashMap>()); + } + return _exchange.getProperty(CamelExchange.LABELS, Map.class); + } + + @Override + public Scope getScope() { + return Scope.EXCHANGE; + } + + @Override + public String getName() { + return _name; + } + + @Override + public Object getValue() { + return _exchange.getProperty(_name); + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelMessage.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelMessage.java new file mode 100644 index 000000000..93cea97c3 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelMessage.java @@ -0,0 +1,192 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.xml.namespace.QName; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.jboss.logging.Logger; +import org.switchyard.Context; +import org.switchyard.Message; +import org.switchyard.common.camel.HandlerDataSource; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.camel.SwitchYardMessage; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; + +/** + * Message implementation which adapt SwitchYard {@link Message} interface to + * {@link org.apache.camel.Message}. + */ +public class CamelMessage extends SwitchYardMessage implements Message { + + private static Logger _logger = Logger.getLogger(CamelMessage.class); + + /** + * Creates new Camel message with specified exchange. + * + * @param exchange The camel exchange. + */ + public CamelMessage(Exchange exchange) { + setExchange(exchange); + } + + @Override + public Message setContent(Object content) { + setBody(content); + return this; + } + + @Override + public Object getContent() { + return getBody(); + } + + @Override + public T getContent(Class type) { + return getBody(type); + } + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected T getBody(Class type, Object body) { + if (type == null) { + throw BusMessages.MESSAGES.nullTypeArgument(); + } + if (body == null) { + return null; + } + if (type.isInstance(body)) { + return type.cast(body); + } + + TransformerRegistry transformerRegistry = getTransformerRegistry(); + if (transformerRegistry == null) { + throw BusMessages.MESSAGES.cannotConvertNoTransformRegistry(body.getClass().getName(), type.getName()); + } + + QName toType = JavaTypes.toMessageType(type); + QName fromType = JavaTypes.toMessageType(body.getClass()); + if (_logger.isDebugEnabled()) { + _logger.debug("Looking for a transformer:[from='" + fromType + "', to='" + toType + "']"); + } + Transformer transformer = transformerRegistry.getTransformer(fromType, toType); + if (transformer == null) { + if (_logger.isDebugEnabled()) { + _logger.debug("No suitable transformer in registry. Trying camel converters for next."); + } + T camelBody = super.getBody(type, body); + if (camelBody == null) { + throw BusMessages.MESSAGES.transformerMustBeRegistered(body.getClass().getName(), type.getName(), fromType.toString(), toType.toString()); + } + return camelBody; + } + + if (_logger.isDebugEnabled()) { + _logger.debug("Applying a transformer:[from='" + fromType + + "', to='" + toType + + "', class=" + transformer.getClass() + + "'] to the body '" + body + "'"); + } + Object transformedContent = transformer.transform(body); + if (transformedContent == null) { + throw BusMessages.MESSAGES.transformerReturnedNull(body.getClass().getName(), type.getName(), transformer.getClass().getName()); + } + if (!type.isInstance(transformedContent)) { + throw BusMessages.MESSAGES.transformerReturnedIncompatibleType(body.getClass().getName(), type.getName(), transformer.getClass().getName(), transformedContent.getClass().getName()); + } + + return type.cast(transformedContent); + } + + @Override + public Message addAttachment(String name, DataSource attachment) { + addAttachment(name, new DataHandler(attachment)); + return this; + } + + @Override + public HandlerDataSource getAttachment(String name) { + DataHandler attachement = super.getAttachment(name); + return attachement != null ? new HandlerDataSource(attachement) : null; + } + + @Override + public void removeAttachment(String name) { + HandlerDataSource attachment = getAttachment(name); + if (attachment != null) { + removeAttachment(name); + } + } + + @Override + public Map getAttachmentMap() { + Map attachements = new HashMap(); + for (Entry attachement : getAttachments().entrySet()) { + attachements.put(attachement.getKey(), attachement.getValue().getDataSource()); + } + return attachements; + } + + @Override + public Context getContext() { + return new CamelCompositeContext(getExchange(), this); + } + + @Override + public CamelMessage copy() { + CamelMessage message = newInstance(); + message.setBody(getBody()); + return message; + } + + @Override + public CamelMessage newInstance() { + return new CamelMessage(getExchange()); + } + + /** + * Mark message as sent. + */ + public void sent() { + getContext().setProperty(CamelExchange.MESSAGE_SENT, true) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } + + /** + * Verify if message was sent or not. + * + * @return True if message was sent. + */ + public boolean isSent() { + return getHeader(CamelExchange.MESSAGE_SENT, false, Boolean.class); + } + + private TransformerRegistry getTransformerRegistry() { + CamelContext context = getExchange().getContext(); + if (context instanceof SwitchYardCamelContext) { + return ((SwitchYardCamelContext) context).getServiceDomain().getTransformerRegistry(); + } + return null; + } +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelMessageProperty.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelMessageProperty.java new file mode 100644 index 000000000..95b7c9292 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelMessageProperty.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.camel.Message; +import org.switchyard.Property; +import org.switchyard.Scope; + +/** + * Property implementation to handle {@link Scope#MESSAGE}. + */ +public class CamelMessageProperty extends CamelPropertyBase implements Property { + + private final Message _message; + private final String _name; + + /** + * Creates new message property. + * + * @param message Message instance. + * @param name Header name. + */ + public CamelMessageProperty(Message message, String name) { + this._message = message; + this._name = name; + } + + @Override + public Scope getScope() { + return Scope.MESSAGE; + } + + @Override + public String getName() { + return _name; + } + + @Override + public Object getValue() { + return _message.getHeader(_name); + } + + @Override + @SuppressWarnings("unchecked") + protected Map> getLabelsBag() { + if (!_message.getHeaders().containsKey(CamelExchange.LABELS)) { + _message.setHeader(CamelExchange.LABELS, new HashMap>()); + } + return _message.getHeader(CamelExchange.LABELS, Map.class); + } +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelPropertyBase.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelPropertyBase.java new file mode 100644 index 000000000..ad4d8d8b4 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/CamelPropertyBase.java @@ -0,0 +1,118 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.switchyard.Property; + +/** + * Base Property class for camel properties - both Message and Exchange scope. + */ +public abstract class CamelPropertyBase implements Property { + + @Override + public Set getLabels() { + Set labels = getLabelsBag().get(getName()); + if (labels == null) { + labels = Collections.emptySet(); + } + return labels; + } + + @Override + public Property addLabels(String... labels) { + if (!getLabelsBag().containsKey(getName())) { + getLabelsBag().put(getName(), new HashSet()); + } + getLabelsBag().get(getName()).addAll(Arrays.asList(labels)); + return this; + } + + @Override + public Property addLabels(Set labels) { + if (!getLabelsBag().containsKey(getName())) { + getLabelsBag().put(getName(), new HashSet()); + } + getLabelsBag().get(getName()).addAll(labels); + return this; + } + + @Override + public Property removeLabels(String... labels) { + if (getLabelsBag().containsKey(getName())) { + getLabelsBag().get(getName()).removeAll(Arrays.asList(labels)); + } + return this; + } + + @Override + public boolean hasLabel(String label) { + return getLabelsBag().containsKey(getName()) ? getLabelsBag().get(getName()).contains(label) : false; + } + + /** + * Retrieves bag which allows to store map between property names and property labels. + * + * @return Map to keep property labels. + */ + protected abstract Map> getLabelsBag(); + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (getName() == null ? 0 : getName().hashCode()); + result = prime * result + (getScope() == null ? 0 : getScope().hashCode()); + result = prime * result + (getValue() == null ? 0 : getValue().hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Property other = (Property) obj; + if (getName() == null) { + if (other.getName() != null) { + return false; + } + } else if (!getName().equals(other.getName())) { + return false; + } + if (getScope() != other.getScope()) { + return false; + } + if (getValue() == null) { + if (other.getValue() != null) { + return false; + } + } else if (!getValue().equals(other.getValue())) { + return false; + } + return true; + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/DefaultErrorListener.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/DefaultErrorListener.java new file mode 100644 index 000000000..dd06c7f53 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/DefaultErrorListener.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import org.jboss.logging.Logger; +import org.switchyard.ErrorListener; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.common.lang.Strings; +import org.switchyard.runtime.util.ExchangeFormatter; + +/** + * Default error listener. + */ +public class DefaultErrorListener implements ErrorListener { + + /** + * Logger. + */ + private static final Logger LOG = Logger.getLogger(DefaultErrorListener.class); + + @Override + public void notify(Exchange exchange, Throwable throwable) { + ExchangePattern pattern = exchange.getContract().getConsumerOperation().getExchangePattern(); + + String message = String.format("%s%nCaught exception of type %s with message: %s", ExchangeFormatter.format(exchange, false), throwable.getClass().getName(), throwable.getMessage()); + StringBuilder causeTrace = new StringBuilder(); + + if (throwable.getCause() != null) { + String causedBy = "%n%sCaused by exception of type %s, message: %s"; + Throwable cause = throwable.getCause(); + int depth = 0; + + while (cause != null) { + causeTrace.append(String.format(causedBy, Strings.repeat(" ", ++depth), cause.getClass().getName(), cause.getMessage())); + cause = cause.getCause(); + } + } + + if (pattern == ExchangePattern.IN_ONLY) { + LOG.error(message + causeTrace.toString(), throwable); + } else { + LOG.debug(message + causeTrace.toString(), throwable); + } + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/ExchangeDispatcher.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/ExchangeDispatcher.java new file mode 100644 index 000000000..7b27ab164 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/ExchangeDispatcher.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.bus.camel; + +import org.apache.camel.ProducerTemplate; +import org.apache.camel.impl.DefaultExchange; +import org.apache.camel.model.ModelCamelContext; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangePhase; +import org.switchyard.ServiceReference; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.qos.Throttling; +import org.switchyard.spi.Dispatcher; + +/** + * Creates a Dispatcher instance for handling message exchange for a SwitchYard + * service. + */ +public class ExchangeDispatcher implements Dispatcher { + + private final ModelCamelContext _context; + private ServiceReference _reference; + private ProducerTemplate _producer; + + /** + * Create a new Dispatcher instance. + * @param context Camel context instance + * @param reference dispatch for this reference + */ + public ExchangeDispatcher(ModelCamelContext context, ServiceReference reference) { + _context = context; + _reference = reference; + _producer = context.createProducerTemplate(); + } + + @Override + public ServiceReference getServiceReference() { + return _reference; + } + + @Override + public Exchange createExchange(ExchangeHandler replyHandler, ExchangePattern pattern) { + DefaultExchange exchange = new DefaultExchange(_context, translate(pattern)); + exchange.setIn(new CamelMessage(exchange)); + return new CamelExchange(this, exchange, replyHandler); + } + + private org.apache.camel.ExchangePattern translate(ExchangePattern pattern) { + return ExchangePattern.IN_OUT == pattern ? org.apache.camel.ExchangePattern.InOut : org.apache.camel.ExchangePattern.InOnly; + } + + @Override + public void dispatch(final Exchange exchange) { + // We can only send Camel exchanges through the camel bus + if (!CamelExchange.class.isInstance(exchange)) { + throw BusMessages.MESSAGES.onlyCamelExchanges(); + } + CamelExchange camelEx = (CamelExchange)exchange; + + // For camel exchanges, the only phase we care about is IN. The dispatch method can also + // be called on the OUT path, but that should be handled by the IN_OUT filter in the Camel + // bus route. + if (!exchange.getPhase().equals(ExchangePhase.IN)) { + return; + } + + Throttling throttling = _reference.getServiceMetadata().getThrottling(); + if (throttling != null && throttling.getMaxRequests() > 0) { + exchange.getMessage().getContext().setProperty( + Throttling.MAX_REQUESTS, throttling.getMaxRequests()) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } + _producer.send("direct:" + exchange.getConsumer().getName(), camelEx.getExchange()); + + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/AfterProcessor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/AfterProcessor.java new file mode 100644 index 000000000..4c16d6ddb --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/AfterProcessor.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.audit; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.switchyard.bus.camel.processors.Processors; + +/** + * Camel processor calling {@link Auditor#afterCall(Processors, Exchange)} of auditor. + */ +public class AfterProcessor implements Processor { + + private final Processors _processor; + private final Auditor _auditor; + + /** + * Creates new processor. + * + * @param processor Processing step. + * @param auditor Auditor instance. + */ + public AfterProcessor(Processors processor, Auditor auditor) { + this._processor = processor; + this._auditor = auditor; + } + + @Override + public void process(Exchange exchange) throws Exception { + _auditor.afterCall(_processor, exchange); + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/Audit.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/Audit.java new file mode 100644 index 000000000..e7c02a5eb --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/Audit.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.audit; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.switchyard.bus.camel.processors.Processors; + +/** + * Type level annotation used on auditor implementations to point which steps + * in SwitchYard processing chain is intent to be audited. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface Audit { + + /** + * Processing steps to be audited. + * + * An empty value returned by this annotation means that all steps should be + * surrounded. + */ + Processors[] value() default {}; + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/AuditInterceptStrategy.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/AuditInterceptStrategy.java new file mode 100644 index 000000000..f8d685391 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/AuditInterceptStrategy.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.audit; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.camel.CamelContext; +import org.apache.camel.Processor; +import org.apache.camel.model.ProcessDefinition; +import org.apache.camel.model.ProcessorDefinition; +import org.apache.camel.processor.Pipeline; +import org.apache.camel.spi.InterceptStrategy; +import org.jboss.logging.Logger; +import org.switchyard.bus.camel.processors.Processors; + +/** + * Intercept strategy which looks for {@link Auditor} implementations and call + * them before/after SwitchYard exchange bus processors. + */ +public class AuditInterceptStrategy implements InterceptStrategy { + + private Logger _logger = Logger.getLogger(AuditInterceptStrategy.class); + + @Override + public Processor wrapProcessorInInterceptors(CamelContext context, + ProcessorDefinition definition, Processor target, + Processor nextTarget) throws Exception { + + if (!(definition instanceof ProcessDefinition)) { + if (_logger.isTraceEnabled()) { + _logger.trace("Ignore " + definition + " as it's not intent to be handled with custom auditors"); + } + return target; + } + ProcessDefinition process = (ProcessDefinition) definition; + + Map auditors = context.getRegistry().lookupByType(Auditor.class); + if (auditors != null) { + List wrappers = new ArrayList(); + for (Entry entry : auditors.entrySet()) { + if (matches(entry.getValue(), process)) { + if (_logger.isTraceEnabled()) { + _logger.trace("Found matching auditor " + entry.getKey() + " for processing step " + process.getRef()); + } + wrappers.add(entry.getValue()); + } + } + + if (wrappers.size() > 0) { + List processors = new ArrayList(); + CompositeAuditor auditor = new CompositeAuditor(wrappers); + Processors step = Processors.valueOf(process.getRef()); + processors.add(new BeforeProcessor(step, auditor)); + processors.add(target); + processors.add(new AfterProcessor(step, auditor)); + return new Pipeline(context, processors); + } + } + if (_logger.isTraceEnabled()) { + _logger.trace("No custom or matching auditors were found, using original processors"); + } + + return target; + } + + /** + * Utility method used to verify if auditor instance matching a given processRef element. + * + * @param auditor Auditor to verify. + * @param process Definition of processRef element in Camel DSL. + * @return True if given auditor have no annotation or annotation is empty. + * False is returned when processor reference do not match any of @Auditor values. + */ + private boolean matches(Auditor auditor, ProcessDefinition process) { + Audit annotation = auditor.getClass().getAnnotation(Audit.class); + if (annotation == null || annotation.value().length == 0) { + return true; + } + + String ref = process.getRef(); + for (Processors processor : annotation.value()) { + if (processor.name().equals(ref)) { + return true; + } + } + return false; + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/Auditor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/Auditor.java new file mode 100644 index 000000000..9b932077e --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/Auditor.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.audit; + +import org.apache.camel.Exchange; +import org.switchyard.bus.camel.processors.Processors; + +/** + * Basic interface for auditing features. + */ +public interface Auditor { + + /** + * Method called before given processor. + * + * @param processor Pointer to processing step in SwitchYard flow. + * @param exchange Related exchange. + */ + void beforeCall(Processors processor, Exchange exchange); + + /** + * Method called after given processor. + * + * @param processor Pointer to processing step in SwitchYard flow. + * @param exchange Related exchange. + */ + void afterCall(Processors processor, Exchange exchange); + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/BeforeProcessor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/BeforeProcessor.java new file mode 100644 index 000000000..0fc52e482 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/BeforeProcessor.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.audit; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.switchyard.bus.camel.processors.Processors; + +/** + * Camel processor calling {@link Auditor#beforeCall(Processors, Exchange)} of auditor. + */ +public class BeforeProcessor implements Processor { + + private final Processors _processor; + private final Auditor _auditor; + + /** + * Creates new processor. + * + * @param processor Processing step. + * @param auditor Auditor instance. + */ + public BeforeProcessor(Processors processor, Auditor auditor) { + this._processor = processor; + this._auditor = auditor; + } + + @Override + public void process(Exchange exchange) throws Exception { + _auditor.beforeCall(_processor, exchange); + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/CompositeAuditor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/CompositeAuditor.java new file mode 100644 index 000000000..cc1e5937b --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/CompositeAuditor.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.audit; + +import java.util.List; + +import org.apache.camel.Exchange; +import org.jboss.logging.Logger; +import org.switchyard.bus.camel.processors.Processors; + +/** + * Fail-safe Implementation of auditor which calls wrapped auditors. + */ +public class CompositeAuditor implements Auditor { + + private Logger _logger = Logger.getLogger(CompositeAuditor.class); + private final List _auditors; + + /** + * Creates new composite. + * + * @param auditors Auditors to be wrapped. + */ + public CompositeAuditor(List auditors) { + this._auditors = auditors; + } + + @Override + public void beforeCall(Processors processor, Exchange exchange) { + for (Auditor auditor : _auditors) { + try { + auditor.beforeCall(processor, exchange); + } catch (Exception e) { + _logger.error(e); + } + } + } + + @Override + public void afterCall(Processors processor, Exchange exchange) { + for (Auditor auditor : _auditors) { + try { + auditor.afterCall(processor, exchange); + } catch (Exception e) { + _logger.error(e); + } + } + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/FaultInterceptStrategy.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/FaultInterceptStrategy.java new file mode 100644 index 000000000..9511d4741 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/FaultInterceptStrategy.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.audit; + +import org.apache.camel.CamelContext; +import org.apache.camel.Processor; +import org.apache.camel.model.ProcessorDefinition; +import org.apache.camel.spi.InterceptStrategy; + +/** + * Intercept strategy catching exceptions and changing state of SwitchYard + * exchange to FAULT. + */ +public class FaultInterceptStrategy implements InterceptStrategy { + + @Override + public Processor wrapProcessorInInterceptors(CamelContext context, + ProcessorDefinition definition, Processor target, + Processor nextTarget) throws Exception { + return new FaultProcessor(target); + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/FaultProcessor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/FaultProcessor.java new file mode 100644 index 000000000..9dfe30422 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/audit/FaultProcessor.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.audit; + +import org.apache.camel.AsyncCallback; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.processor.DelegateAsyncProcessor; +import org.jboss.logging.Logger; +import org.switchyard.bus.camel.CamelExchange; +import org.switchyard.bus.camel.BusLogger; + +/** + * This processor catches exceptions from camel thrown during handling fault replies + * from switchyard. + * + * If exception occurs during fault handling it will be ignored. + */ +public class FaultProcessor extends DelegateAsyncProcessor { + + private Logger _logger = Logger.getLogger(FaultProcessor.class); + + /** + * Creates new fault processor. + * + * @param target Wrapped processor. + */ + public FaultProcessor(Processor target) { + super(target); + } + + @Override + public boolean process(final Exchange exchange, final AsyncCallback callback) { + return super.process(exchange, new AsyncCallback() { + @Override + public void done(boolean doneSync) { + if (doneSync) { // verify exchange only if processing is done + if (CamelExchange.isFault(exchange) && exchange.getException() != null) { + handle(exchange.getException(), exchange); + exchange.setException(null); + } + } + callback.done(doneSync); + } + }); + } + + /** + * Method which tries to send FAULT if there is exception reported by processor + * and exchange state is still OK. + * + * @param throwable Exception thrown by target processor. + * @param camel Camel exchange. + * @param exchange SwitchYard exchange related to exception. + */ + protected void handle(Throwable throwable, Exchange exchange) { + + // exception thrown during handling FAULT state cannot be forwarded + // anywhere, because we already have problem to handle + BusLogger.ROOT_LOGGER.exceptionDuringFaultResponse(throwable); + } + + @Override + public String toString() { + return String.format("FaultProcessor [%s]", getProcessor()); + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/ConsumerCallbackProcessor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/ConsumerCallbackProcessor.java new file mode 100644 index 000000000..fabf0797e --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/ConsumerCallbackProcessor.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.processors; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangeState; +import org.switchyard.bus.camel.CamelExchange; + +/** + * Processor used to call reply chain. + */ +public class ConsumerCallbackProcessor implements Processor { + + @Override + public void process(Exchange ex) throws Exception { + org.switchyard.Exchange syEx = new CamelExchange(ex); + + if (syEx.getState() == ExchangeState.FAULT) { + ExchangeHandler handler = syEx.getReplyHandler(); + if (handler != null) { + handler.handleFault(syEx); + } + } else { + // Only call back with reply messages if the MEP is In-Out + if (ExchangePattern.IN_OUT.equals(syEx.getPattern())) { + syEx.getReplyHandler().handleMessage(syEx); + } + } + } +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/ErrorHandlingProcessor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/ErrorHandlingProcessor.java new file mode 100644 index 000000000..10130a105 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/ErrorHandlingProcessor.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.processors; + +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.util.ExchangeHelper; +import org.jboss.logging.Logger; +import org.switchyard.ErrorListener; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Scope; +import org.switchyard.bus.camel.BusLogger; +import org.switchyard.bus.camel.CamelExchange; + +/** + * Processor put at the beginning of OnExceptionDefinition which turns state of + * SwitchYard exchange into FAULT. + */ +public class ErrorHandlingProcessor implements Processor { + + /** + * Logger. + */ + private static final Logger LOG = Logger.getLogger(ErrorHandlingProcessor.class); + + @Override + public void process(Exchange exchange) throws Exception { + CamelExchange ex = new CamelExchange(exchange); + if (ex.getState() != ExchangeState.FAULT) { + Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); + notifyListeners(exchange.getContext(), ex, exception); + Throwable content = detectHandlerException(exception); + org.switchyard.Property rollbackOnFaultProperty = ex.getContext().getProperty(org.switchyard.Exchange.ROLLBACK_ON_FAULT); + if (rollbackOnFaultProperty == null || rollbackOnFaultProperty.getValue() == null) { + ex.getContext().setProperty(org.switchyard.Exchange.ROLLBACK_ON_FAULT, Boolean.TRUE, Scope.EXCHANGE); + } + ex.sendFault(ex.createMessage().setContent(content)); + ExchangeHelper.setFailureHandled(exchange); + } + } + + private Throwable detectHandlerException(Throwable throwable) { + if (throwable instanceof HandlerException) { + return (HandlerException) throwable; + } + return new HandlerException(throwable); + } + + private void notifyListeners(CamelContext context, org.switchyard.Exchange exchange, Throwable exception) { + Map listeners = context.getRegistry().lookupByType(ErrorListener.class); + if (listeners != null && listeners.size() > 0) { + for (Entry entry : listeners.entrySet()) { + try { + entry.getValue().notify(exchange, exception); + } catch (Exception e) { + BusLogger.ROOT_LOGGER.failedToHandlException(entry.getKey(), exception.getClass()); + } + } + } + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/HandlerProcessor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/HandlerProcessor.java new file mode 100644 index 000000000..cfb44c6fc --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/HandlerProcessor.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.processors; + +import java.util.Arrays; +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangeState; +import org.switchyard.bus.camel.CamelExchange; + +/** + * Processor wrapping SwitchYard {@link ExchangeHandler} invocation. + */ +public class HandlerProcessor implements Processor { + + /** + * Wrapped handlers. + */ + private List _handlers; + + /** + * Creates new processor which delegates execution to SwitchYard {@link ExchangeHandler}. + * + * @param handler Handler to wrap. + */ + public HandlerProcessor(ExchangeHandler handler) { + this(Arrays.asList(handler)); + } + + /** + * Creates new processor which delegates execution to collection of exchange handlers. + * + * @param handlers Exchange handlers used to process messages during dispatching. + */ + public HandlerProcessor(List handlers) { + _handlers = handlers; + } + + @Override + public void process(Exchange ex) throws Exception { + org.switchyard.Exchange exchange = new CamelExchange(ex); + + for (ExchangeHandler handler : _handlers) { + if (exchange.getState() == ExchangeState.FAULT) { + handler.handleFault(exchange); + } else { + handler.handleMessage(exchange); + } + } + } + + @Override + public String toString() { + return String.format("HandlerProcessor [%s]", _handlers); + } + +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/InterceptProcessor.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/InterceptProcessor.java new file mode 100644 index 000000000..eba4fb3ca --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/InterceptProcessor.java @@ -0,0 +1,185 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.processors; + +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.jboss.logging.Logger; +import org.switchyard.ExchangeInterceptor; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.ServiceDomain; +import org.switchyard.bus.camel.BusLogger; +import org.switchyard.bus.camel.CamelExchange; +import org.switchyard.handlers.MessageTraceHandler; + +/** + * Invokes a SwitchYard ExchangeInterceptor around a given processor identified by + * target. The provider and consumer targets happen to correspond to message trace points + * as well, so we have a big old hack here to invoke that handler directly. + */ +public class InterceptProcessor implements Processor { + + private static final String INTERCEPT_PREFIX = "org.switchyard.bus.camel.intercept."; + private static final String BEFORE = "before"; + private static final String AFTER = "after"; + + private String _target; + private String _property; + private ServiceDomain _domain; + private MessageTraceHandler _trace; + private static Logger _log = Logger.getLogger(InterceptProcessor.class); + + /** + * Create a new InterceptorProcessor. + * @param target the interception target + * @param domain service domain for this processor + */ + public InterceptProcessor(String target, ServiceDomain domain) { + _domain = domain; + _target = target; + _property = INTERCEPT_PREFIX + _target; + _trace = new MessageTraceHandler(); + } + + @Override + public void process(Exchange ex) throws Exception { + traceMessage(ex); + fireInterceptors(ex); + } + + @Override + public String toString() { + return "InterceptProcessor@" + System.identityHashCode(this); + } + + private void traceMessage(Exchange exchange) { + // bail if tracing is not enabled + if (!traceEnabled(exchange)) { + return; + } + + try { + CamelExchange syEx = new CamelExchange(exchange); + if (ExchangeState.FAULT.equals(syEx.getState())) { + _trace.handleFault(syEx); + } else { + _trace.handleMessage(syEx); + } + } catch (Exception ex) { + // This is not a critical error, but very annoying if you have + // enabled tracing and nothing comes out. Log at WARN so it's noticed. + _log.warn("Failed while generating message trace.", ex); + } + } + + private void fireInterceptors(Exchange ex) throws HandlerException { + Map interceptors = + ex.getContext().getRegistry().lookupByType(ExchangeInterceptor.class); + + if (interceptors != null && interceptors.size() > 0) { + CamelExchange syEx = new CamelExchange(ex); + try { + // Seed these values up front so that interceptors don't mess with them + boolean callBefore = isBefore(ex); + boolean callAfter = isAfter(ex); + + for (ExchangeInterceptor interceptor : interceptors.values()) { + // Is the interceptor targeting this processor? + if (!matchesTarget(interceptor)) { + continue; + } + + if (callBefore) { + interceptor.before(_target, syEx); + } else if (callAfter) { + try { + interceptor.after(_target, syEx); + } catch (Exception error) { + // If we are already in fault state, don't allow the + // interceptor to throw again - this blows up the route + if (ExchangeState.FAULT.equals(syEx.getState())) { + BusLogger.ROOT_LOGGER.alreadyInFaultState(error); + } else { + if (error instanceof HandlerException) { + throw (HandlerException)error; + } else { + throw new HandlerException(error); + } + } + } + } + } + } finally { + // this is done outside the for loop and catch block to account + // for multiple interceptors and the possibility that one throws + // a runtime exception + if (isBefore(ex)) { + setBefore(ex); + } else { + setAfter(ex); + } + } + } + } + + + boolean traceEnabled(Exchange ex) { + // if message tracing is explicitly enabled/disabled on the domain, then go with that + Object traceProp = _domain.getProperty(MessageTraceHandler.TRACE_ENABLED); + if (traceProp != null) { + boolean enabled = false; + if (Boolean.class.isAssignableFrom(traceProp.getClass())) { + enabled = ((Boolean)traceProp).booleanValue(); + } else if (String.class.isAssignableFrom(traceProp.getClass())) { + enabled = Boolean.valueOf((String)traceProp); + } else { + enabled = Boolean.valueOf(traceProp.toString()); + } + return enabled; + } + + // no setting for the domain, check the exchange + return ex.getProperty(MessageTraceHandler.TRACE_ENABLED, false, Boolean.class); + } + + private void setBefore(Exchange ex) { + ex.setProperty(_property, BEFORE); + } + + private void setAfter(Exchange ex) { + ex.setProperty(_property, AFTER); + } + + private boolean isBefore(Exchange ex) { + return ex.getProperty(_property) == null; + } + + /** + * Check to make sure before has been called - if it hasn't, then don't + * call after. Also verify that after is not called twice in situations + * where a fault/error is thrown after the after was called. + */ + private boolean isAfter(Exchange ex) { + return BEFORE.equals(ex.getProperty(_property)); + } + + private boolean matchesTarget(ExchangeInterceptor interceptor) { + List targets = interceptor.getTargets(); + return targets != null && targets.contains(_target); + } +} diff --git a/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/Processors.java b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/Processors.java new file mode 100644 index 000000000..86cd0f405 --- /dev/null +++ b/core/bus/camel/src/main/java/org/switchyard/bus/camel/processors/Processors.java @@ -0,0 +1,164 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.processors; + +import org.apache.camel.Processor; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangeInterceptor; +import org.switchyard.ServiceDomain; +import org.switchyard.bus.camel.BusMessages; +import org.switchyard.handlers.AddressingHandler; +import org.switchyard.handlers.PolicyHandler; +import org.switchyard.handlers.ProviderHandler; +import org.switchyard.handlers.SecurityHandler; +import org.switchyard.handlers.SecurityHandler.SecurityAction; +import org.switchyard.handlers.TransactionHandler; +import org.switchyard.handlers.TransformHandler; +import org.switchyard.handlers.ValidateHandler; + +/** + * Enumeration representing processors used by exchange bus. + */ +public enum Processors { + + /** + * Addressing handler. + */ + ADDRESSING { + @Override + public Processor create(ServiceDomain domain) { + return wrap(new AddressingHandler(domain)); + } + }, + /** + * Transaction handling processor. + */ + TRANSACTION_HANDLER { + @Override + public Processor create(ServiceDomain domain) { + return wrap(new TransactionHandler()); + } + }, + /** + * Security process wrapper. + */ + SECURITY_PROCESS { + @Override + public Processor create(ServiceDomain domain) { + return wrap(new SecurityHandler(domain, SecurityAction.PROCESS)); + } + }, + /** + * Security cleanup wrapper. + */ + SECURITY_CLEANUP { + @Override + public Processor create(ServiceDomain domain) { + return wrap(new SecurityHandler(domain, SecurityAction.CLEANUP)); + } + }, + /** + * Policy handler. + */ + GENERIC_POLICY { + @Override + public Processor create(ServiceDomain domain) { + return wrap(new PolicyHandler()); + } + }, + /** + * Validation processor wrapper. + */ + VALIDATION { + @Override + public Processor create(ServiceDomain domain) { + return wrap(new ValidateHandler(domain.getValidatorRegistry())); + } + }, + /** + * Transformation handler. + */ + TRANSFORMATION { + @Override + public Processor create(ServiceDomain domain) { + return wrap(new TransformHandler(domain.getTransformerRegistry())); + } + }, + /** + * Processor calling service provider. + */ + PROVIDER_CALLBACK { + @Override + public Processor create(ServiceDomain domain) { + return wrap(new ProviderHandler(domain)); + } + }, + /** + * Reply chain handler. + */ + CONSUMER_CALLBACK { + @Override + public Processor create(ServiceDomain domain) { + return new ConsumerCallbackProcessor(); + } + }, + /** + * Processor which invokes consumer interceptors. + */ + CONSUMER_INTERCEPT { + @Override + public Processor create(ServiceDomain domain) { + return new InterceptProcessor(ExchangeInterceptor.CONSUMER, domain); + } + }, + /** + * Processor which invokes provider interceptors. + */ + PROVIDER_INTERCEPT { + @Override + public Processor create(ServiceDomain domain) { + return new InterceptProcessor(ExchangeInterceptor.PROVIDER, domain); + } + }, + /** + * Special case processor called as first in part of route responsible + * for exception handling. + */ + ERROR_HANDLING { + @Override + public Processor create(ServiceDomain domain) { + return new ErrorHandlingProcessor(); + } + }; + + /** + * Creates new processor for given Service Domain. + * + * @param domain Service domain. + * @return Processor instance. + */ + public Processor create(ServiceDomain domain) { + throw BusMessages.MESSAGES.methodMustBeOverridden(); + } + + /** + * Wraps handler into camel Processor. + * + * @param handler Handler to wrap. + * @return Wrapping processor. + */ + private static Processor wrap(ExchangeHandler handler) { + return new HandlerProcessor(handler); + } +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelCompositeContextTest.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelCompositeContextTest.java new file mode 100644 index 000000000..ee1b5e841 --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelCompositeContextTest.java @@ -0,0 +1,63 @@ +package org.switchyard.bus.camel; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.MockDomain; +import org.switchyard.Scope; +import org.switchyard.ServiceReference; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.internal.ServiceReferenceImpl; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.InOnlyService; + +public class CamelCompositeContextTest { + + private CamelExchangeBus _provider; + private SwitchYardCamelContextImpl _camelContext; + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + _camelContext = new SwitchYardCamelContextImpl(); + _camelContext.setServiceDomain(_domain); + _provider = new CamelExchangeBus(_camelContext); + _provider.init(_domain); + _camelContext.start(); + } + + @After + public void tearDown() throws Exception { + _camelContext.stop(); + } + + @Test + public void testCopyFromExchange() throws Exception { + ServiceReference inOnly = new ServiceReferenceImpl( + new QName("exchange-copy"), new InOnlyService(), _domain, null); + ExchangeDispatcher dispatch = _provider.createDispatcher(inOnly); + + Exchange ex = dispatch.createExchange(null, ExchangePattern.IN_ONLY); + Context ctx = ex.getContext(); + ctx.setProperty("message-prop", "message-val", Scope.MESSAGE); + ctx.setProperty("exchange-prop", "exchange-val", Scope.EXCHANGE).addLabels(BehaviorLabel.TRANSIENT.label()); + Assert.assertEquals(ctx.getProperty("message-prop", Scope.MESSAGE).getValue(), "message-val"); + Assert.assertEquals(ctx.getProperty("exchange-prop", Scope.EXCHANGE).getValue(), "exchange-val"); + Assert.assertTrue(ctx.getProperty("exchange-prop", Scope.EXCHANGE).getLabels().contains(BehaviorLabel.TRANSIENT.label())); + + // Merge the context from ex into the context for ex2 + Exchange ex2 = dispatch.createExchange(null, ExchangePattern.IN_ONLY); + Context ctx2 = ex2.getContext(); + ctx.mergeInto(ctx2); + Assert.assertNotNull(ctx2.getProperty("message-prop", Scope.MESSAGE)); + Assert.assertNull(ctx2.getProperty("exchange-prop", Scope.EXCHANGE)); + } +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelExchangeBusTest.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelExchangeBusTest.java new file mode 100644 index 000000000..2f4421771 --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelExchangeBusTest.java @@ -0,0 +1,348 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.apache.camel.Processor; +import org.apache.camel.builder.LoggingErrorHandlerBuilder; +import org.apache.camel.spi.RouteContext; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.ErrorListener; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangeInterceptor; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.ServiceReference; +import org.switchyard.bus.camel.handler.ErrorInterceptor; +import org.switchyard.bus.camel.handler.RuntimeErrorInHandler; +import org.switchyard.bus.camel.handler.RuntimeErrorInterceptor; +import org.switchyard.bus.camel.handler.TypeInterceptor; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.internal.ServiceReferenceImpl; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.InOutService; +import org.switchyard.spi.Dispatcher; + +public class CamelExchangeBusTest { + + private final static String TEST_CONTENT = "Some content to sent"; + + private CamelExchangeBus _provider; + private SwitchYardCamelContextImpl _camelContext; + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + _camelContext = new SwitchYardCamelContextImpl(); + _camelContext.setServiceDomain(_domain); + _provider = new CamelExchangeBus(_camelContext); + _provider.init(_domain); + _camelContext.start(); + } + + @After + public void tearDown() throws Exception { + _camelContext.stop(); + } + + @Test + public void testCreateDispatcher() throws Exception { + // verify that dispatchers can be created for an InOnly service + ServiceReference inOnly = new ServiceReferenceImpl( + new QName("inOnly"), new InOnlyService(), _domain, null); + assertNotNull(_provider.createDispatcher(inOnly)); + + // verify that dispatchers can be created for an InOut service + ServiceReference inOut = new ServiceReferenceImpl( + new QName("inOut"), new InOutService(), _domain, null); + assertNotNull(_provider.createDispatcher(inOut)); + } + + @Test + public void testGetDispatcher() throws Exception { + ServiceReference ref = new ServiceReferenceImpl( + new QName("testGetDispatcher"), new InOnlyService(), null, null); + Dispatcher dispatch = _provider.createDispatcher(ref); + + assertEquals(dispatch, _provider.getDispatcher(ref)); + } + + /** + * Basic dispatcher test which verifies erroneous response from service. + */ + @Test + public void testServiceFault() { + ServiceReference ref = registerInOutService("inOut", new ErrorExchangeHandler()); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertNoCause("Service is not implemented", exchange); + } + + /** + * Verify consumer callback is called when fault occurs on InOnly. + */ + @Test + public void testFaultReportedOnInOnly() { + ServiceReference ref = registerInOnlyService("inOut", new ErrorExchangeHandler()); + MockHandler consumer = new MockHandler(); + Exchange exchange = ref.createExchange(consumer); + exchange.send(exchange.createMessage().setContent("test")); + + Assert.assertEquals(1, consumer.waitForFaultMessage().getFaults().size()); + } + + /** + * Basic dispatcher test which verifies erroneous interceptor. + */ + @Test + public void testBeforeProviderErrorInOut() { + ErrorInterceptor interceptor = new ErrorInterceptor(false, ExchangeInterceptor.PROVIDER); + _camelContext.getWritebleRegistry().put("interceptor", interceptor); + + ServiceReference ref = registerInOutService("inOut"); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertNoCause("Error before on target Provider", exchange); + Assert.assertEquals(2, interceptor.getCount()); + } + + /** + * Basic dispatcher test which verifies erroneous interceptor. + */ + @Test + public void testAfterProviderErrorInOut() { + ErrorInterceptor interceptor = new ErrorInterceptor(true, ExchangeInterceptor.PROVIDER); + _camelContext.getWritebleRegistry().put("interceptor", interceptor); + + ServiceReference ref = registerInOutService("inOut"); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertNoCause("Error after on target Provider", exchange); + Assert.assertEquals(2, interceptor.getCount()); + } + + /** + * Basic dispatcher test which verifies erroneous interceptor. + */ + @Test + public void testBeforeProviderErrorInOnly() { + ErrorInterceptor interceptor = new ErrorInterceptor(false, ExchangeInterceptor.PROVIDER); + _camelContext.getWritebleRegistry().put("interceptor", interceptor); + + ServiceReference ref = registerInOnlyService("inOnly", new MockHandler()); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertNoCause("Error before on target Provider", exchange); + Assert.assertEquals(2, interceptor.getCount()); + } + + /** + * Basic dispatcher test which verifies erroneous interceptor. + */ + @Test + public void testAfterProviderErrorInOnly() { + ErrorInterceptor interceptor = new ErrorInterceptor(true, ExchangeInterceptor.PROVIDER); + _camelContext.getWritebleRegistry().put("interceptor", interceptor); + + ServiceReference ref = registerInOnlyService("inOnly", new MockHandler()); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertNoCause("Error after on target Provider", exchange); + Assert.assertEquals(2, interceptor.getCount()); + } + + /** + * Basic dispatcher test which verifies erroneous domain handler. + */ + @Test + public void testInRuntimeFault() { + RuntimeErrorInterceptor interceptor = new RuntimeErrorInterceptor( + false, ExchangeInterceptor.PROVIDER); + _camelContext.getWritebleRegistry().put("interceptor", interceptor); + + ServiceReference ref = registerInOutService("inOut"); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertCause("RuntimeException before on target Provider", exchange); + Assert.assertEquals(2, interceptor.getCount()); + } + + /** + * Basic dispatcher test which verifies erroneous response from service. + */ + @Test + public void testOutRuntimeFault() { + RuntimeErrorInterceptor interceptor = new RuntimeErrorInterceptor( + true, ExchangeInterceptor.PROVIDER); + _camelContext.getWritebleRegistry().put("interceptor", interceptor); + + ServiceReference ref = registerInOutService("inOut"); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertCause("RuntimeException after on target Provider", exchange); + Assert.assertEquals(2, interceptor.getCount()); + } + + /** + * Basic dispatcher test which verifies erroneous response from service. + */ + @Test + public void testFaultFault() { + ErrorInterceptor beforeFault = new ErrorInterceptor(false, ExchangeInterceptor.PROVIDER); + ErrorInterceptor afterFault = new ErrorInterceptor(true, ExchangeInterceptor.PROVIDER); + _camelContext.getWritebleRegistry().put("beforeFault", beforeFault); + _camelContext.getWritebleRegistry().put("afterFault", afterFault); + ServiceReference ref = registerInOutService("inOut"); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertNoCause("Error before on target Provider", exchange); + Assert.assertEquals(2, beforeFault.getCount()); + Assert.assertEquals(2, afterFault.getCount()); + } + + @Test + public void testErrorListener() throws InterruptedException { + final AtomicBoolean fired = new AtomicBoolean(); + ErrorListener listener = new ErrorListener() { + @Override + public void notify(Exchange ex, Throwable e) { + fired.compareAndSet(false, true); + } + }; + _camelContext.getWritebleRegistry().put("custom error listener", listener); + ServiceReference ref = registerInOutService("inOut", new RuntimeErrorInHandler()); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertTrue(fired.get()); + assertCause("Runtime error", exchange); + } + + @Test + public void testContentTypes() throws Exception { + TypeInterceptor types = new TypeInterceptor(); + _camelContext.getWritebleRegistry().put("types", types); + + QName inType = new QName("urn:foo", "in"); + QName outType = new QName("urn:bar", "out"); + + ExchangeHandler handler = new BaseHandler() { + @Override + public void handleMessage(Exchange exchange) + throws HandlerException { + exchange.send(exchange.getMessage().copy()); + } + }; + ServiceReference ref = registerInOutServiceWithTypes("typesTest", inType, outType, handler); + sendMessage(ref, TEST_CONTENT); + + Assert.assertEquals(inType, types.getInType()); + Assert.assertEquals(outType, types.getOutType()); + } + + @Test @Ignore + public void testCustomErrorHandler() throws InterruptedException { + final AtomicBoolean fired = new AtomicBoolean(); + _camelContext.getWritebleRegistry().put("custom error handler", new LoggingErrorHandlerBuilder() { + @Override + public Processor createErrorHandler(RouteContext routeContext, final Processor processor) { + fired.compareAndSet(false, true); + return super.createErrorHandler(routeContext, processor); + } + }); + ServiceReference ref = registerInOutService("inOut", new RuntimeErrorInHandler()); + Exchange exchange = sendMessage(ref, TEST_CONTENT); + + assertTrue(fired.get()); + assertCause("Runtime error", exchange); + } + + protected static void assertNoCause(String message, Exchange exchange) { + assertEquals(ExchangeState.FAULT, exchange.getState()); + Exception exception = exchange.getMessage().getContent(Exception.class); + assertNotNull("Exception should not be null", exception); + assertNull("Cause should be null", exception.getCause()); + assertEquals(message, exception.getMessage()); + // SWITCHYARD-1634 + assertNotNull(exchange.getContext().getProperty(Exchange.MESSAGE_ID)); + assertNotNull(exchange.getContext().getProperty(Exchange.RELATES_TO)); + } + + protected static void assertCause(String message, Exchange exchange) { + assertEquals(ExchangeState.FAULT, exchange.getState()); + HandlerException exception = exchange.getMessage().getContent(HandlerException.class); + assertTrue(exception.isWrapper()); + assertNotNull("Cause should not be null", exception.getCause()); + assertEquals(message, exception.getCause().getMessage()); + // SWITCHYARD-1634 + assertNotNull(exchange.getContext().getProperty(Exchange.MESSAGE_ID)); + assertNotNull(exchange.getContext().getProperty(Exchange.RELATES_TO)); + } + + private ServiceReference registerInOutService(String name) { + return registerInOutService(name, new MockHandler().forwardInToOut()); + } + + private ServiceReference registerInOnlyService(String name, ExchangeHandler handler) { + ServiceReferenceImpl reference = new ServiceReferenceImpl(new QName(name), new InOnlyService(), _domain, null); + _domain.registerService(new QName(name), new InOnlyService(), handler); + reference.setDispatcher(_provider.createDispatcher(reference)); + return reference; + } + + private ServiceReference registerInOutService(String name, ExchangeHandler handler) { + ServiceReferenceImpl reference = new ServiceReferenceImpl( + new QName(name), new InOutService(), _domain, null); + _domain.registerService(new QName(name), new InOutService(), handler); + reference.setDispatcher(_provider.createDispatcher(reference)); + return reference; + } + + private Exchange sendMessage(ServiceReference ref, Object content) { + Exchange exchange = ref.createExchange(new MockHandler()); + exchange.send(exchange.createMessage().setContent(content)); + return exchange; + } + + private ServiceReference registerInOutServiceWithTypes( + String serviceName, QName inputType, QName outputType, ExchangeHandler handler) { + + InOutService intf = new InOutService(new InOutOperation("process", inputType, outputType)); + ServiceReferenceImpl reference = new ServiceReferenceImpl( + new QName(serviceName), intf, _domain, null); + _domain.registerService(new QName(serviceName), intf, handler); + reference.setDispatcher(_provider.createDispatcher(reference)); + return reference; + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelShutdownTest.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelShutdownTest.java new file mode 100644 index 000000000..121668753 --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/CamelShutdownTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.HandlerException; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.ServiceReference; +import org.switchyard.common.camel.CamelContextConfigurator; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.internal.ServiceReferenceImpl; +import org.switchyard.metadata.InOutService; + +public class CamelShutdownTest { + + private CamelExchangeBus _provider; + private SwitchYardCamelContextImpl _camelContext; + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + _camelContext = new SwitchYardCamelContextImpl(); + _camelContext.setServiceDomain(_domain); + _provider = new CamelExchangeBus(_camelContext); + _provider.init(_domain); + } + + @Test + public void testShutdownTimeout() throws Exception { + // set the timeout value to 5 seconds and start the camel context + _domain.setProperty(CamelContextConfigurator.SHUTDOWN_TIMEOUT, "5"); + _camelContext.start(); + + // register a service and send a message + ServiceReference ref = registerInOutService("inOut", new TakesForeverHandler()); + sendMessage(ref, 120 * 1000); + + // Give the sending thread a chance to send the message + Thread.sleep(1000); + + // Stop the context and assert that we haven't waited a long time (default is 30s) + long beforeStop = System.currentTimeMillis(); + _camelContext.stop(); + long afterStop = System.currentTimeMillis(); + Assert.assertTrue((afterStop - beforeStop) < 6000); + } + + private ServiceReference registerInOutService(String name, ExchangeHandler handler) { + ServiceReferenceImpl reference = new ServiceReferenceImpl( + new QName(name), new InOutService(), _domain, null); + _domain.registerService(new QName(name), new InOutService(), handler); + reference.setDispatcher(_provider.createDispatcher(reference)); + return reference; + } + + private void sendMessage(final ServiceReference ref, final Object content) throws Exception { + new Thread(new Runnable() { + public void run() { + Exchange exchange = ref.createExchange(new MockHandler()); + exchange.send(exchange.createMessage().setContent(content)); + } + }).start(); + } + + class TakesForeverHandler extends BaseHandler { + public void handleMessage(Exchange exchange) throws HandlerException { + try { + Thread.sleep(exchange.getMessage().getContent(Integer.class)); + } catch (InterruptedException intEx) { + System.out.println("TakesForever thread interrupted!"); + } + } + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/ErrorExchangeHandler.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/ErrorExchangeHandler.java new file mode 100644 index 000000000..89075896e --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/ErrorExchangeHandler.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.HandlerException; + +/** + * An exchange handler which throws exception during message handling and + * error handling. + */ +public class ErrorExchangeHandler implements ExchangeHandler { + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + throw new HandlerException("Service is not implemented"); + } + + @Override + public void handleFault(Exchange exchange) { + // it's service handler this method will not be called + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/ExchangeDispatcherTest.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/ExchangeDispatcherTest.java new file mode 100644 index 000000000..14b4742df --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/ExchangeDispatcherTest.java @@ -0,0 +1,241 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.bus.camel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.apache.camel.impl.DefaultExchange; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.Property; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.common.camel.CamelContextConfigurator; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.internal.ServiceReferenceImpl; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.metadata.ServiceMetadataBuilder; +import org.switchyard.metadata.qos.Throttling; +import org.switchyard.spi.Dispatcher; + +public class ExchangeDispatcherTest { + + private static final String REQUEST = "REQUEST"; + private ServiceDomain _domain; + private CamelExchangeBus _provider; + private SwitchYardCamelContextImpl _camelContext; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + initDomain(_domain); + } + + @After + public void tearDown() throws Exception { + _camelContext.stop(); + } + + @Test + public void testDispatchInOnly() throws Exception { + QName name = new QName("testDispatchInOnly"); + ExchangeSink sink = new ExchangeSink(); + Service service = new MockService(name, new InOnlyService(), sink); + ServiceReference reference = new ServiceReferenceImpl(name, new InOnlyService(), null, null); + ExchangeDispatcher dispatch = _provider.createDispatcher(reference); + + Exchange exchange = new CamelExchange(dispatch, new DefaultExchange(_camelContext), sink); + exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + Message message = exchange.createMessage(); + exchange.send(message); + Thread.sleep(200); + + Assert.assertEquals( + message.getContext().getProperty(Exchange.MESSAGE_ID), + sink.getLastExchange().getMessage().getContext().getProperty(Exchange.MESSAGE_ID)); + } + + @Test + public void throttle() throws Exception { + QName name = new QName("testDispatchInOnly"); + final ExchangeSink sink = new ExchangeSink(1000); + final Service service = new MockService(name, new InOnlyService(), sink); + final ServiceReference reference = new ServiceReferenceImpl(name, new InOnlyService(), null, null); + final ExchangeDispatcher dispatch = _provider.createDispatcher(reference); + + // Set throttling to 1 per second + Throttling throttle = new Throttling().setMaxRequests(1); + ServiceMetadataBuilder.update(reference.getServiceMetadata()).throttling(throttle); + + final int NUM_SENDS = 5; + for (int i = 0; i < NUM_SENDS; i++) { + new Thread(new Runnable() { + public void run() { + Exchange exchange = dispatch.createExchange(sink, ExchangePattern.IN_ONLY); + exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + Message message = exchange.createMessage(); + exchange.send(message); + } + }).start(); + } + + Thread.sleep(500); + Assert.assertTrue("Concurrent requests were not throttled!", + sink.getReceivedCount() < NUM_SENDS); + } + + @Test + public void throttleWithTimePeriod() throws Exception { + ServiceDomain domain = new MockDomain(); + domain.setProperty(CamelContextConfigurator.SHUTDOWN_TIMEOUT, "5"); + initDomain(domain); + + QName name = new QName("testThrottleTimePeriod"); + final ExchangeSink sink = new ExchangeSink(); + final Service service = new MockService(name, new InOnlyService(), sink); + final ServiceReference reference = new ServiceReferenceImpl(name, new InOnlyService(), null, null); + // Set throttling to 1 per minute (60000 ms) + Throttling throttle = new Throttling().setMaxRequests(1).setTimePeriod(60 * 1000); + ServiceMetadataBuilder.update(reference.getServiceMetadata()).throttling(throttle); + + final ExchangeDispatcher dispatch = _provider.createDispatcher(reference); + + final int NUM_SENDS = 5; + for (int i = 0; i < NUM_SENDS; i++) { + new Thread(new Runnable() { + public void run() { + Exchange exchange = dispatch.createExchange(sink, ExchangePattern.IN_ONLY); + exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + Message message = exchange.createMessage(); + exchange.send(message); + } + }).start(); + } + + Thread.sleep(4000); + Assert.assertEquals("Received more than one message per minute - throttling policy violated!", + 1, sink.getReceivedCount()); + } + + @Test + public void testDispatchInOut() throws Exception { + QName name = new QName("testDispatchInOut"); + // provider handler + ExchangeSink inHandler = new ExchangeSink(true); + // consumer handler + ExchangeSink outHandler = new ExchangeSink(); + + Service service = new MockService(name, new InOutService(), inHandler); + ServiceReference reference = new ServiceReferenceImpl(name, new InOutService(), null, null); + Dispatcher dispatch = _provider.createDispatcher(reference); + + Exchange exchange = dispatch.createExchange(outHandler, ExchangePattern.IN_OUT); + exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + Message message = exchange.createMessage(); + exchange.send(message.setContent(REQUEST)); + Thread.sleep(400); + + Exchange lastExchange = outHandler.getLastExchange(); + assertNotNull(lastExchange); + +// assertEquals(REQUEST, lastExchange.getMessage().getContent()); + + Property messageId = message.getContext().getProperty(Exchange.MESSAGE_ID); + assertNotNull("Message id must be available after sending message and receiving response", messageId); + Property relatesTo = lastExchange.getContext().getProperty(Exchange.RELATES_TO); + assertNotNull("Relates to must be specified for outgoing message", relatesTo); + assertEquals("Relates to property should point to in message id", messageId.getValue(), relatesTo.getValue()); + } + + private void initDomain(ServiceDomain domain) throws Exception { + _camelContext = new SwitchYardCamelContextImpl(); + _camelContext.setServiceDomain(domain); + _provider = new CamelExchangeBus(_camelContext); + _provider.init(domain); + _camelContext.start(); + } + + /** + * Holds a reference to the most recent exchange received by the handler. + */ + class ExchangeSink extends BaseHandler { + + static final String REPLY = "REPLY"; + private Exchange _lastExchange; + private boolean _reply; + private int _wait; + private AtomicInteger _numExchanges = new AtomicInteger(); + + ExchangeSink() { + this(false); + } + + ExchangeSink(int wait) { + _wait = wait; + } + + ExchangeSink(boolean reply) { + _reply = reply; + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + _numExchanges.incrementAndGet(); + _lastExchange = exchange; + + try { + Thread.sleep(_wait); + } catch (InterruptedException ex) { + throw new RuntimeException(ex); + } + + if (_reply) { + exchange.getContext().setProperty(REPLY, true); + exchange.send(exchange.createMessage().setContent(REPLY)); + } + } + + public int getReceivedCount() { + return _numExchanges.get(); + } + + Exchange getLastExchange() { + return _lastExchange; + } + + } +} + diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/ExchangeEventsTest.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/ExchangeEventsTest.java new file mode 100644 index 000000000..e9706af45 --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/ExchangeEventsTest.java @@ -0,0 +1,169 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.bus.camel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.EventObject; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.apache.camel.impl.DefaultExchange; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.Property; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.event.EventObserver; +import org.switchyard.internal.ServiceReferenceImpl; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.runtime.event.ExchangeInitiatedEvent; +import org.switchyard.spi.Dispatcher; + +public class ExchangeEventsTest { + + private static final String REQUEST = "REQUEST"; + private ServiceDomain _domain; + private CamelExchangeBus _provider; + private SwitchYardCamelContextImpl _camelContext; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + _camelContext = new SwitchYardCamelContextImpl(); + _camelContext.setServiceDomain(_domain); + _provider = new CamelExchangeBus(_camelContext); + _provider.init(_domain); + _camelContext.start(); + } + + @After + public void tearDown() throws Exception { + _camelContext.stop(); + } + + @Test + public void testExchangeEventsForInOnly() throws Exception { + EventCounter counter = new EventCounter(); + _domain.addEventObserver(counter, ExchangeInitiatedEvent.class); + _domain.addEventObserver(counter, ExchangeCompletionEvent.class); + + QName name = new QName("testDispatchInOnly"); + ExchangeSink sink = new ExchangeSink(); + Service service = new MockService(name, new InOnlyService(), sink); + ServiceReference reference = new ServiceReferenceImpl(name, new InOnlyService(), null, null); + ExchangeDispatcher dispatch = _provider.createDispatcher(reference); + + Exchange exchange = new CamelExchange(dispatch, new DefaultExchange(_camelContext), sink); + exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + Message message = exchange.createMessage(); + exchange.send(message); + Thread.sleep(200); + + Assert.assertEquals(1, counter.initiatedCount); + Assert.assertEquals(1, counter.completedCount); + } + + @Test + public void testExchangeEventsForInOut() throws Exception { + EventCounter counter = new EventCounter(); + _domain.addEventObserver(counter, ExchangeInitiatedEvent.class); + _domain.addEventObserver(counter, ExchangeCompletionEvent.class); + + QName name = new QName("testDispatchInOut"); + // provider handler + ExchangeSink inHandler = new ExchangeSink(true); + // consumer handler + ExchangeSink outHandler = new ExchangeSink(); + + Service service = new MockService(name, new InOutService(), inHandler); + ServiceReference reference = new ServiceReferenceImpl(name, new InOutService(), null, null); + Dispatcher dispatch = _provider.createDispatcher(reference); + + Exchange exchange = dispatch.createExchange(outHandler, ExchangePattern.IN_OUT); + exchange.consumer(reference, reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + exchange.provider(service, service.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION)); + Message message = exchange.createMessage(); + exchange.send(message.setContent(REQUEST)); + Thread.sleep(400); + + Exchange lastExchange = outHandler.getLastExchange(); + assertNotNull(lastExchange); + + Assert.assertEquals(1, counter.initiatedCount); + Assert.assertEquals(1, counter.completedCount); + } + + class EventCounter implements EventObserver { + int initiatedCount; + int completedCount; + public void notify(EventObject event) { + if (event instanceof ExchangeInitiatedEvent) { + ++initiatedCount; + } else if (event instanceof ExchangeCompletionEvent) { + ++completedCount; + } + } + }; + + /** + * Holds a reference to the most recent exchange received by the handler. + */ + class ExchangeSink extends BaseHandler { + + static final String REPLY = "REPLY"; + private Exchange _lastExchange; + private boolean _reply; + + ExchangeSink() { + this(false); + } + + ExchangeSink(boolean reply) { + _reply = reply; + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + _lastExchange = exchange; + if (_reply) { + exchange.getContext().setProperty(REPLY, true); + exchange.send(exchange.createMessage().setContent(REPLY)); + } + } + + Exchange getLastExchange() { + return _lastExchange; + } + + } +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/MockService.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/MockService.java new file mode 100644 index 000000000..7b11c90b1 --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/MockService.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.bus.camel; + +import javax.xml.namespace.QName; + +import org.switchyard.ExchangeHandler; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceMetadata; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.metadata.ServiceMetadataBuilder; + +public class MockService implements Service { + + private QName _serviceName; + private ServiceInterface _serviceInterface; + private ExchangeHandler _handler; + + public MockService(QName serviceName, ExchangeHandler handler) { + this(serviceName, new InOnlyService(), handler); + } + + public MockService(QName serviceName, ServiceInterface serviceInterface, ExchangeHandler handler) { + _serviceName = serviceName; + _serviceInterface = serviceInterface; + _handler = handler; + } + + @Override + public QName getName() { + return _serviceName; + } + + @Override + public ServiceInterface getInterface() { + return _serviceInterface; + } + + @Override + public void unregister() { + + } + + @Override + public ServiceDomain getDomain() { + return null; + } + + @Override + public ExchangeHandler getProviderHandler() { + return _handler; + } + + @Override + public ServiceMetadata getServiceMetadata() { + return ServiceMetadataBuilder.create().build(); + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/ErrorInterceptor.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/ErrorInterceptor.java new file mode 100644 index 000000000..dd00a6a0d --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/ErrorInterceptor.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.handler; + +import java.util.Arrays; +import java.util.List; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeInterceptor; +import org.switchyard.HandlerException; + +/** + * Simple handler throwing exception during IN phase. + */ +public class ErrorInterceptor implements ExchangeInterceptor { + + private boolean waitForAfter; + private String target; + private int count; + + public ErrorInterceptor(boolean waitForAfter, String target) { + this.waitForAfter = waitForAfter; + this.target = target; + } + + @Override + public void before(String target, Exchange exchange) throws HandlerException { + ++count; + if (!waitForAfter) { + throw new HandlerException("Error before on target " + target); + } + } + + @Override + public void after(String target, Exchange exchange) throws HandlerException { + ++count; + if (waitForAfter) { + throw new HandlerException("Error after on target " + target); + } + } + + @Override + public List getTargets() { + return Arrays.asList(target); + } + + public int getCount() { + return count; + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorFaultHandler.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorFaultHandler.java new file mode 100644 index 000000000..23fb1fbd4 --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorFaultHandler.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.handler; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; + +/** + * Handler which throws standard exception during handling message and reports + * runtime exception during handling faults. + */ +public class RuntimeErrorFaultHandler extends BaseHandler { + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + throw new HandlerException("Standard processing exception"); + } + + @Override + public void handleFault(Exchange exchange) { + throw new RuntimeException("Fault processing error"); + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorInHandler.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorInHandler.java new file mode 100644 index 000000000..16e3bc7c5 --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorInHandler.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.handler; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; + +/** + * Exchange handler throwing runtime exception during IN phase. + */ +public class RuntimeErrorInHandler extends BaseHandler { + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + throw new RuntimeException("Runtime error"); + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorInterceptor.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorInterceptor.java new file mode 100644 index 000000000..c52a606da --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorInterceptor.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.handler; + +import java.util.Arrays; +import java.util.List; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeInterceptor; +import org.switchyard.HandlerException; + +/** + * Simple handler throwing exception during IN phase. + */ +public class RuntimeErrorInterceptor implements ExchangeInterceptor { + + private boolean waitForAfter; + private String target; + private int count; + + public RuntimeErrorInterceptor(boolean waitForAfter, String target) { + this.waitForAfter = waitForAfter; + this.target = target; + } + + @Override + public void before(String target, Exchange exchange) throws HandlerException { + ++count; + if (!waitForAfter) { + throw new RuntimeException("RuntimeException before on target " + target); + } + } + + @Override + public void after(String target, Exchange exchange) throws HandlerException { + ++count; + if (waitForAfter) { + throw new RuntimeException("RuntimeException after on target " + target); + } + } + + @Override + public List getTargets() { + return Arrays.asList(target); + } + + public int getCount() { + return count; + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorOutHandler.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorOutHandler.java new file mode 100644 index 000000000..1319db1ed --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/RuntimeErrorOutHandler.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.handler; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; + +/** + * Exchange handler which throws exception during OUT phase. + */ +public class RuntimeErrorOutHandler extends BaseHandler { + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + if (exchange.getPhase() == ExchangePhase.OUT) { + throw new RuntimeException("Outgoing runtime error"); + } + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/TypeInterceptor.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/TypeInterceptor.java new file mode 100644 index 000000000..e83db2132 --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/handler/TypeInterceptor.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.bus.camel.handler; + +import java.util.Arrays; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeInterceptor; +import org.switchyard.HandlerException; +import org.switchyard.Scope; + +/** + * Captures content types used on an exchange. + */ +public class TypeInterceptor implements ExchangeInterceptor { + + private QName inType; + private QName outType; + + + @Override + public void before(String target, Exchange exchange) throws HandlerException { + inType = (QName)exchange.getContext().getProperty(Exchange.CONTENT_TYPE, Scope.MESSAGE).getValue(); + } + + @Override + public void after(String target, Exchange exchange) throws HandlerException { + outType = (QName)exchange.getContext().getProperty(Exchange.CONTENT_TYPE, Scope.MESSAGE).getValue(); + + } + + @Override + public List getTargets() { + return Arrays.asList(PROVIDER); + } + + public QName getInType() { + return inType; + } + + public QName getOutType() { + return outType; + } + +} diff --git a/core/bus/camel/src/test/java/org/switchyard/bus/camel/processors/InterceptorProcessorTest.java b/core/bus/camel/src/test/java/org/switchyard/bus/camel/processors/InterceptorProcessorTest.java new file mode 100644 index 000000000..8a4d8882b --- /dev/null +++ b/core/bus/camel/src/test/java/org/switchyard/bus/camel/processors/InterceptorProcessorTest.java @@ -0,0 +1,62 @@ +package org.switchyard.bus.camel.processors; + +import junit.framework.Assert; + +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.ExchangeInterceptor; +import org.switchyard.MockDomain; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.handlers.MessageTraceHandler; + +public class InterceptorProcessorTest { + + private MockDomain _domain; + private SwitchYardCamelContextImpl _context; + private Exchange _exchange; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + _context = new SwitchYardCamelContextImpl(); + _context.setServiceDomain(_domain); + _context.start(); + _exchange = new DefaultExchange(_context); + } + + @Test + public void exchangeEnabled() throws Exception { + InterceptProcessor ip = new InterceptProcessor(ExchangeInterceptor.CONSUMER, _domain); + _exchange.setProperty(MessageTraceHandler.TRACE_ENABLED, true); + Assert.assertTrue(ip.traceEnabled(_exchange)); + _exchange.setProperty(MessageTraceHandler.TRACE_ENABLED, "true"); + Assert.assertTrue(ip.traceEnabled(_exchange)); + _exchange.setProperty(MessageTraceHandler.TRACE_ENABLED, false); + Assert.assertFalse(ip.traceEnabled(_exchange)); + _exchange.setProperty(MessageTraceHandler.TRACE_ENABLED, "false"); + Assert.assertFalse(ip.traceEnabled(_exchange)); + _exchange.setProperty(MessageTraceHandler.TRACE_ENABLED, null); + Assert.assertFalse(ip.traceEnabled(_exchange)); + } + + @Test + public void domainEnabled() throws Exception { + InterceptProcessor ip = new InterceptProcessor(ExchangeInterceptor.CONSUMER, _domain); + _domain.setProperty(MessageTraceHandler.TRACE_ENABLED, true); + Assert.assertTrue(ip.traceEnabled(_exchange)); + _domain.setProperty(MessageTraceHandler.TRACE_ENABLED, "true"); + Assert.assertTrue(ip.traceEnabled(_exchange)); + _domain.setProperty(MessageTraceHandler.TRACE_ENABLED, false); + Assert.assertFalse(ip.traceEnabled(_exchange)); + _domain.setProperty(MessageTraceHandler.TRACE_ENABLED, "false"); + Assert.assertFalse(ip.traceEnabled(_exchange)); + _domain.setProperty(MessageTraceHandler.TRACE_ENABLED, null); + Assert.assertFalse(ip.traceEnabled(_exchange)); + _domain.setProperty(MessageTraceHandler.TRACE_ENABLED, "blorg"); + Assert.assertFalse(ip.traceEnabled(_exchange)); + _domain.setProperty(MessageTraceHandler.TRACE_ENABLED, new Object()); + Assert.assertFalse(ip.traceEnabled(_exchange)); + } +} diff --git a/core/bus/camel/src/test/resources/configTest/hornetq-configuration.xml b/core/bus/camel/src/test/resources/configTest/hornetq-configuration.xml new file mode 100644 index 000000000..4d8a25c7f --- /dev/null +++ b/core/bus/camel/src/test/resources/configTest/hornetq-configuration.xml @@ -0,0 +1,45 @@ + + + + + target/configTest/bindings + target/configTest/journal + target/configTest/largemessages + target/configTest/paging + + + 65536 + + + + + + org.hornetq.core.remoting.impl.invm.InVMConnectorFactory + + + + + + + org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory + + + + + false + + + diff --git a/core/bus/camel/src/test/resources/log4j.xml b/core/bus/camel/src/test/resources/log4j.xml new file mode 100644 index 000000000..8705e7772 --- /dev/null +++ b/core/bus/camel/src/test/resources/log4j.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/common/camel/pom.xml b/core/common/camel/pom.xml new file mode 100644 index 000000000..6daeb05eb --- /dev/null +++ b/core/common/camel/pom.xml @@ -0,0 +1,82 @@ + + + + 4.0.0 + switchyard-common-camel + bundle + SwitchYard: Common - Camel + The SwitchYard Camel Common Library. + http://switchyard.org + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + + + org.switchyard.common.camel.* + + + javax.enterprise.inject.spi;resolution:=optional, + org.apache.camel.component.cdi*;resolution:=optional, + org.switchyard.common.cdi;resolution:=optional;${switchyard.osgi.import.switchyard.version}, + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-runtime + test-jar + test + + + org.apache.camel + camel-cdi + + + deltaspike-core-impl + org.apache.deltaspike.core + + + deltaspike-cdictrl-api + org.apache.deltaspike.cdictrl + + + + + org.apache.camel + camel-core + + + org.switchyard + switchyard-common-cdi + + + diff --git a/core/common/camel/src/main/java/org/switchyard/common/camel/CamelContextConfigurator.java b/core/common/camel/src/main/java/org/switchyard/common/camel/CamelContextConfigurator.java new file mode 100644 index 000000000..1e48852dd --- /dev/null +++ b/core/common/camel/src/main/java/org/switchyard/common/camel/CamelContextConfigurator.java @@ -0,0 +1,113 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.camel.CamelContext; +import org.apache.camel.CamelContextAware; +import org.apache.camel.ManagementStatisticsLevel; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; + +/** + * Utility class which encapsulates CamelContext configuration based on a + * set of properties. Putting this in a distinct class keeps the property + * constants in a single place and keeps the messy configuration code out + * of SwitchYardCamelContextImpl. + */ +public final class CamelContextConfigurator { + + /** + * Domain property used to configure the timeout value for ShutdownStrategy. + */ + public static final String SHUTDOWN_TIMEOUT = "org.switchyard.camel.ShutdownTimeout"; + + /** + * Domain property used to configure the statistics level for Camel management. The + * value of this property corresponds to the string value of the ManagementStatisticsLevel enum. + */ + public static final String PERFORMANCE_STATISTICS = + "org.switchyard.camel.PerformanceStatistics"; + + /** + * Property which contains the fully-qualified name of a class which implements + * CamelContextAware and can be used to configure the CamelContext used within SwitchYard. + */ + public static final String CAMEL_CONTEXT_CONFIG = + "org.switchyard.camel.CamelContextConfiguration"; + + private CamelContextConfigurator() { + // prevent direct instantiation + } + + /** + * Configure CamelContext based on a ServiceDomain instance. + * @param context CamelContext to configure + * @param domain domain used to configure CamelContext + */ + public static final void configure(CamelContext context, ServiceDomain domain) { + configure(context, domain.getProperties()); + } + + /** + * Configure CamelContext based on a map of properties. + * @param context CamelContext to configure + * @param properties properties to configure + */ + public static final void configure(CamelContext context, Map properties) { + for (Entry property : properties.entrySet()) { + if (property.getValue() != null) { + configure(context, property.getKey(), property.getValue()); + } + } + } + + /** + * Configure CamelContext instance with a property name/value. + * @param context CamelContext to configure + * @param name config property name + * @param value config property value + */ + public static final void configure(CamelContext context, String name, Object value) { + try { + if (name.equals(SHUTDOWN_TIMEOUT)) { + configureShutdownTimeout(context, value); + } else if (name.equals(PERFORMANCE_STATISTICS)) { + configurePerformanceStatistics(context, value); + } else if (name.equals(CAMEL_CONTEXT_CONFIG)) { + configureCamelContextAware(context, value); + } + } catch (Exception ex) { + CommonCamelLogger.ROOT_LOGGER.camelContextConfigurationError(name, value, ex); + } + } + + private static void configureShutdownTimeout(CamelContext context, Object value) { + int timeout = Integer.parseInt(value.toString()); + context.getShutdownStrategy().setTimeout(timeout); + } + + private static void configurePerformanceStatistics(CamelContext context, Object value) { + ManagementStatisticsLevel level = ManagementStatisticsLevel.valueOf(value.toString()); + context.getManagementStrategy().setStatisticsLevel(level); + } + + private static void configureCamelContextAware(CamelContext context, Object value) throws Exception { + Class contextAwareClass = Classes.forName(value.toString()); + CamelContextAware contextAware = (CamelContextAware)contextAwareClass.newInstance(); + contextAware.setCamelContext(context); + } +} diff --git a/core/common/camel/src/main/java/org/switchyard/common/camel/CommonCamelLogger.java b/core/common/camel/src/main/java/org/switchyard/common/camel/CommonCamelLogger.java new file mode 100644 index 000000000..068069a39 --- /dev/null +++ b/core/common/camel/src/main/java/org/switchyard/common/camel/CommonCamelLogger.java @@ -0,0 +1,40 @@ +package org.switchyard.common.camel; + +import static org.jboss.logging.Logger.Level.WARN; + +import org.jboss.logging.Logger; + +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 13200-13399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface CommonCamelLogger { + /** + * Default root logger. + */ + CommonCamelLogger ROOT_LOGGER = Logger.getMessageLogger(CommonCamelLogger.class, CommonCamelLogger.class.getPackage().getName()); + + /** + * cdiNotDetected method definition. + */ + @LogMessage(level = WARN) + @Message(id = 13200, value="CDI environment not detected, disabling Camel CDI integration") + void cdiNotDetected(); + + /** + * camelContextConfigurationError method definition. + * @param propertyName name of the property + * @param propertyValue value of the property + * @param error error when configuring property + */ + @LogMessage(level = WARN) + @Message(id = 13201, value="Unable to set camel context configuration [name = %s, value = %s] : %s") + void camelContextConfigurationError(String propertyName, Object propertyValue, Exception error); + +} diff --git a/core/common/camel/src/main/java/org/switchyard/common/camel/ContextPropertyUtil.java b/core/common/camel/src/main/java/org/switchyard/common/camel/ContextPropertyUtil.java new file mode 100644 index 000000000..3ec2dc6b0 --- /dev/null +++ b/core/common/camel/src/main/java/org/switchyard/common/camel/ContextPropertyUtil.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import org.switchyard.Scope; + +/** + * Utility class for filtering system reserved properties from exchange and message headers. + */ +public final class ContextPropertyUtil { + + private ContextPropertyUtil() { + + } + + /** + * Utility method to verify if given property name is reserved for internal + * usage. + * + * @param propertyName Name of camel exchange property or header. + * @param scope Scope of the property. + * @return True if property is used internally. + */ + public static boolean isReservedProperty(String propertyName, Scope scope) { + return propertyName.startsWith("org.switchyard.bus.camel") + || propertyName.startsWith("org.switchyard.component.camel"); + } +} diff --git a/core/common/camel/src/main/java/org/switchyard/common/camel/HandlerDataSource.java b/core/common/camel/src/main/java/org/switchyard/common/camel/HandlerDataSource.java new file mode 100644 index 000000000..435f10471 --- /dev/null +++ b/core/common/camel/src/main/java/org/switchyard/common/camel/HandlerDataSource.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.activation.DataHandler; +import javax.activation.DataSource; + +/** + * An extension of DataHandler which implements {@link DataSource} interface. + * As result instances of this class may be used as {@link DataHandler} and {@link DataSource}. + */ +public class HandlerDataSource extends DataHandler implements DataSource { + + /** + * Creates new handler. + * + * @param handler Handler to wrap. + */ + public HandlerDataSource(DataHandler handler) { + super(handler.getDataSource()); + } + + @Override + public String getContentType() { + return getDataSource().getContentType(); + } + + @Override + public InputStream getInputStream() throws IOException { + return getDataSource().getInputStream(); + } + + @Override + public String getName() { + return getDataSource().getName(); + } + + @Override + public OutputStream getOutputStream() throws IOException { + return getDataSource().getOutputStream(); + } + +} diff --git a/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardCamelContext.java b/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardCamelContext.java new file mode 100644 index 000000000..5e3a85fe9 --- /dev/null +++ b/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardCamelContext.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import org.apache.camel.impl.SimpleRegistry; +import org.apache.camel.model.ModelCamelContext; +import org.switchyard.ServiceDomain; + +/** + * Extension of default camel context. Supports access to mutable registry and + * provides integration with SwitchYard eventing model. + */ +public interface SwitchYardCamelContext extends ModelCamelContext { + + /** + * Context property name used to store camel context as service domain property. + */ + public static final String CAMEL_CONTEXT_PROPERTY = "CamelContextProperty"; + + /** + * Gets SwitchYard domain associated with this context. + * + * @return SwitchYard domain. + */ + public ServiceDomain getServiceDomain(); + + /** + * Gets mutable registry associated with context. Allows to dynamically register + * bean instances. + * + * @return Registry which allows to put new objects. + */ + public SimpleRegistry getWritebleRegistry(); +} diff --git a/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardCamelContextImpl.java b/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardCamelContextImpl.java new file mode 100644 index 000000000..8c992b5f6 --- /dev/null +++ b/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardCamelContextImpl.java @@ -0,0 +1,216 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import java.util.ArrayList; +import java.util.List; +import java.util.ServiceLoader; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.camel.cdi.CdiBeanRegistry; +import org.apache.camel.cdi.CdiInjector; +import org.apache.camel.impl.CompositeRegistry; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.JndiRegistry; +import org.apache.camel.impl.SimpleRegistry; +import org.apache.camel.spi.EventNotifier; +import org.apache.camel.spi.PackageScanClassResolver; +import org.apache.camel.spi.Registry; +import org.switchyard.ServiceDomain; +import org.switchyard.common.camel.event.CamelEventBridge; +import org.switchyard.common.cdi.CDIUtil; + +/** + * Extension of default camel context. Supports access to mutable registry and + * provides integration with SwitchYard eventing model. + */ +public class SwitchYardCamelContextImpl extends DefaultCamelContext implements SwitchYardCamelContext { + + private final SimpleRegistry _writeableRegistry = new SimpleRegistry(); + private ServiceDomain _domain; + + private AtomicInteger _count = new AtomicInteger(); + + private static final int DEFAULT_TIMEOUT = 30; + + /** + * Flag to turn on/off cdi integration. + */ + private boolean _cdiIntegration; + + /** + * Creates new camel context. + */ + public SwitchYardCamelContextImpl() { + this(true); + } + + /** + * Creates new camel context. + * @param autoDetectCdi Should cdi integration be auto detected and enabled. + */ + public SwitchYardCamelContextImpl(boolean autoDetectCdi) { + _cdiIntegration = autoDetectCdi; + if (isEnableCdiIntegration()) { + CDISupport.setCdiInjector(this); + } else { + CommonCamelLogger.ROOT_LOGGER.cdiNotDetected(); + } + getManagementStrategy().addEventNotifier(new CamelEventBridge()); + } + + /** + * Associates camel context with given service domain. + * + * @param domain Domain to associate. + */ + public void setServiceDomain(ServiceDomain domain) { + _domain = domain; + + for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) { + if (notifier instanceof CamelEventBridge) { + ((CamelEventBridge) notifier).setEventPublisher(domain.getEventPublisher()); + } + } + + PackageScanClassResolver packageScanClassResolver = findPackageScanClassResolver(); + if (packageScanClassResolver != null) { + setPackageScanClassResolver(packageScanClassResolver); + } + + _domain.setProperty(CAMEL_CONTEXT_PROPERTY, this); + } + + /** + * Gets mutable registry associated with context. Allows to dynamically register + * bean instances. + * + * @return Registry which allows to put new objects. + */ + public SimpleRegistry getWritebleRegistry() { + return _writeableRegistry; + } + + /** + * Get the first PackageScanClassResolver Service found on the classpath. + * + * @return The first PackageScanClassResolver Service found on the classpath. + */ + public PackageScanClassResolver findPackageScanClassResolver() { + final ServiceLoader resolverLoaders = ServiceLoader.load(PackageScanClassResolver.class); + + for (PackageScanClassResolver packageScanClassResolver : resolverLoaders) { + return packageScanClassResolver; + } + + return null; + } + + protected CompositeRegistry createRegistry() { + final ServiceLoader registriesLoaders = ServiceLoader.load(Registry.class, getClass().getClassLoader()); + + final List registries = new ArrayList(); + registries.add(new JndiRegistry()); + if (isEnableCdiIntegration()) { + registries.add(new CdiBeanRegistry()); + } + registries.add(_writeableRegistry); + + for (Registry registry : registriesLoaders) { + registries.add(registry); + } + + return new CompositeRegistry(registries); + } + + /** + * Gets SwitchYard domain associated with this context. + * + * @return SwitchYard domain. + */ + public ServiceDomain getServiceDomain() { + return _domain; + } + + /** + * Checks if CDI runtime is enabled for this deployment. + * + * @return True if CDI runtime is detected. + */ + public boolean isEnableCdiIntegration() { + if (!_cdiIntegration) { + return false; + } + return CDISupport.isCDIEnabled(); + } + + /** + * Start camel context and/or increment counter with number of start attempts. + * + * @throws Exception is thrown if starting failed + */ + @Override + public void start() throws Exception { + if (_count.incrementAndGet() == 1) { + applyConfiguration(); + super.start(); + } + } + + /** + * Decrement counter with number of start attempts and/or stop camel context. + * + * @throws Exception is thrown if stopping failed + */ + @Override + public void stop() throws Exception { + if (_count.decrementAndGet() == 0) { + super.stop(); + } + } + + // Applies domain configuration to this camel context + private void applyConfiguration() { + if (_domain == null || _domain.getProperties() == null) { + // no config to apply + return; + } + + // set shutdown timeout default - this can still be overriden by domain props + getShutdownStrategy().setTimeout(DEFAULT_TIMEOUT); + + // configure context with domain properties + CamelContextConfigurator.configure(this, _domain); + } + + static class CDISupport { + + static boolean isCDIEnabled() { + try { + return CDIUtil.lookupBeanManager() != null; + } catch (NoClassDefFoundError e) { + return false; + } + } + + static void addCdiRegistry(List registries) { + registries.add(new CdiBeanRegistry()); + } + + public static void setCdiInjector(SwitchYardCamelContextImpl context) { + context.setInjector(new CdiInjector(context.getInjector())); + } + } + +} diff --git a/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardMessage.java b/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardMessage.java new file mode 100644 index 000000000..8907a793a --- /dev/null +++ b/core/common/camel/src/main/java/org/switchyard/common/camel/SwitchYardMessage.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.camel.impl.DefaultMessage; + +/** + * An extension of camel default message implementation which uses traditional + * case sensitive hash map for storing headers. + */ +public class SwitchYardMessage extends DefaultMessage { + + @Override + protected Map createHeaders() { + return new HashMap(); + } + + @Override + public DefaultMessage newInstance() { + return new SwitchYardMessage(); + } + +} diff --git a/core/common/camel/src/main/java/org/switchyard/common/camel/event/CamelEventBridge.java b/core/common/camel/src/main/java/org/switchyard/common/camel/event/CamelEventBridge.java new file mode 100644 index 000000000..04bde870e --- /dev/null +++ b/core/common/camel/src/main/java/org/switchyard/common/camel/event/CamelEventBridge.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel.event; + +import java.util.EventObject; + +import org.apache.camel.support.EventNotifierSupport; +import org.switchyard.event.EventPublisher; + +/** + * Event bridge, sends camel events through SwitchYard {@link EventPublisher}. + */ +public class CamelEventBridge extends EventNotifierSupport { + + private EventPublisher _publisher; + + /** + * Creates new event bridge from camel to SwitchYard. + * + * @param publisher Event publisher. + */ + public CamelEventBridge(EventPublisher publisher) { + _publisher = publisher; + } + + /** + * Creates new event bridge without event publisher instance. + */ + public CamelEventBridge() { + } + + /** + * Sets event publisher for bridge. + * + * @param publisher Event publisher to use. + */ + public void setEventPublisher(EventPublisher publisher) { + _publisher = publisher; + } + + @Override + public void notify(EventObject event) throws Exception { + _publisher.publish(event); + } + + @Override + public boolean isEnabled(EventObject event) { + return _publisher != null; + } + + @Override + protected void doStart() throws Exception { + // noop + } + + @Override + protected void doStop() throws Exception { + // noop + } +} + diff --git a/core/common/camel/src/test/java/org/switchyard/common/camel/CamelContextConfiguratorTest.java b/core/common/camel/src/test/java/org/switchyard/common/camel/CamelContextConfiguratorTest.java new file mode 100644 index 000000000..f3c43d421 --- /dev/null +++ b/core/common/camel/src/test/java/org/switchyard/common/camel/CamelContextConfiguratorTest.java @@ -0,0 +1,107 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.CamelContextAware; +import org.apache.camel.ManagementStatisticsLevel; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.MockDomain; +import org.switchyard.ServiceDomain; + +/** + * Test configuration of CamelContext through properties and a callback class. + */ +public class CamelContextConfiguratorTest { + + private SwitchYardCamelContextImpl context; + private ServiceDomain domain; + + @Before + public void setUp() { + context = new SwitchYardCamelContextImpl(); + domain = new MockDomain(); + context.setServiceDomain(domain); + } + + @Test + public void configureShutdownTimeout() throws Exception { + final int timeout = 12345; + domain.setProperty(CamelContextConfigurator.SHUTDOWN_TIMEOUT, timeout); + CamelContextConfigurator.configure(context, domain); + Assert.assertEquals(timeout, context.getShutdownStrategy().getTimeout()); + } + + @Test + public void configurePerformanceStatistics() throws Exception { + domain.setProperty(CamelContextConfigurator.PERFORMANCE_STATISTICS, "RoutesOnly"); + CamelContextConfigurator.configure(context, domain); + Assert.assertEquals(ManagementStatisticsLevel.RoutesOnly, + context.getManagementStrategy().getStatisticsLevel()); + + domain.setProperty(CamelContextConfigurator.PERFORMANCE_STATISTICS, "Off"); + CamelContextConfigurator.configure(context, domain); + Assert.assertEquals(ManagementStatisticsLevel.Off, + context.getManagementStrategy().getStatisticsLevel()); + + domain.setProperty(CamelContextConfigurator.PERFORMANCE_STATISTICS, "All"); + CamelContextConfigurator.configure(context, domain); + Assert.assertEquals(ManagementStatisticsLevel.All, + context.getManagementStrategy().getStatisticsLevel()); + } + + @Test + public void configureCamelContextAware() throws Exception { + // specify the CamelContextAware class + domain.setProperty(CamelContextConfigurator.CAMEL_CONTEXT_CONFIG, + MyCustomContextAware.class.getName()); + + // configure the context and check results + CamelContextConfigurator.configure(context, domain); + Assert.assertNotNull(context.getProperty("abc")); + Assert.assertEquals("xyz", context.getProperty("abc")); + } +} + +class MyCustomContextAware implements CamelContextAware { + + private CamelContext context; + private Map customProps; + + public MyCustomContextAware() { + customProps = new HashMap(); + customProps.put("abc", "xyz"); + } + + MyCustomContextAware(Map props) { + customProps = props; + } + + @Override + public void setCamelContext(CamelContext camelContext) { + context = camelContext; + camelContext.setProperties(customProps); + } + + @Override + public CamelContext getCamelContext() { + return context; + } + +} diff --git a/core/common/camel/src/test/java/org/switchyard/common/camel/CamelEventBridgeTest.java b/core/common/camel/src/test/java/org/switchyard/common/camel/CamelEventBridgeTest.java new file mode 100644 index 000000000..7f74e683c --- /dev/null +++ b/core/common/camel/src/test/java/org/switchyard/common/camel/CamelEventBridgeTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import static org.junit.Assert.assertTrue; + +import java.util.EventObject; + +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.management.event.CamelContextStartedEvent; +import org.apache.camel.management.event.CamelContextStoppedEvent; +import org.junit.Test; +import org.switchyard.common.camel.event.CamelEventBridge; +import org.switchyard.event.EventObserver; +import org.switchyard.internal.EventManager; + +/** + * Test of event forwarding from Camel to SwitchYard. + */ +public class CamelEventBridgeTest { + + @Test + public void testEventBridge() throws Exception { + EventManager eventManager = new EventManager(); + CountingObserver observer = new CountingObserver(); + eventManager.addObserver(observer, CamelContextStartedEvent.class); + eventManager.addObserver(observer, CamelContextStoppedEvent.class); + + CamelEventBridge eventBridge = new CamelEventBridge(eventManager); + DefaultCamelContext context = new DefaultCamelContext(); + context.getManagementStrategy().addEventNotifier(eventBridge); + + assertTrue(observer.counter == 0); + context.start(); + assertTrue(observer.counter == 1); + context.stop(); + assertTrue(observer.counter == 2); + } + +} + +/** + * Dummy observer, do not collect events, just count them. + */ +class CountingObserver implements EventObserver { + + int counter; + + @Override + public void notify(EventObject event) { + counter++; + } + +} diff --git a/core/common/camel/src/test/java/org/switchyard/common/camel/SwitchYardCamelContextLifecycleTest.java b/core/common/camel/src/test/java/org/switchyard/common/camel/SwitchYardCamelContextLifecycleTest.java new file mode 100644 index 000000000..337578c13 --- /dev/null +++ b/core/common/camel/src/test/java/org/switchyard/common/camel/SwitchYardCamelContextLifecycleTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.camel; + +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.MockDomain; + +/** + * Test start/stop behavior in camel context extension. + */ +public class SwitchYardCamelContextLifecycleTest { + + private SwitchYardCamelContextImpl context; + + @Before + public void setUp() { + context = new SwitchYardCamelContextImpl(); + context.setServiceDomain(new MockDomain()); + } + + @Test + public void startOnce() throws Exception { + context.start(); + assertTrue(context.isStarted()); + context.start(); + context.stop(); + assertTrue(context.isStarted()); + context.stop(); + assertTrue(context.isStopped()); + } +} diff --git a/core/common/cdi/pom.xml b/core/common/cdi/pom.xml new file mode 100644 index 000000000..165d55de6 --- /dev/null +++ b/core/common/cdi/pom.xml @@ -0,0 +1,47 @@ + + + + 4.0.0 + switchyard-common-cdi + bundle + SwitchYard: Common - CDI + The SwitchYard Common CDI Library. + http://switchyard.org + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + + org.switchyard.common.cdi.* + + + + + org.apache.deltaspike.core + deltaspike-core-api + + + javax.enterprise + cdi-api + + + org.osgi + org.osgi.core + provided + + + diff --git a/core/common/cdi/src/main/java/org/switchyard/common/cdi/CDIUtil.java b/core/common/cdi/src/main/java/org/switchyard/common/cdi/CDIUtil.java new file mode 100644 index 000000000..7283f22c8 --- /dev/null +++ b/core/common/cdi/src/main/java/org/switchyard/common/cdi/CDIUtil.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.cdi; + + +import javax.enterprise.context.spi.CreationalContext; +import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.BeanManager; +import javax.inject.Named; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import java.util.Set; +/** + * CDI bean utilities. + */ +public final class CDIUtil { + + private CDIUtil() {} + + /** + * Looks up a BeanManager. + * @return BeanManager instance + */ + public static BeanManager lookupBeanManager() { + BeanManager beanManager = getCDIBeanManager("java:comp"); + if (beanManager == null) { + beanManager = getCDIBeanManager("java:comp/env"); + } + if (beanManager == null) { + beanManager = getOSGICDIBeanManager(); + } + return beanManager; + } + + /** + * Looks up a CDI Bean. + * @param name bean name + * @return bean instance + */ + public static Object lookupBean(String name) { + BeanManager manager = lookupBeanManager(); + Set> beans = manager.getBeans(name); + if (beans != null && !beans.isEmpty()) { + Bean bean = beans.iterator().next(); + CreationalContext context = manager.createCreationalContext(bean); + return manager.getReference(bean, Object.class, context); + } + return null; + } + + /** + * Gets a value of @Named annotation for the specified class. + * @param clazz class object + * @return bean name + */ + public static String getNamedAnnotationValue(Class clazz) { + Named named = clazz.getAnnotation(Named.class); + if (named == null) { + return null; + } + return named.value(); + } + + private static BeanManager getCDIBeanManager(String jndiLocation) { + Context javaComp = getJavaComp(jndiLocation); + + if (javaComp != null) { + try { + return (BeanManager) javaComp.lookup("BeanManager"); + } catch (NamingException e) { + return null; + } + } else { + return null; + } + } + + private static Context getJavaComp(String jndiName) { + InitialContext initialContext = null; + + try { + initialContext = new InitialContext(); + return (Context) initialContext.lookup(jndiName); + } catch (NamingException e) { + return null; + } catch (Exception e) { + throw new IllegalStateException("Unexpected Exception retrieving '" + jndiName + "' from JNDI namespace.", e); + } finally { + if (initialContext != null) { + try { + initialContext.close(); + } catch (NamingException e) { + throw new IllegalStateException("Unexpected error closing InitialContext.", e); + } + } + } + } + + private static BeanManager getOSGICDIBeanManager() { + try { + return OSGICDISupport.getBeanManager(); + } catch (Throwable t) { + return null; + } + } + +} diff --git a/core/common/cdi/src/main/java/org/switchyard/common/cdi/OSGICDISupport.java b/core/common/cdi/src/main/java/org/switchyard/common/cdi/OSGICDISupport.java new file mode 100644 index 000000000..dd8fd357b --- /dev/null +++ b/core/common/cdi/src/main/java/org/switchyard/common/cdi/OSGICDISupport.java @@ -0,0 +1,53 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.cdi; + +import java.lang.reflect.Method; + +import javax.enterprise.inject.spi.BeanManager; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleReference; +import org.osgi.framework.ServiceReference; + +/** + * Retrieve the BeanManager from the CdiContainer service. + */ +final class OSGICDISupport { + /** + * Retrieve the BeanManager from the CdiContainer service. + */ + static BeanManager getBeanManager() throws Exception { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + if (classLoader instanceof BundleReference) { + Bundle bundle = ((BundleReference) classLoader).getBundle(); + ServiceReference[] refs = bundle.getBundleContext().getServiceReferences( + "org.ops4j.pax.cdi.spi.CdiContainer", "(bundleId=" + bundle.getBundleId() + ")"); + if (refs != null && refs.length == 1) { + Object cdiContainer = bundle.getBundleContext().getService(refs[0]); + try { + Method method = cdiContainer.getClass().getMethod("getBeanManager"); + return (BeanManager) method.invoke(cdiContainer); + } finally { + bundle.getBundleContext().ungetService(refs[0]); + } + } + } + return null; + } + + private OSGICDISupport() { + } + +} diff --git a/core/common/core/pom.xml b/core/common/core/pom.xml new file mode 100644 index 000000000..467d5456e --- /dev/null +++ b/core/common/core/pom.xml @@ -0,0 +1,32 @@ + + + + 4.0.0 + switchyard-common + bundle + SwitchYard: Common + The SwitchYard Common Library. + http://switchyard.org + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + + org.switchyard.common.* + + + diff --git a/core/common/core/src/main/java/org/switchyard/common/CommonCoreLogger.java b/core/common/core/src/main/java/org/switchyard/common/CommonCoreLogger.java new file mode 100644 index 000000000..6c3165bbc --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/CommonCoreLogger.java @@ -0,0 +1,68 @@ +package org.switchyard.common; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.WARN; + +import java.io.File; + +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +import org.jboss.logging.Logger; + +/** + *

+ * This file is using the subset 11200-11399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface CommonCoreLogger { + /** + * Default root logger. + */ + CommonCoreLogger ROOT_LOGGER = Logger.getMessageLogger(CommonCoreLogger.class, CommonCoreLogger.class.getPackage().getName()); + + /** + * exceptionSystemProperties method definition. + * @param se SecurityException + */ + @LogMessage(level = ERROR) + @Message(id = 11200, value="SecurityException while getting System Properties; will default to empty Properties") + void exceptionSystemProperties(@Cause SecurityException se); + + /** + * unknownClasspathURL method definition. + * @param path path + */ + @LogMessage(level = WARN) + @Message(id = 11201, value="Unknown Classpath URL File '%s'.") + void unknownClasspathURL(String path); + + /** + * problemReadingStream method definition. + * @param url url + * @param message message + */ + @LogMessage(level = WARN) + @Message(id = 11202, value="problem reading %s stream: %s") + void problemReadingStream(String url, String message); + + /** + * problemClosingStream method definition. + * @param url url + * @param message message + */ + @LogMessage(level = WARN) + @Message(id = 11203, value="problem closing %s stream: %s") + void problemClosingStream(String url, String message); + + /** + * problemCreatingDirectory method definition. + * @param directory directory + */ + @LogMessage(level = WARN) + @Message(id = 11204, value="problem creating directory: %s") + void problemCreatingDirectory(File directory); +} diff --git a/core/common/core/src/main/java/org/switchyard/common/CommonCoreMessages.java b/core/common/core/src/main/java/org/switchyard/common/CommonCoreMessages.java new file mode 100644 index 000000000..1254d5315 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/CommonCoreMessages.java @@ -0,0 +1,54 @@ +package org.switchyard.common; + +import java.io.IOException; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.common.io.pull.PropertiesPuller.PropertiesType; + +/** + *

+ * This file is using the subset 11400-11599 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface CommonCoreMessages { + /** + * Default messages. + */ + CommonCoreMessages MESSAGES = Messages.getBundle(CommonCoreMessages.class); + + /** + * nameNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 11400, value = "name == null") + IllegalArgumentException nameNull(); + + /** + * invalidCall method definition. + * @return RuntimeException + */ + @Message(id = 11405, value = ("Invalid call. Not a Java message type. " + + "Use isJavaMessageType before calling this method.")) + RuntimeException invalidCall(); + + /** + * couldNotDeleteFile method definition. + * @param filename filename˙ + * @return IOException + */ + @Message(id = 11406, value = ("Could not delete %s")) + IOException couldNotDeleteFile(String filename); + + /** + * unsupportedPropertiesTypeForMethod method definition. + * @param propertiesType propertiesType + * @param method method + * @return IOException + */ + @Message(id = 11407, value = ("Unsupported properties type %s for method %s")) + IOException unsupportedPropertiesTypeForMethod(PropertiesType propertiesType, String method); +} diff --git a/core/common/core/src/main/java/org/switchyard/common/codec/Base64.java b/core/common/core/src/main/java/org/switchyard/common/codec/Base64.java new file mode 100644 index 000000000..a16118f32 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/codec/Base64.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.codec; + +import java.nio.charset.Charset; + +import javax.xml.bind.DatatypeConverter; + +/** + * Base64 utilities. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class Base64 { + + /** + * Encodes a byte array to a Base64-encoded String. + * @param bytes the byte array + * @return the Base64-encoded String + */ + public static final String encode(byte[] bytes) { + return DatatypeConverter.printBase64Binary(bytes); + } + + /** + * Encodes a String to a Base64-encoded String, first obtaining the bytes using the platform-default charset. + * @param value the String + * @return the Base64-encoded String + */ + public static final String encodeFromString(String value) { + return encodeFromString(value, Charset.defaultCharset()); + } + + /** + * Encodes a String to a Base64-encoded String, first obtaining the bytes using the specified charset name. + * @param value the String + * @param charsetName the specified charset name + * @return the Base64-encoded String + */ + public static final String encodeFromString(String value, String charsetName) { + return encodeFromString(value, Charset.forName(charsetName)); + } + + /** + * Encodes a String to a Base64-encoded String, first obtaining the bytes using the specified charset. + * @param value the String + * @param charset the specified charset + * @return the Base64-encoded String + */ + public static final String encodeFromString(String value, Charset charset) { + return encode(value.getBytes(charset)); + } + + /** + * Decodes a Base64-encoded String to a byte array. + * @param encoded the Base64-encoded String + * @return the byte array + */ + public static final byte[] decode(String encoded) { + return DatatypeConverter.parseBase64Binary(encoded); + } + + /** + * Decodes a Base64-encoded String to String, constructed with the platform-default charset. + * @param encoded the Bas64-encoded String + * @return the decoded String + */ + public static final String decodeToString(String encoded) { + return decodeToString(encoded, Charset.defaultCharset()); + } + + /** + * Decodes a Base64-encoded String to String, constructed with the specified charset name. + * @param encoded the Bas64-encoded String + * @param charsetName the specified charset name + * @return the decoded String + */ + public static final String decodeToString(String encoded, String charsetName) { + return decodeToString(encoded, Charset.forName(charsetName)); + } + + /** + * Decodes a Base64-encoded String to String, constructed with the specified charset. + * @param encoded the Bas64-encoded String + * @param charset the specified charset + * @return the decoded String + */ + public static final String decodeToString(String encoded, Charset charset) { + return new String(decode(encoded), charset); + } + + private Base64() {} + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/Buffers.java b/core/common/core/src/main/java/org/switchyard/common/io/Buffers.java new file mode 100644 index 000000000..398ed4317 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/Buffers.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io; + +import java.io.BufferedInputStream; + +/** + * Buffer utilities. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class Buffers { + + /** + * The platform-default buffer size. + */ + public static final int DEFAULT_SIZE = new DefaultSize().get(); + + private Buffers() {}; + + private static final class DefaultSize extends BufferedInputStream { + private DefaultSize() { + super(null); + } + private int get() { + return super.buf.length; + } + } + + /** + * Creates an empty byte array for buffering purposes, using the platform-default buffer size. + * @return the empty byte array + */ + public static byte[] newDefaultBuffer() { + return new byte[DEFAULT_SIZE]; + } + + /** + * Prints defaults. + * @param args ignored + */ + public static void main(String... args) { + System.out.println("DEFAULT_SIZE = " + DEFAULT_SIZE); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/CountingOutputStream.java b/core/common/core/src/main/java/org/switchyard/common/io/CountingOutputStream.java new file mode 100644 index 000000000..e6037d3ec --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/CountingOutputStream.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * An OutputStream that keeps track of the number of bytes written to it. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class CountingOutputStream extends OutputStream { + + private final OutputStream _out; + private int _count; + + /** + * Wraps a given OutputSteam. + * @param out the wrapped OutputStream + */ + public CountingOutputStream(OutputStream out) { + _out = out; + } + + /** + * {@inheritDoc} + */ + @Override + public void write(byte[] b) throws IOException { + _out.write(b); + _count += b.length; + } + + /** + * {@inheritDoc} + */ + @Override + public void write(byte[] b, int off, int len) throws IOException { + _out.write(b, off, len); + _count += len; + } + + /** + * {@inheritDoc} + */ + @Override + public void write(int b) throws IOException { + _out.write(b); + _count++; + } + + /** + * {@inheritDoc} + */ + @Override + public void flush() throws IOException { + _out.flush(); + } + + /** + * {@inheritDoc} + */ + @Override + public void close() throws IOException { + _out.close(); + } + + /** + * Retrieves the number of bytes written. + * @return the number of bytes written + */ + public int getCount() { + return _count; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/Files.java b/core/common/core/src/main/java/org/switchyard/common/io/Files.java new file mode 100644 index 000000000..e90623739 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/Files.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +import org.switchyard.common.CommonCoreLogger; +import org.switchyard.common.CommonCoreMessages; + +/** + * File utilities. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class Files { + + /** + * Copies one file on top of the other. + * @param source the source file + * @param target the destination file + * @throws IOException something went wanky + */ + public static final void copy(File source, File target) throws IOException { + copy(source, target, Buffers.DEFAULT_SIZE); + } + + /** + * Copies one file on top of the other. + * @param source the source file + * @param target the destination file + * @param bufferSize the buffer size to use + * @throws IOException something went wanky + */ + public static final void copy(File source, File target, int bufferSize) throws IOException { + File targetParent = target.getParentFile(); + if (targetParent != null && !targetParent.exists()) { + if (!targetParent.mkdirs()) { + CommonCoreLogger.ROOT_LOGGER.problemCreatingDirectory(targetParent); + } + } + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source)); + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target)); + byte[] buff = new byte[bufferSize]; + int read; + try { + while ((read = bis.read(buff)) != -1) { + bos.write(buff, 0, read); + } + } finally { + bos.flush(); + bos.close(); + bis.close(); + } + } + + /** + * Deletes a file or folder. If a folder all contents will be deleted recursively. + * @param source the source file + * @throws IOException something went wanky + */ + public static final void delete(File source) throws IOException { + if ((source != null) && (source.exists())) { + if (source.isDirectory()) { + for (File f : source.listFiles()) { + delete(f); + } + } + if (!source.delete()) { + throw CommonCoreMessages.MESSAGES.couldNotDeleteFile(source.getName()); + } + } + } + + private Files() {} + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/pull/ElementPuller.java b/core/common/core/src/main/java/org/switchyard/common/io/pull/ElementPuller.java new file mode 100644 index 000000000..cef0690b1 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/pull/ElementPuller.java @@ -0,0 +1,171 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.io.pull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Utility class to safely access ("pull") DOM elements from various sources. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class ElementPuller extends Puller { + + private final boolean _ignoringComments; + + /** + * Constructs a new ElementPuller (ignoring comments when parsing XML). + */ + public ElementPuller() { + _ignoringComments = true; + } + + /** + * Constructs a new ElementPuller (optionally ignoring comments when parsing XML). + * @param ignoringComments whether comments should be ignored when parsing XML. + */ + public ElementPuller(boolean ignoringComments) { + _ignoringComments = ignoringComments; + } + + /** + * {@inheritDoc} + */ + @Override + public Element pull(InputStream stream) throws IOException { + return pull(new InputSource(stream)); + } + + /** + * Pulls an Element from a Reader. + * @param reader a Reader of the element + * @return the element + * @throws IOException if a problem occurred + */ + public Element pull(Reader reader) throws IOException { + return pull(new InputSource(reader)); + } + + /** + * Pulls an Element from an InputSource. + * @param source an InputSource of the element + * @return the element + * @throws IOException if a problem occurred + */ + public Element pull(InputSource source) throws IOException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setIgnoringComments(_ignoringComments); + factory.setNamespaceAware(true); + factory.setValidating(false); + try { + return pull(factory.newDocumentBuilder().parse(source)); + } catch (ParserConfigurationException pce) { + throw new IOException(pce); + } catch (SAXException se) { + throw new IOException(se); + } + } + + /** + * Pulls the root element of a DOM document, additionally normalizing it. + * @param document the document + * @return the element + */ + public Element pull(Document document) { + return pull(document, true); + } + + /** + * Pulls the root element of a DOM document. + * @param document the document + * @param normalize whether or not to normalize the document + * @return the element + */ + public Element pull(Document document, boolean normalize) { + if (normalize) { + document.normalizeDocument(); + } + return pull(document.getDocumentElement(), normalize); + } + + /** + * Returns the element itself, additionally normalizing it. + * @param element the element + * @return the element + */ + public Element pull(Element element) { + return pull(element, true); + } + + /** + * Returns the element, optionally normalizing it. + * @param element the element + * @param normalize whether or not to normalize the element + * @return the element + */ + public Element pull(Element element, boolean normalize) { + if (normalize) { + element.normalize(); + } + return element; + } + + /** + * Pulls (constructs) a basic Element from a qualified name. + * @param qname the qualified name + * @return the element + */ + public Element pull(QName qname) { + StringBuilder sb = new StringBuilder(); + sb.append('<'); + String prefix = qname.getPrefix(); + if (prefix != null && prefix.length() > 0) { + sb.append(prefix); + sb.append(':'); + } + sb.append(qname.getLocalPart()); + String namespace = qname.getNamespaceURI(); + if (namespace != null && namespace.length() > 0) { + sb.append(" xmlns"); + if (prefix != null && prefix.length() > 0) { + sb.append(':'); + sb.append(prefix); + } + sb.append("=\""); + sb.append(namespace); + sb.append('"'); + } + sb.append("/>"); + try { + return pull(new StringReader(sb.toString())); + } catch (IOException ioe) { + // shouldn't happen + throw new RuntimeException(ioe); + } + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/pull/PropertiesPuller.java b/core/common/core/src/main/java/org/switchyard/common/io/pull/PropertiesPuller.java new file mode 100644 index 000000000..ba29939ce --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/pull/PropertiesPuller.java @@ -0,0 +1,126 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.io.pull; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +import org.switchyard.common.CommonCoreMessages; + + +/** + * Utility class to safely access ("pull") Properties from various sources. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class PropertiesPuller extends Puller { + + /** + * The type of the Properties file to pull. + */ + public static enum PropertiesType { + /** A standard properties file. */ + PROPERTIES, + /** An XML properties file. */ + XML + }; + + private final PropertiesType _type; + + /** + * Creates a new PropertiesPuller with type {@link PropertiesType#PROPERTIES}. + */ + public PropertiesPuller() { + this(PropertiesType.PROPERTIES); + } + + /** + * Creates a new PropertiesPuller with the specified PropertiesType. + * @param type the specified PropertiesType + */ + public PropertiesPuller(PropertiesType type) { + _type = type; + } + + /** + * {@inheritDoc} + */ + @Override + public Properties pull(InputStream stream) throws IOException { + Properties props = new Properties(); + if (stream != null) { + switch (_type) { + case PROPERTIES: + props.load(stream); + break; + case XML: + props.loadFromXML(stream); + break; + default: + throw CommonCoreMessages.MESSAGES.unsupportedPropertiesTypeForMethod(_type, "pull(InputStream)"); + } + } + return props; + } + + /** + * Safely pulls Properties from a Reader. + * @param reader a Reader of the resource + * @return the resource + * @throws IOException if a problem occurred + */ + public Properties pull(Reader reader) throws IOException { + Properties props = new Properties(); + if (reader != null) { + switch (_type) { + case PROPERTIES: + props.load(reader); + break; + /* + case XML: + props.loadFromXML(reader); // unsupported by JDK + break; + */ + default: + throw CommonCoreMessages.MESSAGES.unsupportedPropertiesTypeForMethod(_type, "pull(Reader)"); + } + } + return props; + } + + /** + * Safely pulls Properties resource from a Map. + * @param map a Map of the properties + * @return the resource + */ + public Properties pull(Map map) { + Properties props = new Properties(); + if (map != null) { + for (Entry entry : map.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (key != null && value != null) { + props.setProperty(key, value); + } + } + } + return props; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/pull/Puller.java b/core/common/core/src/main/java/org/switchyard/common/io/pull/Puller.java new file mode 100644 index 000000000..ba38a95e4 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/pull/Puller.java @@ -0,0 +1,261 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io.pull; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; + +import org.switchyard.common.io.resource.Resource; +import org.switchyard.common.type.Classes; + +/** + * Utility class to safely access ("pull") resources from various sources. + * + * @param the type of the resource being pulled + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class Puller { + + /** + * Safely pulls a resource from the class path using {@link org.switchyard.common.type.Classes#getResourceAsStream(String, Class)}. + * @param resource the path to the resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(String resource) throws IOException { + return pull(resource, getClass()); + } + + /** + * Safely pulls a resource from the class path using {@link org.switchyard.common.type.Classes#getResourceAsStream(String, Class)}. + * @param resource the path to the resource + * @param caller class calling this method, so we can also try it's classloader + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(String resource, Class caller) throws IOException { + InputStream is = Classes.getResourceAsStream(resource, caller); + if (is != null) { + try { + return pull(is); + } finally { + is.close(); + } + } + return null; + } + + /** + * Safely pulls a resource from the class path using {@link org.switchyard.common.type.Classes#getResourceAsStream(String, ClassLoader)}. + * @param resource the path to the resource + * @param loader the classloader we can also try to find the resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(String resource, ClassLoader loader) throws IOException { + InputStream is = Classes.getResourceAsStream(resource, loader); + if (is != null) { + try { + return pull(is); + } finally { + is.close(); + } + } + return null; + } + + /** + * Safely pulls a resource from a URI. + * @param uri the URI to the resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(URI uri) throws IOException { + return pull(uri.toURL()); + } + + /** + * Safely pulls a resource from a URL. + * @param url the URL to the resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(URL url) throws IOException { + InputStream is = url.openStream(); + try { + return pull(is); + } finally { + if (is != null) { + is.close(); + } + } + } + + /** + * Safely pulls a resource from a Resource. + * @param resource the Resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(Resource resource) throws IOException { + return pull(resource, getClass()); + } + + /** + * Safely pulls a resource from a Resource, using the specified caller class. + * @param resource the Resource + * @param caller the class calling this method + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(Resource resource, Class caller) throws IOException { + return pull(resource.getLocationURL(caller)); + } + + /** + * Safely pulls a resource from a Resource, using the specified classloader. + * @param resource the Resource + * @param loader the classloader to check with + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(Resource resource, ClassLoader loader) throws IOException { + return pull(resource.getLocationURL(loader)); + } + + /** + * Safely pulls a resource from a File. + * @param file the resource File + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public R pull(File file) throws IOException { + InputStream is = new FileInputStream(file); + try { + return pull(is); + } finally { + if (is != null) { + is.close(); + } + } + } + + /** + * Safely pulls a resource from an InputStream. + * @param stream an InputStream of the resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public abstract R pull(InputStream stream) throws IOException; + + /** + * Known path types. + */ + public static enum PathType { + /** A class path. */ + CLASS, + /** A file path. */ + FILE, + /** A URI path. */ + URI, + /** A URL path. */ + URL + } + + /** + * Safely pulls a resource from a path, iterating over the specified path types until it finds it. + * @param path the path + * @param pathTypes the types of paths to try + * @return the resource, or null if not found + */ + public R pullPath(String path, PathType... pathTypes) { + return pullPath(path, getClass(), pathTypes); + } + + /** + * Safely pulls a resource from a path, iterating over the specified path types until it finds it. + * @param path the path + * @param caller class calling this method, so we can also try it's classloader + * @param pathTypes the types of paths to try + * @return the resource, or null if not found + */ + public R pullPath(String path, Class caller, PathType... pathTypes) { + return pullPath(path, caller, null, true, pathTypes); + } + + /** + * Safely pulls a resource from a path, iterating over the specified path types until it finds it. + * @param path the path + * @param loader the classloader we can also try to find the resource + * @param pathTypes the types of paths to try + * @return the resource, or null if not found + */ + public R pullPath(String path, ClassLoader loader, PathType... pathTypes) { + return pullPath(path, null, loader, false, pathTypes); + } + + private R pullPath(String path, Class caller, ClassLoader loader, boolean callerOrLoader, PathType[] pathTypes) { + if (path == null) { + return null; + } + R r = null; + for (PathType pathType : pathTypes) { + if (pathType == null) { + continue; + } + try { + switch (pathType) { + case CLASS: + if (callerOrLoader) { + r = pull(path, caller); + } else { + r = pull(path, loader); + } + break; + case FILE: + File file; + try { + file = new File(new URL(path).getFile()); + } catch (MalformedURLException mue) { + file = new File(path); + } + if (file.exists() && file.isFile()) { + r = pull(file); + } + break; + case URI: + r = pull(new URI(path)); + break; + case URL: + r = pull(new URL(path)); + break; + } + } catch (Throwable t) { + // keep checkstyle happy + t.getMessage(); + } + if (r != null) { + break; + } + } + return r; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/pull/StringPuller.java b/core/common/core/src/main/java/org/switchyard/common/io/pull/StringPuller.java new file mode 100644 index 000000000..20c84a88d --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/pull/StringPuller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.io.pull; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; + +/** + * Utility class to safely access ("pull") Strings from various sources. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class StringPuller extends Puller { + + /** + * {@inheritDoc} + */ + @Override + public String pull(InputStream stream) throws IOException { + return pull(new InputStreamReader(stream)); + } + + /** + * Safely pulls a String from a Reader. + * @param reader a Reader of the resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public String pull(Reader reader) throws IOException { + StringBuffer buffer = new StringBuffer(1024); + reader = new BufferedReader(reader); + char[] c = new char[1024]; + int i = 0; + while ((i = reader.read(c)) != -1) { + buffer.append(c, 0, i); + } + return buffer.toString(); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/resource/BaseResource.java b/core/common/core/src/main/java/org/switchyard/common/io/resource/BaseResource.java new file mode 100644 index 000000000..4e4e079d0 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/resource/BaseResource.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io.resource; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +import org.switchyard.common.type.Classes; + +/** + * BaseResource. + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public abstract class BaseResource implements Resource { + + /** + * {@inheritDoc} + */ + @Override + public URL getLocationURL() { + return getLocationURL(getClass()); + } + + /** + * {@inheritDoc} + */ + @Override + public URL getLocationURL(Class caller) { + return getURL(getLocation(), caller); + } + + /** + * {@inheritDoc} + */ + @Override + public URL getLocationURL(ClassLoader loader) { + return getURL(getLocation(), loader); + } + + /** + * Gets a URL with the specified location and calling class. + * @param location the specified location + * @param caller the calling class to use it's classloader + * @return the URL + */ + public static final URL getURL(String location, Class caller) { + return getURL(location, caller, null); + } + + /** + * Gets a URL with the specified location and calling class. + * @param location the specified location + * @param loader the classloader to check with + * @return the URL + */ + public static final URL getURL(String location, ClassLoader loader) { + return getURL(location, null, loader); + } + + private static final URL getURL(String location, Class caller, ClassLoader loader) { + if (location != null) { + try { + if (location.startsWith("http:") || location.startsWith("https:")) { + return new URL(location); + } + if (location.startsWith("file:")) { + return new File(location.substring(5)).toURI().toURL(); + } + if (caller != null) { + return Classes.getResource(location, caller); + } + if (loader != null) { + return Classes.getResource(location, loader); + } + return Classes.getResource(location, BaseResource.class); + } catch (IOException ioe) { + return null; + } + } + return null; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/resource/Resource.java b/core/common/core/src/main/java/org/switchyard/common/io/resource/Resource.java new file mode 100644 index 000000000..93a14e248 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/resource/Resource.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io.resource; + +import java.net.URL; + +/** + * Represents a resource. + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public interface Resource { + + /** + * Gets the location of the resource. + * @return the location of the resource + */ + public String getLocation(); + + /** + * Gets the URL form of the resource's location. + * @return the URL form of the resource's location + */ + public URL getLocationURL(); + + /** + * Gets the URL form of the resource's location. + * @param caller the caller class so we can check with it's classloader + * @return the URL form of the resource's location + */ + public URL getLocationURL(Class caller); + + /** + * Gets the URL form of the resource's location. + * @param loader the classloader to check with + * @return the URL form of the resource's location + */ + public URL getLocationURL(ClassLoader loader); + + /** + * Gets the type of the resource. + * @return the type of the resource + */ + public ResourceType getType(); + + /** + * Gets the detail of the resource. + * @return the detail of the resource + */ + public ResourceDetail getDetail(); + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/resource/ResourceDetail.java b/core/common/core/src/main/java/org/switchyard/common/io/resource/ResourceDetail.java new file mode 100644 index 000000000..4144476e2 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/resource/ResourceDetail.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io.resource; + +/** + * Represents detailed information of a Resource. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface ResourceDetail { + + /** + * Gets the input type. + * @return the input type + */ + public String getInputType(); + + /** + * Gets the worksheet name. + * @return the worksheet name + */ + public String getWorksheetName(); + + /* SWITCHYARD-1662 + * + * Whether to use external types. + * @return if using external types + * + public boolean isUsingExternalTypes(); + */ + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/resource/ResourceType.java b/core/common/core/src/main/java/org/switchyard/common/io/resource/ResourceType.java new file mode 100644 index 000000000..2c0dfdda8 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/resource/ResourceType.java @@ -0,0 +1,438 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io.resource; + +import java.net.URL; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; + +import org.jboss.logging.Logger; +import org.switchyard.common.CommonCoreMessages; +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.type.Classes; + +/** + * Represents the type of a Resource. + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public final class ResourceType implements Comparable { + + private static final Logger LOGGER = Logger.getLogger(ResourceType.class); + + private static final Map TYPES = new ConcurrentHashMap(); + + static { + install(); + } + + private final String _name; + private String _description; + private Set _extensions; + private Set _inherited; + + private ResourceType(String name, String description, Set extensions, Set inherited) { + _name = name; + _description = description; + _extensions = extensions; + _inherited = inherited; + } + + /** + * The name of the resource type. + * @return the name of the resource type + */ + public String getName() { + return _name; + } + + /** + * The description of the resource type. + * @return the description of the resource type + */ + public String getDescription() { + return _description; + } + + /** + * The extensions of the resource type, including inherited. + * @return the extensions of the resource type + */ + public Set getExtensions() { + return getExtensions(true); + } + + /** + * The extensions of the resource type. + * @param includeInherited if inherited extensions should be included + * @return the extensions of the resource type + */ + public Set getExtensions(boolean includeInherited) { + Set exts = new TreeSet(); + exts.addAll(_extensions); + if (includeInherited) { + for (ResourceType type : _inherited) { + exts.addAll(type.getExtensions(true)); + } + } + return Collections.unmodifiableSet(exts); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public int compareTo(ResourceType type) { + return type != null ? _name.compareTo(type._name) : 1; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_name == null) ? 0 : _name.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ResourceType other = (ResourceType)obj; + if (_name == null) { + if (other._name != null) { + return false; + } + } else if (!_name.equals(other._name)) { + return false; + } + return true; + } + + /** + * Searches for any /org/switchyard/common/io/resource/resourceType.properties it can find on the classpath + * and installs the configured ResourceTypes. This method is safe to invoke multiple times, and might be + * necessary if new ClassLoaders become available. + */ + public static synchronized void install() { + install(ResourceType.class); + } + + /** + * Searches for any /org/switchyard/common/io/resource/resourceType.properties it can find on the classpath + * and installs the configured ResourceTypes. This method is safe to invoke multiple times, and might be + * necessary if new ClassLoaders become available. + * @param caller the calling Class so we can try it's ClassLoader + */ + public static synchronized void install(Class caller) { + install(caller != null ? caller.getClassLoader() : null); + } + + /** + * Searches for any /org/switchyard/common/io/resource/resourceType.properties it can find on the classpath + * and installs the configured ResourceTypes. This method is safe to invoke multiple times, and might be + * necessary if new ClassLoaders become available. + * @param loader a ClassLoader to try + */ + public static synchronized void install(ClassLoader loader) { + List urls; + try { + urls = Classes.getResources("/org/switchyard/common/io/resource/resourceType.properties", loader); + } catch (Throwable t) { + LOGGER.fatal(t.getMessage()); + urls = Collections.emptyList(); + } + PropertiesPuller props_puller = new PropertiesPuller(); + for (URL url : urls) { + try { + Properties props = props_puller.pull(url); + for (Object key : props.keySet()) { + String name = (String)key; + StringTokenizer st = new StringTokenizer(props.getProperty(name), "|"); + String description = st.hasMoreTokens() ? Strings.trimToNull(st.nextToken()) : null; + Set extensions = st.hasMoreTokens() ? Strings.uniqueSplitTrimToNull(st.nextToken(), ",") : null; + // we only want to resolve inheritance once (thus false below) + install(name, description, extensions, false); + } + } catch (Throwable t) { + LOGGER.error(t.getMessage()); + } + } + // resolve inheritance once + resolveInheritance(); + } + + /** + * Installs a resource type with the specified name. + * @param name the name of the resource type + * @return the installed resource type + */ + public static synchronized ResourceType install(String name) { + return install(name, null); + } + + /** + * Installs a resource type with the specified name, description, and extensions. + * @param name the name of the resource type + * @param description the description of the resource type + * @param extensions the extensions of the resource type + * @return the installed resource type + */ + public static synchronized ResourceType install(String name, String description, String... extensions) { + Set ext_set = null; + if (extensions != null) { + for (String ext : extensions) { + ext = Strings.trimToNull(ext); + if (ext != null) { + if (ext_set == null) { + ext_set = new TreeSet(); + } + ext_set.add(ext); + } + } + } + return install(name, description, ext_set); + } + + /** + * Installs a resource type with the specified name, description, and extensions. + * @param name the name of the resource type + * @param description the description of the resource type + * @param extensions the extensions of the resource type + * @return the installed resource type + */ + public static synchronized ResourceType install(String name, String description, Set extensions) { + return install(name, description, extensions, true); + } + + private static synchronized ResourceType install(String name, String description, Set extensions, boolean resolveInheritance) { + // name + name = Strings.trimToNull(name); + if (name == null) { + throw CommonCoreMessages.MESSAGES.nameNull(); + } + name = name.toUpperCase(); + // description + description = Strings.trimToNull(description); + // extensions + Set ext_set = new TreeSet(); + if (extensions != null) { + for (String ext : extensions) { + ext = Strings.trimToNull(ext); + if (ext != null) { + ext = ext.toLowerCase(); + ResourceType preinstalled = forExtension(ext); + if (preinstalled == null) { + ext_set.add(ext); + } else { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Extension [" + ext + "] already installed by [" + preinstalled._name + "], so will not be included in [" + name + "]. Use extension reference [{" + preinstalled._name + "}] instead."); + } + } + } + } + } + // type + ResourceType type = TYPES.get(name); + if (type == null) { + type = new ResourceType(name, description, ext_set, new TreeSet()); + TYPES.put(name, type); + } else { + if (type._description == null && description != null) { + type._description = description; + } + for (String ext : ext_set) { + if (!type._extensions.contains(ext)) { + type._extensions.add(ext); + } + } + } + if (resolveInheritance) { + resolveInheritance(); + } + return type; + } + + private static synchronized void resolveInheritance() { + for (ResourceType type : TYPES.values()) { + Set extensions = new TreeSet(); + for (String ext : type.getExtensions(false)) { + boolean bounded = false; + ResourceType inherited = null; + if (ext.startsWith("{") && ext.endsWith("}")) { + bounded = true; + String name = ext.substring(1, ext.length()-1); + inherited = valueOf(name); + } + if (inherited != null) { + type._inherited.add(inherited); + } else if (!bounded) { + extensions.add(ext); + } + } + type._extensions = extensions; + } + } + + /** + * Returns all known ResourceType names as an array. + * @return the names + */ + public static String[] names() { + Set names = nameSet(); + return names.toArray(new String[names.size()]); + } + + /** + * Returns all known ResourceType names as a Set. + * @return the names + */ + public static Set nameSet() { + return Collections.unmodifiableSet(new TreeSet(TYPES.keySet())); + } + + /** + * Returns all known ResourceTypes as an array. + * @return the types + */ + public static ResourceType[] values() { + Set values = valueSet(); + return values.toArray(new ResourceType[values.size()]); + } + + /** + * Returns all known ResourceTypes as a Set. + * @return the types + */ + public static Set valueSet() { + Set tmpSet = new TreeSet(); + tmpSet.addAll(TYPES.values()); + return Collections.unmodifiableSet(tmpSet); + } + + /** + * Gets the installed resource type with the specified name. Added to mimic Enums; simply calls {@link ResourceType#forName(String)}. + * @param name the specified name + * @return the installed resource type + */ + public static ResourceType valueOf(String name) { + return forName(name); + } + + /** + * Gets the installed resource type with the specified name. + * @param name the specified name + * @return the installed resource type + */ + public static ResourceType forName(String name) { + name = Strings.trimToNull(name); + return name != null ? TYPES.get(name.toUpperCase()) : null; + } + + /** + * Gets the installed resource type with the specified extension in it's primary list (not inherited). + * @param extension the specified extension + * @return the resource type + */ + public static ResourceType forExtension(String extension) { + ResourceType[] types = forExtension(extension, false); + return types.length > 0 ? types[0] : null; + } + + /** + * Gets all installed resource types that include the specified extension. + * @param extension the specified extension + * @param includeInherited if inherited extensions should be included + * @return the resource types + */ + public static ResourceType[] forExtension(String extension, boolean includeInherited) { + Set types = new TreeSet(); + extension = Strings.trimToNull(extension); + if (extension != null) { + extension = extension.toLowerCase(); + for (ResourceType type : TYPES.values()) { + if (type.getExtensions(includeInherited).contains(extension)) { + types.add(type); + } + } + } + return types.toArray(new ResourceType[types.size()]); + } + + /** + * Gets the installed resource type with an extension in it's primary list (not inherited) deduced from the specified location. + * @param location the specified extension + * @return the resource type + */ + public static ResourceType forLocation(String location) { + ResourceType[] types = forLocation(location, false); + return types.length > 0 ? types[0] : null; + } + + /** + * Gets all installed resource types that include an extension in it's primary list deduced from the specified location. + * @param location the specified extension + * @param includeInherited if inherited extensions should be included + * @return the resource types + */ + public static ResourceType[] forLocation(String location, boolean includeInherited) { + if (location != null) { + int pos = location.lastIndexOf('.'); + if (pos != -1) { + String ext = location.substring(pos, location.length()); + return forExtension(ext, includeInherited); + } + } + return null; + } + + /** + * Prints all known ResourceType values to STDOUT, one per line, in the format "NAME: Description [.ext, ...]". + * @param args not required + */ + public static void main(String... args) { + for (ResourceType type : values()) { + System.out.printf("%s: %s %s%n", type.getName(), type.getDescription(), type.getExtensions()); + } + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/io/resource/SimpleResource.java b/core/common/core/src/main/java/org/switchyard/common/io/resource/SimpleResource.java new file mode 100644 index 000000000..df0c9e21b --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/io/resource/SimpleResource.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io.resource; + +/** + * Simple Resource class. + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public class SimpleResource extends BaseResource { + + private String _location; + private ResourceType _type; + private ResourceDetail _detail; + + /** + * Constructs a new SimpleResource with the specified resource location. + * @param location the resource location + */ + public SimpleResource(String location) { + setLocation(location); + } + + /** + * Constructs a new SimpleResource with the specified resource location and type. + * @param location the resource location + * @param type the resource type + */ + public SimpleResource(String location, ResourceType type) { + setLocation(location); + setType(type); + } + + /** + * Constructs a new SimpleResource with the specified resource location and type. + * @param location the resource location + * @param type the resource type + */ + public SimpleResource(String location, String type) { + setLocation(location); + setType(ResourceType.valueOf(type)); + } + + /** + * {@inheritDoc} + */ + @Override + public String getLocation() { + return _location; + } + + /** + * Sets the resource location. + *

If not already set, the resource type will be deduced from the extension of the location, and set.

+ * @param location the resource location + * @return this SimpleResource (useful for chaining) + */ + public SimpleResource setLocation(String location) { + if (location != null && getType() == null) { + setType(ResourceType.forLocation(location)); + } + _location = location; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceType getType() { + return _type; + } + + /** + * Sets the resource type. + * @param type the resource type + * @return this SimpleResource (useful for chaining) + */ + public SimpleResource setType(ResourceType type) { + _type = type; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceDetail getDetail() { + return _detail; + } + + /** + * Sets the resource detail. + * @param detail the resource detail + * @return this SimpleResource (useful for chaining) + */ + public SimpleResource setDetail(ResourceDetail detail) { + _detail = detail; + return this; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/lang/Strings.java b/core/common/core/src/main/java/org/switchyard/common/lang/Strings.java new file mode 100644 index 000000000..85cdb9e67 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/lang/Strings.java @@ -0,0 +1,359 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.lang; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.switchyard.common.property.CompoundPropertyResolver; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.common.property.SystemAndTestPropertyResolver; +import org.switchyard.common.property.SystemPropertyResolver; +import org.switchyard.common.property.TestPropertyResolver; + +/** + * Common String Utilities. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class Strings { + + /** Default regex replacements for cleansing Strings. */ + public static final Map DEFAULT_CLEANSE_REGEX_REPLACEMENTS; + static { + Map map = new LinkedHashMap(); + map.put("[\\W_]", "-"); + DEFAULT_CLEANSE_REGEX_REPLACEMENTS = Collections.unmodifiableMap(map); + } + + private static final Pattern DOUBLE_DOLLAR_LEFT_CURLY_PATTERN = Pattern.compile("\\$\\$\\{"); + private static final Pattern INNER_DOLLAR_CURLIES_PATTERN = Pattern.compile("\\$\\{[[^\\$\\{]&&[^\\}]]*\\}"); + private static final Pattern SINGLE_COLON_PATTERN = Pattern.compile("[^:+]:[^:+]"); + private static final String PENCIL = String.valueOf((char)0x270F); // an actual pencil dingbat, used as a placeholder + private static final String DOLLAR = "\\$"; + private static final String LEFT_CURLY = "{"; + private static final String RIGHT_CURLY = "}"; + private static final String PENCIL_LEFT_CURLY = PENCIL + LEFT_CURLY; + + /** + * Trims the specified String, and if after it is zero-length, return null. + * @param str the specified String + * @return the trim-to-null'd String + */ + public static String trimToNull(String str) { + if (str != null) { + str = str.trim(); + if (str.length() == 0) { + str = null; + } + } + return str; + } + + /** + * Repeats the specified String given number of times. + * @param str String to repeat. + * @param repeatCount Number of repetitions + * @return The repeated String. + */ + public static String repeat(String str, int repeatCount) { + StringBuilder repeated = new StringBuilder(); + if (str.isEmpty() || repeatCount <= 0) { + return repeated.toString(); + } + + do { + repeated.append(str); + } while (--repeatCount > 0); + return repeated.toString(); + } + + /** + * Cleanses a String using the default cleanse regex replacments. + * @param str the String + * @return the cleansed String + * @see {@link #DEFAULT_CLEANSE_REGEX_REPLACEMENTS} + */ + public static String cleanse(String str) { + return cleanse(str, DEFAULT_CLEANSE_REGEX_REPLACEMENTS); + } + + /** + * Cleanses a String using the specified regex replacements. + * @param str the String + * @param regexReplacements the regex replacements + * @return the cleansed String + */ + public static String cleanse(String str, Map regexReplacements) { + if (str != null) { + for (Entry entry : regexReplacements.entrySet()) { + String regex = entry.getKey(); + String replacement = entry.getValue(); + str = str.replaceAll(regex, replacement); + String doubleReplacement = replacement + replacement; + while (str.contains(doubleReplacement)) { + str = str.replaceAll(doubleReplacement, replacement); + } + if (str.startsWith(replacement)) { + str = str.substring(replacement.length()); + } + if (str.endsWith(replacement)) { + str = str.substring(0, str.length()-1); + } + } + } + return str; + } + + /** + * Cleanses a String using the default cleanse regex replacments, then calls {@link #trimToNull(String)} on the result. + * @param str the String + * @return the cleansed and trimmed-to-null String + * @see {@link #DEFAULT_CLEANSE_REGEX_REPLACEMENTS} + */ + public static String cleanseTrimToNull(String str) { + return trimToNull(cleanse(str)); + } + + /** + * Cleanses a String using the specified cleanse regex replacments, then calls {@link #trimToNull(String)} on the result. + * @param str the String + * @param regexReplacements the regex replacements + * @return the cleansed and trimmed-to-null String + */ + public static String cleanseTrimToNull(String str, Map regexReplacements) { + return trimToNull(cleanse(str, regexReplacements)); + } + + /** + * Splits the specified String per the specified delimiters (per StringTokenizer rules), + * then trims each split String, and if not zero-length, becomes part of the returned List. + * @param str the specified String + * @param delim the specified delimiters + * @return the split and trimmed-to-null'd Strings in an unmodifiable List (possibly zero-size, but never null) + */ + public static List splitTrimToNull(String str, String delim) { + List list = new ArrayList(); + if (str != null) { + StringTokenizer st = new StringTokenizer(str, delim); + while (st.hasMoreTokens()) { + String s = trimToNull(st.nextToken()); + if (s != null) { + list.add(s); + } + } + } + return Collections.unmodifiableList(list); + } + + /** + * Same as {@link #splitTrimToNull(String, String)}, except a String array is returned. + * @param str the specified String + * @param delim the specified delimiters + * @return the split and trimmed-to-null'd Strings in an array (possibly zero-length, but never null) + */ + public static String[] splitTrimToNullArray(String str, String delim) { + List list = splitTrimToNull(str, delim); + return list.toArray(new String[list.size()]); + } + + /** + * Splits the specified String per the specified delimiters (per StringTokenizer rules), + * then trims each split String, and if not zero-length, becomes part of the returned Set. + * @param str the specified String + * @param delim the specified delimiters + * @return the split and trimmed-to-null'd Strings in an unmodifiable, insertion-ordered Set (possibly zero-size, but never null) + */ + public static Set uniqueSplitTrimToNull(String str, String delim) { + Set set = new LinkedHashSet(); + if (str != null) { + StringTokenizer st = new StringTokenizer(str, delim); + while (st.hasMoreTokens()) { + String s = trimToNull(st.nextToken()); + if (s != null) { + set.add(s); + } + } + } + return Collections.unmodifiableSet(set); + } + + /** + * Same as {@link #uniqueSplitTrimToNull(String, String)}, except a String array is returned. + * @param str the specified String + * @param delim the specified delimiters + * @return the split and trimmed-to-null'd Strings in an array (possibly zero-length, but never null) + */ + public static String[] uniqueSplitTrimToNullArray(String str, String delim) { + Set set = uniqueSplitTrimToNull(str, delim); + return set.toArray(new String[set.size()]); + } + + /** + * Concatenates Strings using no delimiter, trimming each to null. Nulls are not concatenated. + * @param str the original Strings + * @return the concatenated String + * @see #trimToNull(String) + */ + public static String concat(String... str) { + return concat(null, str); + } + + /** + * Concatenates Strings using the specified delimiter, trimming each to null. Nulls are not concatenated. + * @param delim the delimiter + * @param str the original Strings + * @return the concatenated String + * @see #trimToNull(String) + */ + public static String concat(String delim, String... str) { + return concat(delim, true, str); + } + + /** + * Concatenates Strings using the specified delimiter, possibly trimming each to null. Nulls are not concatenated. + * @param delim the delimiter + * @param trimToNull should each String be trimmed to null first? + * @param str the original Strings + * @return the concatenated String + * @see #trimToNull(String) + */ + public static String concat(String delim, boolean trimToNull, String... str) { + if (str != null && str.length > 0) { + StringBuilder sb = new StringBuilder(); + for (int i=0; i < str.length; i++) { + String s = str[i]; + if (trimToNull) { + s = trimToNull(s); + } + if (s != null) { + sb.append(s); + if (i < str.length-1) { + sb.append(delim); + } + } + } + return sb.toString(); + } + return null; + } + + /** + * Replaces ONLY system properties. + * @param str the original string + * @return the modified string + */ + public static String replaceSystemProperties(String str) { + return replaceProperties(str, SystemPropertyResolver.INSTANCE); + } + + /** + * Replaces ONLY test properties. + * @param str the original string + * @return the modified string + */ + public static String replaceTestProperties(String str) { + return replaceProperties(str, TestPropertyResolver.INSTANCE); + } + + /** + * Replaces BOTH system and test properties. + * @param str the original string + * @return the modified string + */ + public static String replaceSystemAndTestProperties(String str) { + return replaceProperties(str, SystemAndTestPropertyResolver.INSTANCE); + } + + /** + * Replaces properties per the given property resolvers. + * @param str the original string + * @param resolvers the property resolvers + * @return the modified string + */ + public static String replaceProperties(String str, PropertyResolver... resolvers) { + if (str != null) { + PropertyResolver resolver = CompoundPropertyResolver.compact(resolvers); + boolean penciled = false; + while (true) { + Matcher ddlc_mat = DOUBLE_DOLLAR_LEFT_CURLY_PATTERN.matcher(str); + if (ddlc_mat.find()) { + str = ddlc_mat.replaceAll(PENCIL_LEFT_CURLY); + penciled = true; + } + Matcher idc_mat = INNER_DOLLAR_CURLIES_PATTERN.matcher(str); + if (!idc_mat.find()) { + break; + } + int l_pos = idc_mat.start(); + int r_pos = idc_mat.end() - 1; + String prop_key = str.substring(l_pos + 2, r_pos); + String real_key; + String def_val; + Matcher sc_mat = SINGLE_COLON_PATTERN.matcher(prop_key); + if (sc_mat.find()) { + int sc_pos = sc_mat.start() + 1; + real_key = prop_key.substring(0, sc_pos); + def_val = prop_key.substring(sc_pos + 1, prop_key.length()); + } else { + real_key = prop_key; + def_val = null; + } + Object obj_val = resolver.resolveProperty(real_key); + if (obj_val == null) { + obj_val = def_val; + } + String str_val; + if (obj_val != null) { + str_val = obj_val.toString(); + } else { + str_val = PENCIL_LEFT_CURLY + real_key + RIGHT_CURLY; + penciled = true; + } + str = new StringBuilder() + .append(str.substring(0, l_pos)) + .append(str_val) + .append(str.substring(r_pos + 1, str.length())) + .toString(); + } + if (penciled) { + str = str.replaceAll(PENCIL, DOLLAR); + } + } + return str; + } + + /** + * Replaces properties per the given property resolvers. + * @param str the original string + * @param resolvers the property resolvers + * @return the modified string + */ + public static String replaceProperties(String str, Collection resolvers) { + return replaceProperties(str, CompoundPropertyResolver.compact(resolvers)); + } + + private Strings() {} + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/net/SocketAddr.java b/core/common/core/src/main/java/org/switchyard/common/net/SocketAddr.java new file mode 100644 index 000000000..cf6202ed0 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/net/SocketAddr.java @@ -0,0 +1,147 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.net; + +import java.io.Serializable; + +/** + * SocketAddr is a wrapper for IP address or host name + port number combination. + * No host name resolution will be performed by this class. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SocketAddr implements Serializable { + + private static final long serialVersionUID = 628840973822138641L; + + /** + * The default host this socket will be associated with. + */ + public static final String DEFAULT_HOST = "127.0.0.1"; + + /** + * The default port this socket will be associated with. + */ + public static final int DEFAULT_PORT = 8080; + + private String _host = DEFAULT_HOST; + private int _port = DEFAULT_PORT; + + /** + * Default Constructor. + */ + public SocketAddr() { + } + + /** + * Construct the SocketAddr from a string. + * + * The string can be in the form "hostName/ipAddress:portNumber", with the "hostName/ipAddress:" or ":portNumber" part being optional. + * + * @param socket a port name String. + */ + public SocketAddr(final String socket) { + if (socket != null) { + String[] socketTokens = socket.split(":"); + if (socketTokens.length > 0 && socketTokens[0].length() > 0) { + _host = socketTokens[0]; + } + if (socketTokens.length > 1 && socketTokens[1].length() > 0) { + _port = Integer.valueOf(socketTokens[1]); + } + } + } + + /** + * Construct the SocketAddr from host/ip and port values. + * + * @param host a host name or ip address. + * @param port a port number. + */ + public SocketAddr(String host, int port) { + _host = host; + _port = port; + } + + /** + * Set the host name or ip address value. + * + * @param host the host value to set + */ + public void setHost(String host) { + this._host = host; + } + + /** + * Get the host or ip address value. + * + * @return the host + */ + public String getHost() { + return _host; + } + + /** + * Set the port value. + * + * @param port the port to set + */ + public void setPort(int port) { + this._port = port; + } + + /** + * Get the port value. + * + * @return the port + */ + public int getPort() { + return _port; + } + + /** + * Test this SocketAddr for equality with another Object. + * + * @param objectToTest the Object to test with this PortName. + * @return true if equal else false. + */ + public final boolean equals(Object objectToTest) { + if ((objectToTest == null) || (!(objectToTest instanceof SocketAddr))) { + return false; + } + + SocketAddr socket = (SocketAddr) objectToTest; + + return (this._host.equals(socket._host)) && (this._port == socket._port); + } + + /** + * Generate the hashcode for this SocketAddr. + * + * @return The hashcode. + */ + public final int hashCode() { + return _host.hashCode() ^ Integer.valueOf(_port).hashCode(); + } + + /** + * Retruns a String representation of SocketAddr in the form "host:port". + * + * @return A SocketAddr string. + */ + public String toString() { + return _host + ":" + _port; + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/property/CompoundPropertyResolver.java b/core/common/core/src/main/java/org/switchyard/common/property/CompoundPropertyResolver.java new file mode 100644 index 000000000..b47a5674c --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/property/CompoundPropertyResolver.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.property; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Resolves properties from multiple sources. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class CompoundPropertyResolver implements PropertyResolver { + + private List _resolvers = new ArrayList(); + + /** + * Construction with an array of property resolvers. + * @param resolvers the property resolvers + */ + protected CompoundPropertyResolver(PropertyResolver... resolvers) { + if (resolvers != null) { + for (PropertyResolver resolver : resolvers) { + addResolver(resolver); + } + } + } + + /** + * Construction with a collection of property resolvers. + * @param resolvers the property resolvers + */ + protected CompoundPropertyResolver(Collection resolvers) { + if (resolvers != null) { + for (PropertyResolver resolver : resolvers) { + addResolver(resolver); + } + } + } + + private void addResolver(PropertyResolver resolver) { + if (resolver != null && !_resolvers.contains(resolver) && resolver != this) { + if (resolver instanceof CompoundPropertyResolver) { + for (PropertyResolver pr : ((CompoundPropertyResolver)resolver)._resolvers) { + addResolver(pr); + } + } else { + _resolvers.add(resolver); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public Object resolveProperty(String key) { + Object value = null; + if (key != null) { + for (PropertyResolver resolver : _resolvers) { + value = resolver.resolveProperty(key); + if (value != null) { + break; + } + } + } + return value; + } + + /** + * Creates a compact property resolver given an array of property resolvers, weeding out nulls and only compounding when necessary. + * @param resolvers the property resolvers + * @return the always not-null compact property resolver + */ + public static PropertyResolver compact(PropertyResolver... resolvers) { + CompoundPropertyResolver compound = new CompoundPropertyResolver(resolvers); + return compound._resolvers.size() == 1 ? compound._resolvers.get(0) : compound; + } + + /** + * Creates a compact property resolver given a collection of property resolvers, weeding out nulls and only compounding when necessary. + * @param resolvers the property resolvers + * @return the always not-null compact property resolver + */ + public static PropertyResolver compact(Collection resolvers) { + CompoundPropertyResolver compound = new CompoundPropertyResolver(resolvers); + return compound._resolvers.size() == 1 ? compound._resolvers.get(0) : compound; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/property/MapPropertyResolver.java b/core/common/core/src/main/java/org/switchyard/common/property/MapPropertyResolver.java new file mode 100644 index 000000000..c7795d408 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/property/MapPropertyResolver.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.property; + +import java.util.Map; + +/** + * Resolves properties from a Map. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class MapPropertyResolver implements PropertyResolver { + + private final Map _map; + + /** + * Construction with the specified Map. + * @param map the specified Map + */ + public MapPropertyResolver(Map map) { + _map = map; + } + + /** + * Gets the Map. + * @return the Map + */ + public Map getMap() { + return _map; + } + + /** + * {@inheritDoc} + */ + @Override + public final Object resolveProperty(String key) { + return key != null ? _map.get(key) : null; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/property/PropertiesPropertyResolver.java b/core/common/core/src/main/java/org/switchyard/common/property/PropertiesPropertyResolver.java new file mode 100644 index 000000000..3f2a28012 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/property/PropertiesPropertyResolver.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.property; + +import java.util.Properties; + +/** + * Resolves properties from a Properties. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class PropertiesPropertyResolver implements PropertyResolver { + + private final Properties _properties; + + /** + * Construction with the specified Properties. + * @param properties the specified Properties + */ + public PropertiesPropertyResolver(Properties properties) { + _properties = properties; + } + + /** + * Gets the Properties. + * @return the Properties + */ + public Properties getProperties() { + return _properties; + } + + /** + * {@inheritDoc} + */ + @Override + public final Object resolveProperty(String key) { + return key != null ? _properties.getProperty(key) : null; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/property/PropertyResolver.java b/core/common/core/src/main/java/org/switchyard/common/property/PropertyResolver.java new file mode 100644 index 000000000..62a15e65e --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/property/PropertyResolver.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.property; + +/** + * Resolves properties. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface PropertyResolver { + + /** + * Resolves a property. + * @param key the property key + * @return the property value + */ + public Object resolveProperty(String key); + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/property/SystemAndTestPropertyResolver.java b/core/common/core/src/main/java/org/switchyard/common/property/SystemAndTestPropertyResolver.java new file mode 100644 index 000000000..2c23f34d3 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/property/SystemAndTestPropertyResolver.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.property; + +/** + * Resolves properties from both {@link SystemPropertyResolver} and {@link TestPropertyResolver}. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class SystemAndTestPropertyResolver extends CompoundPropertyResolver { + + /** The singleton instance. */ + public static final SystemAndTestPropertyResolver INSTANCE = new SystemAndTestPropertyResolver(); + + /** The singleton constructor. */ + private SystemAndTestPropertyResolver() { + super(SystemPropertyResolver.INSTANCE, TestPropertyResolver.INSTANCE); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/property/SystemPropertyResolver.java b/core/common/core/src/main/java/org/switchyard/common/property/SystemPropertyResolver.java new file mode 100644 index 000000000..9efb03947 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/property/SystemPropertyResolver.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.property; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +/** + * Resolves properties from System Properties and the System environment. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class SystemPropertyResolver implements PropertyResolver { + + /** The singleton instance. */ + public static final SystemPropertyResolver INSTANCE = new SystemPropertyResolver(); + + /** The singleton constructor. */ + private SystemPropertyResolver() {} + + /** + * {@inheritDoc} + */ + @Override + public final Object resolveProperty(final String key) { + return key != null ? AccessController.doPrivileged(new PrivilegedAction() { + public String run() { + String value = System.getProperty(key); + if (value == null && key.startsWith("env.")) { + value = System.getenv(key.substring(4)); + } + return value; + } + }) : null; + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/property/TestPropertyResolver.java b/core/common/core/src/main/java/org/switchyard/common/property/TestPropertyResolver.java new file mode 100644 index 000000000..9982d631c --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/property/TestPropertyResolver.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.property; + +import java.util.concurrent.ConcurrentHashMap; + +/** + * Resolves properties from a test Map. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class TestPropertyResolver extends MapPropertyResolver { + + /** The singleton instance. */ + public static final TestPropertyResolver INSTANCE = new TestPropertyResolver(); + + /** The singleton constructor. */ + private TestPropertyResolver() { + super(new ConcurrentHashMap()); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/Classes.java b/core/common/core/src/main/java/org/switchyard/common/type/Classes.java new file mode 100644 index 000000000..5b0b98e4f --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/Classes.java @@ -0,0 +1,321 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * Utility class to properly load classes and find resources. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class Classes { + + private Classes() {} + + /** + * Loads a class based on name. + * @param name fully qualified classname + * @return the found class, or null if not found + */ + public static Class forName(String name) { + return forName(name, (ClassLoader)null); + } + + /** + * Loads a class based on name. + * @param name fully qualified classname + * @param caller class calling this method, so we can also try it's classloader + * @return the found class, or null if not found + */ + public static Class forName(String name, Class caller) { + return forName(name, caller != null ? caller.getClassLoader() : null); + } + + /** + * Loads a class based on name. + * @param name fully qualified classname + * @param loaders classloader(s) we can also try to find the class + * @return the found class, or null if not found + */ + public static Class forName(String name, ClassLoader... loaders) { + Class c = null; + for (ClassLoader cl : getClassLoaders(loaders)) { + try { + c = Class.forName(name, true, cl); + break; + } catch (Throwable t) { + // ignoring, but to keep checkstyle happy ("Must have at least one statement."): + t.getMessage(); + } + } + return c; + } + + /** + * Finds a classpath resource. + * @param path the path to the resource + * @return URL to the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static URL getResource(String path) throws IOException { + return getResource(path, (ClassLoader)null); + } + + /** + * Finds a classpath resource. + * @param path the path to the resource + * @param caller class calling this method, so we can also try it's classloader + * @return URL to the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static URL getResource(String path, Class caller) throws IOException { + ClassLoader loader = caller != null ? caller.getClassLoader() : null; + URL url = getResource(path, loader); + if (url == null) { + String callerPath = callerPath(path, caller); + if (callerPath != null) { + url = getResource(callerPath, loader); + } + } + return url; + } + + /** + * Finds a classpath resource. + * @param path the path to the resource + * @param loaders classloaders we can also try to find the resource + * @return URL to the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static URL getResource(String path, ClassLoader... loaders) throws IOException { + List urls = getResources(path, loaders); + return urls.size() > 0 ? urls.get(0) : null; + } + + /** + * Finds all matching classpath resources. + * @param path the path to the resource + * @return URL to the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static List getResources(String path) throws IOException { + return getResources(path, (ClassLoader)null); + } + + /** + * Finds all matching classpath resources. + * @param path the path to the resource + * @param caller class calling this method, so we can also try it's classloader + * @return URL to the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static List getResources(String path, Class caller) throws IOException { + ClassLoader loader = caller != null ? caller.getClassLoader() : null; + List urls = getResources(path, loader); + String callerPath = callerPath(path, caller); + if (callerPath != null) { + urls.addAll(getResources(callerPath, loader)); + } + return urls; + } + + /** + * Finds all matching classpath resources. + * @param path the path to the resource + * @param loaders classloader(s) we can also try to find the resource + * @return URL to the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static List getResources(String path, ClassLoader... loaders) throws IOException { + List urls = new ArrayList(); + if (path != null) { + while (path.startsWith("/")) { + path = path.substring(1); + } + for (ClassLoader cl : getClassLoaders(loaders)) { + Enumeration e = cl.getResources(path); + while (e.hasMoreElements()) { + URL url = e.nextElement(); + if (!urls.contains(url)) { + urls.add(url); + } + } + } + } + return urls; + } + + /** + * Finds a classpath resource as an InputStream. + * @param path the path to the resource + * @return InputStream of the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static InputStream getResourceAsStream(String path) throws IOException { + return getResourceAsStream(path, (ClassLoader)null); + } + + /** + * Finds a classpath resource as an InputStream. + * @param path the path to the resource + * @param caller class calling this method, so we can also try it's classloader + * @return InputStream of the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static InputStream getResourceAsStream(String path, Class caller) throws IOException { + ClassLoader loader = caller != null ? caller.getClassLoader() : null; + InputStream in = getResourceAsStream(path, loader); + if (in == null) { + String callerPath = callerPath(path, caller); + if (callerPath != null) { + in = getResourceAsStream(callerPath, loader); + } + } + return in; + } + + /** + * Finds a classpath resource as an InputStream. + * @param path the path to the resource + * @param loaders classloaders we can also try to find the resource + * @return InputStream of the resource, or null if not found + * @throws IOException if a problem occurred + */ + public static InputStream getResourceAsStream(String path, ClassLoader... loaders) throws IOException { + URL url = getResource(path, loaders); + return url != null ? url.openStream() : null; + } + + /** + * Provides a CompoundClassLoader using a non-duplicate List of ClassLoaders in the most appropriate search order. + * @return the CompoundClassLoader + */ + public static ClassLoader getClassLoader() { + return new CompoundClassLoader(getClassLoaders()); + } + + /** + * Provides a CompoundClassLoader using a non-duplicate List of ClassLoaders in the most appropriate search order. + * @param caller class calling this method, so we can also try it's classloader + * @return the CompoundClassLoader + */ + public static ClassLoader getClassLoader(Class caller) { + return new CompoundClassLoader(getClassLoaders(caller)); + } + + /** + * Provides a CompoundClassLoader using a non-duplicate List of ClassLoaders in the most appropriate search order. + * @param loaders user-specified ClassLoader(s) + * @return the CompoundClassLoader + */ + public static ClassLoader getClassLoader(ClassLoader... loaders) { + return new CompoundClassLoader(getClassLoaders(loaders)); + } + + /** + * Provides a non-duplicate List of ClassLoaders in the most appropriate search order. + * @return the non-duplicate List + */ + public static List getClassLoaders() { + return getClassLoaders((ClassLoader)null); + } + + /** + * Provides a non-duplicate List of ClassLoaders in the most appropriate search order. + * @param caller class calling this method, so we can also try it's classloader + * @return the non-duplicate List + */ + public static List getClassLoaders(Class caller) { + return getClassLoaders(caller != null ? caller.getClassLoader() : null); + } + + /** + * Provides a non-duplicate List of ClassLoaders in the most appropriate search order. + * @param loaders user-specified ClassLoader(s) + * @return the non-duplicate List + */ + public static List getClassLoaders(ClassLoader... loaders) { + Set set = new LinkedHashSet(); + // 1. The current Thread context ClassLoader + ClassLoader cl = getTCCL(); + if (cl != null) { + set.add(cl); + } + // 2. The user-specified ClassLoader(s) + if (loaders != null) { + for (ClassLoader loader : loaders) { + if (loader != null) { + set.add(loader); + } + } + } + // 3. This util class' ClassLoader + cl = Classes.class.getClassLoader(); + if (cl != null) { + set.add(cl); + } + // 4. The system ClassLoader (possibly via -Djava.system.class.loader) + cl = ClassLoader.getSystemClassLoader(); + if (cl != null) { + set.add(cl); + } + // 5. The runtime ClassLoader (possibly different than the system ClassLoader) + cl = Class.class.getClassLoader(); + if (cl != null) { + set.add(cl); + } + return new ArrayList(set); + } + + /** + * Shorthand method to get the current Thread's Context ClassLoader. + * @return the current Thread's Context ClassLoader + */ + public static ClassLoader getTCCL() { + return Thread.currentThread().getContextClassLoader(); + } + + /** + * Shorthand method to set the current Thread's Context ClassLoader. + * @param replacement the ClassLoader to set on the current Thread + * @return the ClassLoader that was previously associated with the current Thread, so it can be set back in a finally block, for example. + */ + public static ClassLoader setTCCL(ClassLoader replacement) { + Thread thread = Thread.currentThread(); + ClassLoader previous = thread.getContextClassLoader(); + thread.setContextClassLoader(replacement); + return previous; + } + + private static String callerPath(String path, Class caller) { + String callerPath = null; + if (path != null && caller != null) { + String pkg = caller.getPackage().getName().replace('.', '/'); + if (!path.contains(pkg)) { + callerPath = pkg + "/" + path; + } + } + return callerPath; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/CompoundClassLoader.java b/core/common/core/src/main/java/org/switchyard/common/type/CompoundClassLoader.java new file mode 100644 index 000000000..9a2106b4c --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/CompoundClassLoader.java @@ -0,0 +1,139 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.type; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + +/** + * A ClassLoader implementation that iterates over a collection of other ClassLoaders until it finds everything it's looking for. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class CompoundClassLoader extends ClassLoader { + + private Collection _loaders; + + /** + * Constructs a new CompoundClassLoader. + * @param loaders the loaders to iterate over + */ + public CompoundClassLoader(ClassLoader... loaders) { + _loaders = Arrays.asList(loaders); + } + + /** + * Constructs a new CompoundClassLoader. + * @param loaders the loaders to iterate over + */ + public CompoundClassLoader(Collection loaders) { + _loaders = loaders; + } + + /** + * {@inheritDoc} + */ + @Override + public URL getResource(String name) { + for (ClassLoader loader : _loaders) { + if (loader != null) { + URL resource = loader.getResource(name); + if (resource != null) { + return resource; + } + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public InputStream getResourceAsStream(String name) { + for (ClassLoader loader : _loaders) { + if (loader != null) { + InputStream is = loader.getResourceAsStream(name); + if (is != null) { + return is; + } + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Enumeration getResources(String name) throws IOException { + List urls = new ArrayList(); + for (ClassLoader loader : _loaders) { + if (loader != null) { + try { + Enumeration resources = loader.getResources(name); + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + if (resource != null && !urls.contains(resource)) { + urls.add(resource); + } + } + } catch (IOException ioe) { + // ignoring, but to keep checkstyle happy ("Must have at least one statement."): + ioe.getMessage(); + } + } + } + return Collections.enumeration(urls); + } + + /** + * {@inheritDoc} + */ + @Override + public Class loadClass(String name) throws ClassNotFoundException { + for (ClassLoader loader : _loaders) { + if (loader != null) { + try { + return loader.loadClass(name); + } catch (ClassNotFoundException cnfe) { + // ignoring, but to keep checkstyle happy ("Must have at least one statement."): + cnfe.getMessage(); + } + } + } + throw new ClassNotFoundException(); + } + + /** + * {@inheritDoc} + */ + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + // loader.loadClass(name, resolve) is not visible! + return loadClass(name); + } + + @Override + public String toString() { + return String.format("CompoundClassloader %s", _loaders); + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/classpath/AbstractTypeFilter.java b/core/common/core/src/main/java/org/switchyard/common/type/classpath/AbstractTypeFilter.java new file mode 100644 index 000000000..67243eb55 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/classpath/AbstractTypeFilter.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +import java.util.ArrayList; +import java.util.List; + +import org.jboss.logging.Logger; +import org.switchyard.common.type.Classes; + +/** + * Abstract Java type filter. + * + * @author tom.fennelly@gmail.com + */ +public abstract class AbstractTypeFilter implements Filter { + + private Logger _logger; + private List> _classes = new ArrayList>(); + + /** + * Protected constructor. + */ + protected AbstractTypeFilter() { + _logger = Logger.getLogger(getClass()); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean continueScanning() { + return true; + } + + /** + * Is the Java type a filter match. + * @param clazz The Java type to be checked. + * @return true if the Java type is a match, otherwise false. + */ + public abstract boolean matches(Class clazz); + + /** + * Get the set of filtered (i.e. matching) types. + * @return The set of filtered (i.e. matching) types. + */ + public List> getMatchedTypes() { + return _classes; + } + + /** + * Clear the current set of matched types. + */ + public void clear() { + _classes.clear(); + } + + /** + * Filter the specified resource. + * @param resourceName The classpath resource file name. + */ + public void filter(String resourceName) { + if (resourceName.endsWith(".class")) { + String className = toClassName(resourceName); + + try { + // Assumption here is that these classes are on the scanner's classpath... + Class clazz = Classes.forName(className, getClass()); + if (matches(clazz)) { + _classes.add(clazz); + } + } catch (Throwable throwable) { + _logger.debug("Resource '" + resourceName + "' presented to '" + InstanceOfFilter.class.getName() + "', but not loadable by classloader. Ignoring.", throwable); + } + } + } + + private String toClassName(String resourceName) { + if (resourceName.startsWith("/")) { + resourceName = resourceName.substring(1); + } + if (resourceName.endsWith(".class")) { + resourceName = resourceName.substring(0, resourceName.length() - ".class".length()); + } + resourceName = resourceName.replace('/', '.'); + return resourceName; + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/classpath/ClasspathScanner.java b/core/common/core/src/main/java/org/switchyard/common/type/classpath/ClasspathScanner.java new file mode 100644 index 000000000..3cec1f3a3 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/classpath/ClasspathScanner.java @@ -0,0 +1,152 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +import org.jboss.logging.Logger; +import org.switchyard.common.CommonCoreLogger; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * Classpath scanner. + * + * @author tom.fennelly@gmail.com + */ +public class ClasspathScanner { + + private static Logger _logger = Logger.getLogger(ClasspathScanner.class); + private Filter _filter; + + /** + * Public contractor. + * @param filter Filter instance. + */ + public ClasspathScanner(Filter filter) { + this._filter = filter; + } + + /** + * Scan the specified URL. + *

+ * The URL can be a folder or an Archive file. If a folder URL contains a + * ref value, the folder scanned will be equivalent to + * new File(url.getPath(),url.getRef()). This supports simple + * filtering of a specific subdirectory within a class folder and ensures + * class/file names are generated correctly based on folder structure. For + * example, + *

+ * scan(new URL(new File("./target/test-classes").toURI().toURL(), "#org/switchyard/special/scan")) + *

+ * will scan the folder "org/switchyard/special/scan" within + * "target/test-classes". + * + * @param url URL to scan. + * @throws IOException Error reading from URL target. + */ + public void scan(URL url) throws IOException { + File file = toClassPathFile(url); + + if (file.exists()) { + if (file.isDirectory()) { + handleDirectory(file, url.getRef()); + } else { + handleArchive(file); + } + } else { + CommonCoreLogger.ROOT_LOGGER.unknownClasspathURL(file.getAbsolutePath()); + } + } + + /** + * Convert the supplied classpath URL to a File. + * @param classPathURL The classpath URL. + * @return The File. + * @throws IOException Unable to convert. + */ + public static File toClassPathFile(URL classPathURL) throws IOException { + String urlPath = null; + try { + // decode escape characters like %20 + urlPath = classPathURL.toURI().getPath(); + } catch (URISyntaxException use) { + // fall back to old logic if characters are already decoded + // for example a space in the URL will fail + urlPath = classPathURL.getFile(); + } + String urlRef = classPathURL.getRef(); + + if (urlPath.startsWith("file:")) { + urlPath = urlPath.substring(5); + } + + if (urlPath.indexOf('!') > 0) { + urlPath = urlPath.substring(0, urlPath.indexOf('!')); + } + + return urlRef == null || urlRef.length() == 0 ? new File(urlPath) : new File(urlPath, urlRef); + } + + private void handleArchive(File file) throws IOException { + if (_logger.isDebugEnabled()) { + _logger.debug("Scanning archive: " + file.getAbsolutePath()); + } + + ZipFile zip = new ZipFile(file); + try { + Enumeration entries = zip.entries(); + + while (entries.hasMoreElements()) { + if (!_filter.continueScanning()) { + break; + } + + ZipEntry entry = entries.nextElement(); + String name = entry.getName(); + _filter.filter(name); + } + } catch (IllegalStateException ise) { + throw new IOException(ise); + } finally { + zip.close(); + } + } + + private void handleDirectory(File file, String path) { + if (_logger.isDebugEnabled()) { + _logger.debug("Scanning directory: " + file.getAbsolutePath()); + } + + for (File child : file.listFiles()) { + if (!_filter.continueScanning()) { + break; + } + + String newPath = path == null || path.isEmpty() ? child.getName() : path + '/' + child.getName(); + + if (child.isDirectory()) { + handleDirectory(child, newPath); + } else { + _filter.filter(newPath); + } + } + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/classpath/CompositeFilter.java b/core/common/core/src/main/java/org/switchyard/common/type/classpath/CompositeFilter.java new file mode 100644 index 000000000..f919eee41 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/classpath/CompositeFilter.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Composite Filter holds multiple classpath filters. + */ +public class CompositeFilter extends AbstractTypeFilter { + + private List _filters = new LinkedList(); + + /** + * Public constructor. + * @param filters filters to be held + */ + public CompositeFilter(AbstractTypeFilter... filters) { + _filters.addAll(Arrays.asList(filters)); + } + + /** + * Add a filter. + * @param filter a filter to add + * @return a reference to this filter instance + */ + public CompositeFilter addFilter(AbstractTypeFilter filter) { + _filters.add(filter); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean matches(Class clazz) { + for (AbstractTypeFilter filter : _filters) { + if (!filter.matches(clazz)) { + return false; + } + } + return true; + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/classpath/Filter.java b/core/common/core/src/main/java/org/switchyard/common/type/classpath/Filter.java new file mode 100644 index 000000000..c7939b6eb --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/classpath/Filter.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +/** + * Classpath resource filter. + * + * @author tom.fennelly@gmail.com + */ +public interface Filter { + + /** + * Classpath resource filter method. + * @param resourceName The classpath resource file name. Needs to be converted to + * a proper class name + */ + void filter(String resourceName); + + /** + * Should the scanner continue scanning. + * @return True of the scanner should continue, otherwise false. + */ + boolean continueScanning(); +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/classpath/InstanceOfFilter.java b/core/common/core/src/main/java/org/switchyard/common/type/classpath/InstanceOfFilter.java new file mode 100644 index 000000000..9f79924a2 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/classpath/InstanceOfFilter.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +/** + * Filter classpath classes based on their type. + * + * @author tom.fennelly@gmail.com + */ +public class InstanceOfFilter extends AbstractTypeFilter { + + private Class _searchType; + + /** + * Public constructor. + * @param searchType The Java type to search for. + */ + public InstanceOfFilter(Class searchType) { + this._searchType = searchType; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean matches(Class clazz) { + return _searchType.isAssignableFrom(clazz); + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/classpath/IsAnnotationPresentFilter.java b/core/common/core/src/main/java/org/switchyard/common/type/classpath/IsAnnotationPresentFilter.java new file mode 100644 index 000000000..2333801fd --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/classpath/IsAnnotationPresentFilter.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.LinkedList; +import java.util.List; + +/** + * Filter classpath classes based on presence of an annotation. + * + * @author tom.fennelly@gmail.com + */ +public class IsAnnotationPresentFilter extends AbstractTypeFilter { + + private List> _searchTypes = + new LinkedList>(); + + /** + * Public constructor. + * @param searchType The Java type to search for. + */ + public IsAnnotationPresentFilter(Class searchType) { + _searchTypes.add(searchType); + } + + /** + * Add a search type to this filter. + * @param type the annotation type to filter for + * @return a reference to this filter instance + */ + public IsAnnotationPresentFilter addType(Class type) { + _searchTypes.add(type); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean matches(Class clazz) { + // check for class-level annotation + for (Class annotation : _searchTypes) { + if (clazz.isAnnotationPresent(annotation)) { + return true; + } + } + + // check the fields + for (Class annotation : _searchTypes) { + for (Field field : clazz.getDeclaredFields()) { + if (field.isAnnotationPresent(annotation)) { + return true; + } + } + } + + // not found + return false; + } + + /** + * Is the Java method a filter match. + * @param method The Java method to be checked. + * @return true if the Java method is a match, otherwise false. + */ + public boolean matches(Method method) { + for (Class annotation : _searchTypes) { + if (method.isAnnotationPresent(annotation)) { + return true; + } + } + + // not found + return false; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/classpath/PackageFilter.java b/core/common/core/src/main/java/org/switchyard/common/type/classpath/PackageFilter.java new file mode 100644 index 000000000..3863bc7f9 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/classpath/PackageFilter.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +/** + * Filter classpath classes besed on Java Package. + */ +public class PackageFilter extends AbstractTypeFilter { + + private List _includes = new LinkedList(); + private List _excludes = new LinkedList(); + + /** + * Public constructor. + * @param includes packages to be included + */ + public PackageFilter(Package... includes) { + _includes.addAll(Arrays.asList(includes)); + } + + /** + * Add a Package to be included. + * @param pkg a Package to include + * @return a reference to this filter instance + */ + public PackageFilter addInclude(Package pkg) { + _includes.add(pkg); + return this; + } + + /** + * Add a Package to be excluded. + * @param pkg a Package to exclude + * @return a reference to this filter instance + */ + public PackageFilter addExclude(Package pkg) { + _excludes.add(pkg); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean matches(Class clazz) { + Package pkg = clazz.getPackage(); + if (_includes.isEmpty()) { + return !_excludes.contains(pkg); + } else { + return _includes.contains(pkg) && !_excludes.contains(pkg); + } + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/classpath/ResourceExistsFilter.java b/core/common/core/src/main/java/org/switchyard/common/type/classpath/ResourceExistsFilter.java new file mode 100644 index 000000000..7f9e27768 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/classpath/ResourceExistsFilter.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +/** + * @author tom.fennelly@gmail.com + */ +public class ResourceExistsFilter implements Filter { + + private String _resourceName; + private boolean _resourceFound = false; + + /** + * Public constructor. + * @param resourceName The name of the resource to be checked for. + */ + public ResourceExistsFilter(String resourceName) { + this._resourceName = resourceName; + } + + /** + * {@inheritDoc} + */ + @Override + public void filter(String resourceName) { + _resourceFound = resourceName.equals(_resourceName); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean continueScanning() { + return !_resourceFound; + } + + /** + * Was the resource was found on the scan. + * @return True if the resource was found, otherwise false. + */ + public boolean resourceExists() { + return _resourceFound; + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/reflect/Access.java b/core/common/core/src/main/java/org/switchyard/common/type/reflect/Access.java new file mode 100644 index 000000000..28e41b3b6 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/reflect/Access.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.type.reflect; + +/** + * An abstraction of field and method access. + * + * @param the value type of this access + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface Access { + + /** + * The name of the wrapped access mechanism. + * @return the name + */ + public String getName(); + + /** + * The Class type of the wrapped access mechanism. + * @return the Class type + */ + public Class getType(); + + /** + * Whether the wrapped access mechanism is readable. + * @return true if it's readable + */ + public boolean isReadable(); + + /** + * Whether the wrapped access mechanism is writable. + * @return true if it's writable + */ + public boolean isWriteable(); + + /** + * Reads via the wrapped access mechanism targeting the specified object. + * @param target the target object to read from + * @return the read value + */ + public T read(Object target); + + /** + * Writes via the wrapped access mechanism targeting the specified object. + * @param target the target object to write to + * @param value to value to write + */ + public void write(Object target, T value); + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/reflect/BeanAccess.java b/core/common/core/src/main/java/org/switchyard/common/type/reflect/BeanAccess.java new file mode 100644 index 000000000..73db64285 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/reflect/BeanAccess.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.type.reflect; + +import java.beans.PropertyDescriptor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Access via a wrapped PropertyDescriptor. + * + * @param the value type of this access + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class BeanAccess implements Access { + + private PropertyDescriptor _propDesc; + + /** + * Constructs a new BeanAccess. + * @param propDesc the ProperyDescriptor to wrap + */ + public BeanAccess(PropertyDescriptor propDesc) { + _propDesc = propDesc; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return _propDesc.getName(); + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public Class getType() { + return (Class)_propDesc.getPropertyType(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isReadable() { + return _propDesc.getReadMethod() != null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isWriteable() { + return _propDesc.getWriteMethod() != null; + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public T read(Object target) { + Method readMethod = _propDesc.getReadMethod(); + if (readMethod != null) { + try { + return (T)readMethod.invoke(target); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae); + } catch (InvocationTargetException ite) { + throw new RuntimeException(ite); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public void write(Object target, T value) { + Method writeMethod = _propDesc.getWriteMethod(); + if (writeMethod != null) { + try { + writeMethod.invoke(target, value); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae); + } catch (InvocationTargetException ite) { + throw new RuntimeException(ite); + } + } + } + + @Override + public String toString() { + Class clazz = getType(); + String type = clazz != null ? clazz.getSimpleName() : null; + return String.format("MethodAccess(name=%s, type=%s, readable=%b, writeable=%b)", + getName(), type, isReadable(), isWriteable()); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/reflect/Construction.java b/core/common/core/src/main/java/org/switchyard/common/type/reflect/Construction.java new file mode 100644 index 000000000..38f3de81a --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/reflect/Construction.java @@ -0,0 +1,178 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.type.reflect; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +import org.switchyard.common.type.Classes; + +/** + * A utility class that makes it cleaner to construct objects using reflection. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class Construction { + + private Construction() {} + + /** + * Constructs a new object of the specified type name using it's no-arg constructor. + * @param typeName the class type name of the object + * @return the new object + */ + public static Object construct(String typeName) { + return construct(typeName, Construction.class); + } + + /** + * Constructs a new object of the specified type name using it's no-arg constructor. + * @param typeName the class type name of the object + * @param caller the class calling this method (for classloading purposes) + * @return the new object + */ + public static Object construct(String typeName, Class caller) { + return construct(typeName, (ClassLoader)(caller != null ? caller.getClassLoader() : null)); + } + + /** + * Constructs a new object of the specified type name using it's no-arg constructor. + * @param typeName the class type name of the object + * @param loader the classloader to use for classloading + * @return the new object + */ + public static Object construct(String typeName, ClassLoader loader) { + return construct(Classes.forName(typeName, loader)); + } + + /** + * Constructs a new object of the specified type using it's no-arg constructor. + * @param the type of object + * @param type the class type of the object + * @return the new object + */ + public static T construct(Class type) { + return construct(type, new Class[0], new Object[0]); + } + + /** + * Constructs a new object of the specified type name using a multi-arg constructor. + * @param typeName the class type name of the object + * @param paramTypeNames the type names of the params + * @param params the param objects + * @return the new object + */ + public static Object construct(String typeName, String[] paramTypeNames, Object[] params) { + return construct(typeName, paramTypeNames, params, Construction.class); + } + + /** + * Constructs a new object of the specified type name using a multi-arg constructor. + * @param typeName the class type name of the object + * @param paramTypeNames the type names of the params + * @param params the param objects + * @param caller the class calling this method (for classloading purposes) + * @return the new object + */ + public static Object construct(String typeName, String[] paramTypeNames, Object[] params, Class caller) { + return construct(typeName, paramTypeNames, params, (ClassLoader)(caller != null ? caller.getClassLoader() : null)); + } + + /** + * Constructs a new object of the specified type name using a multi-arg constructor. + * @param typeName the class type name of the object + * @param paramTypeNames the type names of the params + * @param params the param objects + * @param loader the classloader to use for classloading + * @return the new object + */ + public static Object construct(String typeName, String[] paramTypeNames, Object[] params, ClassLoader loader) { + Class type = Classes.forName(typeName, loader); + Class[] paramTypes = new Class[paramTypeNames.length]; + for (int i=0; i < paramTypeNames.length; i++) { + paramTypes[i] = Classes.forName(paramTypeNames[i], loader); + } + return construct(type, paramTypes, params); + } + + /** + * Constructs a new object of the specified type name using a multi-arg constructor. + * @param typeName the class type name of the object + * @param paramTypes the types of the params + * @param params the param objects + * @return the new object + */ + public static Object construct(String typeName, Class[] paramTypes, Object[] params) { + return construct(typeName, paramTypes, params, Construction.class); + } + + /** + * Constructs a new object of the specified type name using a multi-arg constructor. + * @param typeName the class type name of the object + * @param paramTypes the types of the params + * @param params the param objects + * @param caller the class calling this method (for classloading purposes) + * @return the new object + */ + public static Object construct(String typeName, Class[] paramTypes, Object[] params, Class caller) { + return construct(typeName, paramTypes, params, caller != null ? caller.getClassLoader() : null); + } + + /** + * Constructs a new object of the specified type name using a multi-arg constructor. + * @param typeName the class type name of the object + * @param paramTypes the types of the params + * @param params the param objects + * @param loader the classloader to use for classloading + * @return the new object + */ + public static Object construct(String typeName, Class[] paramTypes, Object[] params, ClassLoader loader) { + Class type = Classes.forName(typeName, loader); + return construct(type, paramTypes, params); + } + + /** + * Constructs a new object of the specified type using a multi-arg constructor. + * @param the type of object + * @param type the class type of the object + * @param paramTypes the types of the params + * @param params the param objects + * @return the new object + */ + public static T construct(Class type, Class[] paramTypes, Object[] params) { + Constructor cnst = null; + try { + cnst = type.getDeclaredConstructor(paramTypes); + } catch (NoSuchMethodException nsme1) { + try { + cnst = type.getConstructor(paramTypes); + } catch (NoSuchMethodException nsme2) { + throw new RuntimeException(nsme1); + } + } + if (!cnst.isAccessible()) { + cnst.setAccessible(true); + } + try { + return cnst.newInstance(params); + } catch (InvocationTargetException ite) { + throw new RuntimeException(ite); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae); + } catch (InstantiationException ie) { + throw new RuntimeException(ie); + } + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/reflect/FieldAccess.java b/core/common/core/src/main/java/org/switchyard/common/type/reflect/FieldAccess.java new file mode 100644 index 000000000..b380e3848 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/reflect/FieldAccess.java @@ -0,0 +1,159 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.type.reflect; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +import org.switchyard.common.lang.Strings; + +/** + * Access via a wrapped Field. + * + * @param the value type of this access + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class FieldAccess implements Access { + + private Field _field; + + /** + * Constructs a new FieldAccess. + * @param field the Field to wrap + */ + public FieldAccess(Field field) { + setField(field); + } + + /** + * Constructs a new FieldAccess. + * @param clazz the declaring class + * @param fieldName the field name + */ + public FieldAccess(Class clazz, String fieldName) { + Field field; + fieldName = Strings.trimToNull(fieldName); + if (fieldName != null) { + try { + field = clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException nsfe1) { + try { + field = clazz.getField(fieldName); + } catch (NoSuchFieldException nsfe2) { + field = null; + } + } + + if (field != null) { + setField(field); + } + } + } + + private void setField(Field field) { + _field = field; + if ((field != null) && (!_field.isAccessible())) { + _field.setAccessible(true); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + if (_field != null) { + return _field.getName(); + } else { + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public Class getType() { + if (_field != null) { + return (Class)_field.getType(); + } else { + return null; + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isReadable() { + if (_field != null) { + return !Modifier.isStatic(_field.getModifiers()); + } else { + return false; + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isWriteable() { + if (_field != null) { + int mod = _field.getModifiers(); + return !Modifier.isStatic(mod) && !Modifier.isFinal(mod); + } else { + return false; + } + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public T read(Object target) { + try { + return (T)_field.get(target); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae); + } catch (NullPointerException npe) { + throw new RuntimeException(npe); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void write(Object target, T value) { + try { + _field.set(target, value); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae); + } catch (NullPointerException npe) { + throw new RuntimeException(npe); + } + } + + @Override + public String toString() { + Class clazz = getType(); + String type = clazz != null ? clazz.getSimpleName() : null; + return String.format("FieldAccess(name=%s, type=%s, readable=%b, writeable=%b)", + getName(), type, isReadable(), isWriteable()); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/type/reflect/MethodAccess.java b/core/common/core/src/main/java/org/switchyard/common/type/reflect/MethodAccess.java new file mode 100644 index 000000000..d01b4a9e2 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/type/reflect/MethodAccess.java @@ -0,0 +1,192 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.type.reflect; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.switchyard.common.lang.Strings; + +/** + * Access via wrapped read and write Methods. + * + * @param the value type of this access + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class MethodAccess implements Access { + + private Method _readMethod; + private Method _writeMethod; + private String _name = null; + private Class _type; + + /** + * Constructs a new MethodAccess. + * @param readMethod the read Method to wrap + * @param writeMethod the write Method to wrap + */ + public MethodAccess(Method readMethod, Method writeMethod) { + setMethods(readMethod, writeMethod); + } + + /** + * Constructs a new MethodAccess. + * @param clazz the declaring class + * @param readMethodName the read method name + * @param writeMethodName the write method name + */ + public MethodAccess(Class clazz, String readMethodName, String writeMethodName) { + Method readMethod; + readMethodName = Strings.trimToNull(readMethodName); + if (readMethodName == null) { + readMethod = null; + } else { + try { + readMethod = clazz.getDeclaredMethod(readMethodName); + } catch (NoSuchMethodException nsfe1) { + try { + readMethod = clazz.getMethod(readMethodName); + } catch (NoSuchMethodException nsfe2) { + readMethod = null; + } + } + } + Method writeMethod; + writeMethodName = Strings.trimToNull(writeMethodName); + if (writeMethodName == null) { + writeMethod = null; + } else { + try { + writeMethod = clazz.getDeclaredMethod(writeMethodName); + } catch (NoSuchMethodException nsfe1) { + try { + writeMethod = clazz.getMethod(writeMethodName); + } catch (NoSuchMethodException nsfe2) { + writeMethod = null; + } + } + } + setMethods(readMethod, writeMethod); + } + + @SuppressWarnings("unchecked") + private void setMethods(Method readMethod, Method writeMethod) { + if (readMethod != null) { + _readMethod = readMethod; + if (!_readMethod.isAccessible()) { + _readMethod.setAccessible(true); + } + _type = (Class)_readMethod.getReturnType(); + String name = _readMethod.getName(); + if (name.startsWith("get") || name.startsWith("is")) { + name = name.startsWith("get") ? name.substring(3) : name.substring(2); + char c = Character.toLowerCase(name.charAt(0)); + _name = new StringBuilder().append(c).append(name.substring(1)).toString(); + } + } + if (writeMethod != null) { + _writeMethod = writeMethod; + if (!_writeMethod.isAccessible()) { + _writeMethod.setAccessible(true); + } + if (_type == null) { + _type = (Class)_writeMethod.getParameterTypes()[0]; + } + if (_name == null) { + String name = _writeMethod.getName(); + if (name.startsWith("set")) { + name = name.substring(3); + char c = Character.toLowerCase(name.charAt(0)); + _name = new StringBuilder().append(c).append(name.substring(1)).toString(); + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public Class getType() { + return _type; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isReadable() { + return _readMethod != null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isWriteable() { + return _writeMethod != null; + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public T read(Object target) { + if (_readMethod != null) { + try { + return (T)_readMethod.invoke(target); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae); + } catch (InvocationTargetException ite) { + throw new RuntimeException(ite); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public void write(Object target, T value) { + if (_writeMethod != null) { + try { + _writeMethod.invoke(target, value); + } catch (IllegalAccessException iae) { + throw new RuntimeException(iae); + } catch (InvocationTargetException ite) { + throw new RuntimeException(ite); + } + } + } + + @Override + public String toString() { + Class clazz = getType(); + String type = clazz != null ? clazz.getSimpleName() : null; + return String.format("MethodAccess(name=%s, type=%s, readable=%b, writeable=%b)", + getName(), type, isReadable(), isWriteable()); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/util/ProviderRegistry.java b/core/common/core/src/main/java/org/switchyard/common/util/ProviderRegistry.java new file mode 100644 index 000000000..bb8d65cbf --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/util/ProviderRegistry.java @@ -0,0 +1,142 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @author tags. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A + * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + * You should have received a copy of the GNU Lesser General Public License, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.switchyard.common.util; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ServiceLoader; + +import org.jboss.logging.Logger; +import org.switchyard.common.type.Classes; + +/** + * A registry for service providers which allows for service lookup using a + * registry in place of ServiceLoader. If no registry is available, + * ServiceLoader is used as a fallback. + */ +public final class ProviderRegistry { + + private static Registry _registry; + private static Logger _logger = Logger.getLogger(ProviderRegistry.class); + + private ProviderRegistry() { + } + + /** + * Obtain a provider using the Thread Context ClassLoader. + * + * @param clazz the class of the provider to find + * @param the provider type + * @return a provider of the specified class or null if none is available + */ + public static T getProvider(Class clazz) { + return getProvider(clazz, Classes.getTCCL()); + } + + /** + * Obtain a provider using a specified ClassLoader. + * + * @param clazz the class of the provider to find + * @param loader the class loader + * @param the provider type + * @return a provider of the specified class or null if none is available + */ + public static T getProvider(Class clazz, ClassLoader loader) { + if (_registry != null) { + return _registry.getProvider(clazz); + } + ServiceLoader services = ServiceLoader.load(clazz, loader); + Iterator iterator = services.iterator(); + while (iterator.hasNext()) { + try { + return iterator.next(); + } catch (Throwable t) { + _logger.debug("Error creating provider for class " + clazz.getName(), t); + } + } + return null; + } + + /** + * Obtain a list of providers using the Thread Context ClassLoader. + * + * @param clazz the class of the provider to find + * @param the provider type + * @return the list of providers found + */ + public static List getProviders(Class clazz) { + return getProviders(clazz, Classes.getTCCL()); + } + + /** + * Obtain a list of providers using a specified ClassLoader. + * + * @param clazz the class of the provider to find + * @param loader the class loader + * @param the provider type + * @return the list of providers found + */ + public static List getProviders(Class clazz, ClassLoader loader) { + if (_registry != null) { + return _registry.getProviders(clazz); + } + List list = new ArrayList(); + ServiceLoader services = ServiceLoader.load(clazz, loader); + Iterator iterator = services.iterator(); + while (iterator.hasNext()) { + try { + list.add(iterator.next()); + } catch (Throwable t) { + _logger.debug("Error creating provider for class " + clazz.getName(), t); + } + } + return list; + } + + /** + * Set a registry provider to be used for service lookups. + * @param registry service provider registry + */ + public static void setRegistry(Registry registry) { + ProviderRegistry._registry = registry; + } + + /** + * Represents a pluggable service registry provider. + */ + public interface Registry { + /** + * Return a provider for the specified interface. + * @param clazz the class of the provider to find + * @param the provider type + * @return provider + */ + T getProvider(Class clazz); + + /** + * Return a list of providers for the specified interface. + * @param clazz the class of the provider to find + * @param the provider type + * @return list of providers + */ + List getProviders(Class clazz); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/BaseImplementation.java b/core/common/core/src/main/java/org/switchyard/common/version/BaseImplementation.java new file mode 100644 index 000000000..40b7152bf --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/BaseImplementation.java @@ -0,0 +1,238 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import static org.switchyard.common.version.BaseVersion.compare; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +/** + * BaseImplementation. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public class BaseImplementation implements Implementation { + + private final String _title; + private final String _vendor; + private final String _vendorId; + private final URL _url; + // we maintain a URI internally for equals() and hashCode() since URLs perform name resolution during equals() + private final URI _uri; + private final String _version; + + /** + * Constructs a new BaseImplementation. + * @param title the title + * @param vendor the vendor + * @param vendorId the vendorId + * @param url the url + * @param version the version + */ + public BaseImplementation(String title, String vendor, String vendorId, URL url, String version) { + _title = title; + _vendor = vendor; + _vendorId = vendorId; + _url = url; + _uri = toURI(_url); + _version = version; + } + + /** + * Constructs a new BaseImplementation. + * @param title the title + * @param vendor the vendor + * @param vendorId the vendorId + * @param url the url + * @param version the version + */ + public BaseImplementation(String title, String vendor, String vendorId, String url, String version) { + _title = title; + _vendor = vendor; + _vendorId = vendorId; + _url = toURL(url); + _uri = toURI(_url); + _version = version; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTitle() { + return _title; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVendor() { + return _vendor; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVendorId() { + return _vendorId; + } + + /** + * {@inheritDoc} + */ + @Override + public URL getURL() { + return _url; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVersion() { + return _version; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("%s [title=%s, vendor=%s, vendorId=%s, url=%s, version=%s]", Implementation.class.getSimpleName(), getTitle(), getVendor(), getVendorId(), getURL(), getVersion()); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BaseImplementation other = (BaseImplementation)obj; + if (_title == null) { + if (other._title != null) { + return false; + } + } else if (!_title.equals(other._title)) { + return false; + } + if (_vendor == null) { + if (other._vendor != null) { + return false; + } + } else if (!_vendor.equals(other._vendor)) { + return false; + } + if (_vendorId == null) { + if (other._vendorId != null) { + return false; + } + } else if (!_vendorId.equals(other._vendorId)) { + return false; + } + if (_uri == null) { + if (other._uri != null) { + return false; + } + } else if (!_uri.equals(other._uri)) { + return false; + } + if (_version == null) { + if (other._version != null) { + return false; + } + } else if (!_version.equals(other._version)) { + return false; + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (_title == null ? 0 : _title.hashCode()); + result = prime * result + (_vendor == null ? 0 : _vendor.hashCode()); + result = prime * result + (_vendorId == null ? 0 : _vendorId.hashCode()); + result = prime * result + (_uri == null ? 0 : _uri.hashCode()); + result = prime * result + (_version == null ? 0 : _version.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public int compareTo(Implementation that) { + int comparison = 0; + if (this != that) { + comparison = compare(_title, that.getTitle()); + if (comparison == 0) { + comparison = compare(_vendor, that.getVendor()); + if (comparison == 0) { + comparison = compare(_vendorId, that.getVendorId()); + if (comparison == 0) { + comparison = compare(toString(_url), toString(that.getURL())); + if (comparison == 0) { + comparison = compare(_version, that.getVersion()); + } + } + } + } + } + return comparison; + } + + private URI toURI(URL url) { + if (url != null) { + try { + return url.toURI(); + } catch (URISyntaxException usi) { + return null; + } + } + return null; + } + + private URL toURL(String url) { + if (url != null) { + try { + return new URL(url); + } catch (MalformedURLException mue) { + return null; + } + } + return null; + } + + private String toString(URL url) { + return url != null ? url.toString() : null; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/BaseProject.java b/core/common/core/src/main/java/org/switchyard/common/version/BaseProject.java new file mode 100644 index 000000000..57331c6f5 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/BaseProject.java @@ -0,0 +1,286 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import static org.switchyard.common.version.BaseVersion.compare; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +/** + * BaseProject. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public class BaseProject implements Project { + + private final String _groupId; + private final String _artifactId; + private final String _packaging; + private final String _name; + private final String _description; + private final URL _url; + // we maintain a URI internally for equals() and hashCode() since URLs perform name resolution during equals() + private final URI _uri; + private final String _version; + + /** + * Constructs a new BaseSpecification. + * @param groupId the groupId + * @param artifactId the artifactId + * @param packaging the packaging + * @param name the name + * @param description the description + * @param url the url + * @param version the version + */ + public BaseProject(String groupId, String artifactId, String packaging, String name, String description, URL url, String version) { + _groupId = groupId; + _artifactId = artifactId; + _packaging = packaging; + _name = name; + _description = description; + _url = url; + _uri = toURI(_url); + _version = version; + } + + /** + * Constructs a new BaseSpecification. + * @param groupId the groupId + * @param artifactId the artifactId + * @param packaging the packaging + * @param name the name + * @param description the description + * @param url the url + * @param version the version + */ + public BaseProject(String groupId, String artifactId, String packaging, String name, String description, String url, String version) { + _groupId = groupId; + _artifactId = artifactId; + _packaging = packaging; + _name = name; + _description = description; + _url = toURL(url); + _uri = toURI(_url); + _version = version; + } + + /** + * {@inheritDoc} + */ + @Override + public String getGroupId() { + return _groupId; + } + + /** + * {@inheritDoc} + */ + @Override + public String getArtifactId() { + return _artifactId; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPackaging() { + return _packaging; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public String getDescription() { + return _description; + } + + /** + * {@inheritDoc} + */ + @Override + public URL getURL() { + return _url; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVersion() { + return _version; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("%s [groupId=%s, artifactId=%s, packaging=%s, name=%s, description=%s, url=%s, version=%s]", Project.class.getSimpleName(), getGroupId(), getArtifactId(), getPackaging(), getName(), getDescription(), getURL(), getVersion()); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BaseProject other = (BaseProject)obj; + if (_groupId == null) { + if (other._groupId != null) { + return false; + } + } else if (!_groupId.equals(other._groupId)) { + return false; + } + if (_artifactId == null) { + if (other._artifactId != null) { + return false; + } + } else if (!_artifactId.equals(other._artifactId)) { + return false; + } + if (_packaging == null) { + if (other._packaging != null) { + return false; + } + } else if (!_packaging.equals(other._packaging)) { + return false; + } + if (_name == null) { + if (other._name != null) { + return false; + } + } else if (!_name.equals(other._name)) { + return false; + } + if (_description == null) { + if (other._description != null) { + return false; + } + } else if (!_description.equals(other._description)) { + return false; + } + if (_uri == null) { + if (other._uri != null) { + return false; + } + } else if (!_uri.equals(other._uri)) { + return false; + } + if (_version == null) { + if (other._version != null) { + return false; + } + } else if (!_version.equals(other._version)) { + return false; + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (_groupId == null ? 0 : _groupId.hashCode()); + result = prime * result + (_artifactId == null ? 0 : _artifactId.hashCode()); + result = prime * result + (_packaging == null ? 0 : _packaging.hashCode()); + result = prime * result + (_name == null ? 0 : _name.hashCode()); + result = prime * result + (_description == null ? 0 : _description.hashCode()); + result = prime * result + (_uri == null ? 0 : _uri.hashCode()); + result = prime * result + (_version == null ? 0 : _version.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public int compareTo(Project that) { + int comparison = 0; + if (this != that) { + comparison = compare(_groupId, that.getGroupId()); + if (comparison == 0) { + comparison = compare(_artifactId, that.getArtifactId()); + if (comparison == 0) { + comparison = compare(_packaging, that.getPackaging()); + if (comparison == 0) { + comparison = compare(_name, that.getName()); + if (comparison == 0) { + comparison = compare(_description, that.getDescription()); + if (comparison == 0) { + comparison = compare(toString(_url), toString(that.getURL())); + if (comparison == 0) { + comparison = compare(_version, that.getVersion()); + } + } + } + } + } + } + } + return comparison; + } + + private URI toURI(URL url) { + if (url != null) { + try { + return url.toURI(); + } catch (URISyntaxException usi) { + return null; + } + } + return null; + } + + private URL toURL(String url) { + if (url != null) { + try { + return new URL(url); + } catch (MalformedURLException mue) { + return null; + } + } + return null; + } + + private String toString(URL url) { + return url != null ? url.toString() : null; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/BaseSpecification.java b/core/common/core/src/main/java/org/switchyard/common/version/BaseSpecification.java new file mode 100644 index 000000000..593286ea1 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/BaseSpecification.java @@ -0,0 +1,143 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import static org.switchyard.common.version.BaseVersion.compare; + +/** + * BaseSpecification. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public class BaseSpecification implements Specification { + + private final String _title; + private final String _vendor; + private final String _version; + + /** + * Constructs a new BaseSpecification. + * @param title the title + * @param vendor the vendor + * @param version the version + */ + public BaseSpecification(String title, String vendor, String version) { + _title = title; + _vendor = vendor; + _version = version; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTitle() { + return _title; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVendor() { + return _vendor; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVersion() { + return _version; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("%s [title=%s, vendor=%s, version=%s]", Specification.class.getSimpleName(), getTitle(), getVendor(), getVersion()); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BaseSpecification other = (BaseSpecification)obj; + if (_title == null) { + if (other._title != null) { + return false; + } + } else if (!_title.equals(other._title)) { + return false; + } + if (_vendor == null) { + if (other._vendor != null) { + return false; + } + } else if (!_vendor.equals(other._vendor)) { + return false; + } + if (_version == null) { + if (other._version != null) { + return false; + } + } else if (!_version.equals(other._version)) { + return false; + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (_title == null ? 0 : _title.hashCode()); + result = prime * result + (_vendor == null ? 0 : _vendor.hashCode()); + result = prime * result + (_version == null ? 0 : _version.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public int compareTo(Specification that) { + int comparison = 0; + if (this != that) { + comparison = compare(_title, that.getTitle()); + if (comparison == 0) { + comparison = compare(_vendor, that.getVendor()); + if (comparison == 0) { + comparison = compare(_version, that.getVersion()); + } + } + } + return comparison; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/BaseVersion.java b/core/common/core/src/main/java/org/switchyard/common/version/BaseVersion.java new file mode 100644 index 000000000..a59e197cd --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/BaseVersion.java @@ -0,0 +1,160 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +/** + * BaseVersion. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public class BaseVersion implements Version { + + private final Project _project; + private final Specification _specification; + private final Implementation _implementation; + + /** + * Constructs a new BaseVersion. + * @param project the Project + * @param specification the Specification + * @param implementation the Implementation + */ + public BaseVersion(Project project, Specification specification, Implementation implementation) { + _project = project; + _specification = specification; + _implementation = implementation; + } + + /** + * {@inheritDoc} + */ + @Override + public Project getProject() { + return _project; + } + + /** + * {@inheritDoc} + */ + @Override + public Specification getSpecification() { + return _specification; + } + + /** + * {@inheritDoc} + */ + @Override + public Implementation getImplementation() { + return _implementation; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("%s: %s, %s, %s", Version.class.getSimpleName(), getProject(), getSpecification(), getImplementation()); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BaseVersion other = (BaseVersion)obj; + if (_project == null) { + if (other._project != null) { + return false; + } + } else if (!_project.equals(other._project)) { + return false; + } + if (_specification == null) { + if (other._specification != null) { + return false; + } + } else if (!_specification.equals(other._specification)) { + return false; + } + if (_implementation == null) { + if (other._implementation != null) { + return false; + } + } else if (!_implementation.equals(other._implementation)) { + return false; + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (_project == null ? 0 : _project.hashCode()); + result = prime * result + (_specification == null ? 0 : _specification.hashCode()); + result = prime * result + (_implementation == null ? 0 : _implementation.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public int compareTo(Version that) { + int comparison = 0; + if (this != that) { + if (that == null) { + comparison = -1; + } else { + if (_project != null) { + comparison = _project.compareTo(that.getProject()); + } + if (comparison == 0 && _specification != null) { + comparison = _specification.compareTo(that.getSpecification()); + } + if (comparison == 0 && _implementation != null) { + comparison = _implementation.compareTo(that.getImplementation()); + } + } + } + return comparison; + } + + static int compare(String s1, String s2) { + if (s1 != null) { + if (s2 != null) { + return s1.compareTo(s2); + } + return -1; + } + if (s2 != null) { + return 1; + } + return 0; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/BaseVersionFactory.java b/core/common/core/src/main/java/org/switchyard/common/version/BaseVersionFactory.java new file mode 100644 index 000000000..a91980fde --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/BaseVersionFactory.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import java.util.Collections; +import java.util.Iterator; +import java.util.Set; + +/** + * BaseVersionFactory. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public abstract class BaseVersionFactory extends VersionFactory { + + /** + * {@inheritDoc} + */ + @Override + public final Version getVersion(Query... queries) { + Iterator i = getVersions(true, queries).iterator(); + return i.hasNext() ? i.next() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public final Set getVersions(Query... queries) { + return Collections.unmodifiableSet(getVersions(false, queries)); + } + + /** + * Gets all (or the first) versions matching the provided queries. + * @param returnFirstOnly true if only return the first matching version, false if returning all matching versions + * @param queries the queries + * @return all the matching (or first) version + */ + public abstract Set getVersions(boolean returnFirstOnly, Query... queries); + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/Implementation.java b/core/common/core/src/main/java/org/switchyard/common/version/Implementation.java new file mode 100644 index 000000000..1170a5e64 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/Implementation.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import java.net.URL; + +/** + * Implementation. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public interface Implementation extends Comparable { + + /** + * Gets the title. + * @return the title + */ + public String getTitle(); + + /** + * Gets the vendor. + * @return the vendor + */ + public String getVendor(); + + /** + * Gets the vendor id. + * @return the vendor id + */ + public String getVendorId(); + + /** + * Gets the URL. + * @return the URL + */ + public URL getURL(); + + /** + * Gets the version. + * @return the version + */ + public String getVersion(); + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/Project.java b/core/common/core/src/main/java/org/switchyard/common/version/Project.java new file mode 100644 index 000000000..bdbe695ee --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/Project.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import java.net.URL; + +/** + * Project. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public interface Project extends Comparable { + + /** + * Gets the groupId. + * @return the groupId + */ + public String getGroupId(); + + /** + * Gets the artifactId. + * @return the artifactId + */ + public String getArtifactId(); + + /** + * Gets the packaging. + * @return the packaging + */ + public String getPackaging(); + + /** + * Gets the name. + * @return the name + */ + public String getName(); + + /** + * Gets the description. + * @return the description + */ + public String getDescription(); + + /** + * Gets the URL. + * @return the URL + */ + public URL getURL(); + + /** + * Gets the version. + * @return the version + */ + public String getVersion(); + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/Queries.java b/core/common/core/src/main/java/org/switchyard/common/version/Queries.java new file mode 100644 index 000000000..5632ba4ad --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/Queries.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import static org.switchyard.common.version.QueryType.PROJECT_ARTIFACT_ID; +import static org.switchyard.common.version.QueryType.PROJECT_GROUP_ID; + +/** + * Queries. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public final class Queries { + + private Queries() {} + + /** + * Project Queries. + */ + public static final class Projects { + + private Projects() {} + + /** The PROJECT_GROUP_ID/"org.switchyard" Query. */ + public static final Query SWITCHYARD = new Query(PROJECT_GROUP_ID, "org.switchyard"); + + /** Well-known SwitchYard Project Queries. */ + public static final Query[] + SWITCHYARD_ADMIN = create(SWITCHYARD, "switchyard-admin"), + SWITCHYARD_API = create(SWITCHYARD, "switchyard-api"), + SWITCHYARD_BUS_CAMEL = create(SWITCHYARD, "switchyard-bus-camel"), + SWITCHYARD_COMMON = create(SWITCHYARD, "switchyard-common"), + SWITCHYARD_COMMON_CAMEL = create(SWITCHYARD, "switchyard-common-camel"), + SWITCHYARD_COMMON_CDI = create(SWITCHYARD, "switchyard-common-cdi"), + SWITCHYARD_COMPONENT_BEAN = create(SWITCHYARD, "switchyard-component-bean"), + SWITCHYARD_COMPONENT_BPEL = create(SWITCHYARD, "switchyard-component-bpel"), + SWITCHYARD_COMPONENT_BPM = create(SWITCHYARD, "switchyard-component-bpm"), + SWITCHYARD_COMPONENT_CAMEL = create(SWITCHYARD, "switchyard-component-camel"), + SWITCHYARD_COMPONENT_CAMEL_AMQP = create(SWITCHYARD, "switchyard-component-camel-amqp"), + SWITCHYARD_COMPONENT_CAMEL_ATOM = create(SWITCHYARD, "switchyard-component-camel-atom"), + SWITCHYARD_COMPONENT_CAMEL_CORE = create(SWITCHYARD, "switchyard-component-camel-core"), + SWITCHYARD_COMPONENT_CAMEL_FILE = create(SWITCHYARD, "switchyard-component-camel-file"), + SWITCHYARD_COMPONENT_CAMEL_FTP = create(SWITCHYARD, "switchyard-component-camel-ftp"), + SWITCHYARD_COMPONENT_CAMEL_JMS = create(SWITCHYARD, "switchyard-component-camel-jms"), + SWITCHYARD_COMPONENT_CAMEL_JPA = create(SWITCHYARD, "switchyard-component-camel-jpa"), + SWITCHYARD_COMPONENT_CAMEL_MAIL = create(SWITCHYARD, "switchyard-component-camel-mail"), + SWITCHYARD_COMPONENT_CAMEL_NETTY = create(SWITCHYARD, "switchyard-component-camel-netty"), + SWITCHYARD_COMPONENT_CAMEL_QUARTZ = create(SWITCHYARD, "switchyard-component-camel-quartz"), + SWITCHYARD_COMPONENT_CAMEL_SQL = create(SWITCHYARD, "switchyard-component-camel-sql"), + SWITCHYARD_COMPONENT_CAMEL_SWITCHYARD = create(SWITCHYARD, "switchyard-component-camel-switchyard"), + SWITCHYARD_COMPONENT_CLOJURE = create(SWITCHYARD, "switchyard-component-clojure"), + SWITCHYARD_COMPONENT_COMMON = create(SWITCHYARD, "switchyard-component-common"), + SWITCHYARD_COMPONENT_COMMON_CAMEL = create(SWITCHYARD, "switchyard-component-common-camel"), + SWITCHYARD_COMPONENT_COMMON_KNOWLEDGE = create(SWITCHYARD, "switchyard-component-common-knowledge"), + SWITCHYARD_COMPONENT_HTTP = create(SWITCHYARD, "switchyard-component-http"), + SWITCHYARD_COMPONENT_JCA = create(SWITCHYARD, "switchyard-component-jca"), + SWITCHYARD_COMPONENT_RESTEASY = create(SWITCHYARD, "switchyard-component-reaseasy"), + SWITCHYARD_COMPONENT_RULES = create(SWITCHYARD, "switchyard-component-rules"), + SWITCHYARD_COMPONENT_SCA = create(SWITCHYARD, "switchyard-component-sca"), + SWITCHYARD_COMPONENT_SOAP = create(SWITCHYARD, "switchyard-component-soap"), + SWITCHYARD_CONFIG = create(SWITCHYARD, "switchyard-config"), + SWITCHYARD_DEPLOY = create(SWITCHYARD, "switchyard-deploy"), + SWITCHYARD_DEPLOY_JBOSS_AS7 = create(SWITCHYARD, "switchyard-deploy-jboss-as7"), + SWITCHYARD_DEPLOY_CDI = create(SWITCHYARD, "switchyard-deploy-cdi"), + SWITCHYARD_DEPLOY_WEBAPP = create(SWITCHYARD, "switchyard-deploy-webapp"), + SWITCHYARD_EXTENSIONS_WSDL = create(SWITCHYARD, "switchyard-extensions-wsdl"), + SWITCHYARD_REMOTE = create(SWITCHYARD, "switchyard-remote"), + SWITCHYARD_RUNTIME = create(SWITCHYARD, "switchyard-runtime"), + SWITCHYARD_SECURITY = create(SWITCHYARD, "switchyard-security"), + SWITCHYARD_SECURITY_JBOSS = create(SWITCHYARD, "switchyard-security-jboss"), + SWITCHYARD_SERIAL = create(SWITCHYARD, "switchyard-serial"), + SWITCHYARD_SERIAL_JACKSON = create(SWITCHYARD, "switchyard-serial-jackson"), + SWITCHYARD_TRANSFORM = create(SWITCHYARD, "switchyard-transform"), + SWITCHYARD_VALIDATE = create(SWITCHYARD, "switchyard-validate"); + + /** + * Creates a new Project Query[]. + * @param groupId the Project groupId + * @param artifactId the Project artifactId + * @return the Project Query[] + */ + public static Query[] create(String groupId, String artifactId) { + return create(new Query(PROJECT_GROUP_ID, groupId), artifactId); + } + + /** + * Creates a new Project Query[]. + * @param groupQuery the Project group Query + * @param artifactId the Project artifactId + * @return the Project Query[] + * @throws IllegalArgumentException if the groupQuery is not of type PROJECT_GROUP_ID + */ + public static Query[] create(Query groupQuery, String artifactId) throws IllegalArgumentException { + if (!groupQuery.getType().equals(PROJECT_GROUP_ID)) { + throw new IllegalArgumentException(groupQuery.getType().name() + " != " + PROJECT_GROUP_ID.name()); + } + return new Query[] {groupQuery, new Query(PROJECT_ARTIFACT_ID, artifactId)}; + } + + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/Query.java b/core/common/core/src/main/java/org/switchyard/common/version/Query.java new file mode 100644 index 000000000..bc5cd0e0c --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/Query.java @@ -0,0 +1,125 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import java.net.URL; +import java.util.regex.Pattern; + +/** + * Represents a Query to a VersionFactory. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public final class Query { + + private final QueryType _type; + private final Pattern _pattern; + + /** + * Creates a new Query. + * @param type the QueryType + * @param pattern the Pattern + */ + public Query(QueryType type, Pattern pattern) { + _type = type; + _pattern = pattern; + } + + /** + * Creates a new Query. + * @param type the QueryType + * @param regex the regular expression + */ + public Query(QueryType type, String regex) { + this(type, Pattern.compile(regex)); + } + + /** + * Gets the QueryType. + * @return the QueryType + */ + public QueryType getType() { + return _type; + } + + /** + * Gets the Pattern. + * @return the Pattern + */ + public Pattern getPattern() { + return _pattern; + } + + /** + * Sees if a Version matches this Query. + * @param version the Version + * @return if it matches + */ + public boolean matches(Version version) { + final String input; + switch (getType()) { + case PROJECT_GROUP_ID: + input = version.getProject().getGroupId(); + break; + case PROJECT_ARTIFACT_ID: + input = version.getProject().getArtifactId(); + break; + case PROJECT_PACKAGING: + input = version.getProject().getPackaging(); + break; + case PROJECT_NAME: + input = version.getProject().getName(); + break; + case PROJECT_DESCRIPTION: + input = version.getProject().getDescription(); + break; + case PROJECT_URL: + final URL pUrl = version.getProject().getURL(); + input = pUrl != null ? pUrl.toString() : null; + break; + case PROJECT_VERSION: + input = version.getProject().getVersion(); + break; + case SPECIFICATION_TITLE: + input = version.getSpecification().getTitle(); + break; + case SPECIFICATION_VENDOR: + input = version.getSpecification().getVendor(); + break; + case SPECIFICATION_VERSION: + input = version.getSpecification().getVersion(); + break; + case IMPLEMENTATION_TITLE: + input = version.getImplementation().getTitle(); + break; + case IMPLEMENTATION_VENDOR: + input = version.getImplementation().getVendor(); + break; + case IMPLEMENTATION_VENDOR_ID: + input = version.getImplementation().getVendorId(); + break; + case IMPLEMENTATION_URL: + final URL iUrl = version.getImplementation().getURL(); + input = iUrl != null ? iUrl.toString() : null; + break; + case IMPLEMENTATION_VERSION: + input = version.getImplementation().getVersion(); + break; + default: + input = null; + } + return (input != null) ? getPattern().matcher(input).matches() : false; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/QueryType.java b/core/common/core/src/main/java/org/switchyard/common/version/QueryType.java new file mode 100644 index 000000000..a753c5761 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/QueryType.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +/** + * QueryType. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public enum QueryType { + + /** project groupId. */ + PROJECT_GROUP_ID, + /** project artifactId. */ + PROJECT_ARTIFACT_ID, + /** project packaging. */ + PROJECT_PACKAGING, + /** project name. */ + PROJECT_NAME, + /** project description. */ + PROJECT_DESCRIPTION, + /** project url. */ + PROJECT_URL, + /** project version. */ + PROJECT_VERSION, + + /** specification title. */ + SPECIFICATION_TITLE, + /** specification vendor. */ + SPECIFICATION_VENDOR, + /** specification version. */ + SPECIFICATION_VERSION, + + /** implementation title. */ + IMPLEMENTATION_TITLE, + /** implementation vendor. */ + IMPLEMENTATION_VENDOR, + /** implementation vendorId. */ + IMPLEMENTATION_VENDOR_ID, + /** implementation url. */ + IMPLEMENTATION_URL, + /** implementation version. */ + IMPLEMENTATION_VERSION; + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/Specification.java b/core/common/core/src/main/java/org/switchyard/common/version/Specification.java new file mode 100644 index 000000000..6109bded7 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/Specification.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +/** + * Specification. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public interface Specification extends Comparable { + + /** + * Gets the title. + * @return the title + */ + public String getTitle(); + + /** + * Gets the vendor. + * @return the vendor + */ + public String getVendor(); + + /** + * Gets the version. + * @return the version + */ + public String getVersion(); + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/Version.java b/core/common/core/src/main/java/org/switchyard/common/version/Version.java new file mode 100644 index 000000000..ee5d6d6bf --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/Version.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +/** + * Version. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public interface Version extends Comparable { + + /** + * Gets the Project. + * @return the Project + */ + public Project getProject(); + + /** + * Gets the Specification. + * @return the Specification + */ + public Specification getSpecification(); + + /** + * Gets the Implementation. + * @return the Implementation + */ + public Implementation getImplementation(); + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/VersionFactory.java b/core/common/core/src/main/java/org/switchyard/common/version/VersionFactory.java new file mode 100644 index 000000000..e915ead0d --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/VersionFactory.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import java.util.Set; + +import org.switchyard.common.version.manifest.ManifestVersionFactory; + +/** + * Gets Versions via Queries. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public abstract class VersionFactory { + + // Hardcoding until we actually have a reason to populate dynamically (via ServiceLoader). + private static final VersionFactory INSTANCE = new ManifestVersionFactory(); + + /** + * Gets the first version matching the provided queries. + * @param queries the queries + * @return the first matching version + */ + public abstract Version getVersion(Query... queries); + + /** + * Gets all versions matching the provided queries. + * @param queries the queries + * @return all the matching versions + */ + public abstract Set getVersions(Query... queries); + + /** + * Returns the singleton instance of the VersionFactory. + * @return the singleton instance + */ + public static final VersionFactory instance() { + return INSTANCE; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/Versions.java b/core/common/core/src/main/java/org/switchyard/common/version/Versions.java new file mode 100644 index 000000000..a709c7147 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/Versions.java @@ -0,0 +1,163 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version; + +import static java.lang.System.out; +import static org.switchyard.common.version.Queries.Projects.SWITCHYARD; +import static org.switchyard.common.version.Queries.Projects.SWITCHYARD_COMMON; + +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.Writer; +import java.util.Set; + +import org.jboss.logging.Logger; + +/** + * Versions. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public final class Versions { + + private static final Logger LOGGER = Logger.getLogger(Versions.class); + + private static final String NOTIFICATION_PREFIX = "SwitchYard version "; + + private Versions() {} + + /** + * Gets the simple SwitchYard version String (based on the switchyard-common Project Version). + * @return the simple SwitchYard version String + */ + public static String getSwitchYardVersion() { + return VersionFactory.instance().getVersion(SWITCHYARD_COMMON).getProject().getVersion(); + } + + /** + * Gets the SwitchYard notification (for example, "SwitchYard version 1.0.0.Final"). + * @return the SwitchYard notification + */ + public static String getSwitchYardNotification() { + return NOTIFICATION_PREFIX + getSwitchYardVersion(); + } + + /** + * Logs the SwitchYard notification returned by {@link #getSwitchYardNotification()}. + * @param logger the Logger to log to + */ + public static void logSwitchYardNotification(Logger logger) { + if (logger.isInfoEnabled()) { + logger.info(getSwitchYardNotification()); + } + } + + /** + * Logs the SwichYard notification returned by {@link #getSwitchYardNotification()}. + */ + public static void logSwitchYardNotification() { + logSwitchYardNotification(LOGGER); + } + + /** + * Prints the SwitchYard notification returned by {@link #getSwitchYardNotification()}. + * @param w the Writer to print to + */ + public static void printSwitchYardNotification(Writer w) { + @SuppressWarnings("resource") + PrintWriter pw = (w instanceof PrintWriter) ? (PrintWriter)w : new PrintWriter(w); + pw.println(getSwitchYardNotification()); + pw.flush(); + } + + /** + * Prints the SwitchYard notification returned by {@link #getSwitchYardNotification()}. + * @param os the OutputStream to print to + */ + public static void printSwitchYardNotification(OutputStream os) { + printSwitchYardNotification(new PrintWriter(os)); + } + + /** + * Prints the SwitchYard notification returned by {@link #getSwitchYardNotification()} to STDOUT (System.out). + */ + public static void printSwitchYardNotification() { + printSwitchYardNotification(out); + } + + /** + * Gets the Set of all SwitchYard Versions (those with Project groupIds matching "org.switchyard"). + * @return the Set of all SwitchYard Versions + */ + public static Set getSwitchYardVersions() { + return VersionFactory.instance().getVersions(SWITCHYARD); + } + + /** + * Logs each Version returned by {@link #getSwitchYardVersions()}. + * @param logger the Logger to log to + */ + public static void logSwitchYardVersions(Logger logger) { + if (logger.isInfoEnabled()) { + for (Version version : getSwitchYardVersions()) { + logger.info(version); + } + } + } + + /** + * Logs each Version returned by {@link #getSwitchYardVersions()}. + */ + public static void logSwitchYardVersions() { + logSwitchYardVersions(LOGGER); + } + + /** + * Prints each Version returned by {@link #getSwitchYardVersions()}. + * @param w the Writer to print to + */ + public static void printSwitchYardVersions(Writer w) { + @SuppressWarnings("resource") + PrintWriter pw = (w instanceof PrintWriter) ? (PrintWriter)w : new PrintWriter(w); + for (Version version : getSwitchYardVersions()) { + pw.println(version); + } + pw.flush(); + } + + /** + * Prints each Version returned by {@link #getSwitchYardVersions()}. + * @param os the OutputStream to print to + */ + public static void printSwitchYardVersions(OutputStream os) { + printSwitchYardVersions(new PrintWriter(os)); + } + + /** + * Prints each Version returned by {@link #getSwitchYardVersions()} to STDOUT (System.out). + */ + public static void printSwitchYardVersions() { + printSwitchYardVersions(out); + } + + /** + * Calls {@link #printSwitchYardNotification()} and {@link #printSwitchYardVersions()}. + * @param args unused + */ + public static void main(String... args) { + printSwitchYardNotification(); + printSwitchYardVersions(); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestImplementation.java b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestImplementation.java new file mode 100644 index 000000000..da7edcbcd --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestImplementation.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version.manifest; + +import static java.util.jar.Attributes.Name.IMPLEMENTATION_TITLE; +import static java.util.jar.Attributes.Name.IMPLEMENTATION_URL; +import static java.util.jar.Attributes.Name.IMPLEMENTATION_VENDOR; +import static java.util.jar.Attributes.Name.IMPLEMENTATION_VENDOR_ID; +import static java.util.jar.Attributes.Name.IMPLEMENTATION_VERSION; +import static org.switchyard.common.version.manifest.ManifestVersion.getMainAttributesValue; + +import java.util.jar.Manifest; + +import org.switchyard.common.version.BaseImplementation; + +/** + * ManifestImplementation. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +final class ManifestImplementation extends BaseImplementation { + + ManifestImplementation(Manifest manifest) { + super(getMainAttributesValue(manifest, IMPLEMENTATION_TITLE), + getMainAttributesValue(manifest, IMPLEMENTATION_VENDOR), + getMainAttributesValue(manifest, IMPLEMENTATION_VENDOR_ID), + getMainAttributesValue(manifest, IMPLEMENTATION_URL), + getMainAttributesValue(manifest, IMPLEMENTATION_VERSION)); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestProject.java b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestProject.java new file mode 100644 index 000000000..53a7052d4 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestProject.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version.manifest; + +import static org.switchyard.common.version.manifest.ManifestVersion.getMainAttributesValue; + +import java.util.jar.Manifest; + +import org.switchyard.common.version.BaseProject; + +/** + * ManifestProject. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +final class ManifestProject extends BaseProject { + + ManifestProject(Manifest manifest) { + super(getMainAttributesValue(manifest, "Project-Group-Id"), + getMainAttributesValue(manifest, "Project-Artifact-Id"), + getMainAttributesValue(manifest, "Project-Packaging"), + getMainAttributesValue(manifest, "Project-Name"), + getMainAttributesValue(manifest, "Project-Description"), + getMainAttributesValue(manifest, "Project-URL"), + getMainAttributesValue(manifest, "Project-Version")); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestSpecification.java b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestSpecification.java new file mode 100644 index 000000000..23470aad3 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestSpecification.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version.manifest; + +import static java.util.jar.Attributes.Name.SPECIFICATION_TITLE; +import static java.util.jar.Attributes.Name.SPECIFICATION_VENDOR; +import static java.util.jar.Attributes.Name.SPECIFICATION_VERSION; +import static org.switchyard.common.version.manifest.ManifestVersion.getMainAttributesValue; + +import java.util.jar.Manifest; + +import org.switchyard.common.version.BaseSpecification; + +/** + * ManifestSpecification. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +final class ManifestSpecification extends BaseSpecification { + + ManifestSpecification(Manifest manifest) { + super(getMainAttributesValue(manifest, SPECIFICATION_TITLE), + getMainAttributesValue(manifest, SPECIFICATION_VENDOR), + getMainAttributesValue(manifest, SPECIFICATION_VERSION)); + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestVersion.java b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestVersion.java new file mode 100644 index 000000000..e9d6b8a0f --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestVersion.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version.manifest; + +import java.util.jar.Attributes; +import java.util.jar.Attributes.Name; +import java.util.jar.Manifest; + +import org.switchyard.common.version.BaseVersion; + +/** + * ManifestVersion. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +final class ManifestVersion extends BaseVersion { + + ManifestVersion(Manifest manifest) { + super(new ManifestProject(manifest), new ManifestSpecification(manifest), new ManifestImplementation(manifest)); + } + + static String getMainAttributesValue(Manifest manifest, Name name) { + Attributes attributes = getMainAttributes(manifest); + return (attributes != null) ? attributes.getValue(name) : null; + } + + static String getMainAttributesValue(Manifest manifest, String name) { + Attributes attributes = getMainAttributes(manifest); + return (attributes != null) ? attributes.getValue(name) : null; + } + + private static Attributes getMainAttributes(Manifest manifest) { + return (manifest != null) ? manifest.getMainAttributes() : null; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestVersionFactory.java b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestVersionFactory.java new file mode 100644 index 000000000..580567b7a --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/version/manifest/ManifestVersionFactory.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.version.manifest; + +import static java.util.jar.JarFile.MANIFEST_NAME; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.jar.Manifest; + +import org.jboss.logging.Logger; +import org.switchyard.common.CommonCoreLogger; +import org.switchyard.common.type.Classes; +import org.switchyard.common.version.BaseVersionFactory; +import org.switchyard.common.version.Query; +import org.switchyard.common.version.Version; + +/** + * The factory for ManifestVersion. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public final class ManifestVersionFactory extends BaseVersionFactory { + + private static final Logger LOGGER = Logger.getLogger(ManifestVersionFactory.class); + + /** + * {@inheritDoc} + */ + @Override + public Set getVersions(boolean returnFirstOnly, Query... queries) { + List urls; + try { + urls = Classes.getResources(MANIFEST_NAME, getClass()); + } catch (IOException ioe) { + urls = Collections.emptyList(); + } + Set versions = new TreeSet(); + urlLoop: for (URL url : urls) { + InputStream is = null; + try { + URLConnection conn = url.openConnection(); + // avoid file-locking on Windows + conn.setUseCaches(false); + is = conn.getInputStream(); + Version version = new ManifestVersion(new Manifest(is)); + boolean matches = true; + queryLoop: for (Query query : queries) { + if (!query.matches(version)) { + matches = false; + break queryLoop; + } + } + if (matches) { + versions.add(version); + if (returnFirstOnly) { + break urlLoop; + } + } + } catch (IOException ioe) { + CommonCoreLogger.ROOT_LOGGER.problemReadingStream(url.toString(), ioe.getMessage()); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException ioe) { + CommonCoreLogger.ROOT_LOGGER.problemClosingStream(url.toString(), ioe.getMessage()); + } + } + } + } + return versions; + } + +} diff --git a/core/common/core/src/main/java/org/switchyard/common/xml/Element.java b/core/common/core/src/main/java/org/switchyard/common/xml/Element.java new file mode 100644 index 000000000..eb4d5c8fd --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/xml/Element.java @@ -0,0 +1,137 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.xml; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import javax.xml.namespace.QName; + +import org.xml.sax.Attributes; + +/** + * Simple class representing an element. + * This is used to compare XML documents. + * + * @author Kevin Conner + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class Element implements Node { + /** + * The QName comparator. + */ + private static final Comparator QNAME_COMPARATOR = new QNameComparator(); + + /** + * The name of the element. + */ + private final QName _name; + /** + * Associated attributes. + */ + private final Map _attributes = new TreeMap(QNAME_COMPARATOR); + /** + * Children. + */ + private final List _children = new ArrayList(); + + /** + * Construct the element. + * @param namespaceURI The namespace for the element. + * @param localName The local name of the element. + * @param attributes The associated attributes. + */ + Element(final String namespaceURI, final String localName, final Attributes attributes) { + _name = new QName(namespaceURI, localName); + final int numAttributes = attributes.getLength(); + for (int count = 0; count < numAttributes; count++) { + final String attrNamespaceURI = attributes.getURI(count); + final String attrLocalName = attributes.getLocalName(count); + final String attrValue = attributes.getValue(count); + + this._attributes.put(new QName(attrNamespaceURI, attrLocalName), attrValue); + } + } + + /** + * Add a child node. + * @param child The child node. + */ + void addChild(final Node child) { + _children.add(child); + } + + /** + * Check for equality. + * @param obj the object to test against. + * @return true if the objects are equal. + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + + if (obj == this) { + return true; + } + + if (obj instanceof Element) { + final Element rhs = (Element) obj; + return (_name.equals(rhs._name) && _attributes.equals(rhs._attributes) + && _children.equals(rhs._children)); + } + + return false; + } + + /** + * Return a hash code for this element. + * @return the element hash code. + */ + @Override + public int hashCode() { + return _name.hashCode() ^ _attributes.hashCode() ^ _children.hashCode(); + } + + /** + * The QName comparator class. + * @author kevin + */ + private static final class QNameComparator implements Comparator, Serializable { + /** + * Serial version UID for this comparator. + */ + private static final long serialVersionUID = -8711685004148549433L; + + /** + * Compare the QNames. + * @param name1 The first QName. + * @param name2 The second QName. + * @return + */ + public int compare(final QName name1, final QName name2) { + final int uriComparator = name1.getNamespaceURI().compareTo(name2.getNamespaceURI()); + if (uriComparator != 0) { + return uriComparator; + } + return name1.getLocalPart().compareTo(name2.getLocalPart()); + } + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/xml/IdentitySAXHandler.java b/core/common/core/src/main/java/org/switchyard/common/xml/IdentitySAXHandler.java new file mode 100644 index 000000000..73e7788d7 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/xml/IdentitySAXHandler.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.xml; + +import java.util.ArrayList; +import java.util.List; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * Simple SAX parser creating an identity document for the incoming XML. + * Any leading and trailing whitespace is ignored in the document as are + * namespace prefixes. + * + * @author Kevin Conner + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class IdentitySAXHandler extends DefaultHandler { + /** + * The root element. + */ + private Element _rootElement; + /** + * The current element. + */ + private Element _currentElement; + /** + * The stack of working elements. + */ + private List _stack = new ArrayList(); + /** + * The current text value. + */ + private StringBuilder _currentText = new StringBuilder(); + + /** + * Receive notification of the start of an element. + * @param uri The namespace prefix + * @param localName The local name (without prefix) + * @param name The qualified XML 1.0 name (with prefix) + * @param attributes The specified or defaulted attributes. + * @throws SAXException Any SAX exception, possibly wrapping another exception. + */ + @Override + public void startElement(final String uri, final String localName, final String name, final Attributes attributes) + throws SAXException { + checkText(); + + final Element element = new Element(uri, localName, attributes); + if (_rootElement == null) { + _rootElement = element; + } + + if (_currentElement != null) { + _currentElement.addChild(element); + _stack.add(_currentElement); + } + _currentElement = element; + } + + + /** + * Receive notification of the end of an element. + * @param uri The namespace prefix + * @param localName The local name (without prefix) + * @param name The qualified XML 1.0 name (with prefix) + * @throws SAXException Any SAX exception, possibly wrapping another exception. + */ + @Override + public void endElement(final String uri, final String localName, final String name) + throws SAXException { + checkText(); + + final int lastIndex = (_stack.size() - 1); + if (lastIndex < 0) { + _currentElement = null; + } else { + _currentElement = _stack.remove(lastIndex); + } + } + + /** + * Receive notification of character data inside an element. + * @param ch The charcters + * @param start The start position + * @param length The number of characters to use from the character array + * @throws SAXException Any SAX exception, possibly wrapping another exception. + */ + @Override + public void characters(final char[] ch, final int start, final int length) + throws SAXException { + _currentText.append(ch, start, length); + } + + private void checkText() { + final int textLength = _currentText.length(); + if (textLength > 0) { + int start = 0; + while ((start < textLength) && isXMLWhitespace(_currentText.charAt(start))) { + start++; + } + + int end = textLength - 1; + while ((end >= start) && isXMLWhitespace(_currentText.charAt(end))) { + end--; + } + + if (start <= end) { + _currentElement.addChild(new Text(_currentText.substring(start, end + 1))); + } + _currentText.setLength(0); + _currentText.trimToSize(); + } + } + + private boolean isXMLWhitespace(final char ch) { + return ((ch == ' ') || (ch == '\t') || (ch == '\r') || (ch == '\n')); + } + + /** + * Returns the root element. + * @return the root Element + */ + public Element getRootElement() { + return _rootElement; + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/xml/Node.java b/core/common/core/src/main/java/org/switchyard/common/xml/Node.java new file mode 100644 index 000000000..51834649d --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/xml/Node.java @@ -0,0 +1,24 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.xml; + +/** + * Simple Node tagging XML nodes. + * + * @author Kevin Conner + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public interface Node { +} diff --git a/core/common/core/src/main/java/org/switchyard/common/xml/QNameUtil.java b/core/common/core/src/main/java/org/switchyard/common/xml/QNameUtil.java new file mode 100644 index 000000000..ecdf52314 --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/xml/QNameUtil.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.xml; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.common.CommonCoreMessages; +import org.switchyard.common.type.Classes; + +/** + * QName utility methods. + * + * @author tom.fennelly@gmail.com + */ +public final class QNameUtil { + + private QNameUtil() { + } + + /** + * Java message type. + */ + public static final String JAVA_TYPE = "java"; + + /** + * Java Type prefix. + */ + private static final String JAVA_TYPE_PREFIX = JAVA_TYPE + ":"; + + /** + * Primitive array types. + */ + private static final List PRIMITIVES = Arrays.asList( + "byte[]", "short[]", "int[]", "long[]", "float[]", "double[]", "boolean[]", "char[]" + ); + + /** + * Is the specified message type QName a Java message type. + * @param name The message type {@link javax.xml.namespace.QName} to be tested. + * @return True if it is a Java message type, otherwise false. + */ + public static boolean isJavaMessageType(QName name) { + return name.getLocalPart().startsWith(JAVA_TYPE_PREFIX); + } + + /** + * Get the Java runtime class for the specified message type QName. + * @param name The message type {@link javax.xml.namespace.QName}. + * @return The Java runtime class for the specified message type QName, otherwise null. + */ + public static Class toJavaMessageType(QName name) { + if (!isJavaMessageType(name)) { + throw CommonCoreMessages.MESSAGES.invalidCall(); + } + + String className = name.getLocalPart().substring(JAVA_TYPE_PREFIX.length()); + if (!PRIMITIVES.contains(className) && className.contains("[]")) { + className = className.substring(0, className.length() - 2); + return Array.newInstance(Classes.forName(className), 0).getClass(); + } + return Classes.forName(className); + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/xml/Text.java b/core/common/core/src/main/java/org/switchyard/common/xml/Text.java new file mode 100644 index 000000000..73bffc7bd --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/xml/Text.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.xml; + + +/** + * Simple class representing a text element. + * This is used to compare XML documents. + * + * @author Kevin Conner + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class Text implements Node { + /** + * The text content. + */ + private final String _text; + + /** + * Construct the text element. + * @param text The text value. + */ + Text(final String text) { + _text = text; + } + + /** + * Check for equality. + * @param obj the object to test against. + * @return true if the objects are equal. + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + + if (obj == this) { + return true; + } + + if (obj instanceof Text) { + final Text rhs = (Text) obj; + return (_text.equals(rhs._text)); + } + + return false; + } + + /** + * Return a hash code for this element. + * @return the element hash code. + */ + @Override + public int hashCode() { + return _text.hashCode(); + } +} diff --git a/core/common/core/src/main/java/org/switchyard/common/xml/XMLHelper.java b/core/common/core/src/main/java/org/switchyard/common/xml/XMLHelper.java new file mode 100644 index 000000000..12d1571af --- /dev/null +++ b/core/common/core/src/main/java/org/switchyard/common/xml/XMLHelper.java @@ -0,0 +1,982 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.xml; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLEventWriter; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.stream.events.StartDocument; +import javax.xml.stream.events.XMLEvent; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; + +import org.jboss.logging.Logger; +import org.switchyard.common.lang.Strings; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Helper class for manipulating XML documents. + * + * @author Kevin Conner + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public final class XMLHelper { + private static final Logger LOGGER = Logger.getLogger(XMLHelper.class); + + /** + * The XML input factory. + */ + private static final XMLInputFactory XML_INPUT_FACTORY; + /** + * The XML output factory. + */ + private static final XMLOutputFactory XML_OUTPUT_FACTORY; + /** + * The Document builder factory. + */ + private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY; + /** + * The Document builder for document creation (not parsing). + */ + private static final AtomicReference DOCUMENT_BUILDER = new AtomicReference(); + /** + * The event writer creator for DOM documents. + */ + private static final EventWriterCreator EVENT_WRITER_CREATOR; + /** + * The event reader creator for DOM nodes. + */ + private static final EventReaderCreator EVENT_READER_CREATOR; + /** + * Default output keys to use for writing DOM nodes. + */ + private static final Map DEFAULT_OUTPUT_PROPERTIES; + /** + * Hint to pretty-print Nodes. + */ + public static final String PRETTY_PRINT_HINT = "pretty-print"; + /** + * XSL to pretty-print Nodes. (Hard-coded here so as to be faster than reading in a resource.) + */ + private static final String PRETTY_PRINT_XSL = + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; + + private XMLHelper() { + } + + /** + * Get the XML stream reader. + * @param reader The input reader. + * @return The XML stream reader. + * @throws XMLStreamException For errors obtaining an XML stream reader. + */ + public static XMLStreamReader getXMLStreamReader(final Reader reader) + throws XMLStreamException { + return XML_INPUT_FACTORY.createXMLStreamReader(reader); + } + + /** + * Get the XML stream reader. + * @param is The input stream. + * @return The XML stream reader. + * @throws XMLStreamException For errors obtaining an XML stream reader. + */ + public static XMLStreamReader getXMLStreamReader(final InputStream is) + throws XMLStreamException { + return XML_INPUT_FACTORY.createXMLStreamReader(is); + } + + /** + * Get the XML stream reader. + * @param is The input stream. + * @param encoding The input stream encoding. + * @return The XML stream reader. + * @throws XMLStreamException For errors obtaining an XML stream reader. + */ + public static XMLStreamReader getXMLStreamReader(final InputStream is, final String encoding) + throws XMLStreamException { + return XML_INPUT_FACTORY.createXMLStreamReader(is, encoding); + } + + /** + * Get the XML stream reader. + * @param source The source. + * @return The XML stream reader. + * @throws XMLStreamException For errors obtaining an XML stream reader. + */ + public static XMLStreamReader getXMLStreamReader(final Source source) + throws XMLStreamException { + return XML_INPUT_FACTORY.createXMLStreamReader(source); + } + + /** + * Get the XML event reader. + * @param reader The input reader. + * @return The XML event reader. + * @throws XMLStreamException For errors obtaining an XML event reader. + */ + public static XMLEventReader getXMLEventReader(final Reader reader) + throws XMLStreamException { + return XML_INPUT_FACTORY.createXMLEventReader(reader); + } + + /** + * Get the XML event reader. + * @param is The input stream. + * @return The XML event reader. + * @throws XMLStreamException For errors obtaining an XML event reader. + */ + public static XMLEventReader getXMLEventReader(final InputStream is) + throws XMLStreamException { + return XML_INPUT_FACTORY.createXMLEventReader(is); + } + + /** + * Get the XML event reader. + * @param is The input stream. + * @param encoding The input stream encoding. + * @return The XML event reader. + * @throws XMLStreamException For errors obtaining an XML event reader. + */ + public static XMLEventReader getXMLEventReader(final InputStream is, final String encoding) + throws XMLStreamException { + return XML_INPUT_FACTORY.createXMLEventReader(is, encoding); + } + + /** + * Get the XML event reader. + * @param source The source. + * @return The XML event reader. + * @throws XMLStreamException For errors obtaining an XML event reader. + */ + public static XMLEventReader getXMLEventReader(final Source source) + throws XMLStreamException { + return XML_INPUT_FACTORY.createXMLEventReader(source); + } + + /** + * Get the XML stream writer. + * @param writer The output writer. + * @return The XML stream writer. + * @throws XMLStreamException For errors obtaining an XML stream writer. + */ + public static XMLStreamWriter getXMLStreamWriter(final Writer writer) + throws XMLStreamException { + return XML_OUTPUT_FACTORY.createXMLStreamWriter(writer); + } + + /** + * Get the XML stream writer. + * @param os The output stream. + * @return The XML stream writer. + * @throws XMLStreamException For errors obtaining an XML stream writer. + */ + public static XMLStreamWriter getXMLStreamWriter(final OutputStream os) + throws XMLStreamException { + return XML_OUTPUT_FACTORY.createXMLStreamWriter(os); + } + + /** + * Get the XML stream writer. + * @param os The output stream. + * @param encoding The output stream encoding. + * @return The XML stream writer. + * @throws XMLStreamException For errors obtaining an XML stream writer. + */ + public static XMLStreamWriter getXMLStreamWriter(final OutputStream os, final String encoding) + throws XMLStreamException { + return XML_OUTPUT_FACTORY.createXMLStreamWriter(os, encoding); + } + + /** + * Get the XML stream writer. + * @param result The output result. + * @return The XML stream writer. + * @throws XMLStreamException For errors obtaining an XML stream writer. + */ + public static XMLStreamWriter getXMLStreamWriter(final Result result) + throws XMLStreamException { + return XML_OUTPUT_FACTORY.createXMLStreamWriter(result); + } + + /** + * Get the XML event writer. + * @param writer The output writer. + * @return The XML event writer. + * @throws XMLStreamException For errors obtaining an XML event writer. + */ + public static XMLEventWriter getXMLEventWriter(final Writer writer) + throws XMLStreamException { + return XML_OUTPUT_FACTORY.createXMLEventWriter(writer); + } + + /** + * Get the XML event writer. + * @param os The output stream. + * @return The XML event writer. + * @throws XMLStreamException For errors obtaining an XML event writer. + */ + public static XMLEventWriter getXMLEventWriter(final OutputStream os) + throws XMLStreamException { + return XML_OUTPUT_FACTORY.createXMLEventWriter(os); + } + + /** + * Get the XML event writer. + * @param os The output stream. + * @param encoding The output stream encoding. + * @return The XML event writer. + * @throws XMLStreamException For errors obtaining an XML event writer. + */ + public static XMLEventWriter getXMLEventWriter(final OutputStream os, final String encoding) + throws XMLStreamException { + return XML_OUTPUT_FACTORY.createXMLEventWriter(os, encoding); + } + + /** + * Get the XML event writer. + * @param result The output result. + * @return The XML event writer. + * @throws XMLStreamException For errors obtaining an XML event writer. + */ + public static XMLEventWriter getXMLEventWriter(final Result result) + throws XMLStreamException { + return XML_OUTPUT_FACTORY.createXMLEventWriter(result); + } + + /** + * Copy an XML event stream. + * @param reader The event reader. + * @param writer The event writer. + * @throws XMLStreamException For errors writing to the XML event writer. + */ + public static void copyXMLEventStream(final XMLEventReader reader, final XMLEventWriter writer) + throws XMLStreamException { + copyXMLEventStream(reader, writer, false); + } + + /** + * Copy an XML event stream. + * @param reader The event reader. + * @param writer The event writer. + * @param omitDoc if true, ignore start/end document events. + * @throws XMLStreamException For errors writing to the XML event writer. + */ + public static void copyXMLEventStream(final XMLEventReader reader, final XMLEventWriter writer, final boolean omitDoc) + throws XMLStreamException { + if (omitDoc) { + while (reader.hasNext()) { + final XMLEvent event = reader.nextEvent(); + final int type = event.getEventType(); + if ((type != XMLStreamConstants.START_DOCUMENT) + && (type != XMLStreamConstants.END_DOCUMENT)) { + writer.add(event); + } + } + } else { + writer.add(reader); + } + writer.flush(); + } + + /** + * Validate the specified xml against the schema. + * @param schema The resource schema for validation. + * @param xml The XML to validate. + * @return true if valid, false otherwise. + */ + public static boolean validate(final Schema schema, final String xml) { + final Validator validator = schema.newValidator(); + try { + validator.validate(new StreamSource(new StringReader(xml))); + return true; + } catch (final IOException ioe) { + LOGGER.debug(ioe.getMessage(), ioe); + } catch (final SAXException saxe) { + LOGGER.debug(saxe.getMessage(), saxe); + } + + return false; + } + + /** + * Compare the specified contents as XML. + * @param content1 The first content. + * @param content2 The second content. + * @return true if equals, false otherwise. + * @throws ParserConfigurationException Parser confiuration exception + * @throws SAXException SAX exception + * @throws IOException If unable to read the stream + */ + public static boolean compareXMLContent(final InputStream content1, final InputStream content2) + throws ParserConfigurationException, SAXException, IOException { + return compareXMLContent(new InputSource(content1), new InputSource(content2)); + } + + /** + * Compare the specified contents as XML. + * @param content1 The first content. + * @param content2 The second content. + * @return true if equals, false otherwise. + * @throws ParserConfigurationException Parser confiuration exception + * @throws SAXException SAX exception + * @throws IOException If unable to read the stream + */ + public static boolean compareXMLContent(final String content1, final String content2) + throws ParserConfigurationException, SAXException, IOException { + return compareXMLContent(new StringReader(content1), new StringReader(content2)); + } + + /** + * Compare the specified contents as XML. + * @param content1 The first content. + * @param content2 The second content. + * @return true if equals, false otherwise. + * @throws ParserConfigurationException Parser confiuration exception + * @throws SAXException SAX exception + * @throws IOException If unable to read the stream + */ + public static boolean compareXMLContent(final Reader content1, final Reader content2) + throws ParserConfigurationException, SAXException, IOException { + return compareXMLContent(new InputSource(content1), new InputSource(content2)); + } + + /** + * Compare the specified contents as XML. + * @param content1 The first content. + * @param content2 The second content. + * @return true if equals, false otherwise. + * @throws ParserConfigurationException Parser confiuration exception + * @throws SAXException SAX exception + * @throws IOException If unable to read the stream + */ + public static boolean compareXMLContent(final InputSource content1, final InputSource content2) + throws ParserConfigurationException, SAXException, IOException { + final SAXParserFactory parserFactory = SAXParserFactory.newInstance(); + parserFactory.setNamespaceAware(true); + + final SAXParser parser = parserFactory.newSAXParser(); + + final IdentitySAXHandler handler1 = new IdentitySAXHandler(); + parser.parse(content1, handler1); + + final IdentitySAXHandler handler2 = new IdentitySAXHandler(); + parser.parse(content2, handler2); + + return (handler1.getRootElement().equals(handler2.getRootElement())); + } + + /** + * Compare two DOM Nodes. + * @param node1 The first Node. + * @param node2 The second Node. + * @return true if equals, false otherwise. + * @throws ParserConfigurationException Parser confiuration exception + * @throws TransformerException Transformer exception + * @throws SAXException SAX exception + * @throws IOException If unable to read the stream + */ + public static boolean compareXMLContent(final Node node1, final Node node2) + throws ParserConfigurationException, TransformerException, SAXException, IOException { + TransformerFactory transFactory = TransformerFactory.newInstance(); + Transformer transformer = transFactory.newTransformer(); + StringWriter writer1 = new StringWriter(); + StringWriter writer2 = new StringWriter(); + DOMSource source = new DOMSource(node1); + StreamResult result = new StreamResult(writer1); + transformer.transform(source, result); + source = new DOMSource(node2); + result = new StreamResult(writer2); + transformer.transform(source, result); + return compareXMLContent(writer1.toString(), writer2.toString()); + } + + /** + * Create a document from the specified reader. + * @param reader The XMLEvent reader. + * @return The Document. + * @throws ParserConfigurationException For errors creating the document. + * @throws XMLStreamException For errors reading the event reader. + */ + public static Document createDocument(final XMLEventReader reader) + throws ParserConfigurationException, XMLStreamException { + final Document doc = getNewDocument(); + final XMLEventWriter writer = EVENT_WRITER_CREATOR.createXMLEventWriter(doc); + final XMLEvent event = reader.peek(); + int type = event.getEventType(); + boolean omitDoc = false; + if (type == XMLStreamConstants.START_DOCUMENT) { + StartDocument startDocument = (StartDocument) event; + if (startDocument.getVersion() == null) { + omitDoc = true; + } + } + XMLHelper.copyXMLEventStream(reader, writer, omitDoc); + return doc; + } + + /** + * Read from a DOM node, output to a writer. + * @param node The DOM node. + * @param writer The specified writer. + * @param omitDoc if true, ignore start/end document events. + * @throws XMLStreamException For errors writing to the event writer. + */ + public static void readDomNode(final Node node, final XMLEventWriter writer, final boolean omitDoc) + throws XMLStreamException { + final XMLEventReader reader = EVENT_READER_CREATOR.createXMLEventReader(node); + XMLHelper.copyXMLEventStream(reader, writer, omitDoc); + } + + /** + * Create a new document. + * @return the new document + * @throws ParserConfigurationException for errors during creation + */ + public static Document getNewDocument() + throws ParserConfigurationException { + final DocumentBuilder builder = getCreationDocumentBuilder(); + synchronized (builder) { + // synchronized as it is not guaranteed to be thread safe + return builder.newDocument(); + } + } + + /** + * Create a document from bytes. + * + * @return the created document + * @param xml the input string + * @throws ParserConfigurationException for errors during creation + * @throws IOException if the source could not be read + * @throws SAXException if any parser error occurs + */ + public static Document getDocumentFromString(final String xml) + throws ParserConfigurationException, IOException, SAXException { + final DocumentBuilder builder = getCreationDocumentBuilder(); + synchronized (builder) { + // synchronized as it is not guaranteed to be thread safe + return builder.parse(new InputSource(new StringReader(xml))); + } + } + + /** + * Create a document from InputSource. + * + * @return the created document + * @param source the input source + * @throws ParserConfigurationException for errors during creation + * @throws IOException if the source could not be read + * @throws SAXException if any parser error occurs + */ + public static Document getDocument(final InputSource source) + throws ParserConfigurationException, IOException, SAXException { + final DocumentBuilder builder = getCreationDocumentBuilder(); + synchronized (builder) { + // synchronized as it is not guaranteed to be thread safe + return builder.parse(source); + } + } + + /** + * Get the first child Element of the supplied node that matches a given tag name. + * + * @param node The DOM Node. + * @param name The name of the child node to search for. + * @return The first child element with the matching tag name. + */ + public static Element getFirstChildElementByName(Node node, String name) { + NodeList children = node.getChildNodes(); + int childCount = children.getLength(); + + for (int i = 0; i < childCount; i++) { + Node child = children.item(i); + if (child != null + && child.getNodeType() == Node.ELEMENT_NODE + && child.getLocalName() != null + && child.getLocalName().equals(name)) { + return (Element) child; + } + } + return null; + } + + /** + * Get the sibling Element of the supplied node that matches a given tag name. + * + * @param node The DOM Node. + * @param name The name of the sibling node to search for. + * @return The sibling element with the matching tag name or null otherwise. + */ + public static Element getNextSiblingElementByName(Node node, String name) { + Node sibling = node.getNextSibling(); + while (sibling != null) { + if (sibling.getNodeType() == Node.ELEMENT_NODE + && sibling.getLocalName() != null + && sibling.getLocalName().equals(name)) { + return (Element) sibling; + } + sibling = sibling.getNextSibling(); + } + return null; + } + + /** + * Get the first child Element of the supplied node. + * + * @param node The DOM Node. + * @return The first child element + */ + public static Element getFirstChildElement(Node node) { + NodeList children = node.getChildNodes(); + int childCount = children.getLength(); + + for (int i = 0; i < childCount; i++) { + Node child = children.item(i); + if (child != null + && child.getNodeType() == Node.ELEMENT_NODE) { + return (Element) child; + } + } + return null; + } + + /** + * Get the next sibling Element of the supplied node. + * + * @param node The DOM Node. + * @return The next sibling element + */ + public static Element getNextSiblingElement(Node node) { + Node sibling = node.getNextSibling(); + while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) { + sibling = sibling.getNextSibling(); + } + return (Element) sibling; + } + + /** + * Get the attribute value of an Element. + * + * @param element the element. + * @param namespace the Attribute namespace. + * @param name the Attribute name. + * @return The value of the attribute + */ + public static String getAttribute(Element element, String namespace, String name) { + String value = null; + if (element.hasAttributeNS(namespace, name)) { + value = element.getAttributeNS(namespace, name); + } else if (element.hasAttribute(name)) { + value = element.getAttribute(name); + } + return value; + } + + /** + * Check if an Element has an attribute. + * + * @param element the element. + * @param namespace the Attribute namespace. + * @param name the Attribute name. + * @return true if attribute exists, false otherwise + */ + public static Boolean hasAttribute(Element element, String namespace, String name) { + String value = getAttribute(element, namespace, name); + return (value != null); + } + + /** + * Get the document builder for creation + * @return The document builder + * @throws ParserConfigurationException for errors during creation + */ + private static DocumentBuilder getCreationDocumentBuilder() + throws ParserConfigurationException { + final DocumentBuilder current = DOCUMENT_BUILDER.get(); + if (current != null) { + return current; + } + final DocumentBuilder newBuilder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); + if (DOCUMENT_BUILDER.compareAndSet(null, newBuilder)) { + return newBuilder; + } else { + return DOCUMENT_BUILDER.get(); + } + } + + /** + * Gets the name of the node. + * @param node the node + * @return the name, first trying the local name (getLocalName()), but if null or zero-length, the node name (getNodeName()) + */ + public static String nameOf(Node node) { + if (node != null) { + String name = node.getLocalName(); + if (name == null || name.length() == 0) { + name = node.getNodeName(); + } + return name; + } + return null; + } + + /** + * Gets the value of the node. + * @param node the node + * @return the value of the node if the node is not null, otherwise null + */ + public static String valueOf(Node node) { + if (node != null) { + return node.getNodeValue(); + } + return null; + } + + /** + * Safely creates a QName based on a DOM Document's root element. + * @param document the document + * @return the QName + */ + public static QName createQName(Document document) { + return createQName(document.getDocumentElement()); + } + + /** + * Safely creates a QName based on a DOM Element. + * @param element the element + * @return the QName + */ + public static QName createQName(Element element) { + return createQName(element.getNamespaceURI(), nameOf(element), element.getPrefix()); + } + + /** + * Safely creates a QName based on a name. + * @param name will turn into the local name + * @return the QName + */ + public static QName createQName(String name) { + name = Strings.trimToNull(name); + if (name != null) { + return QName.valueOf(name); + } + return null; + } + + /** + * Safely creates a QName based on a namespace and a name. + * @param namespace the namespace + * @param localName the local name + * @return the QName + */ + public static QName createQName(String namespace, String localName) { + return createQName(namespace, localName, null); + } + /** + * Safely creates a QName based on a namespace, a name and a prefix. + * @param namespace the namespace + * @param localName the local name + * @param prefix the prefix + * @return the QName + */ + public static QName createQName(String namespace, String localName, String prefix) { + localName = Strings.trimToNull(localName); + if (localName != null) { + namespace = Strings.trimToNull(namespace); + prefix = Strings.trimToNull(prefix); + if (namespace != null) { + if (prefix != null) { + return new QName(namespace, localName, prefix); + } + return new QName(namespace, localName); + } + return QName.valueOf(localName); + } + return null; + } + + /** + * Splits a String into multiple QNames with a delimiter of '/'. + * @param str the String to split + * @return the multiple QNames + */ + public static QName[] splitQNames(String str) { + return splitQNames(str, '/'); + } + + /** + * Splits a String into multiple QNames per the specified delimiter. + * @param str the String to split + * @param delim the specified delimiter + * @return the multiple QNames + */ + public static QName[] splitQNames(String str, char delim) { + List qnames = new ArrayList(); + if (str != null) { + List indexes = new ArrayList(); + boolean withinNamespaceURI = false; + char[] ca = str.toCharArray(); + for (int i=0; i < ca.length; i++) { + char c = ca[i]; + if (c == '{') { + withinNamespaceURI = true; + } else if (withinNamespaceURI && c == '}') { + withinNamespaceURI = false; + } else if (!withinNamespaceURI && c == delim) { + indexes.add(Integer.valueOf(i)); + } + } + for (Integer i : indexes) { + QName qname = createQName(str.substring(0, i.intValue())); + if (qname != null) { + qnames.add(qname); + } + str = str.substring(i.intValue()+1, str.length()); + } + if (str.length() > 0) { + QName qname = createQName(str); + if (qname != null) { + qnames.add(qname); + } + } + } + return qnames.toArray(new QName[qnames.size()]); + } + + /** + * Converts a Node to a String. + * @param node the Node + * @return the String + */ + public static String toString(Node node) { + return toString(node, DEFAULT_OUTPUT_PROPERTIES); + } + + /** + * Converts a Node to a String, using the specified output properties. + * @param node the Node + * @param outputProperties the specified output properties + * @return the String + */ + public static String toString(Node node, Map outputProperties) { + StringWriter writer = new StringWriter(); + try { + write(node, writer, outputProperties); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + return writer.toString(); + } + + /** + * Converts a Node to a pretty-print String. + * @param node the Node + * @return the pretty-print String + */ + public static String toPretty(Node node) { + Map outputProperties = new HashMap(); + outputProperties.putAll(DEFAULT_OUTPUT_PROPERTIES); + outputProperties.put(PRETTY_PRINT_HINT, "yes"); + return toString(node, outputProperties); + } + + /** + * Writes a Node to a Writer. + * @param node the Node + * @param writer the Writer + * @throws IOException if a problem occurs while writing + */ + public static void write(Node node, Writer writer) throws IOException { + write(node, writer, DEFAULT_OUTPUT_PROPERTIES); + } + + /** + * Writes a Node to a Writer, using the specified output properties. + * @param node the Node + * @param writer the Writer + * @param outputProperties the specified output properties + * @throws IOException if a problem occurs while writing + */ + public static void write(Node node, Writer writer, Map outputProperties) throws IOException { + try { + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t; + if (isPrettyPrint(outputProperties)) { + t = tf.newTransformer(new StreamSource(new StringReader(PRETTY_PRINT_XSL))); + } else { + t = tf.newTransformer(); + } + for (Map.Entry entry : outputProperties.entrySet()) { + if (!entry.getKey().equals(PRETTY_PRINT_HINT)) { + t.setOutputProperty(entry.getKey(), entry.getValue()); + } + } + t.transform(new DOMSource(node), new StreamResult(writer)); + } catch (TransformerException te) { + throw new IOException(te); + } + } + + private static boolean isPrettyPrint(Map outputProperties) { + String pp = Strings.trimToNull(outputProperties.get(PRETTY_PRINT_HINT)); + if (pp != null) { + pp = pp.toLowerCase(); + return pp.equals("yes") || pp.equals("true"); + } + return false; + } + + /** + * Logs a Node. + * @param node the Node + */ + public static void log(Node node) { + if (LOGGER.isInfoEnabled()) { + LOGGER.info(toString(node)); + } + } + + static { + final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); + xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); + XML_INPUT_FACTORY = xmlInputFactory; + + EVENT_READER_CREATOR = new DefaultEventReaderCreator(); + + XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance(); + + EVENT_WRITER_CREATOR = new DefaultEventWriterCreator(); + + + final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + docBuilderFactory.setNamespaceAware(true); + DOCUMENT_BUILDER_FACTORY = docBuilderFactory; + + DEFAULT_OUTPUT_PROPERTIES = new HashMap(); + DEFAULT_OUTPUT_PROPERTIES.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); + } + + /** + * Interface for the event writer creator. + * @author kevin + */ + private interface EventWriterCreator { + /** + * Create the event writer. + * @param doc The associated document. + * @return The XML event writer. + * @throws XMLStreamException for errors constructing the writer. + */ + XMLEventWriter createXMLEventWriter(final Document doc) + throws XMLStreamException; + } + + /** + * Interface for the event reader creator. + * @author kevin + */ + private interface EventReaderCreator { + /** + * Create the event reader. + * @param node The associated node. + * @return The XML event reader. + * @throws XMLStreamException for errors constructing the reader. + */ + XMLEventReader createXMLEventReader(final Node node) + throws XMLStreamException; + } + + /** + * The default event writer creator + * @author kevin + */ + private static final class DefaultEventWriterCreator implements EventWriterCreator { + /** + * Create the event writer. + * @param doc The associated document. + * @return The XML event writer. + * @throws XMLStreamException for errors constructing the writer. + */ + public XMLEventWriter createXMLEventWriter(final Document doc) + throws XMLStreamException { + return getXMLEventWriter(new DOMResult(doc)); + } + } + + /** + * The default event reader creator + * @author kevin + */ + private static final class DefaultEventReaderCreator implements EventReaderCreator { + /** + * Create the event reader. + * @param node The associated node. + * @return The XML event reader. + * @throws XMLStreamException for errors constructing the reader. + */ + public XMLEventReader createXMLEventReader(final Node node) + throws XMLStreamException { + return getXMLEventReader(new DOMSource(node)); + } + } + +} diff --git a/core/common/core/src/main/resources/org/switchyard/common/io/resource/resourceType.properties b/core/common/core/src/main/resources/org/switchyard/common/io/resource/resourceType.properties new file mode 100644 index 000000000..cc51d95e5 --- /dev/null +++ b/core/common/core/src/main/resources/org/switchyard/common/io/resource/resourceType.properties @@ -0,0 +1,22 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 = Java Class | .class +CSV = Comma Separated Value | .csv +DTD = Data Type Definition | .dtd +JAVA = Java Source | .java +PROPERTIES = Properties | .properties +TXT = Text | .txt +XLS = eXceL Spreadsheet | .xls +XML = eXtensible Markup Language | .xml +XSD = Xml Schema Definition | .xsd +XSL = Xml Stylesheet Language | .xsl diff --git a/core/common/core/src/test/java/org/switchyard/common/codec/Base64Tests.java b/core/common/core/src/test/java/org/switchyard/common/codec/Base64Tests.java new file mode 100644 index 000000000..1c636baf7 --- /dev/null +++ b/core/common/core/src/test/java/org/switchyard/common/codec/Base64Tests.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.codec; + +import junit.framework.Assert; + +import org.junit.Test; + +/** + * Base64 tests. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class Base64Tests { + + @Test + public void testEncodeDecode() throws Exception { + final String expected = "test"; + final String encoded = Base64.encodeFromString(expected); + final String decoded = Base64.decodeToString(encoded); + Assert.assertEquals(expected, decoded); + } + +} diff --git a/core/common/core/src/test/java/org/switchyard/common/io/FilesTests.java b/core/common/core/src/test/java/org/switchyard/common/io/FilesTests.java new file mode 100644 index 000000000..07c9cfa8a --- /dev/null +++ b/core/common/core/src/test/java/org/switchyard/common/io/FilesTests.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io; + +import java.io.File; +import java.io.FileWriter; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; + +/** + * File utilities tests. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class FilesTests { + + @Test + public void testCopy() throws Exception { + final String expected = "test"; + File testFile1 = File.createTempFile("test-1", ".txt"); + FileWriter testFileWriter1 = new FileWriter(testFile1); + testFileWriter1.write(expected); + testFileWriter1.flush(); + testFileWriter1.close(); + File testFile2 = File.createTempFile("test-2", ".txt"); + Files.copy(testFile1, testFile2); + final String actual = new StringPuller().pull(testFile2); + testFile1.delete(); + testFile2.delete(); + Assert.assertEquals(expected, actual); + } + +} diff --git a/core/common/core/src/test/java/org/switchyard/common/io/resource/ResourceTypeTests.java b/core/common/core/src/test/java/org/switchyard/common/io/resource/ResourceTypeTests.java new file mode 100644 index 000000000..2e85fb29d --- /dev/null +++ b/core/common/core/src/test/java/org/switchyard/common/io/resource/ResourceTypeTests.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.io.resource; + +import java.util.Set; + +import org.junit.Assert; +import org.junit.Test; + +/** + * ResourceTypeTests. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class ResourceTypeTests { + + @Test + public void testBasicType() throws Exception { + ResourceType txt1 = ResourceType.valueOf("TXT"); + Assert.assertEquals("Text" , txt1.getDescription()); + Set exts = txt1.getExtensions(); + Assert.assertEquals(1, exts.size()); + Assert.assertEquals(".txt", exts.iterator().next()); + ResourceType txt2 = ResourceType.forName("TXT"); + Assert.assertSame(txt1, txt2); + ResourceType txt3 = ResourceType.forExtension(".txt"); + Assert.assertSame(txt1, txt3); + ResourceType txt4 = ResourceType.forLocation("foo/bar.txt"); + Assert.assertSame(txt1, txt4); + } + + @Test + public void testMultipleExtensions() throws Exception { + ResourceType.install("JPG", null, ".jpg", ".jpeg"); + ResourceType jpg = ResourceType.forExtension(".jpg"); + ResourceType jpeg = ResourceType.forExtension(".jpeg"); + Assert.assertSame(jpg, jpeg); + } + + @Test + @SuppressWarnings("unused") + public void testCustomInheritance() throws Exception { + ResourceType a = ResourceType.install("A", null, ".a"); + ResourceType b = ResourceType.install("B", null, ".b"); + ResourceType ab = ResourceType.install("AB", null, "{A}", "{B}"); + ResourceType c = ResourceType.install("C", null, ".c"); + ResourceType abcd = ResourceType.install("ABCD", null, "{AB}", "{C}", ".d"); + Assert.assertEquals(4, abcd.getExtensions().size()); + Assert.assertEquals(4, abcd.getExtensions(true).size()); + Assert.assertEquals(1, abcd.getExtensions(false).size()); + Assert.assertArrayEquals(new ResourceType[]{a}, ResourceType.forExtension(".a", false)); + Assert.assertArrayEquals(new ResourceType[]{a, ab, abcd}, ResourceType.forExtension(".a", true)); + Assert.assertArrayEquals(new ResourceType[]{a}, ResourceType.forLocation("path/to/foo.a", false)); + Assert.assertArrayEquals(new ResourceType[]{a, ab, abcd}, ResourceType.forLocation("path/to/foo.a", true)); + } + +} diff --git a/core/common/core/src/test/java/org/switchyard/common/lang/StringsTests.java b/core/common/core/src/test/java/org/switchyard/common/lang/StringsTests.java new file mode 100644 index 000000000..761777c6d --- /dev/null +++ b/core/common/core/src/test/java/org/switchyard/common/lang/StringsTests.java @@ -0,0 +1,235 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.lang; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertNull; +import static org.switchyard.common.lang.Strings.repeat; +import static org.switchyard.common.lang.Strings.splitTrimToNull; +import static org.switchyard.common.lang.Strings.splitTrimToNullArray; +import static org.switchyard.common.lang.Strings.trimToNull; +import static org.switchyard.common.lang.Strings.uniqueSplitTrimToNull; +import static org.switchyard.common.lang.Strings.uniqueSplitTrimToNullArray; + +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.property.PropertiesPropertyResolver; +import org.switchyard.common.property.SystemAndTestPropertyResolver; +import org.switchyard.common.property.SystemPropertyResolver; +import org.switchyard.common.property.TestPropertyResolver; + +/** + * StringsTests. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class StringsTests { + + @Test + public void testTrimToNull() throws Exception { + assertNull(trimToNull(" ")); + assertNotNull(trimToNull("x ")); + assertEquals("x y", trimToNull(" x y ")); + } + + @Test + public void testCleanseTrimToNull() throws Exception { + String[][] tests = new String[][]{ + new String[]{"My Cool \n Project", "My-Cool-Project"}, + new String[]{" the One and ___ONLY__* ", "the-One-and-ONLY"}, + new String[]{" --- _", null} + }; + for (String[] test : tests) { + String original = test[0]; + String expected = test[1]; + String actual = Strings.cleanseTrimToNull(original); + //System.out.println("original=[" + original + "], expected=[" + expected + "], actual=[" + actual + "]"); + assertEquals(expected, actual); + } + } + + @Test + public void testRepeatEmptyString() { + assertEquals("", repeat("", 10)); + } + + @Test + public void testRepeatZeroTimes() { + assertEquals("", repeat("a", 0)); + assertEquals("", repeat("a", -1)); + } + + @Test + public void testRepeating() { + assertEquals("a", repeat("a", 1)); + assertEquals("aa", repeat("a", 2)); + } + + @Test + public void testSplitTrimToNull() throws Exception { + List l = splitTrimToNull("foo// bar/ ", "/"); + assertEquals(2, l.size()); + Iterator i = l.iterator(); + assertEquals("foo", i.next()); + assertEquals("bar", i.next()); + } + + @Test + public void testSplitTrimToNullArray() throws Exception { + String[] s = splitTrimToNullArray("foo// bar/ ", "/"); + assertEquals(2, s.length); + assertEquals("foo", s[0]); + assertEquals("bar", s[1]); + } + + @Test + public void testUniqueSplitTrimToNull() throws Exception { + Set s = uniqueSplitTrimToNull("foo// bar//foo/bar/ ", "/"); + assertEquals(2, s.size()); + Iterator i = s.iterator(); + assertEquals("foo", i.next()); + assertEquals("bar", i.next()); + } + + @Test + public void testUniqueSplitTrimToNullArray() throws Exception { + String[] s = uniqueSplitTrimToNullArray("foo// bar//foo/bar/ ", "/"); + assertEquals(2, s.length); + assertEquals("foo", s[0]); + assertEquals("bar", s[1]); + } + + @Test + public void testReplaceSystemProperties() { + final String original = "Hello ${user.name} using ${os.name} skipping ${unknown.property}!"; + final String expected = "Hello " + System.getProperty("user.name") + " using " + System.getProperty("os.name") + " skipping ${unknown.property}!"; + final String actual = Strings.replaceSystemProperties(original); + Assert.assertEquals(expected, actual); + } + + @Test + public void testReplaceCustomProperties() { + Properties custom = new Properties(); + custom.setProperty("foo", "bar"); + final String original = "I have a ${foo} but not a ${baz:wiz}."; + final String expected = "I have a bar but not a wiz."; + final String actual = Strings.replaceProperties(original, new PropertiesPropertyResolver(custom)); + Assert.assertEquals(expected, actual); + } + + @Test + public void testReplaceCompoundProperties() { + Properties custom = new Properties(); + custom.setProperty("foo", "bar"); + custom.setProperty("emotion", "loves"); + final String original = "${user.name} has a ${foo}, and he ${emotion:hates} it, unlike his ${sibling:sister}."; + final String expected = System.getProperty("user.name") + " has a bar, and he loves it, unlike his sister."; + final String actual = Strings.replaceProperties(original, SystemPropertyResolver.INSTANCE, new PropertiesPropertyResolver(custom)); + Assert.assertEquals(expected, actual); + } + + @Test + public void testReplaceEmbeddedProperties() { + Properties custom = new Properties(); + custom.setProperty("goto", "bed"); + custom.setProperty("foo", "${em${goto}ded}"); + custom.setProperty("embedded", "bar"); + custom.setProperty("foobar", "tub"); + final String original = "I have a ${foo} and a ${foo${foo}} but not a ${baz:wiz}."; + final String expected = "I have a bar and a tub but not a wiz."; + final String actual = Strings.replaceProperties(original, new PropertiesPropertyResolver(custom)); + Assert.assertEquals(expected, actual); + } + + @Test + public void testReplaceButEscapeDoubleDollarProperties() { + Properties custom = new Properties(); + custom.setProperty("foo", "bar"); + custom.setProperty("boo", "foo"); + final String original = "I have a ${foo} and a ${baz:wiz}, but not a $${foo}, a $${ba${boo}n} but not a $${ba$${boo}n}, a $${baz:wiz}, or a $${baz:$${oo}${ka}}."; + final String expected = "I have a bar and a wiz, but not a ${foo}, a ${bafoon} but not a ${ba${boo}n}, a ${baz:wiz}, or a ${baz:${oo}${ka}}."; + final String actual = Strings.replaceProperties(original, new PropertiesPropertyResolver(custom)); + Assert.assertEquals(expected, actual); + } + + @Test + public void testReplaceButHandleDoubleColonVaultProperty() { + final String key = "VAULT::ds_ExampleDS::password::N2NhZDYzOTMtNWE0OS00ZGQ0LWE4MmEtMWNlMDMyNDdmNmI2TElORV9CUkVBS3ZhdWx0"; + final String expected = "expected"; + Properties properties = new Properties(); + properties.setProperty(key, expected); + final String original = "${" + key + "}"; + final String actual = Strings.replaceProperties(original, new PropertiesPropertyResolver(properties)); + Assert.assertEquals(expected, actual); + } + + @Test + public void testReplaceButHandleDoubleColonVaultAndCustomProperties() { + final String nested = "VAULT::${vaultBlock:ds_ExampleDS}::${attributeName:changeit}::N2NhZDYzOTMtNWE0OS00ZGQ0LWE4MmEtMWNlMDMyNDdmNmI2TElORV9CUkVBS3ZhdWx0"; + final String key = "VAULT::ds_ExampleDS::password::N2NhZDYzOTMtNWE0OS00ZGQ0LWE4MmEtMWNlMDMyNDdmNmI2TElORV9CUkVBS3ZhdWx0"; + final String expected = "expected"; + Properties properties = new Properties(); + properties.setProperty("attributeName", "password"); + properties.setProperty(key, expected); + final String original = "${" + nested + "}"; + final String actual = Strings.replaceProperties(original, new PropertiesPropertyResolver(properties)); + Assert.assertEquals(expected, actual); + } + + @Before + public void beforeReplaceTestProperties() { + TestPropertyResolver.INSTANCE.getMap().put("test.key", "testValue"); + } + + @After + public void afterReplaceTestProperties() { + TestPropertyResolver.INSTANCE.getMap().clear(); + } + + @Test + public void testReplaceTestProperties() { + final String original = "The test value is ${test.key}."; + final String expected = "The test value is testValue."; + final String actual = Strings.replaceTestProperties(original); + Assert.assertEquals(expected, actual); + } + + @Test + public void testReplaceSystemAndTestProperties() { + final String original = "${user.name}'s test value is ${test.key}."; + final String expected = System.getProperty("user.name") + "'s test value is testValue."; + final String actual = Strings.replaceSystemAndTestProperties(original); + Assert.assertEquals(expected, actual); + } + + @Test + public void testReplaceSystemAndTestAndCustomProperties() { + Properties custom = new Properties(); + custom.setProperty("foo", "bar"); + custom.setProperty("emotion", "loves"); + final String original = "${user.name} has a ${foo}, and he ${emotion:hates} it, unlike his ${sibling:sister}, who has a ${test.key}."; + final String expected = System.getProperty("user.name") + " has a bar, and he loves it, unlike his sister, who has a testValue."; + final String actual = Strings.replaceProperties(original, SystemAndTestPropertyResolver.INSTANCE, new PropertiesPropertyResolver(custom)); + Assert.assertEquals(expected, actual); + } + +} diff --git a/core/common/core/src/test/java/org/switchyard/common/net/SocketAddrTest.java b/core/common/core/src/test/java/org/switchyard/common/net/SocketAddrTest.java new file mode 100644 index 000000000..6f8fcc0c7 --- /dev/null +++ b/core/common/core/src/test/java/org/switchyard/common/net/SocketAddrTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.net; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests for SocketAddr. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SocketAddrTest { + + @Test + public void socketNames() throws Exception { + SocketAddr socket = new SocketAddr("localhost:18001"); + Assert.assertNotNull(socket); + Assert.assertEquals(socket.getHost(), "localhost"); + Assert.assertEquals(socket.getPort(), 18001); + SocketAddr socket1 = new SocketAddr("localhost", 18001); + Assert.assertEquals(socket, socket1); + Assert.assertEquals(socket.hashCode(), socket1.hashCode()); + Assert.assertEquals(socket.toString(), socket1.toString()); + socket = new SocketAddr("127.0.0.1:"); + Assert.assertNotNull(socket); + Assert.assertEquals(socket.getHost(), "127.0.0.1"); + Assert.assertEquals(socket.getPort(), SocketAddr.DEFAULT_PORT); + Assert.assertNotSame(socket, socket1); + Assert.assertNotSame(socket.hashCode(), socket1.hashCode()); + Assert.assertNotSame(socket.toString(), socket1.toString()); + socket = new SocketAddr(":18001"); + Assert.assertNotNull(socket); + Assert.assertEquals(socket.getHost(), SocketAddr.DEFAULT_HOST); + Assert.assertEquals(socket.getPort(), 18001); + socket = new SocketAddr(); + Assert.assertEquals(socket.getHost(), SocketAddr.DEFAULT_HOST); + Assert.assertEquals(socket.getPort(), SocketAddr.DEFAULT_PORT); + socket = new SocketAddr(""); + Assert.assertEquals(socket.getHost(), SocketAddr.DEFAULT_HOST); + Assert.assertEquals(socket.getPort(), SocketAddr.DEFAULT_PORT); + } +} diff --git a/core/common/core/src/test/java/org/switchyard/common/type/classpath/ClasspathScannerTest.java b/core/common/core/src/test/java/org/switchyard/common/type/classpath/ClasspathScannerTest.java new file mode 100644 index 000000000..9003ddb3d --- /dev/null +++ b/core/common/core/src/test/java/org/switchyard/common/type/classpath/ClasspathScannerTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.common.type.classpath; + +import org.junit.Assert; +import org.junit.Test; + +import javax.activation.CommandMap; +import javax.activation.MailcapCommandMap; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.List; + +/** + * @author tom.fennelly@gmail.com + */ +public class ClasspathScannerTest { + + /** + * See https://issues.jboss.org/browse/SWITCHYARD-425 + * @throws IOException + */ + @Test + public void test_folder_with_plus_chars_scan() throws IOException { + String resourceName = "some_resource.txt"; + ResourceExistsFilter filter = new ResourceExistsFilter(resourceName); + ClasspathScanner scanner = new ClasspathScanner(filter); + + // If running this test inside your IDE... you need to set the cwd to be the + // root of the config module !! + + File scanDir = new File("./target/folder+with+plus"); + scanDir.delete(); + scanDir.mkdirs(); + + // Create the resource in the scanDir... + FileWriter writer = new FileWriter(new File(scanDir, resourceName)); + try { + writer.write("something...."); + writer.flush(); + } finally { + writer.close(); + } + + scanner.scan(scanDir.toURI().toURL()); + + Assert.assertTrue(filter.resourceExists()); + } + + @Test + public void test_archive_scan() throws IOException { + InstanceOfFilter filter = new InstanceOfFilter(CommandMap.class); + ClasspathScanner scanner = new ClasspathScanner(filter); + + // If running this test inside your IDE... you need to set the cwd to be the + // root of the config module !! + scanner.scan(new File("./src/test/resources/classpathscan-test.jar").toURI().toURL()); + List> classes = filter.getMatchedTypes(); + + Assert.assertTrue(classes.contains(CommandMap.class)); + Assert.assertTrue(classes.contains(MailcapCommandMap.class)); + } +} diff --git a/core/common/core/src/test/java/org/switchyard/common/xml/XMLHelperTests.java b/core/common/core/src/test/java/org/switchyard/common/xml/XMLHelperTests.java new file mode 100644 index 000000000..d380f5f4c --- /dev/null +++ b/core/common/core/src/test/java/org/switchyard/common/xml/XMLHelperTests.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.common.xml; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; + +/** + * XMLHelperTests. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class XMLHelperTests { + + @Test + public void testSplitQNames() throws Exception { + QName[] q = XMLHelper.splitQNames("foo/bar"); + Assert.assertArrayEquals(new QName[]{new QName("foo"), new QName("bar")}, q); + q = XMLHelper.splitQNames("foo/ "); + Assert.assertArrayEquals(new QName[]{new QName("foo")}, q); + q = XMLHelper.splitQNames("{http://foo.com}foo/{http://bar.com}bar"); + Assert.assertArrayEquals(new QName[]{QName.valueOf("{http://foo.com}foo"), QName.valueOf("{http://bar.com}bar")}, q); + q = XMLHelper.splitQNames("{http://foo.com/f}foo/{http://bar.com/b}bar"); + Assert.assertArrayEquals(new QName[]{QName.valueOf("{http://foo.com/f}foo"), QName.valueOf("{http://bar.com/b}bar")}, q); + } + +} diff --git a/core/common/core/src/test/resources/classpathscan-test.jar b/core/common/core/src/test/resources/classpathscan-test.jar new file mode 100644 index 000000000..1b703ab28 Binary files /dev/null and b/core/common/core/src/test/resources/classpathscan-test.jar differ diff --git a/core/config/pom.xml b/core/config/pom.xml new file mode 100644 index 000000000..34db3e52f --- /dev/null +++ b/core/config/pom.xml @@ -0,0 +1,49 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-config + bundle + SwitchYard: Configuration + The SwitchYard Configuration library. + http://switchyard.org + + + org.switchyard.config.* + + + + + + org.switchyard + switchyard-common + + + + junit + junit + + + xmlunit + xmlunit + + + diff --git a/core/config/src/main/java/org/switchyard/config/BaseConfiguration.java b/core/config/src/main/java/org/switchyard/config/BaseConfiguration.java new file mode 100644 index 000000000..0f3f4eba3 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/BaseConfiguration.java @@ -0,0 +1,375 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config; + +import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE; +import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +import javax.xml.namespace.QName; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; + +import org.switchyard.common.lang.Strings; +import org.switchyard.common.xml.XMLHelper; + +/** + * An abstract representation of a Configuration, containing default implementations for many of the defined methods. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class BaseConfiguration implements Configuration { + + /** + * {@inheritDoc} + */ + @Override + public Set getNamespaces() { + Set set = new TreeSet(); + set.add(XMLNS_ATTRIBUTE_NS_URI); + Configuration config = this; + while (config != null) { + String ns = config.getQName().getNamespaceURI(); + if (ns != null && ns.length() > 0) { + set.add(ns); + } + for (QName attr_qname : config.getAttributeQNames()) { + String attr_ns = attr_qname.getNamespaceURI(); + if (attr_ns != null && attr_ns.length() > 0) { + set.add(attr_ns); + } + String attr_value = config.getAttribute(attr_qname); + if (attr_value != null) { + String attr_lp = attr_qname.getLocalPart(); + if (XMLNS_ATTRIBUTE.equals(attr_lp) || XMLNS_ATTRIBUTE_NS_URI.equals(attr_ns) || "targetNamespace".equals(attr_lp)) { + set.add(attr_value); + } else { + int pos = attr_value.indexOf(':'); + if (pos > -1) { + String attr_value_pfx = Strings.trimToNull(attr_value.substring(0, pos)); + if (attr_value_pfx != null) { + String attr_value_ns = lookupNamespaceURI(attr_value_pfx); + if (attr_value_ns != null) { + set.add(attr_value_ns); + } + } + } + } + } + } + config = config.getParent(); + } + return set; + } + + /** + * {@inheritDoc} + */ + @Override + public Set getChildrenNamespaces() { + Set set = new TreeSet(); + List children = getChildren(); + if (children.size() > 0) { + for (Configuration child : children) { + set.addAll(child.getChildrenNamespaces()); + } + } else { + set.addAll(getNamespaces()); + } + return set; + } + + /** + * {@inheritDoc} + */ + @Override + public Map getNamespacePrefixMap() { + Map map = new TreeMap(); + map.put(XMLNS_ATTRIBUTE_NS_URI, XMLNS_ATTRIBUTE); + int i = 0; + for (String ns : getNamespaces()) { + if (!map.containsKey(ns)) { + String pfx = lookupPrefix(ns); + if (pfx == null) { + boolean unavailable = true; + while (unavailable) { + pfx = "ns" + i++; + unavailable = lookupNamespaceURI(pfx) != null; + } + } + map.put(ns, pfx); + } + } + return map; + } + + /** + * {@inheritDoc} + */ + @Override + public Map getPrefixNamespaceMap() { + Map map = new TreeMap(); + Map nsp_map = getNamespacePrefixMap(); + for (Map.Entry nsp_entry : nsp_map.entrySet()) { + String pfx = nsp_entry.getValue(); + String ns = nsp_entry.getKey(); + if (!map.containsKey(pfx)) { + map.put(pfx, ns); + } + } + return map; + } + + /** + * {@inheritDoc} + */ + @Override + public QName getAttributeAsQName(String name) { + return createAttributeQName(getAttribute(name)); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getAttributeAsQNames(String name, String splitRegex) { + return createAttributeQNames(getAttribute(name), splitRegex); + } + + /** + * {@inheritDoc} + */ + @Override + public QName getAttributeAsQName(QName qname) { + return createAttributeQName(getAttribute(qname)); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getAttributeAsQNames(QName qname, String splitRegex) { + return createAttributeQNames(getAttribute(qname), splitRegex); + } + + private QName createAttributeQName(String value) { + String ns = null; + String lp = null; + String pfx = null; + if (value != null) { + QName qvalue = QName.valueOf(value); + ns = qvalue.getNamespaceURI(); + if (ns.length() > 0) { + lp = qvalue.getLocalPart(); + pfx = lookupPrefix(ns); + } else { + int pos = value.indexOf(':'); + if (pos > -1) { + String[] split = value.split(":", 2); + pfx = split.length > 0 ? split[0] : null; + lp = split.length > 1 ? split[1] : null; + if (pfx != null) { + ns = lookupNamespaceURI(pfx); + } + } else { + lp = value; + } + /* NOTE: we cannot assume that the default namespace of the attribute value is that of the containing element; see: + * - core/api: org.switchyard.policy.PolicyFactory.getPolicy(QName):Policy + * - core/api: org.switchyard.policy.PolicyUtil.containsPolicy(Set, Policy):boolean + * - core/config: org.switchyard.config.model.composite.v1.PolicyConfig.hasRequirement(Model, QName):boolean + if (ns == null || ns.length() == 0) { + ns = getQName().getNamespaceURI(); + } + */ + } + } + return XMLHelper.createQName(ns, lp, pfx); + } + + private Set createAttributeQNames(String values, String splitRegex) { + Set qnames = new LinkedHashSet(); + if (values != null) { + for (String value : values.split(splitRegex)) { + QName qname = createAttributeQName(value); + if (qname != null) { + qnames.add(qname); + } + } + } + return qnames; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration setAttributeAsQName(String name, QName value) { + return setAttribute(name, createAttributeValue(value)); + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration setAttributeAsQName(QName qname, QName value) { + return setAttribute(qname, createAttributeValue(value)); + } + + private String createAttributeValue(QName value) { + if (value != null) { + String lp = value.getLocalPart(); + String ns = value.getNamespaceURI(); + String pfx = lookupPrefix(ns); + if (pfx != null) { + return pfx + ":" + lp; + } else { + pfx = value.getPrefix(); + if (pfx.length() > 0) { + if (lookupNamespaceURI(pfx) != null) { + return pfx + ":" + lp; + } + } + if (ns.length() > 0) { + return value.toString(); + } + } + return lp; + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration getRoot() { + Configuration root = this; + while (root.getParent() != null) { + root = root.getParent(); + } + return root; + } + + /** + * {@inheritDoc} + */ + @Override + public String getRootNamespace() { + return getRoot().getQName().getNamespaceURI(); + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration orderChildren() { + return orderChildren(true); + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration orderChildren(boolean recursive) { + String[] childrenGroups = getChildrenOrder(); + if (childrenGroups != null && childrenGroups.length > 0) { + Map> config_map = new LinkedHashMap>(); + for (String childrenGroup : childrenGroups) { + List config_list; + for (Configuration selected_config : getChildrenMatches(childrenGroup)) { + config_list = config_map.get(childrenGroup); + if (config_list == null) { + config_list = new ArrayList(); + config_map.put(childrenGroup, config_list); + } + config_list.add(selected_config); + } + removeChildrenMatches(childrenGroup); + } + List config_remainder_list = new ArrayList(); + for (Configuration config_remainder : getChildren()) { + config_remainder_list.add(config_remainder); + } + removeChildren(); + for (List config_list : config_map.values()) { + for (Configuration selected_config : config_list) { + addChild(selected_config); + } + } + for (Configuration config_remainder : config_remainder_list) { + addChild(config_remainder); + } + } + if (recursive) { + for (Configuration child_config : getChildren()) { + child_config.orderChildren(true); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Source getSource(OutputKey... keys) { + return new StreamSource(new StringReader(getString(keys))); + } + + /** + * {@inheritDoc} + */ + @Override + public String getString(OutputKey... keys) { + try { + StringWriter writer = new StringWriter(); + write(writer, keys); + return writer.toString().trim(); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void write(OutputStream out, OutputKey... keys) throws IOException { + write(new OutputStreamWriter(out), keys); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return getString(OutputKey.OMIT_XML_DECLARATION, OutputKey.PRETTY_PRINT); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/ConfigLogger.java b/core/config/src/main/java/org/switchyard/config/ConfigLogger.java new file mode 100644 index 000000000..7db017262 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/ConfigLogger.java @@ -0,0 +1,40 @@ +package org.switchyard.config; + +import static org.jboss.logging.Logger.Level.WARN; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 11800-11999 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface ConfigLogger { + /** + * Default root logger. + */ + ConfigLogger ROOT_LOGGER = Logger.getMessageLogger(ConfigLogger.class, ConfigLogger.class.getPackage().getName()); + + /** + * missingComponentReference method definition. + * @param reference reference + * @param component component + */ + @LogMessage(level = WARN) + @Message(id = 11800, value="Missing component reference [%s] for component [%s]") + void missingComponentReference(String reference, String component); + + /** + * missingComponentService method definition. + * @param componentServiceName componentServiceName + * @param componentName componentName + */ + @LogMessage(level = WARN) + @Message(id = 11801, value="missing component service [%s] for component [%s]") + void missingComponentService(String componentServiceName, String componentName); +} diff --git a/core/config/src/main/java/org/switchyard/config/ConfigMessages.java b/core/config/src/main/java/org/switchyard/config/ConfigMessages.java new file mode 100644 index 000000000..eae69cbca --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/ConfigMessages.java @@ -0,0 +1,40 @@ +package org.switchyard.config; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 11600-11799 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface ConfigMessages { + /** + * Default messages. + */ + ConfigMessages MESSAGES = Messages.getBundle(ConfigMessages.class); + + /** + * cannotFindMarshaller method definition. + * @param marshaller marshaller + * @param loader loader + * @return IllegalArgumentException + */ + @Message(id = 11601, value = "Can not find marshaller %s using classloader %s") + IllegalArgumentException cannotFindMarshaller(String marshaller, ClassLoader loader); + + /** + * modelInvalid method definition. + * @param className class name + * @param message message + * @param t t + * @return RuntimeException + */ + @Message(id = 11602, value = "Model [%s] is invalid: %s") + RuntimeException modelInvalid(String className, String message, @Cause Throwable t); +} + diff --git a/core/config/src/main/java/org/switchyard/config/Configuration.java b/core/config/src/main/java/org/switchyard/config/Configuration.java new file mode 100644 index 000000000..769aabdee --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/Configuration.java @@ -0,0 +1,433 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; +import javax.xml.transform.Source; + +import org.switchyard.common.property.PropertyResolver; + +/** + * The central and most important interface of the Configuration API. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface Configuration { + + /** + * Gets the name of this config. + * @return the name + */ + public String getName(); + + /** + * Gets the qualified name of this config. + * @return the qualified name + */ + public QName getQName(); + + /** + * Lookup the namespace uri for the prefix. + * @param prefix the prefix + * @return the namespace uri + */ + public String lookupNamespaceURI(String prefix); + + /** + * Lookup the prefix for a namespace uri. + * @param namespaceURI the namespace uri + * @return the prefix + */ + public String lookupPrefix(String namespaceURI); + + /** + * Gets all namespaces contained by this config and it's recursive parent hierarchy. + * @return the namespaces + */ + public Set getNamespaces(); + + /** + * Gets all namespaces contained by this config and it's recursive child hierarchy. + * @return the namespaces + */ + public Set getChildrenNamespaces(); + + /** + * Gets a mapping of all namespaces to qname prefixes contained by this config and it's recursive parent hierarchy. + * @return the mapping + */ + public Map getNamespacePrefixMap(); + + /** + * Gets a mapping of all qname prefixes to namespaces contained by this config and it's recursive parent hierarchy. + * @return the mapping + */ + public Map getPrefixNamespaceMap(); + + /** + * Gets the value of this config. + * @return the value + */ + public String getValue(); + + /** + * Sets the value of this config. + * @param value the value + * @return this config (useful for chaining) + */ + public Configuration setValue(String value); + + /** + * Gets the list of attribute names of this config. + * @return the attribute names + */ + public List getAttributeNames(); + + /** + * Gets the list of qualified attribute names of this config. + * @return the qualified attribute names + */ + public List getAttributeQNames(); + + /** + * If this config has the specified attribute by name. + * @param name the name of the attribute + * @return true if the attribute is present + */ + public boolean hasAttribute(String name); + + /** + * If this config has the specified attribute by qualified name. + * @param qname the qualified name of the attribute + * @return true if the attribute is present + */ + public boolean hasAttribute(QName qname); + + /** + * Gets the specified attribute by name. + * @param name the name of the attribute + * @return the attribute, or null if it not present + */ + public String getAttribute(String name); + + /** + * Gets the specified attribute by name, as a qualified name. + * @param name the name of the attribute + * @return the attribute, as a qualified name, or null if it not present + */ + public QName getAttributeAsQName(String name); + + /** + * Gets the specified attribute set by name, as qualified names. + * @param name the name of the attribute + * @param splitRegex the regular expression to split the attribute value with + * @return the attribute set, as qualified names, or empty if it not present + * @see {@link String#split(String)} + */ + public Set getAttributeAsQNames(String name, String splitRegex); + + /** + * Gets the specified attribute by qualified name. + * @param qname the qualified name of the attribute + * @return the attribute, or null if it not present + */ + public String getAttribute(QName qname); + + /** + * Gets the specified attribute set by qualified name, as qualified names. + * @param qname the qualified name of the attribute + * @param splitRegex the regular expression to split the attribute value with + * @return the attribute set, as qualified names, or empty if it not present + * @see {@link String#split(String)} + */ + public Set getAttributeAsQNames(QName qname, String splitRegex); + + /** + * Gets the specified attribute by qualified name, as a qualified name. + * @param qname the qualified name of the attribute + * @return the attribute, as a qualified name, or null if it not present + */ + public QName getAttributeAsQName(QName qname); + + /** + * Sets the specified attribute by name. + * @param name the name of the attribute + * @param value the value for the attribute (a null value will remove the attribute) + * @return this Configuration (useful for chaining) + */ + public Configuration setAttribute(String name, String value); + + /** + * Sets the specified attribute by name, as a qualified name. + * @param name the name of the attribute + * @param value the value for the attribute, as a qualified name (a null value will remove the attribute) + * @return this Configuration (useful for chaining) + */ + public Configuration setAttributeAsQName(String name, QName value); + + /** + * Sets the specified attribute by qualified name. + * @param qname the qualified name of the attribute + * @param value the value for the attribute (a null value will remove the attribute) + * @return this Configuration (useful for chaining) + */ + public Configuration setAttribute(QName qname, String value); + + /** + * Sets the specified attribute by qualified name, as a qualified name. + * @param qname the qualified name of the attribute + * @param value the value for the attribute, as a qualified name (a null value will remove the attribute) + * @return this Configuration (useful for chaining) + */ + public Configuration setAttributeAsQName(QName qname, QName value); + + /** + * If this config has a parent config. + * @return true if there is a parent config + */ + public boolean hasParent(); + + /** + * Gets the parent config, if it exists.

+ * + * Guaranteed: child.getParent().equals(child.getParent())
+ * Guaranteed: child.getParent() == child.getParent()
+ * Guaranteed: parent; child = parent.getFirstChild("foo"); parent.equals(child.getParent())
+ * NOT guaranteed: parent; child = parent.getFirstChild("foo"); parent == child.getParent() + * + * @return the parent Configuration, or null if there is no parent + */ + public Configuration getParent(); + + /** + * Gets the root config, or this config if this is the root. + * + * Follows the same guarantees as {@link #getParent()}. + * + * @return the root config + */ + public Configuration getRoot(); + + /** + * Gets the root namespace. + * @return the root namespace + */ + public String getRootNamespace(); + + /** + * If this config has any children configs. + * @return true if this config has children configs + */ + public boolean hasChildren(); + + /** + * If this config has any children configs with the specified name. + * @param name the name of the children configs + * @return true if this config has children configs with the specified name + */ + public boolean hasChildren(String name); + + /** + * If this config has any children configs with the specified qualified name. + * @param qname the qualified name of the children configs + * @return true if this config has children configs with the specified name + */ + public boolean hasChildren(QName qname); + + /** + * Gets all children configs of this config. + * @return all children configs + */ + public List getChildren(); + + /** + * Gets all children configs of this config with the specified name. + * @param name the name of the children configs + * @return all children configs with the specified name + */ + public List getChildren(String name); + + /** + * Gets all children configs of this config with a name that starts with the specified prefix. + * @param name the prefix to match against + * @return all children configs with the specified prefix + */ + public List getChildrenStartsWith(String name); + + /** + * Gets all children configs of this config with a name that matches the specified regexp. + * @param regexp the regexp to match against + * @return all children configs with a matching name + */ + public List getChildrenMatches(String regexp); + + /** + * Gets all children configs of this config with the specified qualified name. + * @param qname the qualified name of the children configs + * @return all children configs with the specified qualified name + */ + public List getChildren(QName qname); + + /** + * Gets the first child config with the specified name. + * @param name name of the child config + * @return the first child config with the specified name + */ + public Configuration getFirstChild(String name); + + /** + * Gets the first child config with a specified name that starts with the specified prefix. + * @param name the prefix to match against + * @return the first child config with the specified prefix + */ + public Configuration getFirstChildStartsWith(String name); + + /** + * Gets the first child config with the specified qualified name. + * @param qname qualified name of the child config + * @return the first child config with the specified qualified name + */ + public Configuration getFirstChild(QName qname); + + /** + * Adds a child config to this config. + * @param child the child to add + * @return this config (useful for chaining) + */ + public Configuration addChild(Configuration child); + + /** + * Removes all children configs from this config. + * @return this config (useful for chaining) + */ + public Configuration removeChildren(); + + /** + * Removes all children configs with the specified name. + * @param name the name of the child configs to remove + * @return this config (useful for chaining) + */ + public Configuration removeChildren(String name); + + /** + * Removes all children configs of this config with a name that starts with the specified prefix. + * @param name the prefix to match against + * @return this config (useful for chaining) + */ + public Configuration removeChildrenStartsWith(String name); + + /** + * Removes all children configs of this config with a name that matches the specified regexp. + * @param regexp the regexp to match against + * @return this config (useful for chaining) + */ + public Configuration removeChildrenMatches(String regexp); + + /** + * Removes all children configs with the specified qualified name. + * @param qname the qualified name of the child configs to remove + * @return this config (useful for chaining) + */ + public Configuration removeChildren(QName qname); + + /** + * Gets the names of the children used to order them by. + * @return the child config names used for ordering + */ + public String[] getChildrenOrder(); + + /** + * Sets the names of the children used to order them by. + * @param childrenOrder the child config names used for ordering + * @return this config (useful for chaining) + */ + public Configuration setChildrenOrder(String... childrenOrder); + + /** + * Orders the child configs based on {@link #getChildrenOrder()}. + * Same as {@link #orderChildren(boolean)} with recursive as true. + * @return this config (useful for chaining) + */ + public Configuration orderChildren(); + + /** + * Orders the child configs based on {@link #getChildrenOrder()}. + * @param recursive whether the children/grandchildren/great-grandchildren/etc should also be ordered + * @return this config (useful for chaining) + */ + public Configuration orderChildren(boolean recursive); + + /** + * Gets the PropertyResolver. + * @return the PropertyResolver + */ + public PropertyResolver getPropertyResolver(); + + /** + * Sets the PropertyResolver. + * @param propertyResolver the PropertyResolver. + * @return this config (useful for chaining) + */ + public Configuration setPropertyResolver(PropertyResolver propertyResolver); + + /** + * Copies this config. + * @return a copy of this config + */ + public Configuration copy(); + + /** + * Normalizes this config. What this actually means is implementation-specific, but useful as their are known times when it should be done. + * @return this config (useful for chaining) + */ + public Configuration normalize(); + + /** + * Gets a source of the underlying config structure. + * @param keys the OutputKeys to respect + * @return the source + */ + public Source getSource(OutputKey... keys); + + /** + * Gets a string of the underlying config structure. + * @param keys the OutputKeys to respect + * @return the string + */ + public String getString(OutputKey... keys); + + /** + * Writes this config out in it's native form (implementation-specific). + * @param out the OutputStream to write to + * @param keys the OutputKeys to respect + * @throws IOException if a problem occurs + */ + public void write(OutputStream out, OutputKey... keys) throws IOException; + + /** + * Writes this config out in it's native form (implementation-specific). + * @param writer the Writer to write to + * @param keys the OutputKeys to respect + * @throws IOException if a problem occurs + */ + public void write(Writer writer, OutputKey... keys) throws IOException; + +} diff --git a/core/config/src/main/java/org/switchyard/config/ConfigurationPuller.java b/core/config/src/main/java/org/switchyard/config/ConfigurationPuller.java new file mode 100644 index 000000000..5a7a6de8d --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/ConfigurationPuller.java @@ -0,0 +1,108 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; + +import javax.xml.namespace.QName; + +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.io.pull.Puller; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; + +/** + * Utility class to safely access ("pull") configs from various sources. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class ConfigurationPuller extends Puller { + + private final ElementPuller _elementPuller; + + /** + * Constructs a new ConfigurationPuller (ignoring comments when parsing XML). + */ + public ConfigurationPuller() { + _elementPuller = new ElementPuller(); + } + + /** + * Constructs a new ConfigurationPuller (optionally ignoring comments when parsing XML). + * @param ignoringComments whether comments should be ignored when parsing XML. + */ + public ConfigurationPuller(boolean ignoringComments) { + _elementPuller = new ElementPuller(ignoringComments); + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration pull(InputStream stream) throws IOException { + return pull(new InputSource(stream)); + } + + /** + * Safely pulls a config from a Reader. + * @param reader a Reader of the config + * @return the config, or null if not found + * @throws IOException if a problem occurred + */ + public Configuration pull(Reader reader) throws IOException { + return pull(new InputSource(reader)); + } + + /** + * Safely pulls a config from an InputSource. + * @param source an InputSource of the config + * @return the config, or null if not found + * @throws IOException if a problem occurred + */ + public Configuration pull(InputSource source) throws IOException { + return new DOMConfiguration(_elementPuller.pull(source)); + } + + /** + * Safely pulls a config from a DOM document. + * @param document the config document + * @return the config, or null if the document is null + */ + public Configuration pull(Document document) { + return new DOMConfiguration(_elementPuller.pull(document)); + } + + /** + * Safely pulls a config from a DOM element. + * @param element the config element + * @return the config, or null if the element is null + */ + public Configuration pull(Element element) { + return new DOMConfiguration(_elementPuller.pull(element)); + } + + /** + * Safely pulls (constructs) an (empty) config from a qualified name. + * @param qname the qualified name + * @return the config, or null if the qualified name is null + */ + public Configuration pull(QName qname) { + return new DOMConfiguration(_elementPuller.pull(qname)); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/Configurations.java b/core/config/src/main/java/org/switchyard/config/Configurations.java new file mode 100644 index 000000000..8f4b612ef --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/Configurations.java @@ -0,0 +1,285 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.StringTokenizer; +import java.util.TreeMap; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; + +import org.switchyard.common.lang.Strings; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * Utility class with helper methods dealing with Configurations. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class Configurations { + + private static final QName DEFAULT_QNAME = XMLHelper.createQName(Configuration.class.getSimpleName().toLowerCase()); + + // HACK: SWITCHYARD-145 + private static final QName COMPOSITE_QNAME = XMLHelper.createQName(SCANamespace.DEFAULT.uri(), CompositeModel.COMPOSITE); + + private static final QName SCHEMA_LOCATION_QNAME = XMLHelper.createQName(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation"); + + private Configurations() {} + + /** + * Creates a new Configuration with the name "configuration". + * @return the new Configuration + */ + public static Configuration newConfiguration() { + return newConfiguration(DEFAULT_QNAME); + } + + /** + * Creates a new Configuration with the specified name. + * @param name the specified name, which will get parsed into a qualified name + * @return the new Configuration + */ + public static Configuration newConfiguration(String name) { + return newConfiguration(XMLHelper.createQName(name)); + } + + /** + * Creates a new Configuration with the specified qualified name. + * @param qname the specified qualified name + * @return the new Configuration + */ + public static Configuration newConfiguration(QName qname) { + return new ConfigurationPuller().pull(qname); + } + + /** + * Merges two configs into a new config. + * Note: The act of merging results in fromConfig and toConfig to be normalized and their children ordered! + * @param fromConfig merge from this config, overriding anything in toConfig + * @param toConfig merge into a copy of this config + * @return the newly merged config + */ + public static Configuration merge(Configuration fromConfig, Configuration toConfig) { + return merge(fromConfig, toConfig, true); + } + + /** + * Merges two configs into a new config. + * Note: The act of merging results in fromConfig and toConfig to be normalized and their children ordered! + * @param fromConfig merge from this config, optionally overriding anything in toConfig + * @param toConfig merge into a copy of this config + * @param fromOverridesTo whether fromConfig attributes/values should override those in toConfig + * @return the newly merged config + */ + public static Configuration merge(Configuration fromConfig, Configuration toConfig, boolean fromOverridesTo) { + QName fromConfigQName = fromConfig.getQName(); + QName toConfigQName = toConfig.getQName(); + if (!fromConfigQName.equals(toConfigQName)) { + throw new IllegalArgumentException(fromConfigQName + " != " + toConfigQName); + } + fromConfig.normalize().orderChildren(); + toConfig.normalize().orderChildren(); + Configuration mergedConfig = toConfig.copy(); + recursiveMerge(fromConfig.copy(), mergedConfig, fromOverridesTo); + mergedConfig.orderChildren(); + return mergedConfig; + } + + private static void recursiveMerge(Configuration from_config, Configuration merged_config, boolean from_overrides_merged) { + List merged_attr_qnames = new ArrayList(); + for (QName merged_config_attr_qname : merged_config.getAttributeQNames()) { + if (SCHEMA_LOCATION_QNAME.equals(merged_config_attr_qname)) { + Map schema_location_map = new LinkedHashMap(); + String merged_config_schema_loc_value = merged_config.getAttribute(merged_config_attr_qname); + StringTokenizer st = new StringTokenizer(merged_config_schema_loc_value); + while (st.hasMoreTokens()) { + String name = st.nextToken(); + if (st.hasMoreTokens()) { + String value = st.nextToken(); + schema_location_map.put(name, value); + } + } + String from_config_schema_loc_value = from_config.getAttribute(merged_config_attr_qname); + if (from_config_schema_loc_value != null) { + st = new StringTokenizer(from_config_schema_loc_value); + while (st.hasMoreTokens()) { + String name = st.nextToken(); + if (st.hasMoreTokens()) { + String value = st.nextToken(); + if (!schema_location_map.containsKey(name) || from_overrides_merged) { + schema_location_map.put(name, value); + } + } + } + } + StringBuilder sb = new StringBuilder(); + for (Map.Entry entry : schema_location_map.entrySet()) { + if (sb.length() != 0) { + sb.append(' '); + } + sb.append(entry.getKey()); + sb.append(' '); + sb.append(entry.getValue()); + } + merged_config.setAttribute(merged_config_attr_qname, sb.toString()); + merged_attr_qnames.add(merged_config_attr_qname); + } else if (from_overrides_merged) { + String from_config_attr_value = from_config.getAttribute(merged_config_attr_qname); + if (from_config_attr_value != null) { + merged_config.setAttribute(merged_config_attr_qname, from_config_attr_value); + merged_attr_qnames.add(merged_config_attr_qname); + } + } else { + merged_attr_qnames.add(merged_config_attr_qname); + } + } + for (QName from_config_attr_qname : from_config.getAttributeQNames()) { + if (!merged_attr_qnames.contains(from_config_attr_qname)) { + String from_config_attr_value = from_config.getAttribute(from_config_attr_qname); + merged_config.setAttribute(from_config_attr_qname, from_config_attr_value); + merged_attr_qnames.add(from_config_attr_qname); + } + } + if (from_overrides_merged) { + String from_config_value = from_config.getValue(); + if (from_config_value != null && from_config_value.length() > 0) { + merged_config.setValue(from_config_value); + } + } + Map merged_config_orphans = new LinkedHashMap(); + for (Configuration merged_config_child : merged_config.getChildren()) { + Key merged_config_child_key = new Key(merged_config_child); + merged_config_orphans.put(merged_config_child_key, merged_config_child); + } + merged_config.removeChildren(); + for (Configuration from_config_child : from_config.getChildren()) { + Key from_config_child_key = new Key(from_config_child); + Configuration merged_config_orphan = merged_config_orphans.remove(from_config_child_key); + if (merged_config_orphan != null) { + recursiveMerge(from_config_child, merged_config_orphan, from_overrides_merged); + merged_config.addChild(merged_config_orphan); + } else if (COMPOSITE_QNAME.equals(from_config_child.getQName())) { + // HACK: SWITCHYARD-145 + boolean candidate_found = false; + for (Entry merged_config_orphan_entry : merged_config_orphans.entrySet()) { + Configuration merged_config_orphan_candidate = merged_config_orphan_entry.getValue(); + if (COMPOSITE_QNAME.equals(merged_config_orphan_candidate.getQName())) { + candidate_found = true; + merged_config_orphans.remove(merged_config_orphan_entry.getKey()); + String from_config_child_name_attr = from_config_child.getAttribute("name"); + if (from_config_child_name_attr != null && from_config_child_name_attr.length() > 0) { + merged_config_orphan_candidate.setAttribute("name", from_config_child_name_attr); + } + recursiveMerge(from_config_child, merged_config_orphan_candidate, from_overrides_merged); + merged_config.addChild(merged_config_orphan_candidate); + break; + } + } + if (!candidate_found) { + merged_config.addChild(from_config_child); + } + } else { + merged_config.addChild(from_config_child); + } + } + for (Configuration merged_config_orphan : merged_config_orphans.values()) { + merged_config.addChild(merged_config_orphan); + } + } + + private static final class Key { + + private static final String[] ID_CANDIDATES = {"id", "name", "type", "class", "interface", "from", "to"}; + + private QName _qname; + private Map _ids; + + private Key(Configuration config) { + _qname = config.getQName(); + _ids = new TreeMap(); + for (String idc : ID_CANDIDATES) { + Object id = Strings.trimToNull(config.getAttribute(XMLHelper.createQName(_qname.getNamespaceURI(), idc))); + if (id == null) { + id = Strings.trimToNull(config.getAttribute(idc)); + } + if (id != null) { + _ids.put(idc, id); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("Key [_qname=%s, _ids=%s]", _qname, _ids); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_ids == null) ? 0 : _ids.hashCode()); + result = prime * result + ((_qname == null) ? 0 : _qname.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Key other = (Key)obj; + if (_ids == null) { + if (other._ids != null) { + return false; + } + } else if (!_ids.equals(other._ids)) { + return false; + } + if (_qname == null) { + if (other._qname != null) { + return false; + } + } else if (!_qname.equals(other._qname)) { + return false; + } + return true; + } + + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/DOMConfiguration.java b/core/config/src/main/java/org/switchyard/config/DOMConfiguration.java new file mode 100644 index 000000000..262404ff1 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/DOMConfiguration.java @@ -0,0 +1,785 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config; + +import static javax.xml.XMLConstants.NULL_NS_URI; +import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.transform.OutputKeys; + +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.common.property.SystemAndTestPropertyResolver; +import org.switchyard.common.xml.XMLHelper; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.Text; + +/** + * A DOM (Document Object Model) representation of a Configuration. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class DOMConfiguration extends BaseConfiguration { + + private static final String CHILDREN_ORDER_KEY = "childrenOrder"; + private static final String CHILDREN_ORDER_DELIM = ","; + private static final String PROPERTY_RESOLVER_KEY = "propertyResolver"; + + private Element _element; + private Element _parent_element; + private DOMConfiguration _parent_config; + + DOMConfiguration(Element element) { + _element = new ElementPuller().pull(element); + getParent(); // initializes parent + } + + private DOMConfiguration(Element element, boolean normalize) { + _element = new ElementPuller().pull(element, normalize); + getParent(); // initializes parent + } + + private DOMConfiguration(Configuration from) { + DOMConfiguration config; + if (from instanceof DOMConfiguration) { + config = (DOMConfiguration)from; + } else { + Element element = new ElementPuller().pull(from.getQName()); + config = new DOMConfiguration(element); + for (QName qname : from.getAttributeQNames()) { + config.setAttribute(qname, from.getAttribute(qname)); + } + for (Configuration grandchild : from.getChildren()) { + config.addChild(grandchild); + } + } + _element = config._element; + getParent(); // initializes parent + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return XMLHelper.nameOf(_element); + } + + /** + * {@inheritDoc} + */ + @Override + public QName getQName() { + return XMLHelper.createQName(_element); + } + + /** + * {@inheritDoc} + */ + @Override + public String lookupNamespaceURI(String prefix) { + return _element.lookupNamespaceURI(prefix); + } + + /** + * {@inheritDoc} + */ + @Override + public String lookupPrefix(String namespaceURI) { + return _element.lookupPrefix(namespaceURI); + } + + /** + * {@inheritDoc} + */ + @Override + public String getValue() { + Node text_node = getTextNode(false); + String value = null; + if (text_node instanceof Text) { + value = ((Text)text_node).getWholeText(); + } else if (text_node != null) { + value = text_node.getNodeValue(); + } + if (value != null) { + return Strings.replaceProperties(value, getPropertyResolver()); + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration setValue(String value) { + if (value != null) { + Node text_node = getTextNode(true); + text_node.setNodeValue(value); + } else { + Node text_node = getTextNode(false); + if (text_node != null) { + _element.removeChild(text_node); + } + } + return this; + } + + private Node getTextNode(boolean create) { + Node first_child_node = _element.getFirstChild(); + if (first_child_node != null) { + if (first_child_node.getNodeType() == Node.TEXT_NODE) { + return first_child_node; + } + Node next_child_node = first_child_node.getNextSibling(); + while (next_child_node != null) { + if (next_child_node.getNodeType() == Node.TEXT_NODE) { + return next_child_node; + } + next_child_node = next_child_node.getNextSibling(); + } + if (create) { + Node text_node = _element.getOwnerDocument().createTextNode(""); + _element.insertBefore(text_node, first_child_node); + return text_node; + } + } + if (create) { + Node text_node = _element.getOwnerDocument().createTextNode(""); + _element.appendChild(text_node); + return text_node; + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public List getAttributeNames() { + List names = new ArrayList(); + NamedNodeMap attrs = _element.getAttributes(); + for (int i=0; i < attrs.getLength(); i++) { + Attr attr = (Attr)attrs.item(i); + String name = XMLHelper.nameOf(attr); + names.add(name); + } + return names; + } + + /** + * {@inheritDoc} + */ + @Override + public List getAttributeQNames() { + List qnames = new ArrayList(); + NamedNodeMap attrs = _element.getAttributes(); + for (int i=0; i < attrs.getLength(); i++) { + Attr attr = (Attr)attrs.item(i); + String name = XMLHelper.nameOf(attr); + if (name != null && name.length() > 0) { + qnames.add(XMLHelper.createQName(attr.getNamespaceURI(), name, attr.getPrefix())); + } + } + return qnames; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasAttribute(String name) { + if (name != null) { + return _element.hasAttribute(name); + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasAttribute(QName qname) { + if (qname != null) { + String namespaceURI = qname.getNamespaceURI(); + String localPart = qname.getLocalPart(); + if (namespaceURI != null && !namespaceURI.equals(NULL_NS_URI)) { + return _element.hasAttributeNS(namespaceURI, localPart); + } else { + return hasAttribute(localPart); + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public String getAttribute(String name) { + if (name != null) { + String value = _element.getAttribute(name); + return "".equals(value) ? null : Strings.replaceProperties(value, getPropertyResolver()); + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getAttribute(QName qname) { + if (qname != null) { + String namespaceURI = qname.getNamespaceURI(); + String localPart = qname.getLocalPart(); + if (namespaceURI != null && !namespaceURI.equals(NULL_NS_URI)) { + Attr attr = _element.getAttributeNodeNS(namespaceURI, localPart); + if (attr != null) { + String value = attr.getValue(); + return "".equals(value) ? null : Strings.replaceProperties(value, getPropertyResolver()); + } + } else { + return getAttribute(localPart); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration setAttribute(String name, String value) { + if (name == null) { + throw new IllegalArgumentException("name == null"); + } + if (value == null) { + _element.removeAttribute(name); + } else { + _element.setAttribute(name, value); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration setAttribute(QName qname, String value) { + if (qname == null) { + throw new IllegalArgumentException("qname == null"); + } + String namespaceURI = qname.getNamespaceURI(); + String localPart = qname.getLocalPart(); + Attr attr = _element.getAttributeNodeNS(namespaceURI, localPart); + if (attr != null) { + if (value == null) { + _element.removeAttributeNode(attr); + } else { + attr.setValue(value); + } + } else if (value != null) { + if (XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) { + _element.setAttributeNS(XMLNS_ATTRIBUTE_NS_URI, "xmlns:"+localPart, value); + } else { + attr = _element.getOwnerDocument().createAttributeNS(namespaceURI, localPart); + String prefix = qname.getPrefix(); + if (prefix != null && prefix.length() > 0) { + attr.setPrefix(prefix); + } + attr.setValue(value); + _element.setAttributeNode(attr); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasParent() { + return _element.getParentNode() instanceof Element; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration getParent() { + Node node = _element.getParentNode(); + if (node instanceof Element) { + Element e = (Element)node; + if (_parent_element != null && _parent_element != e) { + // somebody changed the document structure underneath us! + _parent_config = null; + } + if (_parent_config == null) { + _parent_config = new DOMConfiguration(e, false); + _parent_element = e; + } + } + return _parent_config; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasChildren() { + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + return true; + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasChildren(String name) { + if (name != null) { + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + String node_name = XMLHelper.nameOf(node); + if (node_name.equals(name)) { + return true; + } + } + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasChildren(QName qname) { + if (qname != null) { + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + QName node_qname = XMLHelper.createQName((Element)node); + if (node_qname.equals(qname)) { + return true; + } + } + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public List getChildren() { + List configs = new ArrayList(); + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + configs.add(new DOMConfiguration((Element)node)); + } + } + return configs; + } + + /** + * {@inheritDoc} + */ + @Override + public List getChildren(String name) { + List configs = new ArrayList(); + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + if (XMLHelper.nameOf(node).equals(name)) { + configs.add(new DOMConfiguration((Element)node)); + } + } + } + return configs; + } + + /** + * {@inheritDoc} + */ + @Override + public List getChildrenStartsWith(String name) { + List configs = new ArrayList(); + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + if (XMLHelper.nameOf(node).startsWith(name)) { + configs.add(new DOMConfiguration((Element)node)); + } + } + } + return configs; + } + + /** + * {@inheritDoc} + */ + @Override + public List getChildrenMatches(String regexp) { + List configs = new ArrayList(); + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + if (XMLHelper.nameOf(node).matches(regexp)) { + configs.add(new DOMConfiguration((Element)node)); + } + } + } + return configs; + } + + /** + * {@inheritDoc} + */ + @Override + public List getChildren(QName qname) { + List configs = new ArrayList(); + NodeList nodes = _element.getElementsByTagNameNS(qname.getNamespaceURI(), qname.getLocalPart()); + for (int i=0; i < nodes.getLength(); i++) { + configs.add(new DOMConfiguration((Element)nodes.item(i))); + } + return configs; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration getFirstChild(String name) { + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + if (XMLHelper.nameOf(node).equals(name)) { + return new DOMConfiguration((Element)node); + } + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration getFirstChildStartsWith(String name) { + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + if (XMLHelper.nameOf(node).startsWith(name)) { + return new DOMConfiguration((Element)node); + } + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration getFirstChild(QName qname) { + NodeList nodes = _element.getElementsByTagNameNS(qname.getNamespaceURI(), qname.getLocalPart()); + if (nodes.getLength() > 0) { + Node node = nodes.item(0); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + return new DOMConfiguration((Element)node); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration addChild(Configuration child) { + Document this_doc = _element.getOwnerDocument(); + this_doc.normalizeDocument(); + DOMConfiguration child_config = new DOMConfiguration(child); + Document child_doc = child_config._element.getOwnerDocument(); + if (child_doc != this_doc) { + child_doc.normalizeDocument(); + this_doc.adoptNode(child_config._element); + } + _element.appendChild(child_config._element); + String child_xmlns = Strings.trimToNull(child_config._element.getNamespaceURI()); + if (child_xmlns == null) { + String this_xmlns = Strings.trimToNull(this._element.getNamespaceURI()); + if (this_xmlns != null) { + this_doc.renameNode(child_config._element, this_xmlns, child_config.getName()); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration removeChildren() { + List removals = new ArrayList(); + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + removals.add(node); + } + } + for (Node node : removals) { + _element.removeChild(node); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration removeChildren(String name) { + List removals = new ArrayList(); + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + if (XMLHelper.nameOf(node).equals(name)) { + removals.add(node); + } + } + } + for (Node node : removals) { + _element.removeChild(node); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration removeChildrenStartsWith(String name) { + List removals = new ArrayList(); + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + if (XMLHelper.nameOf(node).startsWith(name)) { + removals.add(node); + } + } + } + for (Node node : removals) { + _element.removeChild(node); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration removeChildrenMatches(String regexp) { + List removals = new ArrayList(); + NodeList nodes = _element.getChildNodes(); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + if (XMLHelper.nameOf(node).matches(regexp)) { + removals.add(node); + } + } + } + for (Node node : removals) { + _element.removeChild(node); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration removeChildren(QName qname) { + List removals = new ArrayList(); + NodeList nodes = _element.getElementsByTagNameNS(qname.getNamespaceURI(), qname.getLocalPart()); + for (int i=0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { + removals.add(node); + } + } + for (Node node : removals) { + _element.removeChild(node); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String[] getChildrenOrder() { + String co = (String)_element.getUserData(CHILDREN_ORDER_KEY); + return Strings.splitTrimToNullArray(co, CHILDREN_ORDER_DELIM); + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration setChildrenOrder(String... childrenOrder) { + String co = Strings.concat(CHILDREN_ORDER_DELIM, childrenOrder); + _element.setUserData(CHILDREN_ORDER_KEY, co, null); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public PropertyResolver getPropertyResolver() { + PropertyResolver propertyResolver = (PropertyResolver)_element.getUserData(PROPERTY_RESOLVER_KEY); + if (propertyResolver == null) { + Configuration parent = getParent(); + propertyResolver = parent != null ? parent.getPropertyResolver() : SystemAndTestPropertyResolver.INSTANCE; + } + return propertyResolver; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration setPropertyResolver(PropertyResolver propertyResolver) { + _element.setUserData(PROPERTY_RESOLVER_KEY, propertyResolver, null); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration copy() { + Element clone = (Element)_element.cloneNode(true); + DOMConfiguration copy = new DOMConfiguration(clone, false); + copy.setChildrenOrder(getChildrenOrder()); + return copy; + } + + /** + * {@inheritDoc} + */ + @Override + public Configuration normalize() { + _element.normalize(); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public void write(Writer writer, OutputKey... keys) throws IOException { + List key_list = Arrays.asList(keys); + if (key_list.contains(OutputKey.NORMALIZE)) { + normalize(); + } + if (key_list.contains(OutputKey.ORDER_CHILDREN)) { + orderChildren(); + } + Map outputProperties = new HashMap(); + if (key_list.contains(OutputKey.OMIT_XML_DECLARATION)) { + outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); + } + if (key_list.contains(OutputKey.PRETTY_PRINT)) { + outputProperties.put(OutputKey.PRETTY_PRINT.hint(), "yes"); + } + XMLHelper.write(_element, writer, outputProperties); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_element == null) ? 0 : _element.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + DOMConfiguration other = (DOMConfiguration)obj; + if (_element == null) { + if (other._element != null) { + return false; + } + } else { + _element.normalize(); + other._element.normalize(); + if (!_element.isEqualNode(other._element)) { + return false; + } + } + return true; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/OutputKey.java b/core/config/src/main/java/org/switchyard/config/OutputKey.java new file mode 100644 index 000000000..3d11baacc --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/OutputKey.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config; + +import org.switchyard.common.lang.Strings; + +/** + * OutputKey hints for Configuration output. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public enum OutputKey { + + /** The normalize hint. */ + NORMALIZE("normalize"), + + /** The omit-xml-declaration hint. */ + OMIT_XML_DECLARATION("omit-xml-declaration"), + + /** The order-children hint. */ + ORDER_CHILDREN("order-children"), + + /** The pretty-print hint. */ + PRETTY_PRINT("pretty-print"); + + private final String _hint; + + /** + * Constructs a new OutputKey with the specified hint. + * @param hint the specified hint + */ + private OutputKey(String hint) { + _hint = hint; + } + + /** + * Gets the hint. + * @return the hint + */ + public String hint() { + return _hint; + } + + /** + * Derives an OutputKey from the specified hint. + * @param hint the hint + * @return the OutputKey + */ + public static OutputKey fromHint(String hint) { + hint = Strings.trimToNull(hint); + if (hint != null) { + for (OutputKey ok : values()) { + if (ok.hint().equalsIgnoreCase(hint)) { + return ok; + } + } + } + return null; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/BaseMarshaller.java b/core/config/src/main/java/org/switchyard/config/model/BaseMarshaller.java new file mode 100644 index 000000000..f6cb9e9b6 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/BaseMarshaller.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; + +import org.switchyard.config.Configuration; + +/** + * Abstract representation of a Marshaller, implementing all the methods with default implementations. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class BaseMarshaller implements Marshaller { + + private Descriptor _desc; + + protected BaseMarshaller(Descriptor desc) { + _desc = desc; + } + + /** + * {@inheritDoc} + */ + @Override + public final Descriptor getDescriptor() { + return _desc; + } + + /** + * By default, will throw an {@link java.lang.UnsupportedOperationException}. + * @param config the config + * @return the new Model + */ + @Override + public Model read(Configuration config) { + throw new UnsupportedOperationException(); + } + + /** + * By default, will delegate the writing to the specified Model. + * @param model the Model to write + * @param out the OutputStream to write to + * @throws IOException if a problem occurred + */ + @Override + public void write(Model model, OutputStream out) throws IOException { + model.write(out); + } + + /** + * By default, will delegate the writing to the specified Model. + * @param model the Model to write + * @param writer the Writer to write to + * @throws IOException if a problem occurred + */ + @Override + public void write(Model model, Writer writer) throws IOException { + model.write(writer); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/BaseModel.java b/core/config/src/main/java/org/switchyard/config/model/BaseModel.java new file mode 100644 index 000000000..d5a5a1cdd --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/BaseModel.java @@ -0,0 +1,468 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.xml.namespace.QName; +import javax.xml.transform.Source; +import javax.xml.validation.Validator; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.Configuration; +import org.switchyard.config.ConfigurationPuller; +import org.switchyard.config.OutputKey; + +/** + * An abstract representation of a Model, containing many helper methods, as well as default implementations for some of the defined methods.. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class BaseModel implements Model { + + private final Configuration _config; + private final Descriptor _desc; + private Model _parent; + + protected BaseModel(String namespace, String name) { + this(XMLHelper.createQName(namespace, name)); + } + + protected BaseModel(QName qname) { + this(new ConfigurationPuller().pull(qname)); + } + + protected BaseModel(Configuration config) { + this(config, null); + } + + protected BaseModel(Configuration config, Descriptor desc) { + _config = config; + _desc = desc != null ? desc : new Descriptor(); + } + + /** + * {@inheritDoc} + */ + @Override + public final Configuration getModelConfiguration() { + return _config; + } + + /** + * {@inheritDoc} + */ + @Override + public final Descriptor getModelDescriptor() { + return _desc; + } + + /** + * Gets the wrapped configuration namespace uri. + * @return Namespace uri of this model instance. + */ + protected final String getNamespaceURI() { + return getModelConfiguration().getQName().getNamespaceURI(); + } + + /** + * Gets the wrapped config's value. + * @return the value + */ + protected final String getModelValue() { + return getModelConfiguration().getValue(); + } + + /** + * Sets the wrapped config's value. + * @param value the value + * @return this model (useful for chaining) + */ + protected final Model setModelValue(String value) { + getModelConfiguration().setValue(value); + return this; + } + + /** + * Gets the wrapped config's value for an attribute with a specified name. + * @param name the attribute name + * @return the attribute value + */ + protected final String getModelAttribute(String name) { + return getModelConfiguration().getAttribute(name); + } + + /** + * Gets the wrapped config's value for an attribute with a specified qualified name. + * @param qname the attribute qualified name + * @return the attribute value + */ + protected final String getModelAttribute(QName qname) { + return getModelConfiguration().getAttribute(qname); + } + + /** + * Gets the wrapped config's value for an attribute with a specified name, as a qualified name. + * @param name the attribute name + * @return the attribute value, as a qualified name + */ + protected final QName getModelAttributeAsQName(String name) { + return getModelConfiguration().getAttributeAsQName(name); + } + + /** + * Gets the wrapped config's value for an attribute with a specified qualified name, as a qualified name. + * @param qname the attribute qualified name + * @return the attribute value, as a qualified name + */ + protected final QName getModelAttributeAsQName(QName qname) { + return getModelConfiguration().getAttributeAsQName(qname); + } + + /** + * Sets the wrapped config's value for an attribute with a specified name. + * @param name the attribute name + * @param value the attribute value (null means "remove the attribute") + * @return this model (useful for chaining) + */ + protected final Model setModelAttribute(String name, String value) { + getModelConfiguration().setAttribute(name, value); + return this; + } + + /** + * Sets the wrapped config's value for an attribute with a specified qualified name. + * @param qname the attribute qualified name + * @param value the attribute value (null means "remove the attribute") + * @return this model (useful for chaining) + */ + protected final Model setModelAttribute(QName qname, String value) { + getModelConfiguration().setAttribute(qname, value); + return this; + } + + /** + * Sets the wrapped config's value for an attribute with a specified name, as a qualified name. + * @param name the attribute name + * @param value the attribute value, as a qualified name (null means "remove the attribute") + * @return this model (useful for chaining) + */ + protected final Model setModelAttributeAsQName(String name, QName value) { + getModelConfiguration().setAttributeAsQName(name, value); + return this; + } + + /** + * Sets the wrapped config's value for an attribute with a specified qualified name, as a qualified name. + * @param qname the attribute qualified name + * @param value the attribute value, as a qualified name (null means "remove the attribute") + * @return this model (useful for chaining) + */ + protected final Model setModelAttributeAsQName(QName qname, QName value) { + getModelConfiguration().setAttributeAsQName(qname, value); + return this; + } + + /** + * Whether or not this model has a parent model. + * @return true if a parent model exists + */ + protected final boolean hasParentModel() { + return getModelParent() != null; + } + + /** + * {@inheritDoc} + */ + @Override + public final Model getModelParent() { + if (_parent == null) { + Configuration parent_config = _config.getParent(); + if (parent_config != null) { + _parent = readModel(parent_config); + } + } + return _parent; + } + + /** + * {@inheritDoc} + */ + @Override + public final Model getModelRoot() { + Model root = this; + while (root.getModelParent() != null) { + root = root.getModelParent(); + } + return root; + } + + /** + * {@inheritDoc} + */ + @Override + public String getModelRootNamespace() { + //return getModelRoot().getModelConfiguration().getQName().getNamespaceURI(); + // the line below is faster than the line above, as it won't invoke readModel + return _config.getRootNamespace(); + } + + /** + * {@inheritDoc} + */ + @Override + public final List getModelChildren() { + List child_models = new ArrayList(); + List child_configs =_config.getChildren(); + if (child_configs != null) { + for (Configuration child_config : child_configs) { + if (child_config != null) { + Model child_model = readModel(child_config); + if (child_model != null) { + child_models.add(child_model); + } + } + } + } + return child_models; + } + + /** + * {@inheritDoc} + */ + @Override + public Validation validateModel() { + Validator validator = _desc.getValidator(_config); + if (validator != null) { + Source source = _config.getSource(); + try { + validator.validate(source); + } catch (Throwable t) { + return new Validation(getClass(), t); + } + } else { + return new Validation(getClass(), false, "validator == null"); + } + return new Validation(getClass(), true); + } + + /** + * {@inheritDoc} + */ + @Override + public Model assertModelValid() { + validateModel().assertValid(); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isModelValid() { + return validateModel().isValid(); + } + + /** + * Gets the first child model with the specified name. + * @param name name of the child model + * @return the first child model with the specified name + */ + protected final Model getFirstChildModel(String name) { + Configuration child_config = _config.getFirstChild(name); + if (child_config != null) { + return readModel(child_config); + } + return null; + } + + /** + * Gets the first child model with a specified name that starts with the specified prefix. + * @param name the prefix to match against + * @return the first child model with the specified prefix + */ + protected final Model getFirstChildModelStartsWith(String name) { + Configuration child_config = _config.getFirstChildStartsWith(name); + if (child_config != null) { + return readModel(child_config); + } + return null; + } + + /** + * Reads (constructs) a Model based on the specified Configuration. + * @param config the Configuration + * @return the new Model + */ + protected final synchronized Model readModel(Configuration config) { + if (config != null) { + Marshaller marsh = _desc.getMarshaller(config); + if (marsh != null) { + return marsh.read(config); + } + } + return null; + } + + /** + * Adds a child model to this model. + * @param child the child to add + * @return this model (useful for chaining) + */ + protected final Model addChildModel(Model child) { + if (child != null) { + _config.addChild(child.getModelConfiguration()); + } + return this; + } + + /** + * First removes all child models with a wrapped Configuration which has a matching qualified name, then adds the single, specified child model. + * @param child the child model to add + * @return this model (useful for chaining) + */ + protected final Model setChildModel(Model child) { + if (child != null) { + Configuration child_config = child.getModelConfiguration(); + _config.removeChildren(child_config.getQName()); + _config.addChild(child_config); + } + return this; + } + + /** + * Gets the names of the children (based on their wrapped Configurations) used to order them by. + * @return the child model's names (based on their wrapped Configurations) used for ordering + */ + protected final String[] getModelChildrenOrder() { + return _config.getChildrenOrder(); + } + + /** + * Sets the names of the children (based on their wrapped Configurations) used to order them by. + * @param childrenOrder the child model names (based on their wrapped Configurations) used for ordering + * @return this model (useful for chaining) + */ + protected Model setModelChildrenOrder(String... childrenOrder) { + String[] existingOrder = getModelChildrenOrder(); + if (existingOrder != null && existingOrder.length > 0) { + List orderList = new ArrayList(); + orderList.addAll(Arrays.asList(existingOrder)); + orderList.addAll(Arrays.asList(childrenOrder)); + _config.setChildrenOrder(orderList.toArray(new String[orderList.size()])); + } else { + _config.setChildrenOrder(childrenOrder); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Model orderModelChildren() { + primeModelChildren(); + getModelConfiguration().orderChildren(); + return this; + } + + /** + * Recursively iterates over the children, which will force instantiation of a Model for every child Configuration. + * @return this model (useful for chaining) + */ + protected final Model primeModelChildren() { + primeModelChildren(this); + return this; + } + + private final void primeModelChildren(Model model) { + for (Model child : model.getModelChildren()) { + primeModelChildren(child); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void write(OutputStream out, OutputKey... keys) throws IOException { + getModelConfiguration().write(out, keys); + } + + /** + * {@inheritDoc} + */ + @Override + public void write(Writer writer, OutputKey... keys) throws IOException { + getModelConfiguration().write(writer, keys); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return _config.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_config == null) ? 0 : _config.hashCode()); + result = prime * result + ((_desc == null) ? 0 : _desc.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + BaseModel other = (BaseModel)obj; + if (_config == null) { + if (other._config != null) { + return false; + } + } else if (!_config.equals(other._config)) { + return false; + } + if (_desc == null) { + if (other._desc != null) { + return false; + } + } else if (!_desc.equals(other._desc)) { + return false; + } + return true; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/BaseNamedModel.java b/core/config/src/main/java/org/switchyard/config/model/BaseNamedModel.java new file mode 100644 index 000000000..eda06bde2 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/BaseNamedModel.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.net.URI; + +import javax.xml.namespace.QName; + +import org.switchyard.common.lang.Strings; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.Configuration; + +/** + * An abstract representation of a NamedModel, useful for subclassing. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class BaseNamedModel extends BaseModel implements NamedModel { + + protected static final String TARGET_NAMESPACE = "targetNamespace"; + + protected BaseNamedModel(QName qname) { + super(qname); + } + + protected BaseNamedModel(String namespace, String name) { + super(namespace, name); + } + + protected BaseNamedModel(Configuration config) { + super(config); + } + + protected BaseNamedModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return getModelAttribute("name"); + } + + /** + * {@inheritDoc} + */ + @Override + public NamedModel setName(String name) { + setModelAttribute("name", name); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getTargetNamespace() { + String tns = null; + Model model = this; + while (model instanceof BaseModel) { + tns = Strings.trimToNull(((BaseModel)model).getModelAttribute(TARGET_NAMESPACE)); + if (tns != null) { + break; + } + model = model.getModelParent(); + } + return tns; + } + + /** + * {@inheritDoc} + */ + @Override + public URI getTargetNamespaceURI() { + String tns = getTargetNamespace(); + return tns != null ? URI.create(tns) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public QName getQName() { + return XMLHelper.createQName(getTargetNamespace(), getName()); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/BaseTypedModel.java b/core/config/src/main/java/org/switchyard/config/model/BaseTypedModel.java new file mode 100644 index 000000000..df183c338 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/BaseTypedModel.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; + +/** + * An abstract representation of a TypedModel, useful for subclassing. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class BaseTypedModel extends BaseModel implements TypedModel { + + protected BaseTypedModel(QName qname) { + super(qname); + } + + protected BaseTypedModel(Configuration config) { + super(config); + } + + protected BaseTypedModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public final String getType() { + String name = getModelConfiguration().getName(); + if (name != null) { + int pos = name.indexOf('.'); + if (pos > -1) { + return name.substring(pos+1, name.length()); + } + } + return null; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/Descriptor.java b/core/config/src/main/java/org/switchyard/config/model/Descriptor.java new file mode 100644 index 000000000..b89d3ee89 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/Descriptor.java @@ -0,0 +1,765 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; +import java.net.URL; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.TreeMap; +import java.util.TreeSet; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Validator; + +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.type.Classes; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.config.ConfigMessages; +import org.switchyard.config.Configuration; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSResourceResolver; + +/** + * Holds meta-information used to create, marshall and validate Models. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class Descriptor { + + /** The default location to looks for a Descriptor's Properties. ALL properties found with this name via {@link org.switchyard.common.type.Classes#getResources(String, Class)} will be combined. */ + public static final String DEFAULT_PROPERTIES = "/org/switchyard/config/model/descriptor.properties"; + + /** The "section" property. */ + public static final String SECTION = "section"; + + /** The "version" property. */ + public static final String VERSION = "version"; + + /** The "namespace" property. */ + public static final String NAMESPACE = "namespace"; + + /** The "schema" property. */ + public static final String SCHEMA = "schema"; + + /** The "noNamespaceSchema" property. */ + public static final String NO_NAMESPACE_SCHEMA = "noNamespaceSchema"; + + /** The "location" property. */ + public static final String LOCATION = "location"; + + /** The "marshaller" property. */ + public static final String MARSHALLER = "marshaller"; + + private Map _all_properties_map = new TreeMap(); + private Map> _prefix_config_map = new HashMap>(); + private Map> _section_prefixes_map = new HashMap>(); + private Map _namespace_prefix_map = new HashMap(); + private Map _nonamespace_location_map = new HashMap(); + private Map,Schema> _namespaces_schema_map = new HashMap,Schema>(); + private Map _namespace_marshaller_map = new HashMap(); + + /** + * Constructs a new Descriptor based on discovered default properties. + */ + public Descriptor() { + addDefaultProperties(); + } + + /** + * Constructs a new Descriptor based on discovered default properties using the classloader of the specified class. + * @param caller the class whose classloader should be used to look up the default properties + */ + public Descriptor(Class caller) { + addDefaultProperties(caller); + } + + /** + * Constructs a new Descriptor based on discovered default properties using the specified classloader. + * @param loader the classloader to use to look up the default properties + */ + public Descriptor(ClassLoader loader) { + addDefaultProperties(loader); + } + + /** + * Constructs a new Descriptor based on the specified properties. + * @param props the Properties + */ + public Descriptor(Properties props) { + addProperties(props); + } + + /** + * Adds discovered default properties. + */ + public void addDefaultProperties() { + addDefaultProperties(Descriptor.class); + } + + /** + * Adds discovered default properties using the classloader of the specified class. + * @param caller the class whose classloader should be used to look up the default properties + */ + public void addDefaultProperties(Class caller) { + addDefaultProperties(caller != null ? caller.getClassLoader() : null); + } + + /** + * Adds discovered default properties using the specified classloader. + * @param loader the classloader to use to look up the default properties + */ + public void addDefaultProperties(ClassLoader loader) { + Properties props = new Properties(); + PropertiesPuller props_puller = new PropertiesPuller(); + try { + List urls = Classes.getResources(DEFAULT_PROPERTIES, loader); + for (URL url : urls) { + Properties url_props = props_puller.pull(url); + Enumeration pn_enum = url_props.propertyNames(); + while (pn_enum.hasMoreElements()) { + String pn = (String)pn_enum.nextElement(); + props.setProperty(pn, url_props.getProperty(pn)); + } + } + } catch (IOException ioe) { + // should never happen + throw new RuntimeException(ioe); + } + addProperties(props); + } + + private void addProperties(Properties props) { + Enumeration e = props.propertyNames(); + while (e.hasMoreElements()) { + String prop_name = (String)e.nextElement(); + String prop_value = props.getProperty(prop_name); + if (prop_value != null) { + _all_properties_map.put(prop_name, prop_value); + int pos = prop_name.lastIndexOf('.'); + String prop_prefix = prop_name.substring(0, pos).trim(); + String prop_suffix = prop_name.substring(pos+1, prop_name.length()).trim(); + Map config = _prefix_config_map.get(prop_prefix); + if (config == null) { + config = new HashMap(); + _prefix_config_map.put(prop_prefix, config); + } + config.put(prop_suffix, prop_value); + if (SECTION.equals(prop_suffix)) { + Set prefixes = _section_prefixes_map.get(prop_value); + if (prefixes == null) { + prefixes = new TreeSet(); + _section_prefixes_map.put(prop_value, prefixes); + } + prefixes.add(prop_prefix); + } else if (NAMESPACE.equals(prop_suffix)) { + _namespace_prefix_map.put(prop_value, prop_prefix); + } else if (NO_NAMESPACE_SCHEMA.equals(prop_suffix)) { + _nonamespace_location_map.put(prop_value, prop_prefix); + } + } + } + } + + /** + * Gets a property value based on property name and namespace of the property. + * @param property the property name + * @param namespace the namespace of the property + * @return the property value, or null if it doesn't exist + */ + public String getProperty(String property, String namespace) { + String prop_prefix = _namespace_prefix_map.get(namespace); + if (prop_prefix != null) { + Map config = _prefix_config_map.get(prop_prefix); + if (config != null) { + return config.get(property); + } + } + // try also find given namespace in prefix map + Map config = _prefix_config_map.get(namespace); + if (config != null) { + return config.get(property); + } + return null; + } + + /** + * Gets the section property, based on the specified namespace. + * @param namespace the namespace + * @return the {@link #SECTION} property value + */ + public String getSectionProperty(String namespace) { + return getProperty(SECTION, namespace); + } + + /** + * Gets the version property, based on the specified namespace. + * @param namespace the namespace + * @return the {@link #VERSION} property value + */ + public String getVersionProperty(String namespace) { + return getProperty(VERSION, namespace); + } + + /** + * Gets the schema property, based on the specified namespace. + * @param namespace the namespace + * @return the {@link #SCHEMA} property value + */ + public String getSchemaProperty(String namespace) { + return getProperty(SCHEMA, namespace); + } + + /** + * Gets the location property, based on the specified namespace. + * @param namespace the namespace + * @return the {@link #LOCATION} property value + */ + public String getLocationProperty(String namespace) { + return getProperty(LOCATION, namespace); + } + + /** + * Gets the marshaller property, based on the specified namespace. + * @param namespace the namespace + * @return the {@link #MARSHALLER} property value + */ + public String getMarshallerProperty(String namespace) { + return getProperty(MARSHALLER, namespace); + } + + /** + * Gets the namespace for the specified section and version. + * @param section the section + * @param version the version + * @return the namespace + */ + public String getNamespace(String section, String version) { + if (section != null && version != null) { + Set prefixes = _section_prefixes_map.get(section); + if (prefixes != null) { + for (String prefix : prefixes) { + Map config = _prefix_config_map.get(prefix); + if (config != null) { + String version_property = config.get(VERSION); + if (version.equals(version_property)) { + String namespace_property = config.get(NAMESPACE); + if (namespace_property != null) { + return namespace_property; + } + } + } + } + } + } + return null; + } + + /** + * Gets the default namespace for a section, based on the highest version of that section. + * @param section the section + * @return the default namespace + */ + public String getDefaultNamespace(String section) { + String default_namespace = null; + Set prefixes = _section_prefixes_map.get(section); + if (prefixes != null) { + float highest_version = 0.0f; + for (String prefix : prefixes) { + Map config = _prefix_config_map.get(prefix); + if (config != null) { + String version_property = config.get(VERSION); + float current_version = version_property != null ? Float.valueOf(version_property).floatValue() : 0.0f; + if (current_version >= highest_version) { + String namespace_property = config.get(NAMESPACE); + if (namespace_property != null) { + highest_version = current_version; + default_namespace = namespace_property; + } + } + } + } + } + return default_namespace; + } + + /** + * Creates a Schema based on the combined schema documents/definitions found that are associated with the specified namespaces. + * @param namespaces the namespaces of the schemas + * @return the new Schema + */ + public synchronized Schema getSchema(Set namespaces) { + Schema schema = _namespaces_schema_map.get(namespaces); + if (schema == null) { + Map nsSourceMap = new TreeMap(new NamespaceComparator()); + try { + for (String namespace : namespaces) { + String schemaLocation = getSchemaLocation(namespace); + if (schemaLocation != null) { + URL url = Classes.getResource(schemaLocation, Descriptor.class); + if (url != null) { + String xsd = new StringPuller().pull(url); + nsSourceMap.put(namespace, new StreamSource(new StringReader(xsd))); + } + } + } + if (nsSourceMap.size() > 0) { + SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + factory.setResourceResolver(new DescriptorLSResourceResolver(this)); + Collection sortedSources = nsSourceMap.values(); + Source[] schemaSources = sortedSources.toArray(new Source[sortedSources.size()]); + schema = factory.newSchema(schemaSources); + _namespaces_schema_map.put(namespaces, schema); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + return schema; + } + + /** + * Creates a new Schema based on the namespaces of the specified Configuration. + * @param config the Configuration + * @return the new Schema + * @see #getSchema(Set) + */ + public Schema getSchema(Configuration config) { + if (config != null) { + return getSchema(config.getChildrenNamespaces()); + } + return null; + } + + /** + * Creates a new Schema based on the namespaces of the Configuration wrapped by the specified Model. + * @param model the Model + * @return the new Schema + * @see #getSchema(Configuration) + * @see #getSchema(Set) + */ + public static Schema getSchema(Model model) { + if (model != null) { + Descriptor desc = model.getModelDescriptor(); + if (desc != null) { + return desc.getSchema(model.getModelConfiguration()); + } + } + return null; + } + + /** + * Creates a Validator based on the combined schema documents/definitions found that are associated with the specified namespace. + * @param namespaces the namespaces of the schemas + * @return the new Validator + */ + public Validator getValidator(Set namespaces) { + return getValidator(getSchema(namespaces)); + } + + /** + * Creates a new Validator based on the namespaces of the specified Configuration. + * @param config the Configuration + * @return the new Validator + * @see #getValidator(Set) + */ + public Validator getValidator(Configuration config) { + return getValidator(getSchema(config)); + } + + /** + * Creates a new Validator based on the namespaces of the Configuration wrapped by the specified Model. + * @param model the Model + * @return the new Validator + * @see #getValidator(Configuration) + * @see #getValidator(Set) + */ + public Validator getValidator(Model model) { + return getValidator(getSchema(model)); + } + + private Validator getValidator(Schema schema) { + if (schema != null) { + Validator validator = schema.newValidator(); + validator.setResourceResolver(new DescriptorLSResourceResolver(this)); + return validator; + } + return null; + } + + /** + * Gets the schema location, based on the specified namespace. + * @param namespace the namespace + * @return the location property value, which is a combination of {@link Descriptor#getLocationProperty(String)} and the {@link #SCHEMA} property value. + */ + public String getSchemaLocation(String namespace) { + return getSchemaLocation(namespace, getSchemaProperty(namespace)); + } + + private String getSchemaLocation(String namespace, String schema) { + String schemaLocation = null; + + if (namespace != null) { + if (schema == null) { + schema = getSchemaProperty(namespace); + } + String location = _nonamespace_location_map.containsKey(schema) + ? getLocationProperty(_nonamespace_location_map.get(schema)) + : getLocationProperty(namespace); + if (location != null) { + schemaLocation = location + "/" + schema; + schemaLocation = schemaLocation.replaceAll("\\\\", "/").replaceAll("//", "/"); + } + } + if (schemaLocation == null && schema != null && schema.startsWith("http://")) { + schema = schema.substring(7); + int pos = schema.indexOf('/'); + if (pos != -1) { + String domain = schema.substring(0, pos); + StringTokenizer st = new StringTokenizer(domain, "."); + int len = st.countTokens(); + String[] parts = new String[len]; + for (int i=0; i < len; i++) { + parts[(len-1)-i] = st.nextToken(); + } + StringBuilder sb = new StringBuilder(); + sb.append('/'); + for (int i=0; i < len; i++) { + sb.append(parts[i]); + if (i != len-1) { + sb.append('/'); + } + } + domain = sb.toString(); + String path = schema.substring(pos, schema.length()); + schemaLocation = domain + path; + } + } + return schemaLocation; + } + + /** + * Lazily gets (and possibly creating and caching) a Marshaller based on the specified namespace. + * @param namespace the namespace + * @return the appropriate Marshaller to use + */ + public synchronized Marshaller getMarshaller(String namespace) { + return getMarshaller(namespace, Classes.getClassLoader(Descriptor.class)); + } + + /** + * Lazily gets (and possibly creating and caching) a Marshaller based on the specified namespace and ClassLoader. + * @param namespace the namespace + * @param loader ClassLoader + * @return the appropriate Marshaller to use + */ + public synchronized Marshaller getMarshaller(String namespace, ClassLoader loader) { + if (namespace == null) { + return null; + } + Marshaller marshaller = _namespace_marshaller_map.get(namespace); + if (marshaller == null) { + String typeName = getMarshallerProperty(namespace); + if (typeName != null) { + Class type = Classes.forName(typeName, loader); + if (type == null) { + throw ConfigMessages.MESSAGES.cannotFindMarshaller(typeName, loader); + } + marshaller = (Marshaller)Construction.construct(type, new Class[]{Descriptor.class}, new Object[]{this}); + if (marshaller != null) { + _namespace_marshaller_map.put(namespace, marshaller); + } + } + } + return marshaller; + } + + /** + * Lazily gets (and possibly creating and caching) a Marshaller based on the namespace of the specified Configuration. + * @param config the Configuration + * @return the appropriate Marshaller to use + * @see #getMarshaller(String) + */ + public Marshaller getMarshaller(Configuration config) { + if (config != null) { + QName qname = config.getQName(); + if (qname != null) { + String namespace = qname.getNamespaceURI(); + if (namespace != null) { + return getMarshaller(namespace); + } + } + } + return null; + } + + /** + * Lazily gets (and possibly creating and caching) a Marshaller based on the namespace of the wrapped Configuration of the specified Model. + * @param model the Model + * @return the appropriate Marshaller to use + * @see #getMarshaller(Configuration) + * @see #getMarshaller(String) + */ + public static Marshaller getMarshaller(Model model) { + if (model != null) { + Descriptor desc = model.getModelDescriptor(); + if (desc != null) { + return desc.getMarshaller(model.getModelConfiguration()); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return _all_properties_map.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_all_properties_map == null) ? 0 : _all_properties_map.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Descriptor other = (Descriptor)obj; + if (_all_properties_map == null) { + if (other._all_properties_map != null) { + return false; + } + } else if (!_all_properties_map.equals(other._all_properties_map)) { + return false; + } + return true; + } + + private static final class DescriptorLSResourceResolver implements LSResourceResolver { + + private Descriptor _descriptor; + + private DescriptorLSResourceResolver(Descriptor descriptor) { + _descriptor = descriptor; + } + + public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { + String schemaLocation = _descriptor.getSchemaLocation(namespaceURI, systemId); + if (schemaLocation == null && baseURI != null && baseURI.endsWith(".dtd")) { + String schema = baseURI.substring(0, baseURI.lastIndexOf('/')+1) + systemId; + schemaLocation = _descriptor.getSchemaLocation(null, schema); + } + if (schemaLocation != null) { + try { + String xsd = new StringPuller().pull(schemaLocation, getClass()); + if (xsd != null) { + return new DescriptorLSInput(xsd, publicId, systemId, baseURI); + } + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } + return null; + } + + } + + private static final class DescriptorLSInput implements LSInput { + + private Reader _characterStream; + private InputStream _byteStream; + private String _stringData; + private String _publicId; + private String _systemId; + private String _baseURI; + private String _encoding; + private boolean _certifiedText; + + private DescriptorLSInput(String xsd, String publicId, String systemId, String baseURI) { + setCharacterStream(new StringReader(xsd)); + setByteStream(new ByteArrayInputStream(xsd.getBytes())); + setStringData(xsd); + setPublicId(publicId); + setSystemId(systemId); + setBaseURI(baseURI); + setEncoding("UTF-8"); + setCertifiedText(false); + } + + /** + * {@inheritDoc} + */ + @Override + public Reader getCharacterStream() { + return _characterStream; + } + + /** + * {@inheritDoc} + */ + @Override + public void setCharacterStream(Reader characterStream) { + _characterStream = characterStream; + } + + /** + * {@inheritDoc} + */ + @Override + public InputStream getByteStream() { + return _byteStream; + } + + /** + * {@inheritDoc} + */ + @Override + public void setByteStream(InputStream byteStream) { + _byteStream = byteStream; + } + + /** + * {@inheritDoc} + */ + @Override + public String getStringData() { + return _stringData; + } + + /** + * {@inheritDoc} + */ + @Override + public void setStringData(String stringData) { + _stringData = stringData; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSystemId() { + return _systemId; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPublicId() { + return _publicId; + } + + /** + * {@inheritDoc} + */ + @Override + public void setPublicId(String publicId) { + _publicId = publicId; + } + + /** + * {@inheritDoc} + */ + @Override + public void setSystemId(String systemId) { + _systemId = systemId; + } + + /** + * {@inheritDoc} + */ + @Override + public String getBaseURI() { + return _baseURI; + } + + /** + * {@inheritDoc} + */ + @Override + public void setBaseURI(String baseURI) { + _baseURI = baseURI; + } + + /** + * {@inheritDoc} + */ + @Override + public String getEncoding() { + return _encoding; + } + + /** + * {@inheritDoc} + */ + @Override + public void setEncoding(String encoding) { + _encoding = encoding; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean getCertifiedText() { + return _certifiedText; + } + + /** + * {@inheritDoc} + */ + @Override + public void setCertifiedText(boolean certifiedText) { + _certifiedText = certifiedText; + } + + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/DescriptorPuller.java b/core/config/src/main/java/org/switchyard/config/model/DescriptorPuller.java new file mode 100644 index 000000000..0700a684e --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/DescriptorPuller.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.Properties; + +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.io.pull.Puller; + +/** + * Utility class to safely access ("pull") Descriptors from various sources. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class DescriptorPuller extends Puller { + + /** + * {@inheritDoc} + */ + @Override + public Descriptor pull(InputStream stream) throws IOException { + return pull(new PropertiesPuller().pull(stream)); + } + + /** + * Safely pulls a Descriptor from a Reader. + * @param reader a Reader of the resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public Descriptor pull(Reader reader) throws IOException { + return pull(new PropertiesPuller().pull(reader)); + } + + /** + * Safely pulls a Descriptor from Properties. + * @param props Properties of the resource + * @return the resource, or null if not found + * @throws IOException if a problem occurred + */ + public Descriptor pull(Properties props) throws IOException { + return new Descriptor(props); + } + + /** + * Creates a default Descriptor. + * @return the resource, never null + * @throws IOException shouldn't happen, but might ;) + */ + public Descriptor pull() throws IOException { + return new Descriptor(); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/Marshaller.java b/core/config/src/main/java/org/switchyard/config/model/Marshaller.java new file mode 100644 index 000000000..df32d64bc --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/Marshaller.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; + +import org.switchyard.config.Configuration; + +/** + * Used to read or write Models. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface Marshaller { + + /** + * Gets the Descriptor used by this Marshaller. + * @return the Descriptor + */ + public Descriptor getDescriptor(); + + /** + * Reads in (constructs) a Model based on the specified Configuration. + * @param config the config + * @return the new Model + */ + public Model read(Configuration config); + + /** + * Writes the specified Model to the specified OutputStream. + * @param model the model + * @param out the OutputStream + * @throws IOException if a problem occurred + */ + public void write(Model model, OutputStream out) throws IOException; + + /** + * Writes the specified Model to the specified Writer. + * @param model the model + * @param writer the Writer + * @throws IOException if a problem occurred + */ + public void write(Model model, Writer writer) throws IOException; + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/MergeScanner.java b/core/config/src/main/java/org/switchyard/config/model/MergeScanner.java new file mode 100644 index 000000000..fe4633de8 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/MergeScanner.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.switchyard.config.Configuration; + +/** + * A {@link Scanner} that merges all {@link Model}s from other Scanners into one. + * + * @param the Model type to scan for (and merge) + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class MergeScanner implements Scanner { + + private final boolean _fromOverridesTo; + private final List> _scanners; + + /** + * Constructs a new MergeScanner using the specified parameters. + * @param fromOverridesTo whether or not each successfully merged Model's values will override the next Model to merge values + * @param scanners the Scanners to merge output from + */ + public MergeScanner(boolean fromOverridesTo, Scanner... scanners) { + _fromOverridesTo = fromOverridesTo; + List> list = new ArrayList>(); + if (scanners != null) { + for (Scanner scanner : scanners) { + if (scanner != null) { + list.add(scanner); + } + } + } + _scanners = list; + } + + /** + * Constructs a new MergeScanner using the specified parameters. + * @param fromOverridesTo whether or not each successfully merged Model's values will override the next Model to merge values + * @param scanners the Scanners to merge output from + */ + public MergeScanner(boolean fromOverridesTo, List> scanners) { + _fromOverridesTo = fromOverridesTo; + _scanners = new ArrayList>(); + if (scanners != null) { + for (Scanner scanner : scanners) { + if (scanner != null) { + _scanners.add(scanner); + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + M merged = null; + for (Scanner scanner : _scanners) { + ScannerOutput scannerOutput = scanner.scan(input); + if (scannerOutput != null) { + List scanned_list = scannerOutput.getModels(); + if (scanned_list != null) { + for (M scanned : scanned_list) { + if (scanned != null) { + if (merged == null) { + merged = scanned; + } else { + merged = Models.merge(scanned, merged, _fromOverridesTo); + } + } + } + } + } + } + Configuration config = merged.getModelConfiguration(); + final String xmlns_x2 = XMLNS_ATTRIBUTE + ":" + XMLNS_ATTRIBUTE; + if (config.hasAttribute(xmlns_x2)) { + String xmlns = config.getAttribute(xmlns_x2); + config.setAttribute(xmlns_x2, null); + config.setAttribute(XMLNS_ATTRIBUTE, xmlns); + } + return new ScannerOutput().setModel(merged); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/Model.java b/core/config/src/main/java/org/switchyard/config/model/Model.java new file mode 100644 index 000000000..89c08bed9 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/Model.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.util.List; + +import org.switchyard.config.Configuration; +import org.switchyard.config.OutputKey; + +/** + * The central and most important interface of the Model API. A Model "wraps" a {@link org.switchyard.config.Configuration Configuration}. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface Model { + + /** + * Gets the wrapped config for this model. + * @return the underlying config + */ + public Configuration getModelConfiguration(); + + /** + * Gets the Descriptor used to create this model. + * @return the descriptor + */ + public Descriptor getModelDescriptor(); + + /** + * Gets the parent model of this model, if there is one. + * @return this model's parent model, or null if there isn't one + */ + public Model getModelParent(); + + /** + * Gets the root model of this model, or this model if this is the root. + * @return this model's root, or this model if this is the root + */ + public Model getModelRoot(); + + /** + * Gets the model's root namespace. + * @return this model's root namespace + */ + public String getModelRootNamespace(); + + /** + * Gets all the child models of this model. + * @return a list of this model's children + */ + public List getModelChildren(); + + /** + * Orders the children based on what was set via {@link #setModelChildrenOrder(String...)}. + * @return this model (useful for chaining) + */ + public Model orderModelChildren(); + + /** + * Validates this model against schema(s) defined in this model's descriptor. + * @return the result of the validation + */ + public Validation validateModel(); + + /** + * Asserts that this model is valid, according to the schema(s) defined in this model's descriptor. + * @return this model (useful for chaining) + */ + public Model assertModelValid(); + + /** + * Whether or not this model is valid, according to the schema(s) defined in this model's descriptor. + * @return true if the model is valid + */ + public boolean isModelValid(); + + /** + * Writes this model out in it's native form (which most likely means writing out the wrapped Configuration). + * @param out the OutputStream to write to + * @param keys the OutputKeys to respect + * @throws IOException if a problem occurs + */ + public void write(OutputStream out, OutputKey... keys) throws IOException; + + /** + * Writes this model out in it's native form (which most likely means writing out the wrapped Configuration). + * @param writer the Writer to write to + * @param keys the OutputKeys to respect + * @throws IOException if a problem occurs + */ + public void write(Writer writer, OutputKey... keys) throws IOException; + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/ModelPuller.java b/core/config/src/main/java/org/switchyard/config/model/ModelPuller.java new file mode 100644 index 000000000..cbe65bbc8 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/ModelPuller.java @@ -0,0 +1,126 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; + +import javax.xml.namespace.QName; + +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.io.pull.Puller; +import org.switchyard.config.ConfigurationPuller; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; + +/** + * Utility class to safely access ("pull") Models from various sources. + * + * @param the Model type + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class ModelPuller extends Puller { + + private Descriptor _desc; + + /** + * Constructs a default ModelPuller (ignoring comments when parsing XML) with a default Descriptor. + */ + public ModelPuller() { + this(null); + } + + /** + * Constructs a ModelPuller (ignoring comments when parsing XML) with the specified Descriptor. + * @param desc the Descriptor + */ + public ModelPuller(Descriptor desc) { + _desc = desc != null ? desc : new Descriptor(); + } + + /** + * Gets the Descriptor used by this ModelResource. + * @return the Descriptor + */ + public final Descriptor getDescriptor() { + return _desc; + } + + /** + * {@inheritDoc} + */ + @Override + public M pull(InputStream stream) throws IOException { + return pull(new ElementPuller().pull(stream)); + } + + /** + * Safely pulls a Model from a Reader. + * @param reader a Reader of the Model + * @return the Model, or null if not found + * @throws IOException if a problem occurred + */ + public M pull(Reader reader) throws IOException { + return pull(new ElementPuller().pull(reader)); + } + + /** + * Safely pulls a Model from an InputSource. + * @param source an InputSource of the Model + * @return the Model, or null if not found + * @throws IOException if a problem occurred + */ + public M pull(InputSource source) throws IOException { + return pull(new ElementPuller().pull(source)); + } + + /** + * Safely constructs a Model from a Document. + * @param document the Model Document + * @return the Model, or null if document is null + */ + public M pull(Document document) { + return pull(new ElementPuller().pull(document)); + } + + /** + * Safely constructs a Model from an Element. + * @param element the Model element + * @return the Model, or null if element is null + */ + @SuppressWarnings("unchecked") + public M pull(Element element) { + String namespace = element.getNamespaceURI(); + if (namespace != null) { + Marshaller marshaller = _desc.getMarshaller(namespace); + if (marshaller != null) { + return (M) marshaller.read(new ConfigurationPuller().pull(element)); + } + } + return null; + } + + /** + * Safely pulls (constructs) a basic Model from a qualified name. + * @param qname the qualified name + * @return the model, or null if the qualified name is null + */ + public M pull(QName qname) { + return pull(new ElementPuller().pull(qname)); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/ModelPullerScanner.java b/core/config/src/main/java/org/switchyard/config/model/ModelPullerScanner.java new file mode 100644 index 000000000..18cdb2e33 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/ModelPullerScanner.java @@ -0,0 +1,265 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.net.URI; +import java.net.URL; + +import javax.xml.namespace.QName; + +import org.switchyard.common.io.resource.Resource; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; + +/** + * A {@link Scanner} that uses {@link org.switchyard.config.model.ModelPuller ModelPuller} to pull {@link org.switchyard.config.model.Model Model}s. + * + * @param the Model type to scan for + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class ModelPullerScanner implements Scanner { + + private Type _type; + private String _classpath; + private Resource _resource; + private Class _caller; + private ClassLoader _loader; + private URI _uri; + private URL _url; + private File _file; + private InputStream _inputStream; + private Reader _reader; + private InputSource _inputSource; + private Document _document; + private Element _element; + private QName _qname; + + /** + * Constructs a default ModelPullerScanner that scans for "/META-INF/switchyard.xml" resource(s). + */ + public ModelPullerScanner() { + this("/META-INF/switchyard.xml"); + } + + /** + * Constructs a ModelPullerScanner that scans for the specified classpath resource. + * @param classpath the classpath resource + */ + public ModelPullerScanner(String classpath) { + this(classpath, ModelPullerScanner.class); + } + + /** + * Constructs a ModelPullerScanner that scans for the specified classpath resource. + * @param classpath the classpath resource + * @param caller class calling this method, so we can also try it's classloader + */ + public ModelPullerScanner(String classpath, Class caller) { + _type = Type.CLASSPATH; + _classpath = classpath; + _caller = caller; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified classpath resource. + * @param classpath the classpath resource + * @param loader the classloader we can also try to find the resource + */ + public ModelPullerScanner(String classpath, ClassLoader loader) { + _type = Type.CLASSPATH; + _classpath = classpath; + _loader = loader; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified Resource. + * @param resource the Resource + */ + public ModelPullerScanner(Resource resource) { + _type = Type.RESOURCE; + _resource = resource; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified Resource using the specified caller class. + * @param resource the Resource + * @param caller the class calling this method + */ + public ModelPullerScanner(Resource resource, Class caller) { + _type = Type.RESOURCE; + _resource = resource; + _caller = caller; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified Resource using the specified classloader. + * @param resource the Resource + * @param loader the classloader to try + */ + public ModelPullerScanner(Resource resource, ClassLoader loader) { + _type = Type.RESOURCE; + _resource = resource; + _loader = loader; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified URI. + * @param uri the URI + */ + public ModelPullerScanner(URI uri) { + _type = Type.URI; + _uri = uri; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified URL. + * @param url the URL + */ + public ModelPullerScanner(URL url) { + _type = Type.URL; + _url = url; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified File. + * @param file the File + */ + public ModelPullerScanner(File file) { + _type = Type.FILE; + _file = file; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified InputStream. + * @param inputStream the InputStream + */ + public ModelPullerScanner(InputStream inputStream) { + _type = Type.INPUT_STREAM; + _inputStream = inputStream; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified Reader. + * @param reader the Reader + */ + public ModelPullerScanner(Reader reader) { + _type = Type.READER; + _reader = reader; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified InputSource. + * @param inputSource the InputSource + */ + public ModelPullerScanner(InputSource inputSource) { + _type = Type.INPUT_SOURCE; + _inputSource = inputSource; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified Document. + * @param document the Document + */ + public ModelPullerScanner(Document document) { + _type = Type.DOCUMENT; + _document = document; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified Element. + * @param element the Element + */ + public ModelPullerScanner(Element element) { + _type = Type.ELEMENT; + _element = element; + } + + /** + * Constructs a ModelPullerScanner that scans for the specified QName. + * @param qname the QName + */ + public ModelPullerScanner(QName qname) { + _type = Type.QNAME; + _qname = qname; + } + + /** + * {@inheritDoc} + */ + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + M model; + switch (_type) { + case CLASSPATH: + if (_caller != null) { + model = new ModelPuller().pull(_classpath, _caller); + } else if (_loader != null) { + model = new ModelPuller().pull(_classpath, _loader); + } else { + model = new ModelPuller().pull(_classpath, getClass()); + } + break; + case RESOURCE: + if (_caller != null) { + model = new ModelPuller().pull(_resource, _caller); + } else if (_loader != null) { + model = new ModelPuller().pull(_resource, _loader); + } else { + model = new ModelPuller().pull(_resource, getClass()); + } + break; + case URI: + model = new ModelPuller().pull(_uri); + break; + case URL: + model = new ModelPuller().pull(_url); + break; + case FILE: + model = new ModelPuller().pull(_file); + break; + case INPUT_STREAM: + model = new ModelPuller().pull(_inputStream); + break; + case READER: + model = new ModelPuller().pull(_reader); + break; + case INPUT_SOURCE: + model = new ModelPuller().pull(_inputSource); + break; + case DOCUMENT: + model = new ModelPuller().pull(_document); + break; + case ELEMENT: + model = new ModelPuller().pull(_element); + break; + case QNAME: + model = new ModelPuller().pull(_qname); + break; + default: + model = null; + } + return new ScannerOutput().setModel(model); + } + + private static enum Type { + CLASSPATH, RESOURCE, URI, URL, FILE, INPUT_STREAM, READER, INPUT_SOURCE, DOCUMENT, ELEMENT, QNAME; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/Models.java b/core/config/src/main/java/org/switchyard/config/model/Models.java new file mode 100644 index 000000000..dc165b823 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/Models.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import org.switchyard.config.Configuration; +import org.switchyard.config.Configurations; + +/** + * Utility class with helper methods dealing with Models. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class Models { + + private Models() {} + + /** + * Merges two models into a new model. + * Note: The act of merging results in fromModel and toModel to have their configurations normalized and children ordered! + * @param the type of Model being merged + * @param fromModel merge from this model, overriding anything in toModel + * @param toModel merge into a copy of this model + * @return the newly merged model + */ + public static M merge(M fromModel, M toModel) { + return merge(fromModel, toModel, true); + } + + /** + * Merges two models into a new model. + * Note: The act of merging results in fromModel and toModel to have their configurations normalized and children ordered! + * @param the type of Model being merged + * @param fromModel merge from this model, optionally overriding anything in toModel + * @param toModel merge into a copy of this model + * @param fromOverridesTo whether fromModel attributes/values should override those in toModel + * @return the newly merged model + */ + public static M merge(M fromModel, M toModel, boolean fromOverridesTo) { + return merge(fromModel, toModel, fromOverridesTo, false); + } + + /** + * Merges two models into a new model. + * Note: The act of merging results in fromModel and toModel to have their configurations normalized and children ordered! + * @param the type of Model being merged + * @param fromModel merge from this model, optionally overriding anything in toModel + * @param toModel merge into a copy of this model + * @param fromOverridesTo whether fromModel attributes/values should override those in toModel + * @param validate whether the newly merged model should be validated before it is returned + * @return the newly merged model + */ + public static M merge(M fromModel, M toModel, boolean fromOverridesTo, boolean validate) { + String from_model_cn = fromModel.getClass().getName(); + String to_model_cn = toModel.getClass().getName(); + if (!from_model_cn.equals(to_model_cn)) { + throw new IllegalArgumentException(from_model_cn + " != " + to_model_cn); + } + Configuration from_model_config = fromModel.getModelConfiguration(); + Configuration to_model_config = toModel.getModelConfiguration(); + Configuration merged_model_config = Configurations.merge(from_model_config, to_model_config, fromOverridesTo); + @SuppressWarnings("unchecked") + M merged_model = (M)Descriptor.getMarshaller(toModel).read(merged_model_config); + merged_model.orderModelChildren(); + if (validate) { + merged_model.assertModelValid(); + } + return merged_model; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/NamedModel.java b/core/config/src/main/java/org/switchyard/config/model/NamedModel.java new file mode 100644 index 000000000..984c43441 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/NamedModel.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.net.URI; + +import javax.xml.namespace.QName; + +/** + * A Model with a name. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface NamedModel extends Model { + + /** + * Gets the name attribute of this Model (not the name of the wrapped Configuration). + * @return the name + */ + public String getName(); + + /** + * Sets the name attribute of this Model (not the name of the wrapped Configuration). + * @param name the name + * @return this NamedModel (useful for chaining) + */ + public NamedModel setName(String name); + + /** + * Gets the targetNamespace of this Model from the wrapped Configuration. + * @return the targetNamespace + */ + public String getTargetNamespace(); + + /** + * Gets the targetNamespace URI of this Model from the wrapped Configuration. + * @return the targetNamespace URI + */ + public URI getTargetNamespaceURI(); + + /** + * Gets the qualified name attribute of this Model (not the qualified name of the wrapped Configuration). + * @return the qualified name + */ + public QName getQName(); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/Namespace.java b/core/config/src/main/java/org/switchyard/config/model/Namespace.java new file mode 100644 index 000000000..481fa7eb5 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/Namespace.java @@ -0,0 +1,178 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.Serializable; + +/** + * Represents config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface Namespace extends Serializable { + + /** + * The namespace section. + * @return the namespace section + */ + public String section(); + + /** + * The namespace version. + * @return the namespace version + */ + public String version(); + + /** + * If the version of the specified namespace matches the version of this namespace. + * @param namespace the specified namespace + * @return if the versions match + */ + public boolean versionMatches(Namespace namespace); + + /** + * The namespace uri. + * @return the namespace uri + */ + public String uri(); + + /** + * If the uri of the specified namespace matches the uri of this namespace. + * @param namespace the specified namespace + * @return if the uris match + */ + public boolean uriMatches(Namespace namespace); + + /** + * If this namespace is the default namespace, rule being: (this == DEFAULT || versionMatches(DEFAULT)). + * @return if this namespace is the default namespace + */ + public boolean isDefault(); + + /** + * A utility class for Namespace enums, since enums can't have extend base classes. + */ + @SuppressWarnings("serial") + public static abstract class Util implements Namespace { + + private final String _section; + private final String _version; + private final String _uri; + + /** + * Constructs a new Util. + * @param descriptor descriptor + * @param section section + * @param version version + */ + protected Util(Descriptor descriptor, String section, String version) { + _section = section; + if (version != null) { + _version = version; + _uri = descriptor.getNamespace(_section, _version); + } else { + _uri = descriptor.getDefaultNamespace(_section); + _version = extractVersion(_uri); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _section; + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _version; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + String version = namespace != null ? namespace.version() : null; + return version != null ? version.equals(_version) : _version == null; + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _uri; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + String uri = namespace != null ? namespace.uri() : null; + return uri != null ? uri.equals(_uri) : _uri == null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return false; + } + + /** + * Extracts the version from the uri. + * @param uri the uri + * @return the version + */ + public static String extractVersion(String uri) { + if (uri != null) { + int pos = uri.lastIndexOf(':'); + if (pos > -1) { + return uri.substring(pos + 1, uri.length()); + } + } + return null; + } + + /** + * Gets a Namespace from a uri. + * @param the Namespace enum type + * @param enumType the Namespace enum type + * @param uri the uri + * @return the Namespace + */ + public static N fromUri(Class enumType, String uri) { + if (uri != null) { + N[] ns = enumType.getEnumConstants(); + if (ns != null) { + for (N n : ns) { + if (n.uri().equals(uri)) { + return n; + } + } + } + } + return null; + } + + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/NamespaceComparator.java b/core/config/src/main/java/org/switchyard/config/model/NamespaceComparator.java new file mode 100644 index 000000000..fdca16479 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/NamespaceComparator.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.Serializable; +import java.util.Comparator; + +/** + * Used for ordering namespaces. + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +class NamespaceComparator implements Comparator, Serializable { + private final static long serialVersionUID = 1L; + private static final String W3 = "http://www.w3.org/"; + + private static final String OASIS_WSS = "http://docs.oasis-open.org/wss/"; + private static final String OASIS_NS = "http://docs.oasis-open.org/ns/"; + + private static final String SY = "urn:switchyard-"; + private static final String SY_CFG = SY + "config:"; + private static final String SY_CFG_SY = SY_CFG + "switchyard"; + private static final String SY_COMP = SY + "component-"; + + /** + * Package-private constructor. + */ + NamespaceComparator() {} + + /** + * {@inheritDoc} + */ + @Override + public int compare(String o1, String o2) { + if (o1 == null) { + if (o2 == null) { + return 0; + } + return -1; + } else if (o2 == null) { + return 1; + } + if (o1.startsWith(W3)) { + if (!o2.startsWith(W3)) { + return -1; + } + } else if (o1.startsWith(OASIS_WSS)) { + if (o2.startsWith(W3)) { + return 1; + } + if (!o2.startsWith(OASIS_WSS)) { + return -1; + } + } else if (o1.startsWith(OASIS_NS)) { + if (o2.startsWith(W3) || o2.startsWith(OASIS_WSS)) { + return 1; + } + if (!o2.startsWith(OASIS_NS)) { + return -1; + } + } else if (o1.startsWith(SY)) { + if (o2.startsWith(W3) || o2.startsWith(OASIS_WSS) || o2.startsWith(OASIS_NS)) { + return 1; + } + if (o1.startsWith(SY_CFG)) { + if (!o2.startsWith(SY_CFG)) { + return -1; + } + if (o1.startsWith(SY_CFG_SY)) { + if (!o2.startsWith(SY_CFG_SY)) { + return -1; + } + } + if (o2.startsWith(SY_CFG_SY)) { + if (!o1.startsWith(SY_CFG_SY)) { + return 1; + } + } + } + if (o1.startsWith(SY_COMP)) { + if (!o2.startsWith(SY_COMP)) { + return -1; + } + } + if (!o2.startsWith(SY)) { + return -1; + } + } else if (o2.startsWith(W3) || o2.startsWith(OASIS_WSS) || o2.startsWith(OASIS_NS) || o2.startsWith(SY)) { + return 1; + } + return o1.compareTo(o2) * -1; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/Scannable.java b/core/config/src/main/java/org/switchyard/config/model/Scannable.java new file mode 100644 index 000000000..7d9ed66e6 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/Scannable.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Annotation that marks a component as being scannable. + *

+ * SwitchYard picks up and installs/configures some application component types by scanning for them on + * the application classpath. This annotation allows you to manage this behavior for a component. + * + * @author tom.fennelly@gmail.com + */ +@Target({TYPE}) +@Retention(RUNTIME) +@Documented +public @interface Scannable { + + /** + * Is the component scannable. Default is true. + */ + boolean value() default true; +} diff --git a/core/config/src/main/java/org/switchyard/config/model/Scanner.java b/core/config/src/main/java/org/switchyard/config/model/Scanner.java new file mode 100644 index 000000000..f18d54ba6 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/Scanner.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.io.IOException; + +/** + * Scans for Models. + * + * @param the target Model after the scan + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface Scanner { + + /** + * Scans for Models. + * @param input the input for the scan + * @return the output of the scan + * @throws IOException if a problem occurrs + */ + public ScannerOutput scan(ScannerInput input) throws IOException; + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/ScannerInput.java b/core/config/src/main/java/org/switchyard/config/model/ScannerInput.java new file mode 100644 index 000000000..5e5988e94 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/ScannerInput.java @@ -0,0 +1,166 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.switchyard.config.model.switchyard.SwitchYardNamespace; + +/** + * The input to a {@link Scanner}. + * + * @param the Model type being scanned for + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class ScannerInput { + + private List _urls; + private SwitchYardNamespace _switchyardNamespace; + private String _compositeName; + private List _includes; + private List _excludes; + + /** + * Constructs a new ScannerInput. + */ + public ScannerInput() { + _urls = new ArrayList(); + _includes = new ArrayList(); + _excludes = new ArrayList(); + } + + /** + * Gets the URLs to scan. + * @return the URLs + */ + public synchronized List getURLs() { + return Collections.unmodifiableList(_urls); + } + + /** + * Sets the URLs to scan. + * @param urls the URLs + * @return this ScannerInput (useful for chaining) + */ + public synchronized ScannerInput setURLs(List urls) { + _urls.clear(); + if (urls != null) { + for (URL url : urls) { + if (url != null) { + _urls.add(url); + } + } + } + return this; + } + + /** + * Gets the Packages to include. + * @return the Packages + */ + public synchronized List getIncludePackages() { + return Collections.unmodifiableList(_includes); + } + + /** + * Sets the Packages to include. + * @param includes packages to include + * @return this ScannerInput (useful for chaining) + */ + public synchronized ScannerInput setIncludePackages(List includes) { + _includes.clear(); + if (includes != null) { + for (Package p : includes) { + if (p != null) { + _includes.add(p); + } + } + } + return this; + } + + /** + * Gets the Packages to exclude. + * @return the Packages + */ + public synchronized List getExcludePackages() { + return Collections.unmodifiableList(_excludes); + } + + /** + * Sets the Packages to exclude. + * @param excludes packages to exclude + * @return this ScannerInput (useful for chaining) + */ + public synchronized ScannerInput setExcludePackages(List excludes) { + _excludes.clear(); + if (excludes != null) { + for (Package p : excludes) { + if (p != null) { + _excludes.add(p); + } + } + } + return this; + } + + /** + * If the switchyard namespace is set. + * @return if the switchyard namespace is set + */ + public boolean isSwitchyardNamespaceSet() { + return _switchyardNamespace != null; + } + + /** + * Gets the switchyard namespace for the scan. + * @return the switchyard namespace + */ + public SwitchYardNamespace getSwitchyardNamespace() { + return isSwitchyardNamespaceSet() ? _switchyardNamespace : SwitchYardNamespace.DEFAULT; + } + + /** + * Sets the switchyard namespace for the scan. + * @param switchyardNamespace the switchyard namespace + * @return this ScannerInput (useful for chaining) + */ + public ScannerInput setSwitchyardNamespace(SwitchYardNamespace switchyardNamespace) { + _switchyardNamespace = switchyardNamespace; + return this; + } + + /** + * Gets the composite name for the scan. + * @return the composite name + */ + public String getCompositeName() { + return _compositeName; + } + + /** + * Sets the composite name for the scan. + * @param compositeName the composite name + * @return this ScannerInput (useful for chaining) + */ + public ScannerInput setCompositeName(String compositeName) { + _compositeName = compositeName; + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/ScannerOutput.java b/core/config/src/main/java/org/switchyard/config/model/ScannerOutput.java new file mode 100644 index 000000000..6ed6597cc --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/ScannerOutput.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * The output of a {@link Scanner}. + * + * @param the Model type being scanned for + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class ScannerOutput { + + private List _models; + + /** + * Constructs a new ScannerOutput. + */ + public ScannerOutput() { + _models = new ArrayList(); + } + + /** + * Gets the first (and possibly only) Model found/created by the scan. + * @return the Model + */ + public synchronized M getModel() { + return _models.size() > 0 ? _models.get(0) : null; + } + + /** + * Sets the first (and possibly only) Model found/created by the scan. + * @param model the Model + * @return this ScannerOutput (useful for chaining) + */ + public synchronized ScannerOutput setModel(M model) { + return setModels(Collections.singletonList(model)); + } + + /** + * Gets the Models found/created by the scan. + * @return the Models + */ + public synchronized List getModels() { + return Collections.unmodifiableList(_models); + } + + /** + * Sets the Models found/created by the scan. + * @param models the Models + * @return this ScannerOutput (useful for chaining) + */ + public synchronized ScannerOutput setModels(List models) { + _models.clear(); + if (models != null) { + for (M m : models) { + if (m != null) { + _models.add(m); + } + } + } + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/TypedModel.java b/core/config/src/main/java/org/switchyard/config/model/TypedModel.java new file mode 100644 index 000000000..c2105e6de --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/TypedModel.java @@ -0,0 +1,29 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +/** + * A Model with a "type". + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface TypedModel extends Model { + + /** + * Gets the "type" of Model this is. + * @return the type name + */ + public String getType(); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/Validation.java b/core/config/src/main/java/org/switchyard/config/model/Validation.java new file mode 100644 index 000000000..2f932c0d9 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/Validation.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import org.switchyard.config.ConfigMessages; + +/** + * Represents the result of a Model validation. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class Validation { + + private Class _modelClass; + private boolean _valid; + private String _message; + private Throwable _cause; + + /** + * Constructs a new Validation. + * @param modelClass the model class + * @param valid whether or not the validation was a success + */ + public Validation(Class modelClass, boolean valid) { + this(modelClass, valid, null); + } + + /** + * Constructs a new Validation. + * @param modelClass the model class + * @param valid whether or not the validation was a success + * @param message the message to report + */ + public Validation(Class modelClass, boolean valid, String message) { + _modelClass = modelClass; + _valid = valid; + _message = message; + } + + /** + * Constructs a new, unsuccessful Validation. + * @param modelClass the model class + * @param cause the cause of the failed validation + */ + public Validation(Class modelClass, Throwable cause) { + this(modelClass, false, cause.getMessage()); + _cause = cause; + } + + /** + * Gets the class of the model which underwent validation. + * @return the class of the model which underwent validation + */ + public Class getModelClass() { + return _modelClass; + } + + /** + * Asserts this validation was successful. + * @return this Validation (useful for chaining) + */ + public Validation assertValid() { + if (!isValid()) { + throw ConfigMessages.MESSAGES.modelInvalid(getModelClass().getName(), getMessage(), getCause()); + } + return this; + } + + /** + * Whether this validation was successful. + * @return true if valid + */ + public boolean isValid() { + return _valid; + } + + /** + * Gets the message to report. + * @return the message + */ + public String getMessage() { + return _message; + } + + /** + * Gets the cause of a failed validation. + * @return the cause + */ + public Throwable getCause() { + return _cause; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composer/ContextMapperModel.java b/core/config/src/main/java/org/switchyard/config/model/composer/ContextMapperModel.java new file mode 100644 index 000000000..c6ac471a5 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composer/ContextMapperModel.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composer; + +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * The "contextMapper" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface ContextMapperModel extends Model { + + /** contextMapper variable. */ + public static final String CONTEXT_MAPPER = "contextMapper"; + + /** + * Gets the parent binding model. + * @return the parent binding model + */ + public BindingModel getBindingModel(); + + /** + * Gets the fully qualified class name of ContextMapper. + * @return the fully qualified class name of ContextMapper + */ + public String getClazz(); + + /** + * Sets the fully qualified class name of ContextMapper. + * @param clazz the fully qualified class name of ContextMapper + * @return this instance (useful for chaining) + */ + public ContextMapperModel setClazz(String clazz); + + /** + * Gets the comma-separated list of regex property includes. + * @return the comma-separated list of regex property includes + */ + public String getIncludes(); + + /** + * Sets the comma-separated list of regex property includes. + * @param includes the comma-separated list of regex property includes + * @return this instance (useful for chaining) + */ + public ContextMapperModel setIncludes(String includes); + + /** + * Gets the comma-separated list of regex property excludes. + * @return the comma-separated list of regex property excludes + */ + public String getExcludes(); + + /** + * Sets the comma-separated list of regex property excludes. + * @param excludes the comma-separated list of regex property excludes + * @return this instance (useful for chaining) + */ + public ContextMapperModel setExcludes(String excludes); + + /** + * Gets the comma-separated list of regex property include namespaces. + * @return the comma-separated list of regex property include namespaces + */ + public String getIncludeNamespaces(); + + /** + * Sets the comma-separated list of regex property include namespaces. + * @param includeNamespaces the comma-separated list of regex property include namespaces + * @return this instance (useful for chaining) + */ + public ContextMapperModel setIncludeNamespaces(String includeNamespaces); + + /** + * Gets the comma-separated list of regex property exclude namespace. + * @return the comma-separated list of regex property exclude namespace + */ + public String getExcludeNamespaces(); + + /** + * Sets the comma-separated list of regex property exclude namespace. + * @param excludeNamespaces the comma-separated list of regex property exclude namespace + * @return this instance (useful for chaining) + */ + public ContextMapperModel setExcludeNamespaces(String excludeNamespaces); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composer/MessageComposerModel.java b/core/config/src/main/java/org/switchyard/config/model/composer/MessageComposerModel.java new file mode 100644 index 000000000..b37f16bdb --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composer/MessageComposerModel.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composer; + +import org.switchyard.config.model.Model; + +/** + * The "messageComposer" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface MessageComposerModel extends Model { + + /** messageComposer variable. */ + public static final String MESSAGE_COMPOSER = "messageComposer"; + + /** + * Gets the fully qualified class name of ContextMapper. + * @return the fully qualified class name of ContextMapper + */ + public String getClazz(); + + /** + * Sets the fully qualified class name of ContextMapper. + * @param clazz fully qualified class name of ContextMapper + * @return this instance (useful for chaining) + */ + public MessageComposerModel setClazz(String clazz); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composer/v1/V1ContextMapperModel.java b/core/config/src/main/java/org/switchyard/config/model/composer/v1/V1ContextMapperModel.java new file mode 100644 index 000000000..754e1a36b --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composer/v1/V1ContextMapperModel.java @@ -0,0 +1,143 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composer.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.common.lang.Strings; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composite.BindingModel; + +/** + * A version 1 ContextMapperModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1ContextMapperModel extends BaseModel implements ContextMapperModel { + + /** + * Constructs a new V1ContextMapperModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1ContextMapperModel(String namespace) { + super(new QName(namespace, CONTEXT_MAPPER)); + } + + /** + * Constructs a new V1ContextMapperModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ContextMapperModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public BindingModel getBindingModel() { + return (BindingModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getClazz() { + return Strings.trimToNull(getModelAttribute("class")); + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapperModel setClazz(String clazz) { + setModelAttribute("class", clazz); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getIncludes() { + return Strings.trimToNull(getModelAttribute("includes")); + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapperModel setIncludes(String includes) { + setModelAttribute("includes", includes); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getExcludes() { + return Strings.trimToNull(getModelAttribute("excludes")); + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapperModel setExcludes(String excludes) { + setModelAttribute("excludes", excludes); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getIncludeNamespaces() { + return Strings.trimToNull(getModelAttribute("includeNamespaces")); + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapperModel setIncludeNamespaces(String includeNamespaces) { + setModelAttribute("includeNamespaces", includeNamespaces); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getExcludeNamespaces() { + return Strings.trimToNull(getModelAttribute("excludeNamespaces")); + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapperModel setExcludeNamespaces(String excludeNamespaces) { + setModelAttribute("excludeNamespaces", excludeNamespaces); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composer/v1/V1MessageComposerModel.java b/core/config/src/main/java/org/switchyard/config/model/composer/v1/V1MessageComposerModel.java new file mode 100644 index 000000000..9ce87afbd --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composer/v1/V1MessageComposerModel.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composer.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.common.lang.Strings; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composer.MessageComposerModel; + +/** + * A version 1 MessageComposerModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1MessageComposerModel extends BaseModel implements MessageComposerModel { + + /** + * Constructs a new V1MessageComposerModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1MessageComposerModel(String namespace) { + super(new QName(namespace, MESSAGE_COMPOSER)); + } + + /** + * Constructs a new V1MessageComposerModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1MessageComposerModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getClazz() { + return Strings.trimToNull(getModelAttribute("class")); + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposerModel setClazz(String clazz) { + setModelAttribute("class", clazz); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/BindingModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/BindingModel.java new file mode 100644 index 000000000..27c7b25ec --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/BindingModel.java @@ -0,0 +1,109 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite; + +import org.switchyard.config.model.TypedModel; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.selector.OperationSelectorModel; + +/** + * The "binding" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface BindingModel extends TypedModel { + + /** The "binding" name. */ + public static final String BINDING = "binding"; + + /** + * Gets the name attribute of this Model (not the name of the wrapped Configuration). + * @return the name + */ + public String getName(); + + /** + * Sets the name attribute of this Model (not the name of the wrapped Configuration). + * @param name the name + * @return this BindingModel (useful for chaining) + */ + public BindingModel setName(String name); + + /** + * Gets the parent service model. This method will return null if + * the binding model is attached to a reference instead of a service. + * @return the parent composite model + */ + public CompositeServiceModel getService(); + + /** + * Gets the parent reference model. This method will return null if + * the binding model is attached to a service instead of a reference. + * @return the parent composite model + */ + public CompositeReferenceModel getReference(); + + /** + * Is this binding attached to a service? + * @return true if this is a service binding, false if it's a reference binding. + */ + public boolean isServiceBinding(); + + /** + * Is this binding attached to a reference? + * @return true if this is a reference binding, false if it's a service binding. + */ + public boolean isReferenceBinding(); + + /** + * Gets the child operation selector model. + * @return the child operation selector model + */ + public OperationSelectorModel getOperationSelector(); + + /** + * Sets the child operation selector model. + * @param model the child operation selector model + * @return this model(useful for chaining) + */ + public BindingModel setOperationSelector(OperationSelectorModel model); + + /** + * Gets the child context mapper model. + * @return the child context mapper model + */ + public ContextMapperModel getContextMapper(); + + /** + * Gets the child message composer model. + * @return the child message composer model + */ + public MessageComposerModel getMessageComposer(); + + /** + * Sets the child context mapper model. + * @param model the context mapper model to set + * @return this BindingModel (useful for chaining) + */ + public BindingModel setContextMapper(ContextMapperModel model); + + /** + * Sets the child message composer model. + * @param model the message composer model to set + * @return this BindingModel (useful for chaining) + */ + public BindingModel setMessageComposer(MessageComposerModel model); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/ComponentImplementationModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/ComponentImplementationModel.java new file mode 100644 index 000000000..a103db383 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/ComponentImplementationModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.TypedModel; + +/** + * The "component/implementation" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface ComponentImplementationModel extends TypedModel { + + /** The "implementation" name. */ + public static final String IMPLEMENTATION = "implementation"; + + /** + * Gets the parent component model. + * @return the parent component model + */ + public ComponentModel getComponent(); + + /** + * Adds the specified policy identifier to the set of required policy + * intents for the reference. + * @param policyQName qualified name of the required policy + */ + public void addPolicyRequirement(QName policyQName); + + /** + * Returns the set of policy intents required for this reference. + * @return set of policy intents required for the reference. + */ + public Set getPolicyRequirements(); + + /** + * Indicates whether a given policy is required for this reference. + * @param policyQName qualified name of the policy to check + * @return true if the policy is required, false otherwise + */ + public boolean hasPolicyRequirement(QName policyQName); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/ComponentModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/ComponentModel.java new file mode 100644 index 000000000..415485155 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/ComponentModel.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite; + +import java.util.List; +import java.util.Map; + +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.config.model.NamedModel; +import org.switchyard.config.model.property.PropertyModel; + +/** + * The "component" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface ComponentModel extends NamedModel, PropertyResolver { + + /** The "component" name. */ + public static final String COMPONENT = "component"; + + /** + * Gets the parent composite model. + * @return the parent composite model + */ + public CompositeModel getComposite(); + + /** + * Gets the child component implementation model. + * @return the child component implementation model + */ + public ComponentImplementationModel getImplementation(); + + /** + * Sets the child copmonent implementation model. + * @param implementation the child component implementation model + * @return this ComponentModel (useful for chaining) + */ + public ComponentModel setImplementation(ComponentImplementationModel implementation); + + /** + * Gets the child component service models. + * @return the child component service models + */ + public List getServices(); + + /** + * Adds a child component service model. + * @param service the child component service model + * @return this ComponentModel (useful for chaining) + */ + public ComponentModel addService(ComponentServiceModel service); + + /** + * Gets the child component reference models. + * @return the child component reference models + */ + public List getReferences(); + + /** + * Adds a child component reference model. + * @param reference the child component reference model + * @return this ComponentModel (useful for chaining) + */ + public ComponentModel addReference(ComponentReferenceModel reference); + + /** + * Gets a child property model. + * @param name property name to get + * @return the child property model + */ + public PropertyModel getProperty(String name); + + /** + * Gets the map of child property model. + * @return map of the child property model + */ + public Map getProperties(); + + /** + * Sets the child properties model. + * @param property the child property model + * @return this ComponentModel (useful for chaining) + */ + public ComponentModel addProperty(PropertyModel property); + + /** + * Sets the component property resolver based on the current state of the model. + */ + public void setComponentPropertyResolver(); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/ComponentReferenceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/ComponentReferenceModel.java new file mode 100644 index 000000000..76391ac21 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/ComponentReferenceModel.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.NamedModel; + +/** + * The "component/reference" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface ComponentReferenceModel extends NamedModel { + + /** The "multiplicity" name. */ + public static final String MULTIPLICITY = CompositeReferenceModel.MULTIPLICITY; + + /** The "reference" name. */ + public static final String REFERENCE = CompositeReferenceModel.REFERENCE; + + /** The "security" name. */ + public static final String SECURITY = "security"; + + /** + * Gets the parent component model. + * @return the parent component model + */ + public ComponentModel getComponent(); + + /** + * Gets the multiplicity attribute. + * @return the multiplicity attribute + */ + public String getMultiplicity(); + + /** + * Sets the multiplicity attribute. + * @param multiplicity the multiplicity attribute + * @return this ComponentReferenceModel (useful for chaining) + */ + public ComponentReferenceModel setMultiplicity(String multiplicity); + + /** + * Gets the child component reference interface model. + * @return the child component reference interface model + */ + public InterfaceModel getInterface(); + + /** + * Sets the child component reference interface model. + * @param interfaze the child component reference interface model + * @return this ComponentReferenceModel (useful for chaining) + */ + public ComponentReferenceModel setInterface(InterfaceModel interfaze); + + /** + * Gets the name of the security section to respect. + * @return the name of the security section to respect + */ + public String getSecurity(); + + /** + * Sets the name of the security section to respect. + * @param security the name of the security section to respect + * @return this ComponentReferenceModel (useful for chaining) + */ + public ComponentReferenceModel setSecurity(String security); + + /** + * Adds the specified policy identifier to the set of required policy + * intents for the reference. + * @param policyQName qualified name of the required policy + */ + public void addPolicyRequirement(QName policyQName); + + /** + * Returns the set of policy intents required for this reference. + * @return set of policy intents required for the reference. + */ + public Set getPolicyRequirements(); + + /** + * Indicates whether a given policy is required for this reference. + * @param policyQName qualified name of the policy to check + * @return true if the policy is required, false otherwise + */ + public boolean hasPolicyRequirement(QName policyQName); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/ComponentServiceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/ComponentServiceModel.java new file mode 100644 index 000000000..2d8a78e8c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/ComponentServiceModel.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.NamedModel; + +/** + * The "component/service" model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface ComponentServiceModel extends NamedModel { + + /** The "service" name. */ + public static final String SERVICE = CompositeServiceModel.SERVICE; + + /** The "security" name. */ + public static final String SECURITY = "security"; + + /** + * Gets the parent component model. + * @return the parent component model + */ + public ComponentModel getComponent(); + + /** + * Gets the child component service interface model. + * @return the child component service interface model + */ + public InterfaceModel getInterface(); + + /** + * Sets the child component service interface model. + * @param interfaze child component service interface model + * @return this ComponentServiceModel (useful for chaining) + */ + public ComponentServiceModel setInterface(InterfaceModel interfaze); + + /** + * Gets the name of the security section to respect. + * @return the name of the security section to respect + */ + public String getSecurity(); + + /** + * Sets the name of the security section to respect. + * @param security the name of the security section to respect + * @return this ComponentServiceModel (useful for chaining) + */ + public ComponentServiceModel setSecurity(String security); + + /** + * Adds the specified policy identifier to the set of required policy + * intents for the service. + * @param policyQName qualified name of the required policy + */ + public void addPolicyRequirement(QName policyQName); + + /** + * Returns the set of policy intents required for this service. + * @return set of policy intents required for the service. + */ + public Set getPolicyRequirements(); + + /** + * Indicates whether a given policy is required for this service. + * @param policyQName qualified name of the policy to check + * @return true if the policy is required, false otherwise + */ + public boolean hasPolicyRequirement(QName policyQName); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/CompositeModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/CompositeModel.java new file mode 100644 index 000000000..b0a855eb4 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/CompositeModel.java @@ -0,0 +1,110 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.composite; + +import java.util.List; +import java.util.Map; + +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.config.model.NamedModel; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * The "composite" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface CompositeModel extends NamedModel, PropertyResolver { + + /** The "composite" name. */ + public static final String COMPOSITE = "composite"; + + /** + * Gets the parent switchyard model. + * @return the parent switchyard model + */ + public SwitchYardModel getSwitchYard(); + + /** + * Gets the child composite service models. + * @return the child composite service models + */ + public List getServices(); + + /** + * Adds a child composite service model. + * @param service the child composite service model + * @return this CompositeModel (useful for chaining) + */ + public CompositeModel addService(CompositeServiceModel service); + + /** + * Gets the child composite reference models. + * @return the child composite reference models + */ + public List getReferences(); + + /** + * Adds a composite reference model. + * @param reference the composite reference model + * @return this CompositeModel (useful for chaining) + */ + public CompositeModel addReference(CompositeReferenceModel reference); + + /** + * Gets the child component models. + * @return the child component models + */ + public List getComponents(); + + /** + * Adds a child component model. + * @param component the child component model + * @return this CompositeModel (useful for chaining) + */ + public CompositeModel addComponent(ComponentModel component); + + /** + * Sets the target namespace for the composite. + * @param namespaceUri namespace URI + */ + public void setTargetNamespace(String namespaceUri); + + /** + * Gets a child property model. + * @param name property name to get + * @return the child property model + */ + public PropertyModel getProperty(String name); + + /** + * Gets the map of child property model. + * @return map of child property model + */ + public Map getProperties(); + + /** + * Sets the child property model. + * @param property the child property model + * @return this CompositeModel (useful for chaining) + */ + public CompositeModel addProperty(PropertyModel property); + + /** + * Sets the composite property resolver based on the current state of the model. + */ + public void setCompositePropertyResolver(); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/CompositeReferenceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/CompositeReferenceModel.java new file mode 100644 index 000000000..f10d4c11c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/CompositeReferenceModel.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.composite; + +import java.util.List; + +import org.switchyard.config.model.NamedModel; + +/** + * The "composite/reference" model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface CompositeReferenceModel extends NamedModel { + + /** The "multiplicity" name. */ + public static final String MULTIPLICITY = "multiplicity"; + /** The default multiplicity (1..1). */ + public static final String DEFAULT_MULTIPLICITY = "1..1"; + + /** The "promote" name. */ + public static final String PROMOTE = "promote"; + + /** The "reference" name. */ + public static final String REFERENCE = "reference"; + + /** + * Gets the parent composite model. + * @return the parent composite model + */ + public CompositeModel getComposite(); + + /** + * Gets the child component reference models. + * @return the child component reference models + */ + public List getComponentReferences(); + + /** + * Gets the promote attribute. + * @return the promote attribute + */ + public String getPromote(); + + /** + * Sets the promote attribute. + * @param promote the promote attribute + * @return this CompositeReferenceModel (useful for chaining) + */ + public CompositeReferenceModel setPromote(String promote); + + /** + * Gets the multiplicity attribute. + * @return the multiplicity attribute + */ + public String getMultiplicity(); + + /** + * Sets the multiplicity attribute. + * @param multiplicity the multiplicity attribute + * @return this CompositeReferenceModel (useful for chaining) + */ + public CompositeReferenceModel setMultiplicity(String multiplicity); + + /** + * Gets the child binding models. + * @return the child binding models + */ + public List getBindings(); + + /** + * Adds a child binding model. + * @param binding the child binding model + * @return this CompositeReferenceModel (useful for chaining) + */ + public CompositeReferenceModel addBinding(BindingModel binding); + + /** + * Gets the child reference interface model. + * @return the child reference interface model + */ + public InterfaceModel getInterface(); + + /** + * Sets the child reference interface model. + * @param interfaze the child reference interface model + * @return this CompositeReferenceModel (useful for chaining) + */ + public CompositeReferenceModel setInterface(InterfaceModel interfaze); + +} + diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/CompositeServiceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/CompositeServiceModel.java new file mode 100644 index 000000000..81b1f2b87 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/CompositeServiceModel.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.composite; + +import java.util.List; + +import org.switchyard.config.model.NamedModel; + +/** + * The "composite/service" model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface CompositeServiceModel extends NamedModel { + + /** The "service" name. */ + public static final String SERVICE = "service"; + + /** The "promote" name. */ + public static final String PROMOTE = "promote"; + + /** + * Gets the parent composite model. + * @return the parent composite model + */ + public CompositeModel getComposite(); + + /** + * Gets the child component service model. + * @return the child component service model + */ + public ComponentServiceModel getComponentService(); + + /** + * Gets the promote attribute. + * @return the promote attribute + */ + public String getPromote(); + + /** + * Sets the promote attribute. + * @param promote the promote attribute + * @return this CompositeServiceModel (useful for chaining) + */ + public CompositeServiceModel setPromote(String promote); + + /** + * Gets the child binding models. + * @return the child binding models + */ + public List getBindings(); + + /** + * Adds a child binding model. + * @param binding the child binding model + * @return this CompositeServiceModel (useful for chaining) + */ + public CompositeServiceModel addBinding(BindingModel binding); + + /** + * Gets the child service interface model. + * @return the child service interface model + */ + public InterfaceModel getInterface(); + + /** + * Sets the child service interface model. + * @param interfaze child service interface model + * @return this CompositeServiceModel (useful for chaining) + */ + public CompositeServiceModel setInterface(InterfaceModel interfaze); + + /** + * Gets the child extensions model. + * @return the child extensions model + */ + public ExtensionsModel getExtensions(); + + /** + * Sets the child extensions model. + * @param extensions child extensions model + * @return this CompositeServiceModel (useful for chaining) + */ + public CompositeServiceModel setExtensions(ExtensionsModel extensions); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/ExtensionsModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/ExtensionsModel.java new file mode 100644 index 000000000..a411b2b54 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/ExtensionsModel.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.composite; + +import org.switchyard.config.model.Model; +import org.switchyard.config.model.switchyard.ThrottlingModel; + +/** + * The "extensions" configuration model. + */ +public interface ExtensionsModel extends Model { + + /** The "extensions" name. */ + public static final String EXTENSIONS = "extensions"; + + /** + * Gets the child throttling model. + * + * @return the child throttling model + */ + public ThrottlingModel getThrottling(); + + /** + * Sets the child throttling model. + * + * @param throttling child throttling model + * @return this ExtensionsModel (useful for chaining) + */ + public ExtensionsModel setThrottling(ThrottlingModel throttling); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/InterfaceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/InterfaceModel.java new file mode 100644 index 000000000..d23ccff12 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/InterfaceModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.composite; + +import org.switchyard.config.model.TypedModel; + +/** + * An "interface" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface InterfaceModel extends TypedModel { + + /** The "interface" name. */ + public static final String INTERFACE = "interface"; + + /** + * Name of standard SCA Java interface. + */ + public static final String JAVA = "java"; + /** + * Name of standard SCA WSDL interface. + */ + public static final String WSDL = "wsdl"; + + + /** + * Gets the name of the interface. + * @return the name of the interface + */ + public String getInterface(); + + /** + * Sets the name of the interface. + * @param interfaze the name of the interface + * @return this InterfaceModel (useful for chaining) + */ + public InterfaceModel setInterface(String interfaze); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/SCABindingModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/SCABindingModel.java new file mode 100644 index 000000000..fa0738965 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/SCABindingModel.java @@ -0,0 +1,132 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite; + + +/** + * SCABindingModel represents the standard binding.sca binding in SCA. SwitchYard supports a + * set of extensions which are represented as attributes on the binding.sca element which are exposed + * via this config model. + */ +public interface SCABindingModel extends BindingModel { + + /** The "sca" name. */ + public static final String SCA = "sca"; + + /** The "target" name. */ + public static final String TARGET = "target"; + + /** The "target" name. */ + public static final String TARGET_NAMESPACE = "targetNamespace"; + + /** The "loadBalance" name. */ + public static final String LOAD_BALANCE = "loadBalance"; + + /** The "clustered" name. */ + public static final String CLUSTERED = "clustered"; + + /** The "clustered" name. */ + public static final String PREFER_LOCAL = "preferLocal"; + + /** + * Indicates whether clustering is enabled. + * @return true if clustering is enabled, false otherwise + */ + boolean isClustered(); + + /** + * Specifies whether clustering is enabled for the service binding. Valid for service and + * reference bindings. + * @param clustered true for enabled, false for disabled + * @return this config model instance + */ + SCABindingModel setClustered(boolean clustered); + + /** + * Indicates whether preferLocal is enabled. + * @return true if preferLocal is enabled, false otherwise + */ + boolean isPreferLocal(); + + /** + * Specifies whether preferLocal is enabled for the service binding. Valid + * reference bindings. + * @param preferLocal true for enabled, false for disabled + * @return this config model instance + */ + SCABindingModel setPreferLocal(boolean preferLocal); + + /** + * Indicates whether load balancing is enabled. + * @return true if load balancing is enabled, false otherwise + */ + boolean isLoadBalanced(); + + /** + * Returns the load balance strategy used by the binding. + * @return the load balance strategy in use + */ + String getLoadBalance(); + + /** + * Specifies the strategy used for load balancing. This attribute is only valid for reference + * bindings. + * @param loadBalance the load balance strategy used + * @return this config model instance + */ + SCABindingModel setLoadBalance(String loadBalance); + + /** + * Indicates whether a target service has been specified for the binding. + * @return true if a target service is specified, false otherwise + */ + boolean hasTarget(); + + /** + * Returns the target service name used for the binding. + * @return target service name + */ + String getTarget(); + + /** + * Specifies the target service name used for this binding. This is valid for reference + * bindings only and allows the service name to be overloaded in case the provider service + * has a different name. + * @param target target service name + * @return this config model instance + */ + SCABindingModel setTarget(String target); + + /** + * Indicates whether a target namespace has been specified for the binding. + * @return true if a target namespace is specified, false otherwise + */ + boolean hasTargetNamespace(); + + /** + * Returns the target namespace used for the binding. + * @return target namespace + */ + String getTargetNamespace(); + + /** + * Specifies the target namespace used for this binding. This is valid for reference + * bindings only and allows the service namespace to be overloaded in case the provider service + * has a different namespace. + * @param namespace target service namespace + * @return this config model instance + */ + SCABindingModel setTargetNamespace(String namespace); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/SCANamespace.java b/core/config/src/main/java/org/switchyard/config/model/composite/SCANamespace.java new file mode 100644 index 000000000..89c2a7f99 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/SCANamespace.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.composite; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A SCA config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum SCANamespace implements Namespace { + + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new SCANamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + SCANamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the SCANamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the SCANamespace + */ + public static SCANamespace fromUri(String uri) { + return Util.fromUri(SCANamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(SCANamespace.class); + private Util(String version) { + super(DESCRIPTOR, "http://docs.oasis-open.org/ns/opencsa/sca", version); + } + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/PolicyConfig.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/PolicyConfig.java new file mode 100644 index 000000000..09325f43d --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/PolicyConfig.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.Set; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Model; + +/** + * Provides methods to help with Policy configuration on SCA config models. + */ +public final class PolicyConfig { + + /** The "requires" name. */ + public static final String REQUIRES = "requires"; + + private PolicyConfig() {} + + /** + * Get the content of the requires attribute as a set of strings. + * @param model the model to query for required policy + * @return set of policy requirements; empty set if nothing found + */ + public static Set getRequirements(Model model) { + return model.getModelConfiguration().getAttributeAsQNames(REQUIRES, " "); + } + + /** + * Set the content of the requires attribute for a given config model. + * @param model the model to set policy requirements on. + * @param requirements the set of policy requirements. + */ + public static void setRequirements(Model model, Set requirements) { + Configuration config = model.getModelConfiguration(); + if (requirements == null || requirements.isEmpty()) { + config.setAttribute(REQUIRES, null); + return; + } + StringBuilder requires = new StringBuilder(); + for (QName req : requirements) { + requires.append(" "); + String ns = req.getNamespaceURI(); + if (XMLConstants.DEFAULT_NS_PREFIX.equals(ns)) { + requires.append(req.getLocalPart()); + } else { + String pfx = config.lookupPrefix(ns); + if (pfx != null) { + requires.append(pfx + ":" + req.getLocalPart()); + } else { + // SCA cvc-datatype-valid.1.2.1 XSD doesn't allow for {namespaceURI}localPart format + //requires.append(req.toString()); + requires.append(req.getLocalPart()); + } + } + } + config.setAttribute(REQUIRES, requires.toString().trim()); + } + + /** + * Adds a policy requirement to the existing list of requirements for a given config model. + * @param model the model to set policy requirements on. + * @param qname the policy requirement to add + */ + public static void addRequirement(Model model, QName qname) { + Set requires = getRequirements(model); + requires.add(qname); + setRequirements(model, requires); + } + + /** + * If a config model contains the given policy requirement. + * @param model the model to check for the policy requirement + * @param qname the policy requirement to check for + * @return whether the policy requirement exists on the config model + */ + public static boolean hasRequirement(Model model, QName qname) { + Set requirements = getRequirements(model); + for (QName requirement : requirements) { + // 1. look for an exact match first + if (requirement.equals(qname)) { + return true; + } + // 2. look for a localName match second for backwards compatibility + // NOTE: similar logic found in: + // - core/api: org.switchyard.policy.PolicyFactory.getPolicy(QName):Policy + // - core/api: org.switchyard.policy.PolicyUtil.containsPolicy(Set, Policy):boolean + // NOTE: NULL_NS_URI works because of no default namespace assumption from parent element made in: + // - core/config: org.switchyard.config.BaseConfiguration.createAttributeQName(String value):QName + if (XMLConstants.NULL_NS_URI.equals(requirement.getNamespaceURI()) && requirement.getLocalPart().equals(qname.getLocalPart())) { + return true; + } + } + return false; + } +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1BindingModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1BindingModel.java new file mode 100644 index 000000000..a61c930a5 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1BindingModel.java @@ -0,0 +1,191 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseTypedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composer.ContextMapperModel; +import org.switchyard.config.model.composer.MessageComposerModel; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.SCANamespace; +import org.switchyard.config.model.selector.OperationSelectorModel; + +/** + * A version 1 BindingModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1BindingModel extends BaseTypedModel implements BindingModel { + + private OperationSelectorModel _operationSelector; + private ContextMapperModel _contextMapper; + private MessageComposerModel _messageComposer; + + /** + * Constructs a new V1BindingModel of the specified "type". + * @param type the "type" of BindingModel + */ + public V1BindingModel(String type) { + super(new QName(SCANamespace.DEFAULT.uri(), BindingModel.BINDING + '.' + type)); + } + + /** + * Constructs a new V1BindingModel of the specified "type" with the specified namespace. + * @param type the "type" of BindingModel + * @param namespace binding namespace + */ + public V1BindingModel(String type, String namespace) { + super(new QName(namespace, BindingModel.BINDING + '.' + type)); + } + + /** + * Constructs a new V1BindingModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1BindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return getModelAttribute("name"); + } + + /** + * {@inheritDoc} + */ + @Override + public BindingModel setName(String name) { + setModelAttribute("name", name); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + protected Model setModelChildrenOrder(String... childrenOrder) { + Set mco = new LinkedHashSet(); + mco.add(OperationSelectorModel.OPERATION_SELECTOR + ".*"); + mco.add(ContextMapperModel.CONTEXT_MAPPER); + mco.add(MessageComposerModel.MESSAGE_COMPOSER); + if (childrenOrder != null) { + mco.addAll(Arrays.asList(childrenOrder)); + } + super.setModelChildrenOrder(mco.toArray(new String[mco.size()])); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeServiceModel getService() { + return isServiceBinding() ? (CompositeServiceModel)getModelParent() : null; + } + + @Override + public CompositeReferenceModel getReference() { + return isReferenceBinding() ? (CompositeReferenceModel)getModelParent() : null; + } + + /** + * {@inheritDoc} + */ + @Override + public OperationSelectorModel getOperationSelector() { + if (_operationSelector == null) { + _operationSelector = (OperationSelectorModel)this.getFirstChildModelStartsWith(OperationSelectorModel.OPERATION_SELECTOR); + } + return _operationSelector; + } + + /** + * {@inheritDoc} + */ + @Override + public BindingModel setOperationSelector(OperationSelectorModel model) { + setChildModel(model); + _operationSelector = model; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ContextMapperModel getContextMapper() { + if (_contextMapper == null) { + _contextMapper = (ContextMapperModel)getFirstChildModel(ContextMapperModel.CONTEXT_MAPPER); + } + return _contextMapper; + } + + /** + * {@inheritDoc} + */ + @Override + public MessageComposerModel getMessageComposer() { + if (_messageComposer == null) { + _messageComposer = (MessageComposerModel)getFirstChildModel(MessageComposerModel.MESSAGE_COMPOSER); + } + return _messageComposer; + } + + /** + * {@inheritDoc} + */ + @Override + public BindingModel setContextMapper(ContextMapperModel model) { + _contextMapper = model; + setChildModel(model); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public BindingModel setMessageComposer(MessageComposerModel model) { + _messageComposer = model; + setChildModel(model); + return this; + } + + @Override + public boolean isServiceBinding() { + return (getModelParent() instanceof CompositeServiceModel); + } + + @Override + public boolean isReferenceBinding() { + return (getModelParent() instanceof CompositeReferenceModel); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentImplementationModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentImplementationModel.java new file mode 100644 index 000000000..6547b2bd7 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentImplementationModel.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseTypedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * A version 1 ComponentImplementationModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1ComponentImplementationModel extends BaseTypedModel implements ComponentImplementationModel { + + /** + * Constructs a new V1ComponentImplementationModel of the specified "type". + * @param type the "type" of ComponentImplementationModel + */ + public V1ComponentImplementationModel(String type) { + this(type, SCANamespace.DEFAULT.uri()); + } + + /** + * Constructs a new V1ComponentImplementationModel of the specified "type", and in the specified namespace. + * @param type the "type" of ComponentImplementationModel + * @param namespace the namespace + */ + public V1ComponentImplementationModel(String type, String namespace) { + super(new QName(namespace, ComponentImplementationModel.IMPLEMENTATION + '.' + type)); + } + + /** + * Constructs a new V1ComponentImplementationModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ComponentImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentModel getComponent() { + return (ComponentModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public void addPolicyRequirement(QName policyQName) { + PolicyConfig.addRequirement(this, policyQName); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getPolicyRequirements() { + return PolicyConfig.getRequirements(this); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasPolicyRequirement(QName policyQName) { + return PolicyConfig.hasRequirement(this, policyQName); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentModel.java new file mode 100644 index 000000000..5ac969bab --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentModel.java @@ -0,0 +1,204 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.common.property.CompoundPropertyResolver; +import org.switchyard.common.property.SystemAndTestPropertyResolver; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.SCANamespace; +import org.switchyard.config.model.property.PropertyModel; + +/** + * A version 1 ComponentModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1ComponentModel extends BaseNamedModel implements ComponentModel { + + private ComponentImplementationModel _implementation; + private List _services = new ArrayList(); + private List _references = new ArrayList(); + private Map _properties = new HashMap(); + + /** + * Constructs a new V1ComponentModel. + */ + public V1ComponentModel() { + super(SCANamespace.DEFAULT.uri(), ComponentModel.COMPONENT); + setModelChildrenOrder(ComponentImplementationModel.IMPLEMENTATION + ".*", ComponentServiceModel.SERVICE, ComponentReferenceModel.REFERENCE, PropertyModel.PROPERTY); + setComponentPropertyResolver(); + } + + /** + * Constructs a new V1ComponentModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ComponentModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration service_config : config.getChildren(ComponentServiceModel.SERVICE)) { + ComponentServiceModel service = (ComponentServiceModel)readModel(service_config); + if (service != null) { + _services.add(service); + } + } + for (Configuration reference_config : config.getChildren(ComponentReferenceModel.REFERENCE)) { + ComponentReferenceModel reference = (ComponentReferenceModel)readModel(reference_config); + if (reference != null) { + _references.add(reference); + } + } + for (Configuration property_config : config.getChildren(PropertyModel.PROPERTY)) { + PropertyModel property = (PropertyModel)readModel(property_config); + if (property != null) { + _properties.put(property.getName(), property); + } + } + + setModelChildrenOrder(ComponentImplementationModel.IMPLEMENTATION + ".*", ComponentServiceModel.SERVICE, ComponentReferenceModel.REFERENCE, PropertyModel.PROPERTY); + setComponentPropertyResolver(); + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeModel getComposite() { + return (CompositeModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentImplementationModel getImplementation() { + if (_implementation == null) { + _implementation = (ComponentImplementationModel)getFirstChildModelStartsWith(ComponentImplementationModel.IMPLEMENTATION); + } + return _implementation; + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentModel setImplementation(ComponentImplementationModel implementation) { + setChildModel(implementation); + _implementation = implementation; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getServices() { + return Collections.unmodifiableList(_services); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized ComponentModel addService(ComponentServiceModel service) { + addChildModel(service); + _services.add(service); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getReferences() { + return Collections.unmodifiableList(_references); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized ComponentModel addReference(ComponentReferenceModel reference) { + addChildModel(reference); + _references.add(reference); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized PropertyModel getProperty(String name) { + return _properties.get(name); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized Map getProperties() { + return Collections.unmodifiableMap(_properties); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized V1ComponentModel addProperty(PropertyModel property) { + addChildModel(property); + _properties.put(property.getName(), property); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Object resolveProperty(String key) { + Object value = null; + if (key != null) { + PropertyModel property = getProperty(key); + value = property != null ? property.getValue() : null; + } + return value; + } + + /** + * {@inheritDoc} + */ + @Override + public void setComponentPropertyResolver() { + Configuration config = getModelConfiguration(); + Configuration parent = config.getParent(); + if (parent != null) { + config.setPropertyResolver(CompoundPropertyResolver.compact(parent.getPropertyResolver(), this)); + } else { + config.setPropertyResolver(CompoundPropertyResolver.compact(SystemAndTestPropertyResolver.INSTANCE, this)); + } + } +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentReferenceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentReferenceModel.java new file mode 100644 index 000000000..25a014e92 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentReferenceModel.java @@ -0,0 +1,145 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * A version 1 ComponentReferenceModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1ComponentReferenceModel extends BaseNamedModel implements ComponentReferenceModel { + + private InterfaceModel _interface; + private String _switchyardNamespace; + + /** + * Constructs a new V1ComponentReferenceModel. + * @param switchyardNamespace switchyardNamespace + */ + public V1ComponentReferenceModel(String switchyardNamespace) { + super(SCANamespace.DEFAULT.uri(), ComponentReferenceModel.REFERENCE); + _switchyardNamespace = switchyardNamespace; + } + + /** + * Constructs a new V1ComponentReferenceModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ComponentReferenceModel(Configuration config, Descriptor desc) { + super(config, desc); + _switchyardNamespace = getModelRootNamespace(); + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentModel getComponent() { + return (ComponentModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getMultiplicity() { + return getModelAttribute(ComponentReferenceModel.MULTIPLICITY); + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentReferenceModel setMultiplicity(String multiplicity) { + setModelAttribute(ComponentReferenceModel.MULTIPLICITY, multiplicity); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public InterfaceModel getInterface() { + if (_interface == null) { + _interface = (InterfaceModel)getFirstChildModelStartsWith(InterfaceModel.INTERFACE); + } + return _interface; + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentReferenceModel setInterface(InterfaceModel interfaze) { + setChildModel(interfaze); + _interface = interfaze; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSecurity() { + return getModelAttribute(new QName(_switchyardNamespace, ComponentReferenceModel.SECURITY)); + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentReferenceModel setSecurity(String security) { + setModelAttribute(new QName(_switchyardNamespace, ComponentReferenceModel.SECURITY), security); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public void addPolicyRequirement(QName policyQName) { + PolicyConfig.addRequirement(this, policyQName); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getPolicyRequirements() { + return PolicyConfig.getRequirements(this); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasPolicyRequirement(QName policyQName) { + return PolicyConfig.hasRequirement(this, policyQName); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentServiceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentServiceModel.java new file mode 100644 index 000000000..a9a980472 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ComponentServiceModel.java @@ -0,0 +1,128 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * A version 1 ComponentServiceModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1ComponentServiceModel extends BaseNamedModel implements ComponentServiceModel { + + private InterfaceModel _interface; + private String _switchyardNamespace; + + /** + * Constructs a new V1ComponentServiceModel. + * @param switchyardNamespace switchyardNamespace + */ + public V1ComponentServiceModel(String switchyardNamespace) { + super(SCANamespace.DEFAULT.uri(), ComponentServiceModel.SERVICE); + _switchyardNamespace = switchyardNamespace; + } + + /** + * Constructs a new V1ComponentServiceModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ComponentServiceModel(Configuration config, Descriptor desc) { + super(config, desc); + _switchyardNamespace = getModelRootNamespace(); + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentModel getComponent() { + return (ComponentModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public InterfaceModel getInterface() { + if (_interface == null) { + _interface = (InterfaceModel)getFirstChildModelStartsWith(InterfaceModel.INTERFACE); + } + return _interface; + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentServiceModel setInterface(InterfaceModel interfaze) { + setChildModel(interfaze); + _interface = interfaze; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSecurity() { + return getModelAttribute(new QName(_switchyardNamespace, ComponentServiceModel.SECURITY)); + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentServiceModel setSecurity(String security) { + setModelAttribute(new QName(_switchyardNamespace, ComponentServiceModel.SECURITY), security); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public void addPolicyRequirement(QName policyQName) { + PolicyConfig.addRequirement(this, policyQName); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getPolicyRequirements() { + return PolicyConfig.getRequirements(this); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasPolicyRequirement(QName policyQName) { + return PolicyConfig.hasRequirement(this, policyQName); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeMarshaller.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeMarshaller.java new file mode 100644 index 000000000..f5cbd156a --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeMarshaller.java @@ -0,0 +1,109 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.implementation.bpel.BPELComponentImplementationModel; +import org.switchyard.config.model.implementation.bpel.v1.V1BPELComponentImplementationModel; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.ExtensionsModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.SCABindingModel; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.property.v1.V1PropertyModel; + +/** + * Marshalls SCA composite Models. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1CompositeMarshaller extends BaseMarshaller { + + private static final String IMPLEMENTATION_BPEL= ComponentImplementationModel.IMPLEMENTATION + "." + BPELComponentImplementationModel.BPEL; + + /** + * Constructs a new V1CompositeMarshaller with the specified Descriptor. + * @param desc the Descriptor + */ + public V1CompositeMarshaller(Descriptor desc) { + super(desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(CompositeModel.COMPOSITE)) { + return new V1CompositeModel(config, desc); + } else if (name.equals(CompositeServiceModel.SERVICE)) { + Configuration config_parent = config.getParent(); + if (config_parent != null) { + if (config_parent.getName().equals(CompositeModel.COMPOSITE)) { + return new V1CompositeServiceModel(config, desc); + } else if (config_parent.getName().equals(ComponentModel.COMPONENT)) { + return new V1ComponentServiceModel(config, desc); + } + } + } else if (name.startsWith(BindingModel.BINDING)) { + if (name.endsWith("." + SCABindingModel.SCA)) { + return new V1SCABindingModel(config, desc); + } else { + return new V1BindingModel(config, desc); + } + } else if (name.equals(ComponentModel.COMPONENT)) { + return new V1ComponentModel(config, desc); + } else if (name.startsWith(ComponentImplementationModel.IMPLEMENTATION)) { + if (name.equals(IMPLEMENTATION_BPEL)) { + return new V1BPELComponentImplementationModel(config, getDescriptor()); + } + return new V1ComponentImplementationModel(config, desc); + } else if (name.startsWith(InterfaceModel.INTERFACE)) { + Configuration config_parent = config.getParent(); + if (config_parent != null) { + // only pick up standard SCA interface types + if (name.endsWith(InterfaceModel.JAVA) || name.endsWith(InterfaceModel.WSDL)) { + return new V1InterfaceModel(config, desc); + } + } + } else if (name.equals(ComponentReferenceModel.REFERENCE)) { + Configuration config_parent = config.getParent(); + if (config_parent != null) { + if (config_parent.getName().equals(CompositeModel.COMPOSITE)) { + return new V1CompositeReferenceModel(config, desc); + } else if (config_parent.getName().equals(ComponentModel.COMPONENT)) { + return new V1ComponentReferenceModel(config, desc); + } + } + } else if (name.equals(PropertyModel.PROPERTY)) { + return new V1PropertyModel(config,desc); + } else if (name.equals(ExtensionsModel.EXTENSIONS)) { + return new V1ExtensionsModel(config,desc); + } + + return null; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeModel.java new file mode 100644 index 000000000..701040eed --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeModel.java @@ -0,0 +1,218 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.switchyard.common.property.CompoundPropertyResolver; +import org.switchyard.common.property.SystemAndTestPropertyResolver; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.SCANamespace; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * A version 1 CompositeModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1CompositeModel extends BaseNamedModel implements CompositeModel { + + private List _services = new ArrayList(); + private List _references = new ArrayList(); + private List _components = new ArrayList(); + private Map _properties = new HashMap(); + + /** + * Constructs a new V1CompositeModel. + */ + public V1CompositeModel() { + super(SCANamespace.DEFAULT.uri(), CompositeModel.COMPOSITE); + setModelChildrenOrder(CompositeServiceModel.SERVICE, CompositeReferenceModel.REFERENCE, ComponentModel.COMPONENT, PropertyModel.PROPERTY); + setCompositePropertyResolver(); + } + + /** + * Constructs a new V1CompositeModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1CompositeModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration service_config : config.getChildren(CompositeServiceModel.SERVICE)) { + CompositeServiceModel service = (CompositeServiceModel)readModel(service_config); + if (service != null) { + _services.add(service); + } + } + for (Configuration reference_config : config.getChildren(CompositeReferenceModel.REFERENCE)) { + CompositeReferenceModel reference = (CompositeReferenceModel)readModel(reference_config); + if (reference != null) { + _references.add(reference); + } + } + for (Configuration component_config : config.getChildren(ComponentModel.COMPONENT)) { + ComponentModel component = (ComponentModel)readModel(component_config); + if (component != null) { + _components.add(component); + } + } + for (Configuration property_config : config.getChildren(PropertyModel.PROPERTY)) { + PropertyModel property = (PropertyModel)readModel(property_config); + if (property != null) { + _properties.put(property.getName(), property); + } + } + + setModelChildrenOrder(CompositeServiceModel.SERVICE, CompositeReferenceModel.REFERENCE, ComponentModel.COMPONENT, PropertyModel.PROPERTY); + setCompositePropertyResolver(); + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel getSwitchYard() { + return (SwitchYardModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getReferences() { + return Collections.unmodifiableList(_references); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized CompositeModel addReference(CompositeReferenceModel reference) { + addChildModel(reference); + _references.add(reference); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getServices() { + return Collections.unmodifiableList(_services); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized CompositeModel addService(CompositeServiceModel service) { + addChildModel(service); + _services.add(service); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getComponents() { + return Collections.unmodifiableList(_components); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized CompositeModel addComponent(ComponentModel component) { + addChildModel(component); + _components.add(component); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public void setTargetNamespace(String namespaceUri) { + this.setModelAttribute(TARGET_NAMESPACE, namespaceUri); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized PropertyModel getProperty(String name) { + return _properties.get(name); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized Map getProperties() { + return Collections.unmodifiableMap(_properties); + } + + /** + * {@inheritDoc} + */ + @Override + public V1CompositeModel addProperty(PropertyModel property) { + addChildModel(property); + _properties.put(property.getName(), property); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Object resolveProperty(String key) { + Object value = null; + if (key != null) { + PropertyModel property = getProperty(key); + value = property != null ? property.getValue() : null; + } + return value; + } + + /** + * {@inheritDoc} + */ + @Override + public void setCompositePropertyResolver() { + Configuration config = getModelConfiguration(); + Configuration parent = config.getParent(); + if (parent != null) { + config.setPropertyResolver(CompoundPropertyResolver.compact(parent.getPropertyResolver(), this)); + } else { + config.setPropertyResolver(CompoundPropertyResolver.compact(SystemAndTestPropertyResolver.INSTANCE, this)); + } + for (ComponentModel component : _components) { + component.setComponentPropertyResolver(); + } + } +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeReferenceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeReferenceModel.java new file mode 100644 index 000000000..d45fc1a38 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeReferenceModel.java @@ -0,0 +1,197 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.switchyard.common.lang.Strings; +import org.switchyard.config.ConfigLogger; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * A version 1 CompositeReferenceModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1CompositeReferenceModel extends BaseNamedModel implements CompositeReferenceModel { + + private List _bindings = new ArrayList(); + private InterfaceModel _interface; + + /** + * Constructs a new V1CompositeReferenceModel. + */ + public V1CompositeReferenceModel() { + super(SCANamespace.DEFAULT.uri(), CompositeReferenceModel.REFERENCE); + setMultiplicity(CompositeReferenceModel.DEFAULT_MULTIPLICITY); + } + + /** + * Constructs a new V1CompositeReferenceModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1CompositeReferenceModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration binding_config : config.getChildrenStartsWith(BindingModel.BINDING)) { + BindingModel binding = (BindingModel)readModel(binding_config); + if (binding != null) { + _bindings.add(binding); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeModel getComposite() { + return (CompositeModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public List getComponentReferences() { + List list = new ArrayList(); + CompositeModel composite = getComposite(); + if (composite != null) { + String[] promotes = Strings.splitTrimToNullArray(getPromote(), " "); + for (String promote : promotes) { + String[] names = Strings.splitTrimToNullArray(promote, "/"); + int namesCount = names.length; + if (namesCount > 0) { + String componentName = names[0]; + String componentReferenceName = (namesCount == 2) ? names[1] : null; + boolean componentMissing = true; + componentLoop: for (ComponentModel component : composite.getComponents()) { + if (componentName.equals(component.getName())) { + List componentReferences = component.getReferences(); + if (namesCount == 1) { + if (componentReferences.size() > 0) { + ComponentReferenceModel componentReference = componentReferences.iterator().next(); + if (componentReference != null) { + list.add(componentReference); + componentMissing = false; + break componentLoop; + } + } + } else if (namesCount == 2) { + for (ComponentReferenceModel componentReference : componentReferences) { + if (componentReferenceName.equals(componentReference.getName())) { + list.add(componentReference); + componentMissing = false; + break componentLoop; + } + } + } + } + } + if (componentMissing) { + ConfigLogger.ROOT_LOGGER.missingComponentReference((componentReferenceName != null ? componentReferenceName : ""), componentName); + } + } + } + } + return list; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPromote() { + return getModelAttribute(CompositeReferenceModel.PROMOTE); + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeReferenceModel setPromote(String promote) { + setModelAttribute(CompositeReferenceModel.PROMOTE, promote); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getMultiplicity() { + return getModelAttribute(CompositeReferenceModel.MULTIPLICITY); + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeReferenceModel setMultiplicity(String multiplicity) { + setModelAttribute(CompositeReferenceModel.MULTIPLICITY, multiplicity); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getBindings() { + return Collections.unmodifiableList(_bindings); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized CompositeReferenceModel addBinding(BindingModel binding) { + addChildModel(binding); + _bindings.add(binding); + return this; + } + + + /** + * {@inheritDoc} + */ + @Override + public InterfaceModel getInterface() { + if (_interface == null) { + _interface = (InterfaceModel)getFirstChildModelStartsWith(InterfaceModel.INTERFACE); + } + return _interface; + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeReferenceModel setInterface(InterfaceModel interfaze) { + setChildModel(interfaze); + _interface = interfaze; + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeServiceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeServiceModel.java new file mode 100644 index 000000000..ec18e8d3d --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1CompositeServiceModel.java @@ -0,0 +1,192 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.switchyard.common.lang.Strings; +import org.switchyard.config.ConfigLogger; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.ExtensionsModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * A version 1 CompositeServiceModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1CompositeServiceModel extends BaseNamedModel implements CompositeServiceModel { + + private List _bindings = new ArrayList(); + private InterfaceModel _interface; + private ExtensionsModel _extensions; + + /** + * Constructs a new V1CompositeServiceModel. + */ + public V1CompositeServiceModel() { + super(SCANamespace.DEFAULT.uri(), CompositeServiceModel.SERVICE); + } + + /** + * Constructs a new V1CompositeServiceModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1CompositeServiceModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration binding_config : config.getChildrenStartsWith(BindingModel.BINDING)) { + BindingModel binding = (BindingModel)readModel(binding_config); + if (binding != null) { + _bindings.add(binding); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeModel getComposite() { + return (CompositeModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public ComponentServiceModel getComponentService() { + CompositeModel composite = getComposite(); + if (composite != null) { + String[] promotes = Strings.splitTrimToNullArray(getPromote(), " "); + switch (promotes.length) { + case 0: + break; + case 1: + String[] names = Strings.splitTrimToNullArray(promotes[0], "/"); + int namesCount = names.length; + if (namesCount > 0) { + String componentName = names[0]; + String componentServiceName = (namesCount == 2) ? names[1] : null; + for (ComponentModel component : composite.getComponents()) { + if (componentName.equals(component.getName())) { + List componentServices = component.getServices(); + if (namesCount == 1) { + if (componentServices.size() > 0) { + ComponentServiceModel componentService = componentServices.iterator().next(); + if (componentService != null) { + return componentService; + } + } + } else if (namesCount == 2) { + for (ComponentServiceModel componentService : componentServices) { + if (componentServiceName.equals(componentService.getName())) { + return componentService; + } + } + } + } + } + ConfigLogger.ROOT_LOGGER.missingComponentService((componentServiceName != null ? componentServiceName : ""), componentName); + } + break; + default: + throw new IllegalArgumentException("A composite service can only promote one component service."); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPromote() { + return getModelAttribute(CompositeServiceModel.PROMOTE); + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeServiceModel setPromote(String promote) { + setModelAttribute(CompositeServiceModel.PROMOTE, promote); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getBindings() { + return Collections.unmodifiableList(_bindings); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized CompositeServiceModel addBinding(BindingModel binding) { + addChildModel(binding); + _bindings.add(binding); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public InterfaceModel getInterface() { + if (_interface == null) { + _interface = (InterfaceModel)getFirstChildModelStartsWith(InterfaceModel.INTERFACE); + } + return _interface; + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeServiceModel setInterface(InterfaceModel interfaze) { + setChildModel(interfaze); + _interface = interfaze; + return this; + } + + @Override + public ExtensionsModel getExtensions() { + if (_extensions == null) { + _extensions = (ExtensionsModel) getFirstChildModel(ExtensionsModel.EXTENSIONS); + } + return _extensions; + } + + @Override + public CompositeServiceModel setExtensions(ExtensionsModel extensions) { + setChildModel(extensions); + _extensions = extensions; + return this; + } +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ExtensionsModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ExtensionsModel.java new file mode 100644 index 000000000..a3d727b1c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1ExtensionsModel.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.ExtensionsModel; +import org.switchyard.config.model.composite.SCANamespace; +import org.switchyard.config.model.switchyard.ThrottlingModel; + +/** + * A version 1 ExtensionsModel. + */ +public class V1ExtensionsModel extends BaseModel implements ExtensionsModel { + + private ThrottlingModel _throttling; + + /** + * Constructs a new V1ExtensionsModel. + */ + public V1ExtensionsModel() { + super(new QName(SCANamespace.DEFAULT.uri(), V1ExtensionsModel.EXTENSIONS)); + } + + /** + * Constructs a new V1ExtensionsModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ExtensionsModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public ThrottlingModel getThrottling() { + if (_throttling == null) { + _throttling = (ThrottlingModel) getFirstChildModel(ThrottlingModel.THROTTLING); + } + return _throttling; + } + + @Override + public ExtensionsModel setThrottling(ThrottlingModel throttling) { + setChildModel(throttling); + _throttling = throttling; + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1InterfaceModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1InterfaceModel.java new file mode 100644 index 000000000..cb4827727 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1InterfaceModel.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseTypedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * A representation of an InterfaceModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1InterfaceModel extends BaseTypedModel implements InterfaceModel { + + /** + * Creates a new, empty interface model of the specified type. + * @param type interface type + */ + public V1InterfaceModel(String type) { + this(type, SCANamespace.DEFAULT.uri()); + } + + /** + * Creates a new, empty interface model with the specified type and namespace. + * @param type interface type + * @param namespace namespace + */ + public V1InterfaceModel(String type, String namespace) { + super(new QName(namespace, InterfaceModel.INTERFACE + '.' + type)); + } + + /** + * Creates a new InterfaceModel from the specified configuration. + * @param config configuration + * @param desc descriptor + */ + public V1InterfaceModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getInterface() { + return getModelAttribute(InterfaceModel.INTERFACE); + } + + /** + * {@inheritDoc} + */ + @Override + public InterfaceModel setInterface(String interfaze) { + setModelAttribute(InterfaceModel.INTERFACE, interfaze); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1SCABindingModel.java b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1SCABindingModel.java new file mode 100644 index 000000000..439bd8ea6 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/composite/v1/V1SCABindingModel.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.SCABindingModel; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * V1 implementation in SCABindingModel. + */ +public class V1SCABindingModel extends V1BindingModel implements SCABindingModel { + + private String _switchyardNamespace; + + /** + * Create a new V1SCABindingModel. + * @param switchyardNamespace switchyardNamespace + */ + public V1SCABindingModel(String switchyardNamespace) { + super(SCABindingModel.SCA, SCANamespace.DEFAULT.uri()); + _switchyardNamespace = switchyardNamespace; + } + + /** + * Create a new V1SCABindingModel. + * @param config raw config model + * @param desc descriptor + */ + public V1SCABindingModel(Configuration config, Descriptor desc) { + super(config, desc); + _switchyardNamespace = getModelRootNamespace(); + } + + @Override + public boolean isClustered() { + return Boolean.valueOf(getModelAttribute(new QName(_switchyardNamespace, CLUSTERED))); + } + + @Override + public SCABindingModel setClustered(boolean clustered) { + setModelAttribute(new QName(_switchyardNamespace, CLUSTERED), String.valueOf(clustered)); + return this; + } + + @Override + public boolean isPreferLocal() { + return Boolean.valueOf(getModelAttribute(new QName(_switchyardNamespace, PREFER_LOCAL))); + } + + @Override + public SCABindingModel setPreferLocal(boolean preferLocal) { + setModelAttribute(new QName(_switchyardNamespace, PREFER_LOCAL), String.valueOf(false)); + return this; + } + + @Override + public boolean isLoadBalanced() { + return getLoadBalance() != null; + } + + @Override + public String getLoadBalance() { + return getModelAttribute(new QName(_switchyardNamespace, LOAD_BALANCE)); + } + + @Override + public SCABindingModel setLoadBalance(String loadBalance) { + setModelAttribute(new QName(_switchyardNamespace, LOAD_BALANCE), loadBalance); + return this; + } + + @Override + public boolean hasTarget() { + return getTarget() != null; + } + + @Override + public String getTarget() { + return getModelAttribute(new QName(_switchyardNamespace, TARGET)); + } + + @Override + public SCABindingModel setTarget(String target) { + setModelAttribute(new QName(_switchyardNamespace, TARGET), target); + return this; + } + + @Override + public boolean hasTargetNamespace() { + return getTargetNamespace() != null; + } + + @Override + public String getTargetNamespace() { + return getModelAttribute(new QName(_switchyardNamespace, TARGET_NAMESPACE)); + } + + @Override + public SCABindingModel setTargetNamespace(String namespace) { + setModelAttribute(new QName(_switchyardNamespace, TARGET_NAMESPACE), namespace); + return this; + } +} diff --git a/core/config/src/main/java/org/switchyard/config/model/domain/DomainModel.java b/core/config/src/main/java/org/switchyard/config/model/domain/DomainModel.java new file mode 100644 index 000000000..3e0c5f07a --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/domain/DomainModel.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.domain; + +import org.switchyard.config.model.NamedModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * The "domain" configuration model. + */ +public interface DomainModel extends NamedModel { + + /** The "domain" name. */ + public static final String DOMAIN = "domain"; + + /** + * Gets the parent switchyard model. + * @return the parent switchyard model + */ + public SwitchYardModel getSwitchYard(); + + /** + * Gets the properties defined for the domain. + * @return properties for the domain + */ + public PropertiesModel getProperties(); + + /** + * Sets the child properties model. + * @param properties the child properties model. + * @return this DomainModel (useful for chaining) + */ + public DomainModel setProperties(PropertiesModel properties); + + /** + * Gets the child securities model. + * @return the child securities model + */ + public SecuritiesModel getSecurities(); + + /** + * Sets the child securities model. + * @param securities the child securities model + * @return this DomainModel (useful for chaining) + */ + public DomainModel setSecurities(SecuritiesModel securities); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/domain/SecuritiesModel.java b/core/config/src/main/java/org/switchyard/config/model/domain/SecuritiesModel.java new file mode 100644 index 000000000..7a570bf32 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/domain/SecuritiesModel.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.domain; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * The "securities" configuration model. + */ +public interface SecuritiesModel extends Model { + + /** The "securities" name. */ + public static final String SECURITIES = "securities"; + + /** + * Gets the parent domain model. + * @return the parent domain model + */ + public DomainModel getDomain(); + + /** + * Gets the child security models. + * @return the child security models + */ + public List getSecurities(); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/domain/SecurityModel.java b/core/config/src/main/java/org/switchyard/config/model/domain/SecurityModel.java new file mode 100644 index 000000000..f6e2f0a8c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/domain/SecurityModel.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.domain; + +import java.util.Set; + +import org.switchyard.config.model.NamedModel; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * A Security Model. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface SecurityModel extends NamedModel { + + /** + * The security XML element. + */ + public static final String SECURITY = "security"; + + /** + * Gets the parent securities model. + * @return the parent securities model + */ + public SecuritiesModel getSecurities(); + + /** + * Gets the CallbackHandler class. + * @param loader the ClassLoader to use + * @return the CallbackHandler class + */ + public Class getCallbackHandler(ClassLoader loader); + + /** + * Sets the CallbackHandler class. + * @param callbackHandler the CallbackHandler class + * @return this SecurityModel (useful for chaining) + */ + public SecurityModel setCallbackHandler(Class callbackHandler); + + /** + * Gets the roles allowed. + * @return the roles allowed + */ + public Set getRolesAllowed(); + + /** + * Sets the roles allowed. + * @param rolesAllowed the roles allowed + * @return this SecurityModel (useful for chaining) + */ + public SecurityModel setRolesAllowed(Set rolesAllowed); + + /** + * Gets the run as. + * @return the run as + */ + public String getRunAs(); + + /** + * Sets the run as. + * @param runAs the run as + * @return this SecurityModel (useful for chaining) + */ + public SecurityModel setRunAs(String runAs); + + /** + * Gets the properties. + * @return the properties + */ + public PropertiesModel getProperties(); + + /** + * Sets the properties. + * @param properties the properties + * @return this SecurityModel (useful for chaining) + */ + public SecurityModel setProperties(PropertiesModel properties); + + /** + * Gets the security domain. + * @return the security domain + */ + public String getSecurityDomain(); + + /** + * Sets the security domain. + * @param securityDomain the security domain + * @return this SecurityModel (useful for chaining) + */ + public SecurityModel setSecurityDomain(String securityDomain); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1DomainModel.java b/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1DomainModel.java new file mode 100644 index 000000000..0d691acab --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1DomainModel.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.domain.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.domain.DomainModel; +import org.switchyard.config.model.domain.SecuritiesModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.model.validate.ValidatesModel; + +/** + * Implementation of DomainModel : v1. + */ +public class V1DomainModel extends BaseNamedModel implements DomainModel { + + private PropertiesModel _properties; + private SecuritiesModel _securities; + + /** + * Constructs a new V1DomainModel. + * @param namespace namespace + */ + public V1DomainModel(String namespace) { + super(namespace, DomainModel.DOMAIN); + setModelChildrenOrder(TransformsModel.TRANSFORMS, ValidatesModel.VALIDATES, PropertiesModel.PROPERTIES, SecuritiesModel.SECURITIES); + } + + /** + * Constructs a new V1DomainModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1DomainModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(TransformsModel.TRANSFORMS, ValidatesModel.VALIDATES, PropertiesModel.PROPERTIES, SecuritiesModel.SECURITIES); + } + + @Override + public SwitchYardModel getSwitchYard() { + return (SwitchYardModel)getModelParent(); + } + + @Override + public synchronized PropertiesModel getProperties() { + if (_properties == null) { + _properties = (PropertiesModel)getFirstChildModel(PropertiesModel.PROPERTIES); + } + return _properties; + } + + @Override + public DomainModel setProperties(PropertiesModel properties) { + setChildModel(properties); + _properties = properties; + SwitchYardModel switchyard = getSwitchYard(); + if (switchyard != null) { + switchyard.setDomainPropertyResolver(); + } + return this; + } + + @Override + public SecuritiesModel getSecurities() { + if (_securities == null) { + _securities = (SecuritiesModel)getFirstChildModel(SecuritiesModel.SECURITIES); + } + return _securities; + } + + @Override + public DomainModel setSecurities(SecuritiesModel securities) { + setChildModel(securities); + _securities = securities; + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1SecuritiesModel.java b/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1SecuritiesModel.java new file mode 100644 index 000000000..27d3859ae --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1SecuritiesModel.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.domain.v1; + +import static org.switchyard.config.model.domain.SecurityModel.SECURITY; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.domain.DomainModel; +import org.switchyard.config.model.domain.SecuritiesModel; +import org.switchyard.config.model.domain.SecurityModel; + +/** + * A version 1 SecuritiesModel. + */ +public class V1SecuritiesModel extends BaseModel implements SecuritiesModel { + + private List _securities = new ArrayList(); + + /** + * Constructs a new V1SecuritiesModel. + * @param namespace namespace + */ + public V1SecuritiesModel(String namespace) { + super(new QName(namespace, SECURITIES)); + setModelChildrenOrder(SECURITY); + } + + /** + * Constructs a new V1SecuritiesModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1SecuritiesModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration security_config : config.getChildrenStartsWith(SECURITY)) { + SecurityModel security = (SecurityModel)readModel(security_config); + if (security != null) { + _securities.add(security); + } + } + setModelChildrenOrder(SECURITY); + } + + /** + * {@inheritDoc} + */ + @Override + public DomainModel getDomain() { + return (DomainModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getSecurities() { + return Collections.unmodifiableList(_securities); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1SecurityModel.java b/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1SecurityModel.java new file mode 100644 index 000000000..9ea280500 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/domain/v1/V1SecurityModel.java @@ -0,0 +1,165 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.domain.v1; + +import static org.switchyard.config.model.property.PropertiesModel.PROPERTIES; + +import java.util.Set; + +import org.switchyard.common.lang.Strings; +import org.switchyard.common.type.Classes; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.domain.SecuritiesModel; +import org.switchyard.config.model.domain.SecurityModel; +import org.switchyard.config.model.property.PropertiesModel; + +/** + * The 1st version SecurityModel. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class V1SecurityModel extends BaseNamedModel implements SecurityModel { + + private static final String CALLBACK_HANDLER = "callbackHandler"; + private static final String ROLES_ALLOWED = "rolesAllowed"; + private static final String RUN_AS = "runAs"; + private static final String SECURITY_DOMAIN = "securityDomain"; + + private PropertiesModel _properties; + + /** + * Creates a new V1SecurityModel. + * @param namespace namespace + */ + public V1SecurityModel(String namespace) { + super(namespace, SECURITY); + setModelChildrenOrder(PROPERTIES); + } + + /** + * Creates a new V1SecurityModel. + * @param config the configuration + * @param desc the descriptor + */ + public V1SecurityModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(PROPERTIES); + } + + /** + * {@inheritDoc} + */ + @Override + public SecuritiesModel getSecurities() { + return (SecuritiesModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getCallbackHandler(ClassLoader loader) { + String c = Strings.trimToNull(getModelAttribute(CALLBACK_HANDLER)); + return c != null ? Classes.forName(c, loader) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public SecurityModel setCallbackHandler(Class clazz) { + String c = clazz != null ? clazz.getName() : null; + setModelAttribute(CALLBACK_HANDLER, c); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Set getRolesAllowed() { + String ra = getModelAttribute(ROLES_ALLOWED); + return Strings.uniqueSplitTrimToNull(ra, ","); + } + + /** + * {@inheritDoc} + */ + @Override + public SecurityModel setRolesAllowed(Set rolesAllowed) { + String[] ra = rolesAllowed != null ? rolesAllowed.toArray(new String[rolesAllowed.size()]) : null; + setModelAttribute(ROLES_ALLOWED, Strings.concat(",", ra)); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getRunAs() { + String runAs = getModelAttribute(RUN_AS); + return Strings.trimToNull(runAs); + } + + /** + * {@inheritDoc} + */ + @Override + public SecurityModel setRunAs(String runAs) { + setModelAttribute(RUN_AS, runAs); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized PropertiesModel getProperties() { + if (_properties == null) { + _properties = (PropertiesModel)getFirstChildModel(PROPERTIES); + } + return _properties; + } + + /** + * {@inheritDoc} + */ + @Override + public SecurityModel setProperties(PropertiesModel properties) { + setChildModel(properties); + _properties = properties; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSecurityDomain() { + String securityDomain = getModelAttribute(SECURITY_DOMAIN); + return Strings.trimToNull(securityDomain); + } + + /** + * {@inheritDoc} + */ + @Override + public SecurityModel setSecurityDomain(String securityDomainName) { + setModelAttribute(SECURITY_DOMAIN, securityDomainName); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/BPELComponentImplementationModel.java b/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/BPELComponentImplementationModel.java new file mode 100644 index 000000000..6e5a0de8e --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/BPELComponentImplementationModel.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.implementation.bpel; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.composite.ComponentImplementationModel; + +/** + * A "bpel" ComponentImplementationModel. + * + */ +public interface BPELComponentImplementationModel extends ComponentImplementationModel { + + /** + * The "bpel" implementation type. + */ + public static final String BPEL = "bpel"; + + /** + * Gets the "process" attribute. + * + * @return the "process" attribute + */ + public String getProcess(); + + /** + * Gets the "process" attribute as a QName. + * + * @return the "process" attribute + */ + public QName getProcessQName(); + + /** + * Sets the "process" attribute. + * + * @param process the "process" attribute + * @return this instance (useful for chaining) + */ + public BPELComponentImplementationModel setProcess(String process); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/ProcessConstants.java b/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/ProcessConstants.java new file mode 100644 index 000000000..12dddc190 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/ProcessConstants.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.implementation.bpel; + +import javax.xml.namespace.QName; + +/** + * Various constants and context variables. + * + */ +public final class ProcessConstants { + + private ProcessConstants() { + } + + /** + * The default process namespace. + */ + public static final String PROCESS_NAMESPACE = "http://docs.oasis-open.org/ns/opencsa/sca/200912"; + + /** processDescriptor . */ + public static final String PROCESS = "process"; + + /** {http://docs.oasis-open.org/ns/opencsa/sca/200912}process . */ + public static final String PROCESS_VAR = new QName(PROCESS_NAMESPACE, PROCESS).toString(); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/v1/V1BPELComponentImplementationModel.java b/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/v1/V1BPELComponentImplementationModel.java new file mode 100644 index 000000000..2a1bce5fe --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/implementation/bpel/v1/V1BPELComponentImplementationModel.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.implementation.bpel.v1; + +import static org.switchyard.config.model.implementation.bpel.ProcessConstants.PROCESS; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.SCANamespace; +import org.switchyard.config.model.composite.v1.V1ComponentImplementationModel; +import org.switchyard.config.model.implementation.bpel.BPELComponentImplementationModel; + +/** + * A "bpel" implementation of a ComponentImplementationModel. + * + */ +public class V1BPELComponentImplementationModel extends V1ComponentImplementationModel implements BPELComponentImplementationModel { + + /** + * Default constructor for application use. + */ + public V1BPELComponentImplementationModel() { + super(BPEL, SCANamespace.DEFAULT.uri()); + } + + /** + * Constructor for Marshaller use (ie: V1BPELMarshaller). + * + * @param config the Configuration + * @param desc the Descriptor + */ + public V1BPELComponentImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + public String getProcess() { + return getModelAttribute(PROCESS); + } + + /** + * {@inheritDoc} + */ + public QName getProcessQName() { + return getModelConfiguration().getAttributeAsQName(PROCESS); + } + + /** + * {@inheritDoc} + */ + public BPELComponentImplementationModel setProcess(String process) { + setModelAttribute(PROCESS, process); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/property/PropertiesModel.java b/core/config/src/main/java/org/switchyard/config/model/property/PropertiesModel.java new file mode 100644 index 000000000..f2f29aabe --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/property/PropertiesModel.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.property; + +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.config.model.Model; + +/** + * The "properties" configuration model. + */ +public interface PropertiesModel extends Model, PropertyResolver { + + /** The "properties" name. */ + public static final String PROPERTIES = "properties"; + + /** + * Gets the load attribute. + * @return the load attribute + */ + public String getLoad(); + + /** + * Sets the load attribute. + * @param load the load attribute + * @return this PropertiesModel (useful for chaining) + */ + public PropertiesModel setLoad(String load); + + /** + * Gets the child property models.

+ * NOTE: This only retrieves child property models, and does not include properties loaded via the load attribute. + * To access all property values, you can use {@link #getPropertyValue(String)}, {@link #toProperties()} or {@link #toMap()}. + * @return the child property models + */ + public List getProperties(); + + /** + * Adds a child property model. + * @param property the child property model to add + * @return this PropertiesModel (useful for chaining) + */ + public PropertiesModel addProperty(PropertyModel property); + + /** + * Fetch a property model by name.

+ * NOTE: This only retrieves a child property model, and does not include properties loaded via the load attribute. + * To access all property values, you can use {@link #getPropertyValue(String)}, {@link #toProperties()} or {@link #toMap()}. + * @param name name of the property + * @return property with the specified name, or null if no such property exists + */ + public PropertyModel getProperty(String name); + + /** + * Gets a property value by name. + * @param name the name of the property + * @return the property value, or null if no such property exists + */ + public String getPropertyValue(String name); + + /** + * Removes a child property model. + * @param propertyName the name of the property + * @return the removed property or null if the named property was not present + */ + public PropertyModel removeProperty(String propertyName); + + /** + * Converts this PropertiesModel to a Properties. + * @return the Properties + */ + public Properties toProperties(); + + /** + * Converts this PropertiesModel to a Map. + * @return the Map + */ + public Map toMap(); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/property/PropertyModel.java b/core/config/src/main/java/org/switchyard/config/model/property/PropertyModel.java new file mode 100644 index 000000000..9b6677ff5 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/property/PropertyModel.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.property; + +import org.switchyard.config.model.Model; + +/** + * The "property" configuration model. + */ +public interface PropertyModel extends Model { + + /** The "property" name. */ + public static final String PROPERTY = "property"; + + /** + * Gets the parent properties model. + * @return the parent properties model. + */ + public PropertiesModel getProperties(); + + /** + * Gets the name attribute. + * @return the name attribute + */ + public String getName(); + + /** + * Sets the name attribute. + * @param name the name attribute + * @return this PropertyModel (useful for chaining) + */ + public PropertyModel setName(String name); + + /** + * Gets the value attribute. + * @return the value attribute + */ + public String getValue(); + + /** + * Sets the value attribute. + * @param value the value attribute + * @return this PropertyModel (useful for chaining) + */ + public PropertyModel setValue(String value); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/property/v1/V1PropertiesModel.java b/core/config/src/main/java/org/switchyard/config/model/property/v1/V1PropertiesModel.java new file mode 100644 index 000000000..b957422a9 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/property/v1/V1PropertiesModel.java @@ -0,0 +1,185 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.property.v1; + +import static org.switchyard.config.model.property.PropertyModel.PROPERTY; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.property.PropertyModel; + +/** + * A version 1 PropertiesModel. + */ +public class V1PropertiesModel extends BaseModel implements PropertiesModel { + + private List _properties = new ArrayList(); + + /** + * Creates a new PropertiesModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1PropertiesModel(String namespace) { + super(new QName(namespace, PROPERTIES)); + setModelChildrenOrder(PROPERTY); + } + + /** + * Creates a new PropertiesModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1PropertiesModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration property_config : config.getChildren(PROPERTY)) { + PropertyModel property = (PropertyModel)readModel(property_config); + if (property != null) { + _properties.add(property); + } + } + setModelChildrenOrder(PROPERTY); + } + + /** + * {@inheritDoc} + */ + @Override + public String getLoad() { + // introduced in v2 + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public PropertiesModel setLoad(String load) { + // introduced in v2 + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getProperties() { + return Collections.unmodifiableList(_properties); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized PropertiesModel addProperty(PropertyModel property) { + addChildModel(property); + _properties.add(property); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public PropertyModel getProperty(String name) { + PropertyModel property = null; + for (PropertyModel p : _properties) { + if (p.getName().equals(name)) { + property = p; + break; + } + } + return property; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPropertyValue(String name) { + String value = null; + if (name != null) { + PropertyModel property = getProperty(name); + value = property != null ? property.getValue() : null; + } + return value; + } + + /** + * {@inheritDoc} + */ + @Override + public PropertyModel removeProperty(String propertyName) { + PropertyModel removed = null; + + for (PropertyModel property : _properties) { + if (property.getName().equals(propertyName)) { + removed = property; + _properties.remove(property); + } + } + return removed; + } + + /** + * {@inheritDoc} + */ + @Override + public Properties toProperties() { + Properties properties = new Properties(); + for (PropertyModel pm : getProperties()) { + String name = pm.getName(); + String value = pm.getValue(); + if (name != null && value != null) { + properties.setProperty(name, value); + } + } + return properties; + } + + /** + * {@inheritDoc} + */ + @Override + public Map toMap() { + Map map = new HashMap(); + for (PropertyModel pm : getProperties()) { + String name = pm.getName(); + String value = pm.getValue(); + if (name != null && value != null) { + map.put(name, value); + } + } + return map; + } + + /** + * {@inheritDoc} + */ + @Override + public Object resolveProperty(String key) { + return getPropertyValue(key); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/property/v1/V1PropertyModel.java b/core/config/src/main/java/org/switchyard/config/model/property/v1/V1PropertyModel.java new file mode 100644 index 000000000..a27a4c46e --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/property/v1/V1PropertyModel.java @@ -0,0 +1,98 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.property.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.property.PropertyModel; + +/** + * Implementation of PropertyModel : v1. + */ +public class V1PropertyModel extends BaseModel implements PropertyModel { + + private boolean _valueRecursionCheck; + + /** + * Creates a new PropertyModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1PropertyModel(String namespace) { + super(new QName(namespace, PROPERTY)); + } + + /** + * Creates a new PropertyModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1PropertyModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public PropertiesModel getProperties() { + return (PropertiesModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return getModelAttribute("name"); + } + + /** + * {@inheritDoc} + */ + @Override + public PropertyModel setName(String name) { + setModelAttribute("name", name); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized String getValue() { + if (_valueRecursionCheck) { + return null; + } + _valueRecursionCheck = true; + try { + return getModelAttribute("value"); + } finally { + _valueRecursionCheck = false; + } + } + + /** + * {@inheritDoc} + */ + @Override + public PropertyModel setValue(String value) { + setModelAttribute("value", value); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/property/v2/V2PropertiesModel.java b/core/config/src/main/java/org/switchyard/config/model/property/v2/V2PropertiesModel.java new file mode 100644 index 000000000..af1c2eb12 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/property/v2/V2PropertiesModel.java @@ -0,0 +1,141 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.property.v2; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.io.pull.PropertiesPuller.PropertiesType; +import org.switchyard.common.io.pull.Puller.PathType; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.property.v1.V1PropertiesModel; + +/** + * A version 2 PropertiesModel. NOTE: Like other config models, this one is NOT thread-safe! + */ +public class V2PropertiesModel extends V1PropertiesModel { + + private Properties _loadProperties = null; + + /** + * Creates a new PropertiesModel in the specified namespace. + * @param namespace the specified namespace + */ + public V2PropertiesModel(String namespace) { + super(namespace); + loadProperies(); + } + + /** + * Creates a new PropertiesModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V2PropertiesModel(Configuration config, Descriptor desc) { + super(config, desc); + loadProperies(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getLoad() { + return getModelAttribute("load"); + } + + /** + * {@inheritDoc} + */ + @Override + public PropertiesModel setLoad(String load) { + setModelAttribute("load", load); + loadProperies(); + return this; + } + + private void loadProperies() { + _loadProperties = null; + String propsPath = getLoad(); + if (propsPath != null) { + PropertiesType propsType = propsPath.endsWith(".xml") ? PropertiesType.XML : PropertiesType.PROPERTIES; + PropertiesPuller propsPuller = new PropertiesPuller(propsType); + Properties props = propsPuller.pullPath(propsPath, getClass(), PathType.values()); + if (props != null) { + _loadProperties = props; + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getPropertyValue(String name) { + // defined properties (via super) always win + String prop = super.getPropertyValue(name); + if (prop == null && name != null && _loadProperties != null) { + prop = _loadProperties.getProperty(name); + } + return prop; + } + + /** + * {@inheritDoc} + */ + @Override + public Properties toProperties() { + Properties properties = new Properties(); + if (_loadProperties != null) { + for (Object key : _loadProperties.keySet()) { + String name = (String)key; + String value = _loadProperties.getProperty(name); + properties.setProperty(name, value); + } + } + // defined properties (via super) always win + Properties superProperties = super.toProperties(); + if (superProperties != null) { + for (Object key : superProperties.keySet()) { + String name = (String)key; + String value = superProperties.getProperty(name); + properties.setProperty(name, value); + } + } + return properties; + } + + /** + * {@inheritDoc} + */ + @Override + public Map toMap() { + Map map = new HashMap(); + if (_loadProperties != null) { + for (Object key : _loadProperties.keySet()) { + String name = (String)key; + String value = _loadProperties.getProperty(name); + map.put(name, value); + } + } + // defined properties (via super) always win + map.putAll(super.toMap()); + return map; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/resource/ResourceDetailModel.java b/core/config/src/main/java/org/switchyard/config/model/resource/ResourceDetailModel.java new file mode 100644 index 000000000..4e0a13562 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/resource/ResourceDetailModel.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.resource; + +import org.switchyard.common.io.resource.ResourceDetail; +import org.switchyard.config.model.Model; + +/** + * A detail model for a Resource. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface ResourceDetailModel extends ResourceDetail, Model { + + /** + * The resourceDetail XML element. + */ + public static final String RESOURCE_DETAIL = "resourceDetail"; + + /** + * Sets the input type. + * @param inputType the input type + * @return this ResourceDetailModel (useful for chaining) + */ + public ResourceDetailModel setInputType(String inputType); + + /** + * Sets the worksheet name. + * @param worksheetName the worksheet name + * @return this ResourceDetailModel (useful for chaining) + */ + public ResourceDetailModel setWorksheetName(String worksheetName); + + /* SWITCHYARD-1662 + * + * Sets whether to use external types. + * @param usingExternalTypes if using external types + * @return this ResourceDetailModel (useful for chaining) + * + public ResourceDetailModel setUsingExternalTypes(boolean usingExternalTypes); + */ + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/resource/ResourceModel.java b/core/config/src/main/java/org/switchyard/config/model/resource/ResourceModel.java new file mode 100644 index 000000000..4f3232293 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/resource/ResourceModel.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.resource; + +import org.switchyard.common.io.resource.Resource; +import org.switchyard.common.io.resource.ResourceDetail; +import org.switchyard.common.io.resource.ResourceType; +import org.switchyard.config.model.Model; + +/** + * A configuration model for Resources. + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public interface ResourceModel extends Resource, Model { + + /** + * The resource XML element. + */ + public static final String RESOURCE = "resource"; + + /** + * Sets the location of the Resource. + * @param location the location of the Resource. + * @return this ResourceModel (useful for chaining) + */ + public ResourceModel setLocation(String location); + + /** + * Sets the type of the Resource. + * @param type the type of Resource + * @return this ResourceModel (useful for chaining) + */ + public ResourceModel setType(ResourceType type); + + /** + * Sets the detail of the Resource. + * @param detail the detail of Resource + * @return this ResourceModel (useful for chaining) + */ + public ResourceModel setDetail(ResourceDetail detail); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/resource/ResourcesModel.java b/core/config/src/main/java/org/switchyard/config/model/resource/ResourcesModel.java new file mode 100644 index 000000000..0d3004810 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/resource/ResourcesModel.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.resource; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * The "resources" configuration model. + */ +public interface ResourcesModel extends Model { + + /** The "resources" name. */ + public static final String RESOURCES = "resources"; + + /** + * Gets the child resource models. + * @return the child resource models + */ + public List getResources(); + + /** + * Adds a child resource model. + * @param resource the child resource model + * @return this ResourcesModel (useful for chaining) + */ + public ResourcesModel addResource(ResourceModel resource); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourceDetailModel.java b/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourceDetailModel.java new file mode 100644 index 000000000..3878cf53b --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourceDetailModel.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.resource.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.resource.ResourceDetailModel; + +/** + * The 1st version ResourceDetailModel. + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public class V1ResourceDetailModel extends BaseModel implements ResourceDetailModel { + + /** + * Creates a new ResourceDetailModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1ResourceDetailModel(String namespace) { + super(new QName(namespace, RESOURCE_DETAIL)); + } + + /** + * Creates a new ResourceDetailModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ResourceDetailModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getInputType() { + return getModelAttribute("inputType"); + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceDetailModel setInputType(String inputType) { + setModelAttribute("inputType", inputType); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getWorksheetName() { + return getModelAttribute("worksheetName"); + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceDetailModel setWorksheetName(String worksheetName) { + setModelAttribute("worksheetName", worksheetName); + return this; + } + + /* SWITCHYARD-1662 + * + * + * {@inheritDoc} + * + @Override + public boolean isUsingExternalTypes() { + return Boolean.valueOf(getModelAttribute("usingExternalTypes")).booleanValue(); + } + */ + + /* SWITCHYARD-1662 + * + * + * {@inheritDoc} + * + @Override + public ResourceDetailModel setUsingExternalTypes(boolean usingExternalTypes) { + setModelAttribute("usingExternalTypes", String.valueOf(usingExternalTypes)); + return this; + } + */ + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourceModel.java b/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourceModel.java new file mode 100644 index 000000000..40c0d9429 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourceModel.java @@ -0,0 +1,154 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.resource.v1; + +import static org.switchyard.config.model.resource.ResourceDetailModel.RESOURCE_DETAIL; + +import java.net.URL; + +import javax.xml.namespace.QName; + +import org.switchyard.common.io.resource.BaseResource; +import org.switchyard.common.io.resource.ResourceDetail; +import org.switchyard.common.io.resource.ResourceType; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.resource.ResourceDetailModel; +import org.switchyard.config.model.resource.ResourceModel; + +/** + * The 1st version ResourceModel. + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +public class V1ResourceModel extends BaseModel implements ResourceModel { + + private ResourceDetailModel _detail; + + /** + * Creates a new ResourceModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1ResourceModel(String namespace) { + super(new QName(namespace, RESOURCE)); + setModelChildrenOrder(RESOURCE_DETAIL); + } + + /** + * Creates a new ResourceModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ResourceModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(RESOURCE_DETAIL); + } + + /** + * {@inheritDoc} + */ + @Override + public String getLocation() { + return getModelAttribute("location"); + } + + /** + * {@inheritDoc} + */ + @Override + public URL getLocationURL() { + return getLocationURL(getClass()); + } + + /** + * {@inheritDoc} + */ + @Override + public URL getLocationURL(Class caller) { + return BaseResource.getURL(getLocation(), caller); + } + + /** + * {@inheritDoc} + */ + @Override + public URL getLocationURL(ClassLoader loader) { + return BaseResource.getURL(getLocation(), loader); + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceModel setLocation(String location) { + if (location != null && getType() == null) { + setType(ResourceType.forLocation(location)); + } + setModelAttribute("location", location); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceType getType() { + String rt = getModelAttribute("type"); + return rt != null ? ResourceType.valueOf(rt) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceModel setType(ResourceType type) { + String rt = type != null ? type.getName() : null; + setModelAttribute("type", rt); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceDetail getDetail() { + if (_detail == null) { + _detail = (ResourceDetailModel)getFirstChildModel(RESOURCE_DETAIL); + } + return _detail; + } + + /** + * {@inheritDoc} + */ + @Override + public ResourceModel setDetail(ResourceDetail detail) { + ResourceDetailModel child = null; + if (detail instanceof ResourceDetailModel) { + child = (ResourceDetailModel)detail; + } else if (detail != null) { + child = new V1ResourceDetailModel(getNamespaceURI()); + child.setInputType(detail.getInputType()); + child.setWorksheetName(detail.getWorksheetName()); + /* SWITCHYARD-1662 + child.setUsingExternalTypes(detail.isUsingExternalTypes()); + */ + } + setChildModel(child); + _detail = child; + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourcesModel.java b/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourcesModel.java new file mode 100644 index 000000000..0c04b1d3c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/resource/v1/V1ResourcesModel.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.resource.v1; + +import static org.switchyard.config.model.resource.ResourceModel.RESOURCE; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.resource.ResourceModel; +import org.switchyard.config.model.resource.ResourcesModel; + +/** + * A version 1 ResourcesModel. + */ +public class V1ResourcesModel extends BaseModel implements ResourcesModel { + + private List _resources = new ArrayList(); + + /** + * Creates a new ResourcesModel in the specified namespace. + * @param namespace the specified namespace + */ + public V1ResourcesModel(String namespace) { + super(new QName(namespace, RESOURCES)); + setModelChildrenOrder(RESOURCE); + } + + /** + * Creates a new ResourcesModel with the specified configuration and descriptor. + * @param config the configuration + * @param desc the descriptor + */ + public V1ResourcesModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration resource_config : config.getChildren(RESOURCE)) { + ResourceModel resource = (ResourceModel)readModel(resource_config); + if (resource != null) { + _resources.add(resource); + } + } + setModelChildrenOrder(RESOURCE); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getResources() { + return Collections.unmodifiableList(_resources); + } + + /** + * {@inheritDoc} + */ + @Override + public ResourcesModel addResource(ResourceModel resource) { + addChildModel(resource); + _resources.add(resource); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/JavaOperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/JavaOperationSelectorModel.java new file mode 100644 index 000000000..09b10152a --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/JavaOperationSelectorModel.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.selector; + + + +/** + * Java OperationSelector model. + */ +public interface JavaOperationSelectorModel extends OperationSelectorModel { + + /** The "java" name. */ + public static final String JAVA = "java"; + + /** class attribute. */ + public static final String CLASS = "class"; + + /** + * Get the fully qualified class name of OperationSelector. + * @return class name + */ + String getClazz(); + + /** + * Set the fully qualified class name of OperationSelector. + * @param clazz the fully qualified class name of OperationSelector + * @return this OperationSelectorModel for chaining + */ + JavaOperationSelectorModel setClazz(String clazz); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/OperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/OperationSelectorModel.java new file mode 100644 index 000000000..d4bd83cf3 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/OperationSelectorModel.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.selector; + +import org.switchyard.config.model.Model; + +/** + * The "operationSelector" configuration model. + */ +public interface OperationSelectorModel extends Model { + + /** operationSelector variable. */ + public static final String OPERATION_SELECTOR = "operationSelector"; + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/RegexOperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/RegexOperationSelectorModel.java new file mode 100644 index 000000000..aba531000 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/RegexOperationSelectorModel.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.selector; + + + +/** + * Regex OperationSelector model. + */ +public interface RegexOperationSelectorModel extends OperationSelectorModel { + + /** The "regex" name. */ + public static final String REGEX = "regex"; + + /** expression attribute. */ + public static final String EXPRESSION = "expression"; + + /** + * Get Regex expression. + * @return Regex expression + */ + String getExpression(); + + /** + * Set Regex expression. + * @param expression Regex expression + * @return this OperationSelectorModel for chaining + */ + RegexOperationSelectorModel setExpression(String expression); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/StaticOperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/StaticOperationSelectorModel.java new file mode 100644 index 000000000..d87358cdc --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/StaticOperationSelectorModel.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.selector; + + + +/** + * Static OperationSelector model. + */ +public interface StaticOperationSelectorModel extends OperationSelectorModel { + + /** operationName attribute. */ + public static final String OPERATION_NAME = "operationName"; + + /** + * Get operation name. + * @return operation name + */ + String getOperationName(); + + /** + * Set operation name. + * @param name operation name + * @return this OperationSelectorModel for chaining + */ + StaticOperationSelectorModel setOperationName(String name); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/XPathOperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/XPathOperationSelectorModel.java new file mode 100644 index 000000000..811d21547 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/XPathOperationSelectorModel.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.selector; + + + +/** + * XPath OperationSelector model. + */ +public interface XPathOperationSelectorModel extends OperationSelectorModel { + + /** The "xpath" name. */ + public static final String XPATH = "xpath"; + + /** expression attribute. */ + public static final String EXPRESSION = "expression"; + + /** + * Get XPath expression. + * @return XPath expression + */ + String getExpression(); + + /** + * Set XPath expression. + * @param expression XPath expression + * @return this OperationSelectorModel for chaining + */ + XPathOperationSelectorModel setExpression(String expression); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1JavaOperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1JavaOperationSelectorModel.java new file mode 100644 index 000000000..b8a512dc7 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1JavaOperationSelectorModel.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.selector.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.common.lang.Strings; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.selector.JavaOperationSelectorModel; + +/** + * V1 Java OperationSelector Model. + */ +public class V1JavaOperationSelectorModel extends BaseModel implements JavaOperationSelectorModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1JavaOperationSelectorModel(String namespace) { + super(new QName(namespace, OPERATION_SELECTOR + '.' + JAVA)); + } + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V1JavaOperationSelectorModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getClazz() { + return Strings.trimToNull(getModelAttribute(CLASS)); + } + + @Override + public JavaOperationSelectorModel setClazz(String clazz) { + setModelAttribute("class", clazz); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1RegexOperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1RegexOperationSelectorModel.java new file mode 100644 index 000000000..df2cb4dca --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1RegexOperationSelectorModel.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.selector.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.selector.RegexOperationSelectorModel; + +/** + * V1 Regex OperationSelector Model. + */ +public class V1RegexOperationSelectorModel extends BaseModel implements RegexOperationSelectorModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1RegexOperationSelectorModel(String namespace) { + super(new QName(namespace, OPERATION_SELECTOR + '.' + REGEX)); + } + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V1RegexOperationSelectorModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getExpression() { + return getModelAttribute(EXPRESSION); + } + + @Override + public RegexOperationSelectorModel setExpression(String expression) { + setModelAttribute(EXPRESSION, expression); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1StaticOperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1StaticOperationSelectorModel.java new file mode 100644 index 000000000..337a83c8c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1StaticOperationSelectorModel.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.selector.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.selector.StaticOperationSelectorModel; + +/** + * V1 Static OperationSelector Model. + */ +public class V1StaticOperationSelectorModel extends BaseModel implements StaticOperationSelectorModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1StaticOperationSelectorModel(String namespace) { + super(new QName(namespace, OPERATION_SELECTOR)); + } + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V1StaticOperationSelectorModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getOperationName() { + return getModelAttribute(OPERATION_NAME); + } + + @Override + public StaticOperationSelectorModel setOperationName(String name) { + setModelAttribute(OPERATION_NAME, name); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1XPathOperationSelectorModel.java b/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1XPathOperationSelectorModel.java new file mode 100644 index 000000000..c27f90098 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/selector/v1/V1XPathOperationSelectorModel.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.selector.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.selector.XPathOperationSelectorModel; + +/** + * V1 XPath OperationSelector Model. + */ +public class V1XPathOperationSelectorModel extends BaseModel implements XPathOperationSelectorModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1XPathOperationSelectorModel(String namespace) { + super(new QName(namespace, OPERATION_SELECTOR + '.' + XPATH)); + } + + /** + * Constructor. + * @param config configuration + * @param desc descriptor + */ + public V1XPathOperationSelectorModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getExpression() { + return getModelAttribute(EXPRESSION); + } + + @Override + public XPathOperationSelectorModel setExpression(String expression) { + setModelAttribute(EXPRESSION, expression); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/ArtifactModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/ArtifactModel.java new file mode 100644 index 000000000..b848122cf --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/ArtifactModel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard; + +import org.switchyard.config.model.Model; + +/** + * The "artifact" configuration model. + */ +public interface ArtifactModel extends Model { + + /** The "artifact" name. */ + public static final String ARTIFACT = "artifact"; + + /** The "name" name. */ + public static final String NAME = "name"; + + /** The "url" name. */ + public static final String URL = "url"; + + /** + * Gets the name attribute. + * @return the name attribute + */ + public String getName(); + + /** + * Sets the name attribute. + * @param name the name attribute + * @return this ArtifactModel (useful for chaining) + */ + public ArtifactModel setName(String name); + + /** + * Gets the url attribute. + * @return the url attribute + */ + public String getURL(); + + /** + * Sets the url attribute. + * @param url the url attribute + * @return this ArtifactModel (useful for chaining) + */ + public ArtifactModel setURL(String url); + + /** + * Gets the parent artifacts model. + * @return the parent artifacts model. + */ + public ArtifactsModel getArtifacts(); + + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/ArtifactsModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/ArtifactsModel.java new file mode 100644 index 000000000..61de8285c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/ArtifactsModel.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard; + +import java.util.List; + +import org.switchyard.config.model.Model; +/** + * The "artifacts" configuration model. + */ +public interface ArtifactsModel extends Model { + + /** The "artifacts" name. */ + public static final String ARTIFACTS = "artifacts"; + + /** + * Gets the parent switchyard model. + * @return the parent switchyard model + */ + public SwitchYardModel getSwitchYard(); + + /** + * Gets the child artifact models. + * @return the child artifact models + */ + public List getArtifacts(); + + /** + * Adds a child artifact model. + * @param artifact the child artifact model to add + * @return this ArtifactsModel (useful for chaining) + */ + public ArtifactsModel addArtifact(ArtifactModel artifact); + + /** + * Fetch a artifact model by name. + * @param name name of the artifact + * @return artifact with the specified name, or null if no such artifact exists + */ + public ArtifactModel getArtifact(String name); + + /** + * Removes a child artifact model. + * @param artifactName the name of the artifact + * @return the removed artifact or null if the named artifact was not present + */ + public ArtifactModel removeArtifact(String artifactName); +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/EsbInterfaceModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/EsbInterfaceModel.java new file mode 100644 index 000000000..c183b2991 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/EsbInterfaceModel.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.composite.InterfaceModel; + +/** + * An "esb" InterfaceModel. + */ +public interface EsbInterfaceModel extends InterfaceModel { + + /** + * The "esb" interface type. + */ + static final String ESB = "esb"; + + /** + * The "inputType" parameter name. + */ + static final String INPUT_TYPE = "inputType"; + + /** + * The "outputType" parameter name. + */ + static final String OUTPUT_TYPE = "outputType"; + + /** + * The "faultType" parameter name. + */ + static final String FAULT_TYPE = "faultType"; + + /** + * Returns the input type for the interface. + * @return input type + */ + QName getInputType(); + + /** + * Returns the output type for the interface. + * @return input type + */ + QName getOutputType(); + + /** + * Returns the fault type for the interface. + * @return input type + */ + QName getFaultType(); + + /** + * Sets the input type for the interface. + * @param input input type + * @return reference to this InterfaceModel + */ + EsbInterfaceModel setInputType(QName input); + + /** + * Sets the output type for the interface. + * @param output output type + * @return reference to this InterfaceModel + */ + EsbInterfaceModel setOutputType(QName output); + + /** + * Sets the fault type for the interface. + * @param fault fault type + * @return reference to this InterfaceModel + */ + EsbInterfaceModel setFaultType(QName fault); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/SwitchYardModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/SwitchYardModel.java new file mode 100644 index 000000000..7d0927ef2 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/SwitchYardModel.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard; + +import org.switchyard.config.model.NamedModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.domain.DomainModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.model.validate.ValidatesModel; + +/** + * The root "switchyard" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface SwitchYardModel extends NamedModel { + + /** The "switchyard" name. */ + public static final String SWITCHYARD = "switchyard"; + + /** + * Gets the child composite model. + * @return the child composite model + */ + public CompositeModel getComposite(); + + /** + * Sets the child composite model. + * @param composite the child composite model + * @return this SwitchYardModel (useful for chaining) + */ + public SwitchYardModel setComposite(CompositeModel composite); + + /** + * Gets the child transforms model. + * @return the child transforms model + */ + public TransformsModel getTransforms(); + + /** + * Sets the child transforms model. + * @param transforms the child transforms model. + * @return this SwitchYardModel (useful for chaining) + */ + public SwitchYardModel setTransforms(TransformsModel transforms); + + /** + * Gets the child validates model. + * @return the child validates model + */ + public ValidatesModel getValidates(); + + /** + * Sets the child artifacts model. + * @param artifacts the child artifacts model. + * @return this SwitchYardModel (useful for chaining) + */ + public SwitchYardModel setArtifacts(ArtifactsModel artifacts); + + /** + * Gets the child artifacts model. + * @return the child artifacts model + */ + public ArtifactsModel getArtifacts(); + + /** + * Sets the child validates model. + * @param validatesModel the child validates model. + * @return this SwitchYardModel (useful for chaining) + */ + public SwitchYardModel setValidates(ValidatesModel validatesModel); + + /** + * Gets the child domain model. + * @return the child domain model + */ + public DomainModel getDomain(); + + /** + * Sets the child domain model. + * @param domain the child domain model. + * @return this SwitchyardModel (useful for chaining) + */ + public SwitchYardModel setDomain(DomainModel domain); + + /** + * Sets the domain property resolver based on the current state of the model. + */ + public void setDomainPropertyResolver(); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/SwitchYardNamespace.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/SwitchYardNamespace.java new file mode 100644 index 000000000..a15bb7869 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/SwitchYardNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A SwitchYard config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum SwitchYardNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new SwitchYardNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + SwitchYardNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the SwitchYardNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the SwitchYardNamespace + */ + public static SwitchYardNamespace fromUri(String uri) { + return Util.fromUri(SwitchYardNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(SwitchYardNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-config:switchyard", version); + } + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/ThrottlingModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/ThrottlingModel.java new file mode 100644 index 000000000..663a44f1f --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/ThrottlingModel.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard; + +import org.switchyard.config.model.Model; + +/** + * The "throttling" configuration model. + */ +public interface ThrottlingModel extends Model { + + /** The "throttling" name. */ + public static final String THROTTLING = "throttling"; + + /** The "timePeriod" attribute. */ + public static final String TIME_PERIOD = "timePeriod"; + + /** The "maxRequests" attribute. */ + public static final String MAX_REQUESTS = "maxRequests"; + + /** + * Gets the timePeriod attribute. + * @return the timePeriod attribute + */ + public Long getTimePeriod(); + + /** + * Sets the timePeriod attribute. + * @param timePeriod the timePeriod attribute + * @return this ThrottlingModel (useful for chaining) + */ + public ThrottlingModel setTimePeriod(Long timePeriod); + + /** + * Gets the maxRequests attribute. + * @return the maxRequests attribute + */ + public int getMaxRequests(); + + /** + * Sets the maxRequests attribute. + * @param maxRequests the timePeriod attribute + * @return this ThrottlingModel (useful for chaining) + */ + public ThrottlingModel setMaxRequests(int maxRequests); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ArtifactModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ArtifactModel.java new file mode 100644 index 000000000..e04e36538 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ArtifactModel.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.switchyard.ArtifactModel; +import org.switchyard.config.model.switchyard.ArtifactsModel; + +/** + * Implementation of ArtifactModel : v1. + */ +public class V1ArtifactModel extends BaseModel implements ArtifactModel { + + /** + * Constructs a new V1ArtifactModel. + * @param namespace namespace + */ + public V1ArtifactModel(String namespace) { + super(new QName(namespace, ArtifactModel.ARTIFACT)); + } + + /** + * Constructs a new V1ArtifactModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ArtifactModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public ArtifactsModel getArtifacts() { + return (ArtifactsModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return getModelAttribute(ArtifactModel.NAME); + } + + /** + * {@inheritDoc} + */ + @Override + public ArtifactModel setName(String name) { + setModelAttribute(ArtifactModel.NAME, name); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getURL() { + return getModelAttribute(ArtifactModel.URL); + } + + /** + * {@inheritDoc} + */ + @Override + public ArtifactModel setURL(String url) { + setModelAttribute(ArtifactModel.URL, url); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ArtifactsModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ArtifactsModel.java new file mode 100644 index 000000000..7dd73a7de --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ArtifactsModel.java @@ -0,0 +1,115 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard.v1; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.switchyard.ArtifactModel; +import org.switchyard.config.model.switchyard.ArtifactsModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * A version 1 ArtifactsModel. + */ +public class V1ArtifactsModel extends BaseModel implements ArtifactsModel { + + private List _artifacts = new ArrayList(); + + /** + * Constructs a new V1ArtifactsModel. + * @param namespace namespace + */ + public V1ArtifactsModel(String namespace) { + super(new QName(namespace, ArtifactsModel.ARTIFACTS)); + setModelChildrenOrder(ArtifactModel.ARTIFACT); + } + + /** + * Constructs a new V1ArtifactsModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ArtifactsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration artifact_config : config.getChildrenStartsWith(ArtifactModel.ARTIFACT)) { + ArtifactModel artifact = (ArtifactModel)readModel(artifact_config); + if (artifact != null) { + _artifacts.add(artifact); + } + } + setModelChildrenOrder(ArtifactModel.ARTIFACT); + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel getSwitchYard() { + return (SwitchYardModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getArtifacts() { + return Collections.unmodifiableList(_artifacts); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized ArtifactsModel addArtifact(ArtifactModel artifact) { + addChildModel(artifact); + _artifacts.add(artifact); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ArtifactModel getArtifact(String name) { + ArtifactModel artifact = null; + for (ArtifactModel a : _artifacts) { + if (a.getName().equals(name)) { + artifact = a; + break; + } + } + return artifact; + } + + @Override + public ArtifactModel removeArtifact(String artifactName) { + ArtifactModel removed = null; + + for (ArtifactModel artifact : _artifacts) { + if (artifact.getName().equals(artifactName)) { + removed = artifact; + _artifacts.remove(artifact); + } + } + return removed; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1EsbInterfaceModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1EsbInterfaceModel.java new file mode 100644 index 000000000..b461ecf12 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1EsbInterfaceModel.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1InterfaceModel; +import org.switchyard.config.model.switchyard.EsbInterfaceModel; + +/** + * An "esb" implementation of InterfaceModel. + */ +public class V1EsbInterfaceModel extends V1InterfaceModel implements EsbInterfaceModel { + + /** + * Default constructor for application use. + */ + public V1EsbInterfaceModel() { + super(ESB); + } + + /** + * Constructor for Marshaller use. + * + * @param config the Configuration + * @param desc the Descriptor + */ + public V1EsbInterfaceModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public QName getInputType() { + return getQName(getModelAttribute(INPUT_TYPE)); + } + + @Override + public QName getOutputType() { + return getQName(getModelAttribute(OUTPUT_TYPE)); + } + + @Override + public QName getFaultType() { + return getQName(getModelAttribute(FAULT_TYPE)); + } + + @Override + public EsbInterfaceModel setInputType(QName input) { + setModelAttribute(INPUT_TYPE, input.toString()); + return this; + } + + @Override + public EsbInterfaceModel setOutputType(QName output) { + setModelAttribute(OUTPUT_TYPE, output.toString()); + return this; + } + + @Override + public EsbInterfaceModel setFaultType(QName fault) { + setModelAttribute(FAULT_TYPE, fault.toString()); + return this; + } + + private QName getQName(String name) { + return name == null ? null : QName.valueOf(name); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1SwitchYardMarshaller.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1SwitchYardMarshaller.java new file mode 100644 index 000000000..7ebae4b2d --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1SwitchYardMarshaller.java @@ -0,0 +1,126 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.domain.DomainModel; +import org.switchyard.config.model.domain.SecuritiesModel; +import org.switchyard.config.model.domain.SecurityModel; +import org.switchyard.config.model.domain.v1.V1DomainModel; +import org.switchyard.config.model.domain.v1.V1SecuritiesModel; +import org.switchyard.config.model.domain.v1.V1SecurityModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.property.PropertyModel; +import org.switchyard.config.model.property.v1.V1PropertiesModel; +import org.switchyard.config.model.property.v1.V1PropertyModel; +import org.switchyard.config.model.resource.ResourceDetailModel; +import org.switchyard.config.model.resource.ResourceModel; +import org.switchyard.config.model.resource.ResourcesModel; +import org.switchyard.config.model.resource.v1.V1ResourceDetailModel; +import org.switchyard.config.model.resource.v1.V1ResourceModel; +import org.switchyard.config.model.resource.v1.V1ResourcesModel; +import org.switchyard.config.model.selector.JavaOperationSelectorModel; +import org.switchyard.config.model.selector.OperationSelectorModel; +import org.switchyard.config.model.selector.RegexOperationSelectorModel; +import org.switchyard.config.model.selector.XPathOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1JavaOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1RegexOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1StaticOperationSelectorModel; +import org.switchyard.config.model.selector.v1.V1XPathOperationSelectorModel; +import org.switchyard.config.model.switchyard.ArtifactModel; +import org.switchyard.config.model.switchyard.ArtifactsModel; +import org.switchyard.config.model.switchyard.EsbInterfaceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.ThrottlingModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.model.transform.v1.V1TransformsModel; +import org.switchyard.config.model.validate.ValidatesModel; +import org.switchyard.config.model.validate.v1.V1ValidatesModel; + +/** + * Marshalls switchyard Models. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1SwitchYardMarshaller extends BaseMarshaller { + + /** + * The complete local name "interface.esb". + */ + private static final String INTERFACE_ESB = InterfaceModel.INTERFACE + "." + EsbInterfaceModel.ESB; + + /** + * Constructs a new V1SwitchYardMarshaller with the specified Descriptor. + * @param desc the Descriptor + */ + public V1SwitchYardMarshaller(Descriptor desc) { + super(desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(SwitchYardModel.SWITCHYARD)) { + return new V1SwitchYardModel(config, desc); + } else if (name.equals(TransformsModel.TRANSFORMS)) { + return new V1TransformsModel(config, desc); + } else if (name.equals(ValidatesModel.VALIDATES)) { + return new V1ValidatesModel(config, desc); + } else if (name.equals(ArtifactsModel.ARTIFACTS)) { + return new V1ArtifactsModel(config, desc); + } else if (name.equals(ArtifactModel.ARTIFACT)) { + return new V1ArtifactModel(config, desc); + } else if (name.equals(PropertiesModel.PROPERTIES)) { + return new V1PropertiesModel(config, desc); + } else if (name.equals(PropertyModel.PROPERTY)) { + return new V1PropertyModel(config, desc); + } else if (name.equals(SecuritiesModel.SECURITIES)) { + return new V1SecuritiesModel(config, desc); + } else if (name.equals(SecurityModel.SECURITY)) { + return new V1SecurityModel(config, desc); + } else if (name.equals(DomainModel.DOMAIN)) { + return new V1DomainModel(config, desc); + } else if (name.equals(ResourcesModel.RESOURCES)) { + return new V1ResourcesModel(config, desc); + } else if (name.equals(ResourceModel.RESOURCE)) { + return new V1ResourceModel(config, desc); + } else if (name.equals(ResourceDetailModel.RESOURCE_DETAIL)) { + return new V1ResourceDetailModel(config, desc); + } else if (name.equals(ThrottlingModel.THROTTLING)) { + return new V1ThrottlingModel(config, desc); + } else if (name.equals(INTERFACE_ESB)) { + return new V1EsbInterfaceModel(config, desc); + } else if (name.startsWith(OperationSelectorModel.OPERATION_SELECTOR)) { + if (name.equals(OperationSelectorModel.OPERATION_SELECTOR)) { + return new V1StaticOperationSelectorModel(config, desc); + } else if (name.endsWith(XPathOperationSelectorModel.XPATH)) { + return new V1XPathOperationSelectorModel(config, desc); + } else if (name.endsWith(RegexOperationSelectorModel.REGEX)) { + return new V1RegexOperationSelectorModel(config, desc); + } else if (name.endsWith(JavaOperationSelectorModel.JAVA)) { + return new V1JavaOperationSelectorModel(config, desc); + } + } + return null; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1SwitchYardModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1SwitchYardModel.java new file mode 100644 index 000000000..b9d0f593b --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1SwitchYardModel.java @@ -0,0 +1,186 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard.v1; + +import org.switchyard.common.property.CompoundPropertyResolver; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.domain.DomainModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.switchyard.ArtifactsModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.model.validate.ValidatesModel; + +/** + * A version 1 SwitchYardModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1SwitchYardModel extends BaseNamedModel implements SwitchYardModel { + + private CompositeModel _composite; + private ArtifactsModel _artifacts; + private TransformsModel _transforms; + private ValidatesModel _validates; + private DomainModel _domain; + + /** + * Constructs a new V1SwitchYardModel. + * @param namespace the namespace + */ + public V1SwitchYardModel(String namespace) { + super(namespace, SwitchYardModel.SWITCHYARD); + setModelChildrenOrder(CompositeModel.COMPOSITE, TransformsModel.TRANSFORMS, ValidatesModel.VALIDATES, DomainModel.DOMAIN, ArtifactsModel.ARTIFACTS); + setDomainPropertyResolver(); + } + + /** + * Constructs a new V1SwitchYardModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1SwitchYardModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(CompositeModel.COMPOSITE, TransformsModel.TRANSFORMS, ValidatesModel.VALIDATES, DomainModel.DOMAIN, ArtifactsModel.ARTIFACTS); + setDomainPropertyResolver(); + } + + /** + * {@inheritDoc} + */ + @Override + public CompositeModel getComposite() { + if (_composite == null) { + _composite = (CompositeModel)getFirstChildModelStartsWith(CompositeModel.COMPOSITE); + } + return _composite; + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel setComposite(CompositeModel composite) { + setChildModel(composite); + _composite = composite; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public TransformsModel getTransforms() { + if (_transforms == null) { + _transforms = (TransformsModel)getFirstChildModelStartsWith(TransformsModel.TRANSFORMS); + } + return _transforms; + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel setTransforms(TransformsModel transforms) { + setChildModel(transforms); + _transforms = transforms; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ValidatesModel getValidates() { + if (_validates == null) { + _validates = (ValidatesModel)getFirstChildModelStartsWith(ValidatesModel.VALIDATES); + } + return _validates; + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel setValidates(ValidatesModel validatesModel) { + setChildModel(validatesModel); + _validates = validatesModel; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public ArtifactsModel getArtifacts() { + if (_artifacts == null) { + _artifacts = (ArtifactsModel)getFirstChildModelStartsWith(ArtifactsModel.ARTIFACTS); + } + return _artifacts; + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel setArtifacts(ArtifactsModel artifactsModel) { + setChildModel(artifactsModel); + _artifacts = artifactsModel; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public DomainModel getDomain() { + if (_domain == null) { + _domain = (DomainModel)getFirstChildModelStartsWith(DomainModel.DOMAIN); + } + return _domain; + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel setDomain(DomainModel domain) { + setChildModel(domain); + _domain = domain; + setDomainPropertyResolver(); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public void setDomainPropertyResolver() { + DomainModel domain = getDomain(); + if (domain != null) { + PropertiesModel properties = domain.getProperties(); + if (properties != null) { + Configuration config = getModelConfiguration(); + config.setPropertyResolver(CompoundPropertyResolver.compact(config.getPropertyResolver(), properties)); + } + } + if (_composite != null) { + _composite.setCompositePropertyResolver(); + } + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ThrottlingModel.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ThrottlingModel.java new file mode 100644 index 000000000..9ecc9f35c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/v1/V1ThrottlingModel.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.switchyard.ThrottlingModel; + +/** + * Implementation of ThrottlingModel : v1. + */ +public class V1ThrottlingModel extends BaseModel implements ThrottlingModel { + + /** + * Constructs a new V1ThrottlingModel. + * @param namespace namespace + */ + public V1ThrottlingModel(String namespace) { + super(new QName(namespace, ThrottlingModel.THROTTLING)); + } + + /** + * Constructs a new V1ThrottlingModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ThrottlingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Long getTimePeriod() { + final String value = getModelAttribute(ThrottlingModel.TIME_PERIOD); + return value == null ? null : Long.valueOf(value); + } + + /** + * {@inheritDoc} + */ + @Override + public ThrottlingModel setTimePeriod(Long timePeriod) { + setModelAttribute(ThrottlingModel.TIME_PERIOD, timePeriod == null ? null : timePeriod.toString()); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public int getMaxRequests() { + return Integer.valueOf(getModelAttribute(ThrottlingModel.MAX_REQUESTS)); + } + + /** + * {@inheritDoc} + */ + @Override + public ThrottlingModel setMaxRequests(int maxRequests) { + setModelAttribute(ThrottlingModel.MAX_REQUESTS, String.valueOf(maxRequests)); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/switchyard/v2/V2SwitchYardMarshaller.java b/core/config/src/main/java/org/switchyard/config/model/switchyard/v2/V2SwitchYardMarshaller.java new file mode 100644 index 000000000..fa8878577 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/switchyard/v2/V2SwitchYardMarshaller.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard.v2; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.property.v2.V2PropertiesModel; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardMarshaller; + +/** + * Marshalls v2 switchyard Models. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2SwitchYardMarshaller extends V1SwitchYardMarshaller { + + /** + * Constructs a new V2SwitchYardMarshaller with the specified Descriptor. + * @param desc the Descriptor + */ + public V2SwitchYardMarshaller(Descriptor desc) { + super(desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(PropertiesModel.PROPERTIES)) { + return new V2PropertiesModel(config, desc); + } + return super.read(config); + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/transform/TransformModel.java b/core/config/src/main/java/org/switchyard/config/model/transform/TransformModel.java new file mode 100644 index 000000000..90e385d2c --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/transform/TransformModel.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.transform; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.Model; + +/** + * The "transform" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface TransformModel extends Model { + + /** The "transform" name. */ + public static final String TRANSFORM = "transform"; + + /** The "from" name. */ + public static final String FROM = "from"; + + /** The "to" name. */ + public static final String TO = "to"; + + /** + * Gets the parent transforms model. + * @return the parent transforms model. + */ + public TransformsModel getTransforms(); + + /** + * Gets the from attribute. + * @return the from attribute + */ + public QName getFrom(); + + /** + * Sets the from attribute. + * @param from the from attribute + * @return this TransformModel (useful for chaining) + */ + public TransformModel setFrom(QName from); + + /** + * Gets the to attribute. + * @return the to attribute + */ + public QName getTo(); + + /** + * Sets the to attribute. + * @param to the to attribute + * @return this TransformModel (useful for chaining) + */ + public TransformModel setTo(QName to); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/transform/TransformsModel.java b/core/config/src/main/java/org/switchyard/config/model/transform/TransformsModel.java new file mode 100644 index 000000000..d2ac3b0ea --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/transform/TransformsModel.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.transform; + +import java.util.List; + +import org.switchyard.config.model.Model; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * The "transforms" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface TransformsModel extends Model { + + /** The "transforms" name. */ + public static final String TRANSFORMS = "transforms"; + + /** + * Gets the parent switchyard model. + * @return the parent switchyard model + */ + public SwitchYardModel getSwitchYard(); + + /** + * Gets the child transform models. + * @return the child transform models + */ + public List getTransforms(); + + /** + * Adds a child transform model. + * @param transform the child transform model to add + * @return this TransformsModel (useful for chaining) + */ + public TransformsModel addTransform(TransformModel transform); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/transform/v1/V1BaseTransformModel.java b/core/config/src/main/java/org/switchyard/config/model/transform/v1/V1BaseTransformModel.java new file mode 100644 index 000000000..86c6ac3f1 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/transform/v1/V1BaseTransformModel.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.transform.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseTypedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.TransformsModel; + +/** + * An abstract representation of a TransformModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public abstract class V1BaseTransformModel extends BaseTypedModel implements TransformModel { + + protected V1BaseTransformModel(String namespace, String type) { + this(new QName(namespace, TransformModel.TRANSFORM + '.' + type)); + } + + protected V1BaseTransformModel(QName qname) { + super(qname); + } + + protected V1BaseTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public TransformsModel getTransforms() { + return (TransformsModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public QName getFrom() { + return XMLHelper.createQName(getModelAttribute(TransformModel.FROM)); + } + + /** + * {@inheritDoc} + */ + @Override + public TransformModel setFrom(QName from) { + setModelAttribute(TransformModel.FROM, from != null ? from.toString() : null); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public QName getTo() { + return XMLHelper.createQName(getModelAttribute(TransformModel.TO)); + } + + /** + * {@inheritDoc} + */ + @Override + public TransformModel setTo(QName to) { + setModelAttribute(TransformModel.TO, to != null ? to.toString() : null); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/transform/v1/V1TransformsModel.java b/core/config/src/main/java/org/switchyard/config/model/transform/v1/V1TransformsModel.java new file mode 100644 index 000000000..b627ffc95 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/transform/v1/V1TransformsModel.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.transform.v1; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.TransformsModel; + +/** + * A version 1 TransformsModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1TransformsModel extends BaseModel implements TransformsModel { + + private List _transforms = new ArrayList(); + + /** + * Constructs a new V1TransformsModel. + * @param namespace namespace + */ + public V1TransformsModel(String namespace) { + super(new QName(namespace, TransformsModel.TRANSFORMS)); + setModelChildrenOrder(TransformModel.TRANSFORM); + } + + /** + * Constructs a new V1TransformsModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1TransformsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration transform_config : config.getChildrenStartsWith(TransformModel.TRANSFORM)) { + TransformModel transform = (TransformModel)readModel(transform_config); + if (transform != null) { + _transforms.add(transform); + } + } + setModelChildrenOrder(TransformModel.TRANSFORM); + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel getSwitchYard() { + return (SwitchYardModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getTransforms() { + return Collections.unmodifiableList(_transforms); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized TransformsModel addTransform(TransformModel transform) { + addChildModel(transform); + _transforms.add(transform); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/validate/ValidateModel.java b/core/config/src/main/java/org/switchyard/config/model/validate/ValidateModel.java new file mode 100644 index 000000000..3567b64c2 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/validate/ValidateModel.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.validate; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.Model; + +/** + * The "validate" configuration model. + * + * @author Tomohisa Igarashi + */ +public interface ValidateModel extends Model { + + /** The "validate" name. */ + public static final String VALIDATE = "validate"; + + /** The "name" name. */ + public static final String NAME = "name"; + + /** + * Gets the parent validates model. + * @return the parent validates model. + */ + public ValidatesModel getValidates(); + + /** + * Gets the name attribute. + * @return the name attribute + */ + public QName getName(); + + /** + * Sets the name attribute. + * @param name the name attribute + * @return this ValidateModel (useful for chaining) + */ + public ValidateModel setName(QName name); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/validate/ValidatesModel.java b/core/config/src/main/java/org/switchyard/config/model/validate/ValidatesModel.java new file mode 100644 index 000000000..ba0b90ad3 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/validate/ValidatesModel.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.validate; + +import java.util.List; + +import org.switchyard.config.model.Model; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * The "validates" configuration model. + * + * @author Tomohisa Igarashi + */ +public interface ValidatesModel extends Model { + + /** The "validates" name. */ + public static final String VALIDATES = "validates"; + + /** + * Gets the parent switchyard model. + * @return the parent switchyard model + */ + public SwitchYardModel getSwitchYard(); + + /** + * Gets the child validate models. + * @return the child validate models + */ + public List getValidates(); + + /** + * Adds a child validate model. + * @param validate the child validate model to add + * @return this ValidatesModel (useful for chaining) + */ + public ValidatesModel addValidate(ValidateModel validate); + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/validate/v1/V1BaseValidateModel.java b/core/config/src/main/java/org/switchyard/config/model/validate/v1/V1BaseValidateModel.java new file mode 100644 index 000000000..77d81d3a4 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/validate/v1/V1BaseValidateModel.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.validate.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseTypedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.ValidatesModel; + +/** + * An abstract representation of a ValidateModel. + * + * @author Tomohisa Igarashi + */ +public abstract class V1BaseValidateModel extends BaseTypedModel implements ValidateModel { + + protected V1BaseValidateModel(String namespace, String type) { + this(new QName(namespace, ValidateModel.VALIDATE + '.' + type)); + } + + protected V1BaseValidateModel(QName qname) { + super(qname); + } + + protected V1BaseValidateModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public ValidatesModel getValidates() { + return (ValidatesModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public QName getName() { + return XMLHelper.createQName(getModelAttribute(ValidateModel.NAME)); + } + + /** + * {@inheritDoc} + */ + @Override + public ValidateModel setName(QName name) { + setModelAttribute(ValidateModel.NAME, name != null ? name.toString() : null); + return this; + } + +} diff --git a/core/config/src/main/java/org/switchyard/config/model/validate/v1/V1ValidatesModel.java b/core/config/src/main/java/org/switchyard/config/model/validate/v1/V1ValidatesModel.java new file mode 100644 index 000000000..72d952683 --- /dev/null +++ b/core/config/src/main/java/org/switchyard/config/model/validate/v1/V1ValidatesModel.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.validate.v1; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.ValidatesModel; + +/** + * A version 1 ValidatesModel. + * + * @author Tomohisa Igarashi + */ +public class V1ValidatesModel extends BaseModel implements ValidatesModel { + + private List _validates = new ArrayList(); + + /** + * Constructs a new V1ValidatesModel. + * @param namespace namespace + */ + public V1ValidatesModel(String namespace) { + super(new QName(namespace, ValidatesModel.VALIDATES)); + setModelChildrenOrder(ValidateModel.VALIDATE); + } + + /** + * Constructs a new V1ValidatesModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1ValidatesModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration validate_config : config.getChildrenStartsWith(ValidateModel.VALIDATE)) { + ValidateModel validate = (ValidateModel)readModel(validate_config); + if (validate != null) { + _validates.add(validate); + } + } + setModelChildrenOrder(ValidateModel.VALIDATE); + } + + /** + * {@inheritDoc} + */ + @Override + public SwitchYardModel getSwitchYard() { + return (SwitchYardModel)getModelParent(); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized List getValidates() { + return Collections.unmodifiableList(_validates); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized ValidatesModel addValidate(ValidateModel validate) { + addChildModel(validate); + _validates.add(validate); + return this; + } + +} diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-1.1-cd06.xsd new file mode 100644 index 000000000..bd376f51b --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-1.1-cd06.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ejb-1.1-cd02-rev2.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ejb-1.1-cd02-rev2.xsd new file mode 100644 index 000000000..0b388fcf1 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ejb-1.1-cd02-rev2.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-jca-1.1-cd04-rev2.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-jca-1.1-cd04-rev2.xsd new file mode 100644 index 000000000..75446411d --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-jca-1.1-cd04-rev2.xsd @@ -0,0 +1,169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-jms-1.1-csd05.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-jms-1.1-csd05.xsd new file mode 100644 index 000000000..8e303f3a3 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-jms-1.1-csd05.xsd @@ -0,0 +1,212 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-sca-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-sca-1.1-cd06.xsd new file mode 100644 index 000000000..9cc22601b --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-sca-1.1-cd06.xsd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ws-1.1-cd04-rev2.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ws-1.1-cd04-rev2.xsd new file mode 100644 index 000000000..f080e4ef4 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ws-1.1-cd04-rev2.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ws-callback-1.1-cd04-rev1.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ws-callback-1.1-cd04-rev1.xsd new file mode 100644 index 000000000..7d5482e9f --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-binding-ws-callback-1.1-cd04-rev1.xsd @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-1.1-cd06.xsd new file mode 100644 index 000000000..a3dea7eab --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-1.1-cd06.xsd @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-c-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-c-1.1-cd06.xsd new file mode 100644 index 000000000..f2fbdee6f --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-c-1.1-cd06.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-cpp-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-cpp-1.1-cd06.xsd new file mode 100644 index 000000000..816f5af5a --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-cpp-1.1-cd06.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-java-1.1-csd03.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-java-1.1-csd03.xsd new file mode 100644 index 000000000..89b90965a --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-contribution-java-1.1-csd03.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-core-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-core-1.1-cd06.xsd new file mode 100644 index 000000000..668e3b1ce --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-core-1.1-cd06.xsd @@ -0,0 +1,468 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-definitions-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-definitions-1.1-cd06.xsd new file mode 100644 index 000000000..478142113 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-definitions-1.1-cd06.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-bpel-1.1-cd03.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-bpel-1.1-cd03.xsd new file mode 100644 index 000000000..e450ec067 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-bpel-1.1-cd03.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-c-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-c-1.1-cd06.xsd new file mode 100644 index 000000000..eb0fe8b50 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-c-1.1-cd06.xsd @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-composite-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-composite-1.1-cd06.xsd new file mode 100644 index 000000000..77ef5f3b0 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-composite-1.1-cd06.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-cpp-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-cpp-1.1-cd06.xsd new file mode 100644 index 000000000..d174c5c3d --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-cpp-1.1-cd06.xsd @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-java-1.1-csd03.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-java-1.1-csd03.xsd new file mode 100644 index 000000000..4fbbff25e --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-java-1.1-csd03.xsd @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-spring-1.1-csd01.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-spring-1.1-csd01.xsd new file mode 100644 index 000000000..279b9abdb --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-implementation-spring-1.1-csd01.xsd @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-c-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-c-1.1-cd06.xsd new file mode 100644 index 000000000..ed4f27a21 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-c-1.1-cd06.xsd @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-cpp-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-cpp-1.1-cd06.xsd new file mode 100644 index 000000000..e10c98bc7 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-cpp-1.1-cd06.xsd @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-java-1.1-csd05.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-java-1.1-csd05.xsd new file mode 100644 index 000000000..a505ddd3f --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-java-1.1-csd05.xsd @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-wsdl-1.1-cd06.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-wsdl-1.1-cd06.xsd new file mode 100644 index 000000000..d90d5197b --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-interface-wsdl-1.1-cd06.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-policy-1.1-cd04.xsd b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-policy-1.1-cd04.xsd new file mode 100644 index 000000000..8de738cf7 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-policy-1.1-cd04.xsd @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-policy-1.1-intents-definitions-cd04.xml b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-policy-1.1-intents-definitions-cd04.xml new file mode 100644 index 000000000..87505e766 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/ns/opencsa/sca/200912/sca-policy-1.1-intents-definitions-cd04.xml @@ -0,0 +1,249 @@ + + + + + + + + Communication through the binding requires that the + server is authenticated by the client + + + + + + + + Communication through the binding requires that the + client is authenticated by the server + + + + + + + + A convenience intent to help migration + + + + + + Communication through the binding requires that the + client and server to authenticate each other + + + + + + Communication through the binding prevents unauthorized + users from reading the messages + + + + + + + + Communication through the binding prevents tampering + with the messages sent between the client and the service. + + + + + + + + Ensures clients are authorized to use services. + + + + + + + + This intent is used to indicate that a message sent + by a client is always delivered to the component. + + + + + + This intent is used to indicate that a message that was + successfully sent by a client is not delivered more than + once to the component. + + + + + + This profile intent is used to indicate that a message sent + by a client is always delivered to the component. It also + indicates that duplicate messages are not delivered to the + component. + + + + + + This intent is used to indicate that all the messages are + delivered to the component in the order they were sent by + the client. + + + + + + + A managed transaction environment is necessary in order to + run the component. The specific type of managed transaction + needed is not constrained. + + + + For a component marked with managedTransaction.global + a global transaction needs to be present before dispatching + any method on the component - using any transaction + propagated from the client or else beginning and completing + a new transaction. + + + + + A component marked with managedTransaction.local needs to + run within a local transaction containment (LTC) that + is started and ended by the SCA runtime. + + + + + + + A component marked with noManagedTransaction needs to run without + a managed transaction, under neither a global transaction nor + an LTC. A transaction propagated to the hosting SCA runtime + is not joined by the hosting runtime on behalf of a + component marked with noManagedtransaction. + + + + + + For a reference marked as transactedOneWay any OneWay invocation + messages are transacted as part of a client global + transaction. + For a service marked as transactedOneWay any OneWay invocation + message are received from the transport binding in a + transacted fashion, under the service’s global transaction. + + + + + + For a reference indicates that any OneWay invocation messages + are sent immediately regardless of any client transaction. + For a service indicates that any OneWay invocation is + received immediately regardless of any target service + transaction. + + + + + + A service marked with propagatesTransaction is dispatched + under any propagated (client) transaction and the service binding + needs to be capable of receiving a transaction context. + A reference marked with propagatesTransaction propagates any + transaction context under which the client runs when the + reference is used for a request-response interaction and the + binding of a reference marked with propagatesTransaction needs to + be capable of propagating a transaction context. + + + + + + A service marked with suspendsTransaction is not dispatched + under any propagated (client) transaction. + A reference marked with suspendsTransaction does not propagate + any transaction context under which the client runs when the + reference is used. + + + + + + Used to indicate that the component requires both the + managedTransaction.global and the propagatesTransactions + intents + + + + + + + Indicates that request/response operations for the + interface of this wire are "long running" and must be + treated as two separate message transmissions + + + + + + Specifies that the EJB API is needed to communicate with + the service or reference. + + + + + + Specifies that the SOAP messaging model is used for delivering + messages. + + + + + + + + Requires that the messages are delivered and received via the + JMS API. + + + + + + This intent can only be used on a reference. Indicates that the + client is not able to handle new inbound connections. The binding + and callback binding are configured so that any + response or callback comes either through a back channel of the + connection from the client to the server or by having the client + poll the server for messages. + + + + \ No newline at end of file diff --git a/core/config/src/main/resources/org/oasis-open/docs/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd b/core/config/src/main/resources/org/oasis-open/docs/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd new file mode 100644 index 000000000..71f9b129d --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd @@ -0,0 +1,195 @@ + + + + + + + + + This type represents an element with arbitrary attributes. + + + + + + + + + + + This type is used for password elements per Section 4.1. + + + + + + + + + + This type is used for elements containing stringified binary data. + + + + + + + + + + This type represents a username token per Section 4.1 + + + + + + + + + + + A security token that is encoded in binary + + + + + + + + + + A security token key identifier + + + + + + + + + + Typedef to allow a list of usages (as URIs). + + + + + + This global attribute is used to indicate the usage of a referenced or indicated token within the containing context + + + + + This type represents a reference to an external security token. + + + + + + + + This type represents a reference to an embedded security token. + + + + + + + + + + This type is used reference a security token. + + + + + + + + + + + This complexType defines header block to use for security-relevant data directed at a specific SOAP actor. + + + + + The use of "any" is to allow extensibility and different forms of security data. + + + + + + + + This complexType defines a container for elements to be specified from any namespace as properties/parameters of a DSIG transformation. + + + + + The use of "any" is to allow extensibility from any namespace. + + + + + + + + This element defines the wsse:UsernameToken element per Section 4.1. + + + + + This element defines the wsse:BinarySecurityToken element per Section 4.2. + + + + + This element defines a security token reference + + + + + This element defines a security token embedded reference + + + + + This element defines a key identifier reference + + + + + This element defines the wsse:SecurityTokenReference per Section 4.3. + + + + + This element defines the wsse:Security SOAP header element per Section 4. + + + + + This element contains properties for transformations from any namespace, including DSIG. + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/oasis-open/docs/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd b/core/config/src/main/resources/org/oasis-open/docs/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd new file mode 100644 index 000000000..a8b6452d4 --- /dev/null +++ b/core/config/src/main/resources/org/oasis-open/docs/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd @@ -0,0 +1,105 @@ + + + + + + + +This type defines the fault code value for Timestamp message expiration. + + + + + + + + + + +This global attribute supports annotating arbitrary elements with an ID. + + + + + + +Convenience attribute group used to simplify this schema. + + + + + + + + + +This type is for elements whose [children] is a psuedo-dateTime and can have arbitrary attributes. + + + + + + + + + + + +This type is for elements whose [children] is an anyURI and can have arbitrary attributes. + + + + + + + + + + + + +This complex type ties together the timestamp related elements into a composite type. + + + + + + + + + + + + + + +This element allows Timestamps to be applied anywhere element wildcards are present, +including as a SOAP header. + + + + + + + +This element allows an expiration time to be applied anywhere element wildcards are present. + + + + + + +This element allows a creation time to be applied anywhere element wildcards are present. + + + + diff --git a/core/config/src/main/resources/org/switchyard/config/model/descriptor.properties b/core/config/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..ecc923bb8 --- /dev/null +++ b/core/config/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,39 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +swyd_1_0.section=urn:switchyard-config:switchyard +swyd_1_0.version=1.0 +swyd_1_0.namespace=urn:switchyard-config:switchyard:1.0 +swyd_1_0.schema=switchyard_1_0.xsd +swyd_1_0.location=/org/switchyard/config/model/switchyard/v1/ +swyd_1_0.marshaller=org.switchyard.config.model.switchyard.v1.V1SwitchYardMarshaller + +swyd_1_1.section=urn:switchyard-config:switchyard +swyd_1_1.version=1.1 +swyd_1_1.namespace=urn:switchyard-config:switchyard:1.1 +swyd_1_1.schema=switchyard_1_1.xsd +swyd_1_1.location=/org/switchyard/config/model/switchyard/v1/ +swyd_1_1.marshaller=org.switchyard.config.model.switchyard.v1.V1SwitchYardMarshaller + +swyd_2_0.section=urn:switchyard-config:switchyard +swyd_2_0.version=2.0 +swyd_2_0.namespace=urn:switchyard-config:switchyard:2.0 +swyd_2_0.schema=switchyard_2_0.xsd +swyd_2_0.location=/org/switchyard/config/model/switchyard/v2/ +swyd_2_0.marshaller=org.switchyard.config.model.switchyard.v2.V2SwitchYardMarshaller + +sca_1_1.section=http://docs.oasis-open.org/ns/opencsa/sca +sca_1_1.version=1.1 +sca_1_1.namespace=http://docs.oasis-open.org/ns/opencsa/sca/200912 +sca_1_1.schema=sca-1.1-cd06.xsd +sca_1_1.location=/org/oasis-open/docs/ns/opencsa/sca/200912/ +sca_1_1.marshaller=org.switchyard.config.model.composite.v1.V1CompositeMarshaller diff --git a/core/config/src/main/resources/org/switchyard/config/model/switchyard/v1/switchyard_1_0.xsd b/core/config/src/main/resources/org/switchyard/config/model/switchyard/v1/switchyard_1_0.xsd new file mode 100644 index 000000000..a995a07cd --- /dev/null +++ b/core/config/src/main/resources/org/switchyard/config/model/switchyard/v1/switchyard_1_0.xsd @@ -0,0 +1,291 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Static Operation Selector Configuration. + + + + + + + + Operation name. + + + + + + + + + + + + XPath Operation Selector Configuration. + + + + + + + + XPath expression. + + + + + + + + + + + + XPath Operation Selector Configuration. + + + + + + + + Regex expression. + + + + + + + + + + + + Java Operation Selector Configuration. + + + + + + + + operation selector implementation class name. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SCA extension for configuring throttling details. + + + + + + The time period in milliseconds over which requests are counted. Defaults to 1000 (1 second). + + + + + + + The maximum number of requests which can be processed during the specified timePeriod. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/switchyard/config/model/switchyard/v1/switchyard_1_1.xsd b/core/config/src/main/resources/org/switchyard/config/model/switchyard/v1/switchyard_1_1.xsd new file mode 100644 index 000000000..822419fe3 --- /dev/null +++ b/core/config/src/main/resources/org/switchyard/config/model/switchyard/v1/switchyard_1_1.xsd @@ -0,0 +1,291 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Static Operation Selector Configuration. + + + + + + + + Operation name. + + + + + + + + + + + + XPath Operation Selector Configuration. + + + + + + + + XPath expression. + + + + + + + + + + + + XPath Operation Selector Configuration. + + + + + + + + Regex expression. + + + + + + + + + + + + Java Operation Selector Configuration. + + + + + + + + operation selector implementation class name. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SCA extension for configuring throttling details. + + + + + + The time period in milliseconds over which requests are counted. Defaults to 1000 (1 second). + + + + + + + The maximum number of requests which can be processed during the specified timePeriod. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/switchyard/config/model/switchyard/v2/switchyard_2_0.xsd b/core/config/src/main/resources/org/switchyard/config/model/switchyard/v2/switchyard_2_0.xsd new file mode 100644 index 000000000..6043ada4d --- /dev/null +++ b/core/config/src/main/resources/org/switchyard/config/model/switchyard/v2/switchyard_2_0.xsd @@ -0,0 +1,301 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Static Operation Selector Configuration. + + + + + + + + Operation name. + + + + + + + + + + + + XPath Operation Selector Configuration. + + + + + + + + XPath expression. + + + + + + + + + + + + XPath Operation Selector Configuration. + + + + + + + + Regex expression. + + + + + + + + + + + + Java Operation Selector Configuration. + + + + + + + + operation selector implementation class name. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SCA extension for configuring throttling details. + + + + + + The time period in milliseconds over which requests are counted. Defaults to 1000 (1 second). + + + + + + + The maximum number of requests which can be processed during the specified timePeriod. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/w3/www/2001/XMLSchema.dtd b/core/config/src/main/resources/org/w3/www/2001/XMLSchema.dtd new file mode 100644 index 000000000..e8e8f7625 --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/2001/XMLSchema.dtd @@ -0,0 +1,402 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%xs-datatypes; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/w3/www/2001/datatypes.dtd b/core/config/src/main/resources/org/w3/www/2001/datatypes.dtd new file mode 100644 index 000000000..8e48553be --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/2001/datatypes.dtd @@ -0,0 +1,203 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/w3/www/2001/xml.xsd b/core/config/src/main/resources/org/w3/www/2001/xml.xsd new file mode 100644 index 000000000..57b747fcd --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/2001/xml.xsd @@ -0,0 +1,287 @@ + + + + + + +

+

About the XML namespace

+ +
+

+ This schema document describes the XML namespace, in a form + suitable for import by other schema documents. +

+

+ See + http://www.w3.org/XML/1998/namespace.html and + + http://www.w3.org/TR/REC-xml for information + about this namespace. +

+

+ Note that local names in this namespace are intended to be + defined only by the World Wide Web Consortium or its subgroups. + The names currently defined in this namespace are listed below. + They should not be used with conflicting semantics by any Working + Group, specification, or document instance. +

+

+ See further below in this document for more information about how to refer to this schema document from your own + XSD schema documents and about the + namespace-versioning policy governing this schema document. +

+
+
+ + + + + + +
+ +

lang (as an attribute name)

+

+ denotes an attribute whose value + is a language code for the natural language of the content of + any element; its value is inherited. This name is reserved + by virtue of its definition in the XML specification.

+ +
+
+

Notes

+

+ Attempting to install the relevant ISO 2- and 3-letter + codes as the enumerated possible values is probably never + going to be a realistic possibility. +

+

+ See BCP 47 at + http://www.rfc-editor.org/rfc/bcp/bcp47.txt + and the IANA language subtag registry at + + http://www.iana.org/assignments/language-subtag-registry + for further information. +

+

+ The union allows for the 'un-declaration' of xml:lang with + the empty string. +

+
+
+
+ + + + + + + + + +
+ + + + +
+ +

space (as an attribute name)

+

+ denotes an attribute whose + value is a keyword indicating what whitespace processing + discipline is intended for the content of the element; its + value is inherited. This name is reserved by virtue of its + definition in the XML specification.

+ +
+
+
+ + + + + + +
+ + + +
+ +

base (as an attribute name)

+

+ denotes an attribute whose value + provides a URI to be used as the base for interpreting any + relative URIs in the scope of the element on which it + appears; its value is inherited. This name is reserved + by virtue of its definition in the XML Base specification.

+ +

+ See http://www.w3.org/TR/xmlbase/ + for information about this attribute. +

+
+
+
+
+ + + + +
+ +

id (as an attribute name)

+

+ denotes an attribute whose value + should be interpreted as if declared to be of type ID. + This name is reserved by virtue of its definition in the + xml:id specification.

+ +

+ See http://www.w3.org/TR/xml-id/ + for information about this attribute. +

+
+
+
+
+ + + + + + + + + + +
+ +

Father (in any context at all)

+ +
+

+ denotes Jon Bosak, the chair of + the original XML Working Group. This name is reserved by + the following decision of the W3C XML Plenary and + XML Coordination groups: +

+
+

+ In appreciation for his vision, leadership and + dedication the W3C XML Plenary on this 10th day of + February, 2000, reserves for Jon Bosak in perpetuity + the XML name "xml:Father". +

+
+
+
+
+
+ + + +
+

About this schema document

+ +
+

+ This schema defines attributes and an attribute group suitable + for use by schemas wishing to allow xml:base, + xml:lang, xml:space or + xml:id attributes on elements they define. +

+

+ To enable this, such a schema must import this schema for + the XML namespace, e.g. as follows: +

+
+          <schema . . .>
+           . . .
+           <import namespace="http://www.w3.org/XML/1998/namespace"
+                      schemaLocation="http://www.w3.org/2001/xml.xsd"/>
+     
+

+ or +

+
+           <import namespace="http://www.w3.org/XML/1998/namespace"
+                      schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
+     
+

+ Subsequently, qualified reference to any of the attributes or the + group defined below will have the desired effect, e.g. +

+
+          <type . . .>
+           . . .
+           <attributeGroup ref="xml:specialAttrs"/>
+     
+

+ will define a type which will schema-validate an instance element + with any of those attributes. +

+
+
+
+
+ + + +
+

Versioning policy for this schema document

+
+

+ In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + + http://www.w3.org/2009/01/xml.xsd. +

+

+ At the date of issue it can also be found at + + http://www.w3.org/2001/xml.xsd. +

+

+ The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML + Schema itself, or with the XML namespace itself. In other words, + if the XML Schema or XML namespaces change, the version of this + document at + http://www.w3.org/2001/xml.xsd + + will change accordingly; the version at + + http://www.w3.org/2009/01/xml.xsd + + will not change. +

+

+ Previous dated (and unchanging) versions of this schema + document are at: +

+ +
+
+
+
+ + + diff --git a/core/config/src/main/resources/org/w3/www/2006/03/addressing/ws-addr.xsd b/core/config/src/main/resources/org/w3/www/2006/03/addressing/ws-addr.xsd new file mode 100644 index 000000000..9f07d156c --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/2006/03/addressing/ws-addr.xsd @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/w3/www/2007/02/ws-policy.xsd b/core/config/src/main/resources/org/w3/www/2007/02/ws-policy.xsd new file mode 100644 index 000000000..6d412c31e --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/2007/02/ws-policy.xsd @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/w3/www/2007/05/wsdl/wsdl20-instance.xsd b/core/config/src/main/resources/org/w3/www/2007/05/wsdl/wsdl20-instance.xsd new file mode 100644 index 000000000..21918bd8a --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/2007/05/wsdl/wsdl20-instance.xsd @@ -0,0 +1,35 @@ + + + + + + + + + This attribute can be used to provide some hints on where + additional WSDL information for a given namespace can be + found in order to help with QName resolution + + + + + + + + diff --git a/core/config/src/main/resources/org/w3/www/2008/09/xsd.xsl b/core/config/src/main/resources/org/w3/www/2008/09/xsd.xsl new file mode 100644 index 000000000..4619c00ae --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/2008/09/xsd.xsl @@ -0,0 +1,991 @@ + + + + + + + + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + Schema document for + + + namespace + + + + unspecified namespace + + + + + + + + + + + + + + text/css + .bodytext .bodytext { + margin-left: 0; + margin-right: 0; + } + .bodytext { + margin-left: 15%; + margin-right: 2%; + } + .annotation { + + + } + .same-ns { + color: Green; + } + .diff-ns { + color: maroon; + } + .warning { + color: red; + } + p.note { + font-style: italic; + } + p.dt { + font-weight: bold; + } + span.rfc { + font-variant: small-caps; + } + + + + + + + + * * + + + + + + + + + + + bodytext + + + + + + + + + + + + + + + + + + + + + + annotation + + + + + + Annotation + + + + + + + + bodytext + + + + + + + + + + + + + + ! Unrecognized children in xs:documentation element + + + + + + + + + + + + + + + + + + + + + + +   + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bodytext + + + + + Notes + + + + + External documentation at + + + + + + + + + + + + + + + Formal declaration in XSD source form + + + + + + + + + + + + + + + + + + + + + + + + + + + + + < + + + + + break + nobreak + + + + + + + + + + + > + + </ + + > + + /> + + + + + + + + + nobreak + + + + + + + + + + + + + + + + + + + + + + + =" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + " + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warning: not matched. + + warning + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + external-link same-ns + + + + + + external-link diff-ns + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + attnames + + + + + + attvals + + + + + + + + + + + + + + + + + + unknown + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/w3/www/2009/01/xml.xsd b/core/config/src/main/resources/org/w3/www/2009/01/xml.xsd new file mode 100644 index 000000000..7bd2e5511 --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/2009/01/xml.xsd @@ -0,0 +1,286 @@ + + + + + + +
+

About the XML namespace

+ +
+

+ This schema document describes the XML namespace, in a form + suitable for import by other schema documents. +

+

+ See + http://www.w3.org/XML/1998/namespace.html and + + http://www.w3.org/TR/REC-xml for information + about this namespace. +

+

+ Note that local names in this namespace are intended to be + defined only by the World Wide Web Consortium or its subgroups. + The names currently defined in this namespace are listed below. + They should not be used with conflicting semantics by any Working + Group, specification, or document instance. +

+

+ See further below in this document for more information about how to refer to this schema document from your own + XSD schema documents and about the + namespace-versioning policy governing this schema document. +

+
+
+
+
+ + + + +
+ +

lang (as an attribute name)

+

+ denotes an attribute whose value + is a language code for the natural language of the content of + any element; its value is inherited. This name is reserved + by virtue of its definition in the XML specification.

+ +
+
+

Notes

+

+ Attempting to install the relevant ISO 2- and 3-letter + codes as the enumerated possible values is probably never + going to be a realistic possibility. +

+

+ See BCP 47 at + http://www.rfc-editor.org/rfc/bcp/bcp47.txt + and the IANA language subtag registry at + + http://www.iana.org/assignments/language-subtag-registry + for further information. +

+

+ The union allows for the 'un-declaration' of xml:lang with + the empty string. +

+
+
+
+ + + + + + + + + +
+ + + + +
+ +

space (as an attribute name)

+

+ denotes an attribute whose + value is a keyword indicating what whitespace processing + discipline is intended for the content of the element; its + value is inherited. This name is reserved by virtue of its + definition in the XML specification.

+ +
+
+
+ + + + + + +
+ + + +
+ +

base (as an attribute name)

+

+ denotes an attribute whose value + provides a URI to be used as the base for interpreting any + relative URIs in the scope of the element on which it + appears; its value is inherited. This name is reserved + by virtue of its definition in the XML Base specification.

+ +

+ See http://www.w3.org/TR/xmlbase/ + for information about this attribute. +

+
+
+
+
+ + + + +
+ +

id (as an attribute name)

+

+ denotes an attribute whose value + should be interpreted as if declared to be of type ID. + This name is reserved by virtue of its definition in the + xml:id specification.

+ +

+ See http://www.w3.org/TR/xml-id/ + for information about this attribute. +

+
+
+
+
+ + + + + + + + + + +
+ +

Father (in any context at all)

+ +
+

+ denotes Jon Bosak, the chair of + the original XML Working Group. This name is reserved by + the following decision of the W3C XML Plenary and + XML Coordination groups: +

+
+

+ In appreciation for his vision, leadership and + dedication the W3C XML Plenary on this 10th day of + February, 2000, reserves for Jon Bosak in perpetuity + the XML name "xml:Father". +

+
+
+
+
+
+ + + +
+

About this schema document

+ +
+

+ This schema defines attributes and an attribute group suitable + for use by schemas wishing to allow xml:base, + xml:lang, xml:space or + xml:id attributes on elements they define. +

+

+ To enable this, such a schema must import this schema for + the XML namespace, e.g. as follows: +

+
+          <schema . . .>
+           . . .
+           <import namespace="http://www.w3.org/XML/1998/namespace"
+                      schemaLocation="http://www.w3.org/2001/xml.xsd"/>
+     
+

+ or +

+
+           <import namespace="http://www.w3.org/XML/1998/namespace"
+                      schemaLocation="http://www.w3.org/2009/01/xml.xsd"/>
+     
+

+ Subsequently, qualified reference to any of the attributes or the + group defined below will have the desired effect, e.g. +

+
+          <type . . .>
+           . . .
+           <attributeGroup ref="xml:specialAttrs"/>
+     
+

+ will define a type which will schema-validate an instance element + with any of those attributes. +

+
+
+
+
+ + + +
+

Versioning policy for this schema document

+
+

+ In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + + http://www.w3.org/2009/01/xml.xsd. +

+

+ At the date of issue it can also be found at + + http://www.w3.org/2001/xml.xsd. +

+

+ The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML + Schema itself, or with the XML namespace itself. In other words, + if the XML Schema or XML namespaces change, the version of this + document at + http://www.w3.org/2001/xml.xsd + + will change accordingly; the version at + + http://www.w3.org/2009/01/xml.xsd + + will not change. +

+

+ Previous dated (and unchanging) versions of this schema + document are at: +

+ +
+
+
+
+ +
diff --git a/core/config/src/main/resources/org/w3/www/People/cmsmcq/lib/xslt10.dtd b/core/config/src/main/resources/org/w3/www/People/cmsmcq/lib/xslt10.dtd new file mode 100644 index 000000000..5c3c44c70 --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/People/cmsmcq/lib/xslt10.dtd @@ -0,0 +1,373 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/main/resources/org/w3/www/TR/xmldsig-core/xmldsig-core-schema.xsd b/core/config/src/main/resources/org/w3/www/TR/xmldsig-core/xmldsig-core-schema.xsd new file mode 100644 index 000000000..1c1297342 --- /dev/null +++ b/core/config/src/main/resources/org/w3/www/TR/xmldsig-core/xmldsig-core-schema.xsd @@ -0,0 +1,318 @@ + + + + + + ]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/java/org/switchyard/config/ConfigurationTests.java b/core/config/src/test/java/org/switchyard/config/ConfigurationTests.java new file mode 100644 index 000000000..2461d1ca1 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/ConfigurationTests.java @@ -0,0 +1,259 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config; + +import java.io.IOException; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.BaseNamedModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.MergeScanner; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.ModelPullerScanner; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; + +/** + * ConfigurationTests. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class ConfigurationTests { + + private static final String FROM_XML = "/org/switchyard/config/ConfigurationTests-From.xml"; + private static final String TO_XML = "/org/switchyard/config/ConfigurationTests-To.xml"; + private static final String FROM_OVERRIDES_TO_XML = "/org/switchyard/config/ConfigurationTests-FromOverridesTo.xml"; + private static final String FROM_DOESNT_OVERRIDE_TO_XML = "/org/switchyard/config/ConfigurationTests-FromDoesntOverrideTo.xml"; + private static final String NAMESPACES_XML = "/org/switchyard/config/ConfigurationTests-Namespaces.xml"; + private static final String ORDER_CHILDREN_UNORDERED_XML = "/org/switchyard/config/ConfigurationTests-OrderChildren-Unordered.xml"; + private static final String ORDER_CHILDREN_ORDERED_XML = "/org/switchyard/config/ConfigurationTests-OrderChildren-Ordered.xml"; + private static final String CDATA_VALUE_XML = "/org/switchyard/config/ConfigurationTests-CdataValue.xml"; + + private ConfigurationPuller _cfg_puller; + private StringPuller _str_puller; + + @Before + public void before() { + _cfg_puller = new ConfigurationPuller(); + _str_puller = new StringPuller(); + } + + @After + public void after() { + _cfg_puller = null; + _str_puller = null; + } + + @Test + public void testCreateEmptyConfig() throws Exception { + String name = "root"; + Configuration config = _cfg_puller.pull(new QName(name)); + Assert.assertEquals(name, config.getName()); + Assert.assertEquals(new QName(name), config.getQName()); + } + + @Test + public void testMerge() throws Exception { + XMLUnit.setIgnoreWhitespace(true); + Diff diff; + String from_overrides_to_xml = _str_puller.pull(FROM_OVERRIDES_TO_XML, getClass()); + diff = XMLUnit.compareXML(from_overrides_to_xml, merge(true)); + Assert.assertTrue(diff.toString(), diff.identical()); + String from_doesnt_override_to_xml = _str_puller.pull(FROM_DOESNT_OVERRIDE_TO_XML, getClass()); + diff = XMLUnit.compareXML(from_doesnt_override_to_xml, merge(false)); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + private String merge(boolean fromOverridesTo) throws Exception { + Configuration from_config = _cfg_puller.pull(FROM_XML, getClass()); + Configuration to_config = _cfg_puller.pull(TO_XML, getClass()); + Configuration merged_config = Configurations.merge(from_config, to_config, fromOverridesTo).setChildrenOrder("my", "his", "mythology").orderChildren(); + return merged_config.toString(); + } + + @Test + public void testParenthood() throws Exception { + Configuration parent = _cfg_puller.pull(NAMESPACES_XML, getClass()); + Assert.assertFalse(parent.hasParent()); + Assert.assertNull(parent.getParent()); + Configuration child = parent.getFirstChild("two"); + Assert.assertTrue(child.hasParent()); + Assert.assertNotNull(child.getParent()); + Assert.assertEquals("one", child.getParent().getName()); + Assert.assertSame(child.getParent(), child.getParent()); + } + + @Test + public void testQNames() throws Exception { + QName expected = new QName("http://foo.org", "bar", "foo"); + QName actual = _cfg_puller.pull(expected).getQName(); + Assert.assertEquals(expected, actual); + Assert.assertEquals(expected.getNamespaceURI(), actual.getNamespaceURI()); + Assert.assertEquals(expected.getLocalPart(), actual.getLocalPart()); + Assert.assertEquals(expected.getPrefix(), actual.getPrefix()); + } + + @Test + public void testNamespaceCollections() throws Exception { + Configuration config = _cfg_puller.pull(NAMESPACES_XML, getClass()); + Set n_set = config.getNamespaces(); + Assert.assertEquals(5, n_set.size()); + Map np_map = config.getNamespacePrefixMap(); + Assert.assertEquals(5, np_map.size()); + Map pn_map = config.getPrefixNamespaceMap(); + Assert.assertEquals(5, pn_map.size()); + } + + @Test + public void testNamespacesValues() throws Exception { + Configuration config_one = _cfg_puller.pull(NAMESPACES_XML, getClass()); + validateNamespacesConfig(config_one); + } + + private void validateNamespacesConfig(Configuration config_one) throws Exception { + Assert.assertEquals("urn:test", config_one.getAttribute("targetNamespace")); + Assert.assertEquals("http://a.org/a.xsd", config_one.getQName().getNamespaceURI()); + Assert.assertEquals("bar", config_one.getAttribute("foo")); + Assert.assertEquals("stuff", config_one.getFirstChild("two").getValue()); + Assert.assertEquals("stuff", config_one.getFirstChild(new QName("http://b.org/b.xsd", "two")).getValue()); + Assert.assertEquals("whiz", config_one.getFirstChild("two").getAttribute("baz")); + Assert.assertEquals("girl", config_one.getFirstChild(new QName("http://b.org/b.xsd", "two")).getAttribute(new QName("http://c.org/c.xsd", "boy"))); + Configuration config_three = config_one.getChildren().get(1); + Assert.assertEquals("metal", config_three.getValue()); + Assert.assertEquals("woman", config_three.getAttribute(new QName("http://b.org/b.xsd", "man"))); + Assert.assertEquals("robot", config_three.getAttribute("toy")); + Configuration config_four = config_one.getChildren().get(2); + QName nuts = config_four.getAttributeAsQName(new QName("http://b.org/b.xsd", "nuts")); + Assert.assertEquals("http://b.org/b.xsd", nuts.getNamespaceURI()); + Assert.assertEquals("bolts", nuts.getLocalPart()); + Assert.assertEquals("b", nuts.getPrefix()); + QName pins = config_four.getAttributeAsQName("pins"); + Assert.assertEquals("http://c.org/c.xsd", pins.getNamespaceURI()); + Assert.assertEquals("needles", pins.getLocalPart()); + Assert.assertEquals("c", pins.getPrefix()); + QName pipes = config_four.getAttributeAsQName("pipes"); + Assert.assertEquals("", pipes.getNamespaceURI()); + Assert.assertEquals("rusted", pipes.getLocalPart()); + Assert.assertEquals("", pipes.getPrefix()); + } + + @Test + public void testNamespacesMerge() throws Exception { + @SuppressWarnings("unchecked") + Scanner[] scanners = new Scanner[]{ + new Scanner() { + public ScannerOutput scan(ScannerInput input) throws IOException { + return new ScannerOutput().setModel(new TestModel()); + } + }, + new ModelPullerScanner(NAMESPACES_XML, getClass().getClassLoader()) + }; + MergeScanner merge_scanner = new MergeScanner(true, scanners); + ScannerInput scanner_input = new ScannerInput(); + Model model = merge_scanner.scan(scanner_input).getModel(); + Configuration config_one = model.getModelConfiguration(); + try { + validateNamespacesConfig(config_one); + } catch (Error e) { + //System.err.println(config_one); + throw e; + } + } + + @Test + public void testAttributeAsQName() throws Exception { + Configuration config = _cfg_puller.pull(NAMESPACES_XML, getClass()); + config.setAttributeAsQName("testB", new QName("http://b.org/b.xsd", "B", "b")); + Assert.assertEquals("b:B", config.getAttribute("testB")); + QName testB = config.getAttributeAsQName("testB"); + Assert.assertEquals("http://b.org/b.xsd", testB.getNamespaceURI()); + Assert.assertEquals("B", testB.getLocalPart()); + Assert.assertEquals("b", testB.getPrefix()); + config.setAttribute("testB", "{http://b.org/b.xsd}B"); + Assert.assertEquals("{http://b.org/b.xsd}B", config.getAttribute("testB")); + testB = config.getAttributeAsQName("testB"); + Assert.assertEquals("http://b.org/b.xsd", testB.getNamespaceURI()); + Assert.assertEquals("B", testB.getLocalPart()); + Assert.assertEquals("b", testB.getPrefix()); + QName qnameC = new QName("http://c.org/c.xsd", "testC", "c"); + config.setAttributeAsQName(qnameC, new QName("", "C", "c")); + Assert.assertEquals("c:C", config.getAttribute(qnameC)); + QName testC = config.getAttributeAsQName(qnameC); + Assert.assertEquals("http://c.org/c.xsd", testC.getNamespaceURI()); + Assert.assertEquals("C", testC.getLocalPart()); + Assert.assertEquals("c", testC.getPrefix()); + config.setAttributeAsQName("testZ", new QName("http://z.org/z.xsd", "Z", "")); + Assert.assertEquals("{http://z.org/z.xsd}Z", config.getAttribute("testZ")); + QName testZ = config.getAttributeAsQName("testZ"); + Assert.assertEquals("http://z.org/z.xsd", testZ.getNamespaceURI()); + Assert.assertEquals("Z", testZ.getLocalPart()); + Assert.assertEquals("", testZ.getPrefix()); + } + + @Test + public void testOrderChildren() throws Exception { + Configuration root = _cfg_puller.pull(ORDER_CHILDREN_UNORDERED_XML, getClass()); + root.setChildrenOrder("one", "two", "three", "four"); + Configuration one = root.getFirstChild("one"); + one.setChildrenOrder("a", "b", "c"); + Configuration three = root.getFirstChild("three"); + three.setChildrenOrder("c", "b", "a"); + String actual_xml = root.orderChildren().toString(); + String expected_xml = _str_puller.pull(ORDER_CHILDREN_ORDERED_XML, getClass()); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(expected_xml, actual_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testCdataValue() throws Exception { + Configuration config = _cfg_puller.pull(CDATA_VALUE_XML, getClass()); + Assert.assertEquals("test-simple-value", config.getFirstChild("simple").getValue()); + Assert.assertEquals("test-complex-value", config.getFirstChild("complex").getValue()); + } + + public static final class TestModel extends BaseNamedModel { + + public TestModel() { + super("http://a.org/a.xsd", "one"); + } + + public TestModel(Configuration config) { + super(config); + } + } + + public static final class TestMarshaller extends BaseMarshaller { + public TestMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(Configuration config) { + return new TestModel(config); + } + } +} diff --git a/core/config/src/test/java/org/switchyard/config/model/ModelTests.java b/core/config/src/test/java/org/switchyard/config/model/ModelTests.java new file mode 100644 index 000000000..ff12b50aa --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/ModelTests.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model; + +import java.util.Set; +import java.util.TreeSet; + +import org.junit.Assert; +import org.junit.Test; + +/** + * ModelTests. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class ModelTests { + + private static final String[] NS = new String[] { + "http://www.w3.org/2000/09/xmldsig#", + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", + "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", + "http://docs.oasis-open.org/ns/opencsa/sca/200912", + "urn:switchyard-config:switchyard:1.0", + "urn:switchyard-config:transform:1.0", + "urn:switchyard-component-soap:config:2.0", + "urn:switchyard-component-soap:config:1.0", + "urn:switchyard-component-bean:config:2.0", + "urn:switchyard-component-bean:config:1.0", + "http://my.custom.namespace:2.0", + "http://my.custom.namespace:1.0" + }; + + @Test + public void testNamespaceComparator() throws Exception { + Set ns = new TreeSet(new NamespaceComparator()); + ns.add(NS[6]); + ns.add(NS[7]); + ns.add(NS[10]); + ns.add(NS[2]); + ns.add(NS[1]); + ns.add(NS[9]); + ns.add(NS[8]); + ns.add(NS[3]); + ns.add(NS[0]); + ns.add(NS[5]); + ns.add(NS[4]); + ns.add(NS[11]); + Assert.assertArrayEquals(NS, ns.toArray(new String[ns.size()])); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/CompositeModelTests.java b/core/config/src/test/java/org/switchyard/config/model/composite/CompositeModelTests.java new file mode 100644 index 000000000..aa817cc09 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/CompositeModelTests.java @@ -0,0 +1,335 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.composite; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import org.junit.Assert; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.lang.Strings; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.Models; +import org.switchyard.config.model.composite.test.bogus.BogusImplementationModel; +import org.switchyard.config.model.composite.test.extension.ExtensionBindingModel; +import org.switchyard.config.model.composite.test.soap.PortModel; +import org.switchyard.config.model.composite.test.soap.SOAPBindingModel; +import org.switchyard.config.model.composite.test.soap.WSDLModel; +import org.switchyard.config.model.composite.v1.V1ComponentImplementationModel; +import org.switchyard.config.test.xmlunit.SchemaLocationDifferenceListener; + +/** + * CompositeModelTests. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class CompositeModelTests { + + private static final String INCOMPLETE_XML = "/org/switchyard/config/model/composite/CompositeModelTests-Incomplete.xml"; + private static final String FRAGMENT_XML = "/org/switchyard/config/model/composite/CompositeModelTests-Fragment.xml"; + private static final String COMPLETE_XML = "/org/switchyard/config/model/composite/CompositeModelTests-Complete.xml"; + private static final String EXTENDED_XML = "/org/switchyard/config/model/composite/CompositeModelTests-Extended.xml"; + private static final String EXTENSION_XML = "/org/switchyard/config/model/composite/CompositeModelTests-Extension.xml"; + private static final String SCA_BINDING_XML = "/org/switchyard/config/model/composite/CompositeModelTests-SCABinding.xml"; + private static final String PROMOTE_XML = "/org/switchyard/config/model/composite/CompositeModelTests-Promote.xml"; + private static final String PROPERTIES_SELF_REFERRING_XML = "/org/switchyard/config/model/composite/CompositeModelTests-PropertiesSelfReferring.xml"; + + private static ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void testCreateEmptyModel() throws Exception { + String namespace = SCANamespace.DEFAULT.uri(); + String name = CompositeModel.COMPOSITE; + Model model = new ModelPuller().pull(XMLHelper.createQName(namespace, name)); + assertTrue(model instanceof CompositeModel); + assertEquals(name, model.getModelConfiguration().getName()); + assertEquals(new QName(namespace, name), model.getModelConfiguration().getQName()); + } + + @Test + public void testMerge() throws Exception { + CompositeModel incomplete_composite = _puller.pull(INCOMPLETE_XML, getClass()); + CompositeModel fragment_composite = _puller.pull(FRAGMENT_XML, getClass()); + CompositeModel merged_composite = Models.merge(fragment_composite, incomplete_composite); + CompositeModel complete_composite = _puller.pull(COMPLETE_XML, getClass()); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(complete_composite.toString(), merged_composite.toString()); + diff.overrideDifferenceListener(new SchemaLocationDifferenceListener()); + assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testReadCustomViaConfig() throws Exception { + CompositeModel composite = _puller.pull(COMPLETE_XML, getClass()); + CompositeServiceModel compositeService = composite.getServices().get(0); + BindingModel binding = compositeService.getBindings().get(0); + assertEquals("soap", binding.getType()); + Configuration port_config = binding.getModelConfiguration().getFirstChild(PortModel.PORT); + assertEquals("MyWebService/SOAPPort", port_config.getValue()); + assertEquals("true", port_config.getAttribute(PortModel.SECURE)); + Configuration wsdl_config = binding.getModelConfiguration().getFirstChild(WSDLModel.WSDL); + assertEquals("service.wsdl", wsdl_config.getValue()); + assertEquals("foobar", wsdl_config.getAttribute(WSDLModel.DESCRIPTION)); + } + + @Test + public void testReadCustomViaModel() throws Exception { + CompositeModel composite = _puller.pull(COMPLETE_XML, getClass()); + CompositeServiceModel compositeService = composite.getServices().get(0); + BindingModel binding = (BindingModel)compositeService.getBindings().get(0); + assertTrue(binding instanceof SOAPBindingModel); + SOAPBindingModel soap_binding = (SOAPBindingModel)compositeService.getBindings().get(0); + assertEquals("soap", binding.getType()); + PortModel port = soap_binding.getPort(); + assertEquals("MyWebService/SOAPPort", port.getPort()); + assertEquals(true, port.isSecure()); + WSDLModel wsdl = soap_binding.getWSDL(); + assertEquals("service.wsdl", wsdl.getLocation()); + assertEquals("foobar", wsdl.getDescription()); + } + + @Test + public void testReadComplete() throws Exception { + CompositeModel composite = _puller.pull(COMPLETE_XML, getClass()); + assertEquals(SCANamespace.DEFAULT.uri(), composite.getModelConfiguration().getQName().getNamespaceURI()); + assertEquals("m1app", composite.getName()); + CompositeServiceModel compositeService = composite.getServices().get(0); + assertEquals("M1AppService", compositeService.getName()); + assertEquals("SimpleService", compositeService.getPromote()); + SOAPBindingModel binding1 = (SOAPBindingModel)compositeService.getBindings().get(0); + assertEquals("soap", binding1.getType()); + PortModel port = binding1.getPort(); + assertEquals("MyWebService/SOAPPort", port.getPort()); + assertEquals(true, port.isSecure()); + WSDLModel wsdl1 = binding1.getWSDL(); + assertEquals("service.wsdl", wsdl1.getLocation()); + assertEquals("foobar", wsdl1.getDescription()); + CompositeReferenceModel compositeReference = composite.getReferences().get(0); + assertEquals("SomeOtherService", compositeReference.getName()); + assertEquals("SimpleService/AnotherService", compositeReference.getPromote()); + SOAPBindingModel binding2 = (SOAPBindingModel)compositeReference.getBindings().get(0); + assertEquals("soap", binding2.getType()); + WSDLModel wsdl = binding2.getWSDL(); + assertEquals("http://exmample.org:8080/services/SomeOtherService?wsdl", wsdl.getLocation()); + ComponentModel component1 = composite.getComponents().get(0); + assertEquals("SimpleService", component1.getName()); + ComponentImplementationModel implementation1 = component1.getImplementation(); + assertEquals("bean", implementation1.getType()); + ComponentServiceModel componentService1 = component1.getServices().get(0); + assertEquals("SimpleService", componentService1.getName()); + InterfaceModel interface1 = componentService1.getInterface(); + assertEquals("java", interface1.getType()); + assertEquals("org.switchyard.example.m1app.SimpleService", interface1.getInterface()); + ComponentReferenceModel reference = component1.getReferences().get(0); + assertEquals("anotherService", reference.getName()); + InterfaceModel interface2 = reference.getInterface(); + assertEquals("java", interface2.getType()); + assertEquals("org.switchyard.example.m1app.AnotherService", interface2.getInterface()); + ComponentModel component2 = composite.getComponents().get(1); + assertEquals("AnotherService", component2.getName()); + ComponentImplementationModel implementation2 = component2.getImplementation(); + assertEquals("bean", implementation2.getType()); + ComponentServiceModel componentService2 = component2.getServices().get(0); + assertEquals("AnotherService", componentService2.getName()); + InterfaceModel interface3 = componentService2.getInterface(); + assertEquals("java", interface3.getType()); + assertEquals("org.switchyard.example.m1app.AnotherService", interface3.getInterface()); + } + + @Test + public void testBindingModel() throws Exception { + CompositeModel composite = _puller.pull(COMPLETE_XML, getClass()); + // Test service binding + BindingModel serviceBinding = composite.getServices().get(0).getBindings().get(0); + assertTrue(serviceBinding.isServiceBinding()); + assertFalse(serviceBinding.isReferenceBinding()); + assertNotNull(serviceBinding.getService()); + assertNull(serviceBinding.getReference()); + // Test reference binding + BindingModel referenceBinding = composite.getReferences().get(0).getBindings().get(0); + assertTrue(referenceBinding.isReferenceBinding()); + assertFalse(referenceBinding.isServiceBinding()); + assertNotNull(referenceBinding.getReference()); + assertNull(referenceBinding.getService()); + } + + @Test + public void testPropertyModel() throws Exception { + CompositeModel composite = _puller.pull(COMPLETE_XML, getClass()); + // Test composite property + assertEquals(2, composite.getProperties().size()); + PropertyResolver compositePr = composite.getModelConfiguration().getPropertyResolver(); + assertEquals("composite.bar", compositePr.resolveProperty("composite.foo")); + assertEquals("composite." + System.getProperty("user.name"), composite.resolveProperty("composite.userName")); + // Test component property + ComponentModel component = composite.getComponents().get(0); + assertEquals(3, component.getProperties().size()); + PropertyResolver componentPr = component.getModelConfiguration().getPropertyResolver(); + assertEquals("composite.bar", componentPr.resolveProperty("composite.foo")); + assertEquals("component.bar", componentPr.resolveProperty("component.foo")); + assertEquals("component." + System.getProperty("user.name"), componentPr.resolveProperty("component.userName")); + } + + @Test + public void testSelfReferringPropertyModel() throws Exception { + CompositeModel composite = _puller.pull(PROPERTIES_SELF_REFERRING_XML, getClass()); + // Test component property + ComponentModel component = composite.getComponents().get(1); + assertEquals(5, component.getProperties().size()); + PropertyResolver componentPr = component.getModelConfiguration().getPropertyResolver(); + + Object result = componentPr.resolveProperty("creditTerms"); + assertTrue("${creditTerms}".equals(result)); + + result = componentPr.resolveProperty("foobar"); + assertTrue("foobar".equals((String) result)); + + result = componentPr.resolveProperty("bar"); + assertTrue("${bar}".equals(result)); + + result = componentPr.resolveProperty("bar"); + assertTrue("${bar}".equals(result)); + } + + @Test + public void testWriteComplete() throws Exception { + String old_xml = new StringPuller().pull(COMPLETE_XML, getClass()); + CompositeModel composite = _puller.pull(new StringReader(old_xml)); + String new_xml = composite.toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testReadExtended() throws Exception { + CompositeModel cm = _puller.pull(EXTENDED_XML, getClass()); + BogusImplementationModel bim = (BogusImplementationModel)cm.getComponents().get(0).getImplementation(); + assertEquals("bar", bim.getFoo()); + } + + @Test + public void testReadExtendedWithService() throws Exception { + CompositeModel cm = _puller.pull(EXTENDED_XML, getClass()); + ComponentModel component = cm.getComponents().get(0); + assertEquals(1, component.getServices().size()); + } + + @Test + public void testParenthood() throws Exception { + CompositeModel composite_1 = _puller.pull(COMPLETE_XML, getClass()); + CompositeServiceModel service_1 = composite_1.getServices().get(0); + SOAPBindingModel binding = (SOAPBindingModel)service_1.getBindings().get(0); + CompositeServiceModel service_2 = binding.getService(); + CompositeModel composite_2 = service_2.getComposite(); + assertEquals(service_1, service_2); + assertEquals(composite_1, composite_2); + } + + @Test + public void testValidation() throws Exception { + CompositeModel composite = _puller.pull(COMPLETE_XML, getClass()); + composite.assertModelValid(); + } + + @Test + public void testVerifyQNameUponCreation() throws Exception { + final String type = "customtype"; + final V1ComponentImplementationModel model = new V1ComponentImplementationModel(type); + assertEquals(type, model.getType()); + } + + @Test + public void testReadExtensionRefferingNoNamespacedSchema() throws Exception { + CompositeModel composite = _puller.pull(EXTENSION_XML, getClass()); + CompositeServiceModel compositeService = composite.getServices().get(0); + BindingModel binding = compositeService.getBindings().get(0); + + assertTrue(binding instanceof ExtensionBindingModel); + ExtensionBindingModel extension = (ExtensionBindingModel) binding; + assertEquals("extension", extension.getType()); + assertEquals("Bar", extension.getGroup()); + assertEquals("Foo", extension.getName()); + } + + @Test + public void testSCABinding() throws Exception { + CompositeModel composite = _puller.pull(SCA_BINDING_XML, getClass()); + + // test binding.sca on composite service + CompositeServiceModel compositeService = composite.getServices().get(0); + BindingModel sb = compositeService.getBindings().get(0); + assertTrue(sb instanceof SCABindingModel); + + // test binding.sca on composite reference + CompositeReferenceModel compositeReference = composite.getReferences().get(0); + BindingModel rb = compositeReference.getBindings().get(0); + assertTrue(rb instanceof SCABindingModel); + } + + @Test + public void testPromote() throws Exception { + CompositeModel composite = _puller.pull(PROMOTE_XML, getClass()); + CompositeServiceModel singlePromoteCompositeSrv = null; + for (CompositeServiceModel compositeSrv : composite.getServices()) { + if ("SinglePromoteExampleService".equals(compositeSrv.getName())) { + singlePromoteCompositeSrv = compositeSrv; + } + } + Assert.assertNotNull("null SinglePromoteExampleService", singlePromoteCompositeSrv); + ComponentServiceModel componentSrv = singlePromoteCompositeSrv.getComponentService(); + Assert.assertNotNull("null FooExampleService", componentSrv); + Assert.assertEquals("FooExampleService", componentSrv.getName()); + CompositeReferenceModel singlePromoteCompositeRef = null; + CompositeReferenceModel multiPromoteCompositeRef = null; + for (CompositeReferenceModel compositeRef : composite.getReferences()) { + if ("SinglePromoteExampleReference".equals(compositeRef.getName())) { + singlePromoteCompositeRef = compositeRef; + } else if ("MultiPromoteExampleReference".equals(compositeRef.getName())) { + multiPromoteCompositeRef = compositeRef; + } + } + Assert.assertNotNull("null SinglePromoteExampleReference", singlePromoteCompositeRef); + Assert.assertEquals(1, singlePromoteCompositeRef.getComponentReferences().size()); + Assert.assertNotNull("null MultiPromoteExampleReference", multiPromoteCompositeRef); + Assert.assertEquals(2, multiPromoteCompositeRef.getComponentReferences().size()); + } + + @Test + public void testValidationOfExtensionRefferingNoNamespacedSchema() throws Exception { + _puller.pull(EXTENSION_XML, getClass()).assertModelValid(); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/test/bogus/BogusImplementationModel.java b/core/config/src/test/java/org/switchyard/config/model/composite/test/bogus/BogusImplementationModel.java new file mode 100644 index 000000000..b3955c614 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/test/bogus/BogusImplementationModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.test.bogus; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1ComponentImplementationModel; + +/** + * BogusImplementationModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class BogusImplementationModel extends V1ComponentImplementationModel { + + public static final String FOO = "foo"; + + public BogusImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + public String getFoo() { + return getModelAttribute(FOO); + } + + public BogusImplementationModel setFoo(String foo) { + setModelAttribute(FOO, foo); + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/test/bogus/BogusMarshaller.java b/core/config/src/test/java/org/switchyard/config/model/composite/test/bogus/BogusMarshaller.java new file mode 100644 index 000000000..d9e8e544f --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/test/bogus/BogusMarshaller.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.test.bogus; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.v1.V1CompositeMarshaller; + +/** + * BogusMarshaller. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class BogusMarshaller extends V1CompositeMarshaller { + + public BogusMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(Configuration config) { + if (config.getName().startsWith(ComponentImplementationModel.IMPLEMENTATION)) { + return new BogusImplementationModel(config, getDescriptor()); + } + return super.read(config); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/test/extension/ExtensionBindingModel.java b/core/config/src/test/java/org/switchyard/config/model/composite/test/extension/ExtensionBindingModel.java new file mode 100644 index 000000000..490090b75 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/test/extension/ExtensionBindingModel.java @@ -0,0 +1,32 @@ +package org.switchyard.config.model.composite.test.extension; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1BindingModel; + +public class ExtensionBindingModel extends V1BindingModel { + + private static final String NAME = "name"; + private static final String GROUP = "group"; + + public ExtensionBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + public String getName() { + return getConfig(NAME); + } + + public String getGroup() { + return getConfig(GROUP); + } + + protected String getConfig(String configName) { + Configuration config = getModelConfiguration().getFirstChild(configName); + if (config != null) { + return config.getValue(); + } + return null; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/test/extension/ExtensionMarshaller.java b/core/config/src/test/java/org/switchyard/config/model/composite/test/extension/ExtensionMarshaller.java new file mode 100644 index 000000000..9b5fc3493 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/test/extension/ExtensionMarshaller.java @@ -0,0 +1,22 @@ +package org.switchyard.config.model.composite.test.extension; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; + +public class ExtensionMarshaller extends BaseMarshaller { + + protected ExtensionMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(Configuration config) { + if ("binding.extension".equals(config.getName())) { + return new ExtensionBindingModel(config, getDescriptor()); + } + return null; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/PortModel.java b/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/PortModel.java new file mode 100644 index 000000000..71799ba60 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/PortModel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.test.soap; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * PortModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class PortModel extends BaseModel { + + public static final String PORT = "port"; + public static final String SECURE = "secure"; + + public PortModel() { + super(new QName(SCANamespace.DEFAULT.uri(), PORT)); + } + + public PortModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + public SOAPBindingModel getBinding() { + return (SOAPBindingModel)getModelParent(); + } + + public boolean isSecure() { + String secure = getModelAttribute(SECURE); + return secure != null ? Boolean.parseBoolean(secure) : false; + } + + public PortModel setSecure(boolean secure) { + setModelAttribute(SECURE, String.valueOf(secure)); + return this; + } + + public String getPort() { + return getModelValue(); + } + + public PortModel setPort(String port) { + setModelValue(port); + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/SOAPBindingModel.java b/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/SOAPBindingModel.java new file mode 100644 index 000000000..2ef4b37a5 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/SOAPBindingModel.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.test.soap; + +import static org.switchyard.config.model.composite.test.soap.PortModel.PORT; +import static org.switchyard.config.model.composite.test.soap.WSDLModel.WSDL; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1BindingModel; + +/** + * SOAPBindingModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SOAPBindingModel extends V1BindingModel { + + public static final String SOAP = "soap"; + public static final String PORT_NUM = "portNum"; + + private PortModel _port; + private WSDLModel _wsdl; + + public SOAPBindingModel() { + super(SOAP); + setModelChildrenOrder(PORT, WSDL, PORT_NUM); + } + + public SOAPBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(PORT, WSDL, PORT_NUM); + } + + public PortModel getPort() { + if (_port == null) { + _port = (PortModel)getFirstChildModel(PORT); + } + return _port; + } + + public Integer getPortNum() { + Configuration config = getModelConfiguration().getFirstChild(PORT_NUM); + return config != null ? Integer.valueOf(config.getValue()) : null; + } + + public SOAPBindingModel setPort(PortModel port) { + setChildModel(port); + _port = port; + return this; + } + + public WSDLModel getWSDL() { + if (_wsdl == null) { + _wsdl = (WSDLModel)getFirstChildModelStartsWith(WSDL); + } + return _wsdl; + } + + public SOAPBindingModel setWSDL(WSDLModel wsdl) { + setChildModel(wsdl); + _wsdl = wsdl; + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/SOAPMarshaller.java b/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/SOAPMarshaller.java new file mode 100644 index 000000000..5efe936b8 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/SOAPMarshaller.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.test.soap; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; + +/** + * SOAPMarshaller. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SOAPMarshaller extends BaseMarshaller { + + public SOAPMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(Configuration config) { + Descriptor desc = getDescriptor(); + String name = config.getName(); + if (name.startsWith(BindingModel.BINDING)) { + return new SOAPBindingModel(config, desc); + } else if (name.equals(PortModel.PORT)) { + return new PortModel(config, desc); + } else if (name.equals(WSDLModel.WSDL)) { + return new WSDLModel(config, desc); + } + return null; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/WSDLModel.java b/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/WSDLModel.java new file mode 100644 index 000000000..16a519ce8 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/composite/test/soap/WSDLModel.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.composite.test.soap; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.SCANamespace; + +/** + * WSDLModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class WSDLModel extends BaseModel { + + public static final String WSDL = "wsdl"; + public static final String DESCRIPTION = "description"; + + public WSDLModel() { + super(new QName(SCANamespace.DEFAULT.uri(), WSDL)); + } + + public WSDLModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + public SOAPBindingModel getBinding() { + return (SOAPBindingModel)getModelParent(); + } + + public String getDescription() { + return getModelAttribute(DESCRIPTION); + } + + public WSDLModel setDescription(String description) { + setModelAttribute(DESCRIPTION, description); + return this; + } + + public String getLocation() { + return getModelValue(); + } + + public WSDLModel setLocation(String location) { + setModelValue(location); + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/property/PropertiesModelTests.java b/core/config/src/test/java/org/switchyard/config/model/property/PropertiesModelTests.java new file mode 100644 index 000000000..d1514333b --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/property/PropertiesModelTests.java @@ -0,0 +1,85 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.property; + +import java.io.StringReader; +import java.util.Map; +import java.util.Properties; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * SwitchYardModelTests. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class PropertiesModelTests { + + private static final String XML = "/org/switchyard/config/model/property/PropertiesModelTests.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void testRead() throws Exception { + SwitchYardModel switchyard = _puller.pull(XML, getClass()); + PropertiesModel propsModel = switchyard.getDomain().getProperties(); + Assert.assertEquals(2, propsModel.getProperties().size()); // only includes (child) property models, not loaded properties + Properties propsProps = propsModel.toProperties(); + Assert.assertEquals(3, propsProps.size()); // combined properties contains all properties + Map propsMap = propsModel.toMap(); + Assert.assertEquals(3, propsMap.size()); // combined map contains all properties + Assert.assertEquals("tiger", propsModel.getPropertyValue("cat")); // property model overrides loaded properties + Assert.assertEquals("tiger", propsModel.resolveProperty("cat")); + Assert.assertEquals("tiger", propsProps.getProperty("cat")); + Assert.assertEquals("tiger", propsMap.get("cat")); + Assert.assertEquals("vizsla", propsModel.getPropertyValue("dog")); // only exists in property model, combined properties, and map + Assert.assertEquals("vizsla", propsModel.resolveProperty("dog")); + Assert.assertEquals("vizsla", propsProps.getProperty("dog")); + Assert.assertEquals("vizsla", propsMap.get("dog")); + Assert.assertNull(propsModel.getProperty("bird")); // only exists in loaded properties, combined properties, and map + Assert.assertEquals("crow", propsModel.getPropertyValue("bird")); + Assert.assertEquals("crow", propsModel.resolveProperty("bird")); + Assert.assertEquals("crow", propsProps.getProperty("bird")); + Assert.assertEquals("crow", propsMap.get("bird")); + } + + @Test + public void testWrite() throws Exception { + String old_xml = new StringPuller().pull(XML, getClass()); + SwitchYardModel switchyard = _puller.pull(new StringReader(old_xml)); + String new_xml = switchyard.toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testValidate() throws Exception { + SwitchYardModel switchyard = _puller.pull(XML, getClass()); + switchyard.assertModelValid(); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/EsbInterfaceTests.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/EsbInterfaceTests.java new file mode 100644 index 000000000..74e5fc25d --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/EsbInterfaceTests.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.ComponentModel; + +/** + * Test interface.esb configuration in composite model. + */ +public class EsbInterfaceTests { + + private static final String ESB_INTERFACE_XML = + "/org/switchyard/config/model/switchyard/EsbInterfaceTests.xml"; + + private SwitchYardModel _model; + + @Before + public void before() throws Exception { + ModelPuller puller = new ModelPuller(); + _model = puller.pull(ESB_INTERFACE_XML, getClass()); + Assert.assertTrue(_model.isModelValid()); + } + + @Test + public void testServiceInterface() { + ComponentModel comp = _model.getComposite().getComponents().get(0); + EsbInterfaceModel serviceInterface = (EsbInterfaceModel)comp.getServices().get(0).getInterface(); + Assert.assertNotNull(serviceInterface); + Assert.assertEquals(EsbInterfaceModel.ESB, serviceInterface.getType()); + } + + @Test + public void testReferenceInterface() { + ComponentModel comp = _model.getComposite().getComponents().get(0); + EsbInterfaceModel referenceInterface = (EsbInterfaceModel)comp.getReferences().get(0).getInterface(); + Assert.assertNotNull(referenceInterface); + Assert.assertEquals(EsbInterfaceModel.ESB, referenceInterface.getType()); + Assert.assertEquals(new QName("urn:123", "abc"), referenceInterface.getInputType()); + Assert.assertEquals("xyz", referenceInterface.getOutputType().toString()); + Assert.assertEquals("omg", referenceInterface.getFaultType().toString()); + } +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/PolicyConfigTests.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/PolicyConfigTests.java new file mode 100644 index 000000000..61062a66b --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/PolicyConfigTests.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard; + +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.v1.V1ComponentReferenceModel; +import org.switchyard.config.model.composite.v1.V1ComponentServiceModel; + +/** + * Test policy-related configuration in composite model. + */ +public class PolicyConfigTests { + + private static final QName POLICY_FOO = new QName("foo"); + private static final QName POLICY_BAR = new QName("bar"); + + private static final String CUSTOM_NS = "http://www.custom.org/ns/custom/1.0"; + private static final QName POLICY_THINGAMAGIG = new QName(CUSTOM_NS, "thingamagig", "cstm"); + private static final QName POLICY_NONAMESPACE_CLIENT_AUTHENTICATION = new QName("clientAuthentication"); + private static final QName POLICY_QUALIFIED_AUTHORIZATION = new QName("http://docs.oasis-open.org/ns/opencsa/sca/200912", "authorization", "sca"); + + private static final String POLICY_XML = + "/org/switchyard/config/model/composite/PolicyTests.xml"; + + private CompositeModel _model; + + @Before + public void before() throws Exception { + ModelPuller puller = new ModelPuller(); + _model = puller.pull(POLICY_XML, getClass()); + } + + @Test + public void requiresOnService() throws Exception { + ComponentModel comp = _model.getComponents().get(0); + ComponentServiceModel svc = comp.getServices().get(0); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_FOO)); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_BAR)); + } + + @Test + public void requiresOnReference() throws Exception { + ComponentModel comp = _model.getComponents().get(0); + ComponentReferenceModel ref = comp.getReferences().get(0); + Assert.assertTrue(ref.hasPolicyRequirement(POLICY_BAR)); + } + + @Test + public void buildPolicyConfig() throws Exception { + // Test service policy + ComponentServiceModel svc = new V1ComponentServiceModel(SwitchYardNamespace.DEFAULT.uri()); + svc.addPolicyRequirement(POLICY_FOO); + svc.addPolicyRequirement(POLICY_BAR); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_FOO)); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_BAR)); + + // Test reference policy + ComponentReferenceModel ref = new V1ComponentReferenceModel(SwitchYardNamespace.DEFAULT.uri()); + ref.addPolicyRequirement(POLICY_BAR); + Assert.assertTrue(ref.hasPolicyRequirement(POLICY_BAR)); + Assert.assertFalse(ref.hasPolicyRequirement(POLICY_FOO)); + svc.addPolicyRequirement(POLICY_FOO); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_FOO)); + } + + @Test + public void testAddedRequirements() throws Exception { + _model.getModelConfiguration().setAttribute("xmlns:cstm", CUSTOM_NS); + // a re-pull is necessary because of how we're setting the attribute above + _model = new ModelPuller().pull(new StringReader(_model.toString())); + ComponentModel comp = _model.getComponents().get(0); + ComponentServiceModel svc = comp.getServices().get(0); + svc.addPolicyRequirement(POLICY_THINGAMAGIG); + svc.addPolicyRequirement(POLICY_NONAMESPACE_CLIENT_AUTHENTICATION); + svc.addPolicyRequirement(POLICY_QUALIFIED_AUTHORIZATION); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_FOO)); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_BAR)); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_THINGAMAGIG)); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_NONAMESPACE_CLIENT_AUTHENTICATION)); + Assert.assertTrue(svc.hasPolicyRequirement(POLICY_QUALIFIED_AUTHORIZATION)); + } +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/SCABindingExtensionTests.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/SCABindingExtensionTests.java new file mode 100644 index 000000000..59232d3e0 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/SCABindingExtensionTests.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.SCABindingModel; +import org.switchyard.config.model.composite.v1.V1SCABindingModel; + +/** + * SCABindingExtensionTests. + */ +public class SCABindingExtensionTests { + + private static final String SCA_BINDING_XML = "/org/switchyard/config/model/switchyard/SCABindingTests.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void testCreate() throws Exception { + final String TARGET = "foo"; + final String TARGET_NS = "urn:bar"; + final String STRATEGY = "RoundRobin"; + + SCABindingModel scab = new V1SCABindingModel(SwitchYardNamespace.DEFAULT.uri()); + scab.setClustered(true) + .setLoadBalance(STRATEGY) + .setTarget(TARGET) + .setTargetNamespace(TARGET_NS); + + Assert.assertEquals(STRATEGY, scab.getLoadBalance()); + Assert.assertEquals(TARGET, scab.getTarget()); + Assert.assertEquals(TARGET_NS, scab.getTargetNamespace()); + + Assert.assertTrue(scab.isClustered()); + Assert.assertTrue(scab.hasTarget()); + Assert.assertTrue(scab.hasTargetNamespace()); + Assert.assertTrue(scab.isLoadBalanced()); + } + + @Test + public void testRead() throws Exception { + SwitchYardModel switchyard = _puller.pull(SCA_BINDING_XML, getClass()); + SCABindingModel sb = (SCABindingModel)switchyard.getComposite().getServices().get(0).getBindings().get(0); + SCABindingModel rb = (SCABindingModel)switchyard.getComposite().getReferences().get(0).getBindings().get(0); + + Assert.assertTrue(sb.isClustered()); + Assert.assertFalse(sb.isLoadBalanced()); + Assert.assertFalse(sb.hasTarget()); + Assert.assertFalse(sb.hasTargetNamespace()); + + Assert.assertTrue(rb.isClustered()); + Assert.assertEquals("RoundRobin", rb.getLoadBalance()); + Assert.assertEquals("somethingElse", rb.getTarget()); + Assert.assertEquals("urn:another:uri", rb.getTargetNamespace()); + } + + @Test + public void testValidation() throws Exception { + SwitchYardModel switchyard = _puller.pull(SCA_BINDING_XML, getClass()); + switchyard.assertModelValid(); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/SwitchYardModelTests.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/SwitchYardModelTests.java new file mode 100644 index 000000000..53fba110c --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/SwitchYardModelTests.java @@ -0,0 +1,218 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard; + +import java.io.StringReader; +import java.util.LinkedHashSet; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.Models; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.test.soap.PortModel; +import org.switchyard.config.model.composite.test.soap.SOAPBindingModel; +import org.switchyard.config.model.domain.DomainModel; +import org.switchyard.config.model.domain.SecuritiesModel; +import org.switchyard.config.model.domain.SecurityModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.switchyard.test.java.JavaTransformModel; +import org.switchyard.config.model.switchyard.test.smooks.SmooksConfigModel; +import org.switchyard.config.model.switchyard.test.smooks.SmooksTransformModel; +import org.switchyard.config.model.switchyard.v1.V1ArtifactModel; +import org.switchyard.config.model.switchyard.v1.V1ArtifactsModel; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.test.xmlunit.SchemaLocationDifferenceListener; + + +/** + * SwitchYardModelTests. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SwitchYardModelTests { + + private static final String INCOMPLETE_XML = "/org/switchyard/config/model/switchyard/SwitchYardModelTests-Incomplete.xml"; + private static final String FRAGMENT_XML = "/org/switchyard/config/model/switchyard/SwitchYardModelTests-Fragment.xml"; + private static final String COMPLETE_XML = "/org/switchyard/config/model/switchyard/SwitchYardModelTests-Complete.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void testCreateEmptyModel() throws Exception { + String name = SwitchYardModel.SWITCHYARD; + Model model = new ModelPuller().pull(XMLHelper.createQName(SwitchYardNamespace.V_1_1.uri(), name)); + Assert.assertTrue(model instanceof SwitchYardModel); + Assert.assertEquals(name, model.getModelConfiguration().getName()); + Assert.assertEquals(new QName(SwitchYardNamespace.V_1_1.uri(), name), model.getModelConfiguration().getQName()); + } + + @Test + public void testMerge() throws Exception { + SwitchYardModel incomplete_switchyard = _puller.pull(INCOMPLETE_XML, getClass()); + SwitchYardModel fragment_switchyard = _puller.pull(FRAGMENT_XML, getClass()); + SwitchYardModel merged_switchyard = Models.merge(fragment_switchyard, incomplete_switchyard); + XMLUnit.setIgnoreWhitespace(true); + SwitchYardModel complete_switchyard = _puller.pull(COMPLETE_XML, getClass()); + Diff diff = XMLUnit.compareXML(complete_switchyard.toString(), merged_switchyard.toString()); + diff.overrideDifferenceListener(new SchemaLocationDifferenceListener()); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testReadComplete() throws Exception { + SwitchYardModel switchyard = _puller.pull(COMPLETE_XML, getClass()); + CompositeModel composite = switchyard.getComposite(); + CompositeServiceModel service = composite.getServices().get(0); + // Verify composite service binding + SOAPBindingModel binding = (SOAPBindingModel)service.getBindings().get(0); + PortModel port = binding.getPort(); + Assert.assertEquals("MyWebService/SOAPPort", port.getPort()); + Assert.assertEquals("service.wsdl", binding.getWSDL().getLocation()); + ComponentModel component = port.getBinding().getService().getComposite().getComponents().get(0); + ComponentServiceModel componentService = component.getServices().get(0); + Assert.assertEquals("SimpleService", componentService.getName()); + Assert.assertTrue(componentService.hasPolicyRequirement(new QName("clientAuthentication"))); + Assert.assertEquals("theSecurityName", componentService.getSecurity()); + ComponentReferenceModel componentReference = component.getReferences().get(0); + Assert.assertEquals("anotherService", componentReference.getName()); + Assert.assertTrue(componentReference.hasPolicyRequirement(new QName("clientAuthentication"))); + Assert.assertEquals("theSecurityName", componentReference.getSecurity()); + String name = component.getName(); + Assert.assertEquals("SimpleService", name); + // Verify transform configuration + TransformsModel transforms = switchyard.getTransforms(); + JavaTransformModel java_transform = (JavaTransformModel)transforms.getTransforms().get(0); + Assert.assertEquals("msgA", java_transform.getFrom().getLocalPart()); + Assert.assertEquals("msgB", java_transform.getTo().getLocalPart()); + Assert.assertEquals("org.examples.transform.AtoBTransform", java_transform.getClazz()); + SmooksTransformModel smooks_transform = (SmooksTransformModel)transforms.getTransforms().get(1); + Assert.assertEquals("msgC", smooks_transform.getFrom().getLocalPart()); + Assert.assertEquals("msgD", smooks_transform.getTo().getLocalPart()); + SmooksConfigModel smooks_config = smooks_transform.getConfig(); + Assert.assertEquals("stuff", smooks_config.getData()); + // Verify domain configuration + DomainModel domain = switchyard.getDomain(); + Assert.assertEquals("TestDomain", domain.getName()); + // Verify property configuration + PropertiesModel props = domain.getProperties(); + Assert.assertEquals(8, props.getProperties().size()); + Assert.assertEquals("bar", props.getPropertyValue("foo")); + Assert.assertEquals("fish", props.getPropertyValue("tuna")); + Assert.assertEquals(System.getProperty("user.name"), props.getPropertyValue("userName")); + Assert.assertEquals(System.getProperty("os.name"), props.getPropertyValue("osName")); + Assert.assertEquals("iam", props.getPropertyValue("whoIsWill")); + Assert.assertEquals("stuff", props.getPropertyValue("smooksConfig")); + Assert.assertEquals("MyWebService", props.getPropertyValue("soapServiceName")); + Assert.assertEquals("service", props.getPropertyValue("soapWsdlName")); + Assert.assertEquals(switchyard, domain.getSwitchYard()); + // Verify artifact configuration + ArtifactsModel artifacts = switchyard.getArtifacts(); + Assert.assertEquals(1, artifacts.getArtifacts().size()); + ArtifactModel artifact = artifacts.getArtifact("OrderService"); + Assert.assertNotNull("ArtifactModel for OrderService was not read!", artifact); + Assert.assertEquals("OrderService", artifact.getName()); + Assert.assertEquals("http://localhost:8080/guvnorsoa/rest/packages/OrderService", artifact.getURL()); + // Verify security configuration + SecuritiesModel securities = domain.getSecurities(); + Assert.assertEquals(domain, securities.getDomain()); + SecurityModel security = securities.getSecurities().iterator().next(); + Assert.assertEquals(securities, security.getSecurities()); + Assert.assertEquals(Object.class, security.getCallbackHandler(getClass().getClassLoader())); + Assert.assertEquals("theSecurityName", security.getName()); + Set rolesAllowed = new LinkedHashSet(); + rolesAllowed.add("administrator"); + rolesAllowed.add("user"); + Assert.assertEquals(rolesAllowed, security.getRolesAllowed()); + Assert.assertEquals("leader", security.getRunAs()); + Assert.assertEquals("theSecurityDomain", security.getSecurityDomain()); + Assert.assertEquals("iam", security.getProperties().toProperties().getProperty("will")); + Assert.assertEquals("iam", security.getProperties().toMap().get("will")); + } + + @Test + public void testArtifactCreate() throws Exception { + ArtifactsModel artifacts = new V1ArtifactsModel(SwitchYardNamespace.V_1_0.uri()); + ArtifactModel artifact = new V1ArtifactModel(SwitchYardNamespace.V_1_0.uri()); + artifact.setName("foo"); + artifact.setURL("file://tmp/foo"); + artifacts.addArtifact(artifact); + + Assert.assertEquals("foo", artifact.getName()); + Assert.assertEquals("file://tmp/foo", artifact.getURL()); + + SwitchYardModel syModel = new V1SwitchYardModel(SwitchYardNamespace.V_1_0.uri()); + syModel.setArtifacts(artifacts); + Assert.assertEquals(artifacts, syModel.getArtifacts()); + } + + @Test + public void testWriteComplete() throws Exception { + String old_xml = new StringPuller().pull(COMPLETE_XML, getClass()); + SwitchYardModel switchyard = _puller.pull(new StringReader(old_xml)); + String new_xml = switchyard.toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testValidation() throws Exception { + SwitchYardModel switchyard = _puller.pull(COMPLETE_XML, getClass()); + switchyard.assertModelValid(); + } + + @Test + public void testTargetNamespace() throws Exception { + SwitchYardModel switchyard = _puller.pull(COMPLETE_XML, getClass()); + Assert.assertEquals("m1app", switchyard.getName()); + Assert.assertEquals(new QName("m1app"), switchyard.getQName()); + final String tns = "urn:m1app:example:1.0"; + CompositeModel composite = switchyard.getComposite(); + Assert.assertEquals("m1app", composite.getName()); + Assert.assertEquals(new QName(tns, "m1app"), composite.getQName()); + CompositeServiceModel compositeService = composite.getServices().iterator().next(); + Assert.assertEquals("M1AppService", compositeService.getName()); + Assert.assertEquals(new QName(tns, "M1AppService"), compositeService.getQName()); + ComponentModel component = composite.getComponents().iterator().next(); + Assert.assertEquals("SimpleService", component.getName()); + Assert.assertEquals(new QName(tns, "SimpleService"), component.getQName()); + ComponentServiceModel componentService = component.getServices().iterator().next(); + Assert.assertEquals("SimpleService", componentService.getName()); + Assert.assertEquals(new QName(tns, "SimpleService"), componentService.getQName()); + ComponentReferenceModel componentReference = component.getReferences().iterator().next(); + Assert.assertEquals("anotherService", componentReference.getName()); + Assert.assertEquals(new QName(tns, "anotherService"), componentReference.getQName()); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/ThrottlingExtensionTests.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/ThrottlingExtensionTests.java new file mode 100644 index 000000000..40872fa50 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/ThrottlingExtensionTests.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.model.switchyard; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.ExtensionsModel; +import org.switchyard.config.model.switchyard.v1.V1ThrottlingModel; + +/** + * ThrottlingExtensionTests. + */ +public class ThrottlingExtensionTests { + + private static final String THROTTLING_XML = "/org/switchyard/config/model/switchyard/ThrottlingExtensionTests.xml"; + private static final String THROTTLING_XML2 = "/org/switchyard/config/model/switchyard/ThrottlingExtensionTests2.xml"; + private static final Integer MAX_REQUESTS = 50; + private static final Long TIME_PERIOD = 2000L; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void testCreate() throws Exception { + ThrottlingModel throttling = new V1ThrottlingModel(SwitchYardNamespace.DEFAULT.uri()); + throttling.setMaxRequests(MAX_REQUESTS).setTimePeriod(TIME_PERIOD); + + Assert.assertEquals(MAX_REQUESTS, (Integer) throttling.getMaxRequests()); + Assert.assertEquals(TIME_PERIOD, throttling.getTimePeriod()); + } + + @Test + public void testRead() throws Exception { + SwitchYardModel switchyard = _puller.pull(THROTTLING_XML, getClass()); + ExtensionsModel extensions = switchyard.getComposite().getServices().get(0).getExtensions(); + ThrottlingModel throttling = extensions.getThrottling(); + + Assert.assertEquals(MAX_REQUESTS, (Integer) throttling.getMaxRequests()); + Assert.assertEquals(TIME_PERIOD, throttling.getTimePeriod()); + } + + @Test + public void testPropertySubstitution() throws Exception { + System.setProperty("property.messages.per.poll", "50"); + SwitchYardModel switchyard = _puller.pull(THROTTLING_XML2, getClass()); + switchyard.assertModelValid(); + ExtensionsModel extensions = switchyard.getComposite().getServices().get(0).getExtensions(); + ThrottlingModel throttling = extensions.getThrottling(); + + Assert.assertEquals(MAX_REQUESTS, (Integer) throttling.getMaxRequests()); + Assert.assertEquals(TIME_PERIOD, throttling.getTimePeriod()); + } + + @Test + public void testValidation() throws Exception { + SwitchYardModel switchyard = _puller.pull(THROTTLING_XML, getClass()); + switchyard.assertModelValid(); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/java/JavaMarshaller.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/java/JavaMarshaller.java new file mode 100644 index 000000000..5a7a3ac9f --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/java/JavaMarshaller.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.java; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardMarshaller; +import org.switchyard.config.model.transform.TransformModel; + +/** + * JavaMarshaller. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class JavaMarshaller extends V1SwitchYardMarshaller { + + private static final String TRANSFORM_JAVA = TransformModel.TRANSFORM + "." + JavaTransformModel.JAVA; + + public JavaMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(TRANSFORM_JAVA)) { + return new JavaTransformModel(config, desc); + } + return super.read(config); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/java/JavaTransformModel.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/java/JavaTransformModel.java new file mode 100644 index 000000000..9f008443e --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/java/JavaTransformModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.java; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; + +/** + * JavaTransformModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class JavaTransformModel extends V1BaseTransformModel { + + public static final String JAVA = "java"; + public static final String CLASS = "class"; + + public JavaTransformModel() { + super(new QName("urn:switchyard-config:test-java:1.0", TransformModel.TRANSFORM + '.' + JAVA)); + } + + public JavaTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + public String getClazz() { + return getModelAttribute(CLASS); + } + + public JavaTransformModel setClazz(String clazz) { + setModelAttribute(CLASS, clazz); + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksConfigModel.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksConfigModel.java new file mode 100644 index 000000000..eb8f726df --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksConfigModel.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.smooks; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; + +/** + * SmooksConfigModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SmooksConfigModel extends BaseModel { + + public static final String CONFIG = "config"; + + public SmooksConfigModel() { + super(new QName("urn:switchyard-config:test-smooks:1.0", CONFIG)); + } + + public SmooksConfigModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + public SmooksTransformModel getTransform() { + return (SmooksTransformModel)getModelParent(); + } + + public String getData() { + return getModelValue(); + } + + public SmooksConfigModel setData(String data) { + setModelValue(data); + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksMarshaller.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksMarshaller.java new file mode 100644 index 000000000..2b2be894e --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksMarshaller.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.smooks; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardMarshaller; +import org.switchyard.config.model.transform.TransformModel; + +/** + * JavaMarshaller. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SmooksMarshaller extends V1SwitchYardMarshaller { + + private static final String TRANSFORM_SMOOKS = TransformModel.TRANSFORM + "." + SmooksTransformModel.SMOOKS; + + public SmooksMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(TRANSFORM_SMOOKS)) { + return new SmooksTransformModel(config, desc); + } else if (name.equals(SmooksConfigModel.CONFIG)) { + return new SmooksConfigModel(config, desc); + } + return super.read(config); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksTransformModel.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksTransformModel.java new file mode 100644 index 000000000..af104a4f4 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/smooks/SmooksTransformModel.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.smooks; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; + +/** + * SmooksTransformModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SmooksTransformModel extends V1BaseTransformModel { + + public static final String SMOOKS = "smooks"; + + private SmooksConfigModel _config; + + public SmooksTransformModel() { + super(new QName("urn:switchyard-config:test-smooks:1.0", SMOOKS)); + setModelChildrenOrder(SmooksConfigModel.CONFIG); + } + + public SmooksTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(SmooksConfigModel.CONFIG); + } + + public SmooksConfigModel getConfig() { + if (_config == null) { + _config = (SmooksConfigModel)getFirstChildModelStartsWith(SmooksConfigModel.CONFIG); + } + return _config; + } + + public SmooksTransformModel setConfig(SmooksConfigModel config) { + setChildModel(config); + _config = config; + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/java/JavaMarshaller.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/java/JavaMarshaller.java new file mode 100644 index 000000000..ace3b5a3d --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/java/JavaMarshaller.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.validate.java; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardMarshaller; +import org.switchyard.config.model.validate.ValidateModel; + +/** + * JavaMarshaller. + * + * @author Tomohisa Igarashi + */ +public class JavaMarshaller extends V1SwitchYardMarshaller { + + private static final String VALIDATE_JAVA = ValidateModel.VALIDATE + "." + JavaValidateModel.JAVA; + + public JavaMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(VALIDATE_JAVA)) { + return new JavaValidateModel(config, desc); + } + return super.read(config); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/java/JavaValidateModel.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/java/JavaValidateModel.java new file mode 100644 index 000000000..24cba3c4c --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/java/JavaValidateModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.validate.java; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.v1.V1BaseValidateModel; + +/** + * JavaTransformModel. + * + * @author Tomohisa Igarashi + */ +public class JavaValidateModel extends V1BaseValidateModel { + + public static final String JAVA = "java"; + public static final String CLASS = "class"; + + public JavaValidateModel() { + super(new QName("urn:switchyard-config:test-validate-java:1.0", ValidateModel.VALIDATE + '.' + JAVA)); + } + + public JavaValidateModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + public String getClazz() { + return getModelAttribute(CLASS); + } + + public JavaValidateModel setClazz(String clazz) { + setModelAttribute(CLASS, clazz); + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/xml/XmlMarshaller.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/xml/XmlMarshaller.java new file mode 100644 index 000000000..8612af452 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/xml/XmlMarshaller.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.validate.xml; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardMarshaller; +import org.switchyard.config.model.validate.ValidateModel; + +/** + * XmlMarshaller. + * + * @author Tomohisa Igarashi + */ +public class XmlMarshaller extends V1SwitchYardMarshaller { + + private static final String VALIDATE_XML = ValidateModel.VALIDATE + "." + XmlValidateModel.XML; + + public XmlMarshaller(Descriptor desc) { + super(desc); + } + + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(VALIDATE_XML)) { + return new XmlValidateModel(config, desc); + } + return super.read(config); + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/xml/XmlValidateModel.java b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/xml/XmlValidateModel.java new file mode 100644 index 000000000..f43c8cf69 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/model/switchyard/test/validate/xml/XmlValidateModel.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.model.switchyard.test.validate.xml; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.v1.V1BaseValidateModel; + +/** + * XmlValidateModel. + * + * @author Tomohisa Igarashi + */ +public class XmlValidateModel extends V1BaseValidateModel { + + public static final String XML = "xml"; + public static final String SCHEMA_TYPE = "schemaType"; + public static final String SCHEMA_FILE = "schemaFile"; + public static final String FAIL_ON_WARN = "failOnWarn"; + + public XmlValidateModel() { + super(new QName("urn:switchyard-config:test-validate-xml:1.0", ValidateModel.VALIDATE + '.' + XML)); + } + + public XmlValidateModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + public String getSchemaType() { + return getModelAttribute(SCHEMA_TYPE); + } + + public XmlValidateModel setSchemaType(String type) { + setModelAttribute(SCHEMA_TYPE, type); + return this; + } + + public String getSchemaFile() { + return getModelAttribute(SCHEMA_FILE); + } + + public XmlValidateModel setSchemaFile(String file) { + setModelAttribute(SCHEMA_FILE, file); + return this; + } + + public boolean getFailOnWarning() { + String fow = getModelAttribute(FAIL_ON_WARN); + return Boolean.parseBoolean(fow); + } + + public XmlValidateModel setFailOnWarning(boolean fow) { + setModelAttribute(FAIL_ON_WARN, Boolean.toString(fow)); + return this; + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/test/xmlunit/SchemaLocationDifferenceListener.java b/core/config/src/test/java/org/switchyard/config/test/xmlunit/SchemaLocationDifferenceListener.java new file mode 100644 index 000000000..2aba55a8e --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/test/xmlunit/SchemaLocationDifferenceListener.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.config.test.xmlunit; + +import java.util.StringTokenizer; + +import org.custommonkey.xmlunit.Difference; +import org.custommonkey.xmlunit.DifferenceConstants; +import org.custommonkey.xmlunit.DifferenceListener; +import org.custommonkey.xmlunit.NodeDetail; +import org.switchyard.common.lang.Strings; +import org.w3c.dom.Node; + +/** + * Helps compare the xsi:schemaLocation attribute, who's potentially non-standard whitespace in between parts can cause problems. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class SchemaLocationDifferenceListener implements DifferenceListener { + + /** + * {@inheritDoc} + */ + @Override + public int differenceFound(Difference diff) { + if (diff.getId() == DifferenceConstants.SCHEMA_LOCATION_ID) { + String control = reduceWhitespace(diff.getControlNodeDetail()); + String test = reduceWhitespace(diff.getTestNodeDetail()); + if ((control == null && test == null) || (control != null && control.equals(test))) { + return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; + } + } + return RETURN_ACCEPT_DIFFERENCE; + } + + private String reduceWhitespace(NodeDetail nd) { + String value = nd.getValue(); + if (value != null) { + StringBuilder sb = new StringBuilder(); + StringTokenizer st = new StringTokenizer(value); + while (st.hasMoreTokens()) { + sb.append(st.nextToken()); + if (st.hasMoreTokens()) { + sb.append(' '); + } + } + value = Strings.trimToNull(sb.toString()); + } + return value; + } + + /** + * {@inheritDoc} + */ + @Override + public void skippedComparison(Node control, Node test) { + } + +} diff --git a/core/config/src/test/java/org/switchyard/config/util/classpath/ConfigClasspathScanTest.java b/core/config/src/test/java/org/switchyard/config/util/classpath/ConfigClasspathScanTest.java new file mode 100644 index 000000000..c6aa2e111 --- /dev/null +++ b/core/config/src/test/java/org/switchyard/config/util/classpath/ConfigClasspathScanTest.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.config.util.classpath; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.common.type.classpath.ClasspathScanner; +import org.switchyard.common.type.classpath.InstanceOfFilter; +import org.switchyard.config.BaseConfiguration; +import org.switchyard.config.Configuration; +import org.switchyard.config.DOMConfiguration; + +/** + * @author tom.fennelly@gmail.com + */ +public class ConfigClasspathScanTest { + + @Test + public void test_folder_scan() throws IOException { + InstanceOfFilter filter = new InstanceOfFilter(Configuration.class); + ClasspathScanner scanner = new ClasspathScanner(filter); + + // If running this test inside your IDE... you need to set the cwd to be the + // root of the config module !! + scanner.scan(new File("./target/classes").toURI().toURL()); + List> classes = filter.getMatchedTypes(); + + Assert.assertTrue(classes.contains(Configuration.class)); + Assert.assertTrue(classes.contains(BaseConfiguration.class)); + Assert.assertTrue(classes.contains(DOMConfiguration.class)); + } +} diff --git a/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-CdataValue.xml b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-CdataValue.xml new file mode 100644 index 000000000..d8d409ae3 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-CdataValue.xml @@ -0,0 +1,18 @@ + + + + test-simple-value> + test--value + \ No newline at end of file diff --git a/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-From.xml b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-From.xml new file mode 100644 index 000000000..f8e1c7a45 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-From.xml @@ -0,0 +1,18 @@ + + + + stuff + greek + \ No newline at end of file diff --git a/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-FromDoesntOverrideTo.xml b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-FromDoesntOverrideTo.xml new file mode 100644 index 000000000..c59612f30 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-FromDoesntOverrideTo.xml @@ -0,0 +1,19 @@ + + + + stuff + junk + roman + diff --git a/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-FromOverridesTo.xml b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-FromOverridesTo.xml new file mode 100644 index 000000000..5f0d927d8 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-FromOverridesTo.xml @@ -0,0 +1,19 @@ + + + + stuff + junk + greek + \ No newline at end of file diff --git a/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-Namespaces.xml b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-Namespaces.xml new file mode 100644 index 000000000..97af6c24d --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-Namespaces.xml @@ -0,0 +1,19 @@ + + + + stuff + metal + + \ No newline at end of file diff --git a/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-OrderChildren-Ordered.xml b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-OrderChildren-Ordered.xml new file mode 100644 index 000000000..ff8c68303 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-OrderChildren-Ordered.xml @@ -0,0 +1,30 @@ + + + + + a + b + c + + 2 + + c + b + a + + 4 + foo + bar + diff --git a/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-OrderChildren-Unordered.xml b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-OrderChildren-Unordered.xml new file mode 100644 index 000000000..bba65936f --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-OrderChildren-Unordered.xml @@ -0,0 +1,30 @@ + + + + 2 + + b + a + c + + foo + 4 + + b + a + c + + bar + diff --git a/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-To.xml b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-To.xml new file mode 100644 index 000000000..06a2f16d1 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/ConfigurationTests-To.xml @@ -0,0 +1,18 @@ + + + + junk + roman + \ No newline at end of file diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Complete.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Complete.xml new file mode 100644 index 000000000..f573b26e1 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Complete.xml @@ -0,0 +1,56 @@ + + + + + + MyWebService/SOAPPort + service.wsdl + ${foo:5500} + + + + + http://exmample.org:8080/services/SomeOtherService?wsdl + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Extended.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Extended.xml new file mode 100644 index 000000000..9180adc22 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Extended.xml @@ -0,0 +1,27 @@ + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Extension.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Extension.xml new file mode 100644 index 000000000..0a8150d60 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Extension.xml @@ -0,0 +1,28 @@ + + + + + + + + Foo + Bar + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Fragment.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Fragment.xml new file mode 100644 index 000000000..27d794e11 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Fragment.xml @@ -0,0 +1,33 @@ + + + + + + MyWebService/SOAPPort + service.wsdl + ${foo:5500} + + + + + http://exmample.org:8080/services/SomeOtherService?wsdl + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Incomplete.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Incomplete.xml new file mode 100644 index 000000000..7b2206301 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Incomplete.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Promote.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Promote.xml new file mode 100644 index 000000000..af39baf8d --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-Promote.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-PropertiesSelfReferring.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-PropertiesSelfReferring.xml new file mode 100644 index 000000000..81e046bc3 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-PropertiesSelfReferring.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-SCABinding.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-SCABinding.xml new file mode 100644 index 000000000..efdeffae5 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/CompositeModelTests-SCABinding.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/PolicyTests.xml b/core/config/src/test/resources/org/switchyard/config/model/composite/PolicyTests.xml new file mode 100644 index 000000000..bd6488cd6 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/PolicyTests.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/test/bean/bean.xsd b/core/config/src/test/resources/org/switchyard/config/model/composite/test/bean/bean.xsd new file mode 100644 index 000000000..efd2f9d55 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/test/bean/bean.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/test/bogus/bogus.xsd b/core/config/src/test/resources/org/switchyard/config/model/composite/test/bogus/bogus.xsd new file mode 100644 index 000000000..d4e9b21c1 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/test/bogus/bogus.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/test/common/common.xsd b/core/config/src/test/resources/org/switchyard/config/model/composite/test/common/common.xsd new file mode 100644 index 000000000..3ead0bae9 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/test/common/common.xsd @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/test/extension/extension.xsd b/core/config/src/test/resources/org/switchyard/config/model/composite/test/extension/extension.xsd new file mode 100644 index 000000000..634fd9f07 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/test/extension/extension.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/composite/test/soap/soap.xsd b/core/config/src/test/resources/org/switchyard/config/model/composite/test/soap/soap.xsd new file mode 100644 index 000000000..dfe21e8bb --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/composite/test/soap/soap.xsd @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/descriptor.properties b/core/config/src/test/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..12b2d569f --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,79 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +soap_1_0.section=urn:switchyard-config:test-soap +soap_1_0.version=1.0 +soap_1_0.namespace=urn:switchyard-config:test-soap:1.0 +soap_1_0.schema=soap.xsd +soap_1_0.location=/org/switchyard/config/model/composite/test/soap/ +soap_1_0.marshaller=org.switchyard.config.model.composite.test.soap.SOAPMarshaller + +bean_1_0.section=urn:switchyard-config:test-bean +bean_1_0.version=1.0 +bean_1_0.namespace=urn:switchyard-config:test-bean:1.0 +bean_1_0.schema=bean.xsd +bean_1_0.location=/org/switchyard/config/model/composite/test/bean/ +bean_1_0.marshaller=org.switchyard.config.model.composite.v1.V1CompositeMarshaller + +bogus_1_0.section=urn:switchyard-config:test-bogus +bogus_1_0.version=1.0 +bogus_1_0.namespace=urn:switchyard-config:test-bogus:1.0 +bogus_1_0.schema=bogus.xsd +bogus_1_0.location=/org/switchyard/config/model/composite/test/bogus/ +bogus_1_0.marshaller=org.switchyard.config.model.composite.test.bogus.BogusMarshaller + +extension_1_0.section=urn:switchyard-config:test-ext +extension_1_0.version=1.0 +extension_1_0.namespace=urn:switchyard-config:test-ext:1.0 +extension_1_0.schema=extension.xsd +extension_1_0.location=/org/switchyard/config/model/composite/test/extension/ +extension_1_0.marshaller=org.switchyard.config.model.composite.test.extension.ExtensionMarshaller + +common_1_0.section=common +common_1_0.version=1.0 +common_1_0.noNamespaceSchema=common.xsd +common_1_0.location=/org/switchyard/config/model/composite/test/common/ + +java_1_0.section=urn:switchyard-config:test-java +java_1_0.version=1.0 +java_1_0.namespace=urn:switchyard-config:test-java:1.0 +java_1_0.schema=java.xsd +java_1_0.location=/org/switchyard/config/model/switchyard/test/java/ +java_1_0.marshaller=org.switchyard.config.model.switchyard.test.java.JavaMarshaller + +smooks_1_0.section=urn:switchyard-config:test-smooks +smooks_1_0.version=1.0 +smooks_1_0.namespace=urn:switchyard-config:test-smooks:1.0 +smooks_1_0.schema=smooks.xsd +smooks_1_0.location=/org/switchyard/config/model/switchyard/test/smooks/ +smooks_1_0.marshaller=org.switchyard.config.model.switchyard.test.smooks.SmooksMarshaller + +validate_java_1_0.section=urn:switchyard-config:test-validate-java +validate_java_1_0.version=1.0 +validate_java_1_0.namespace=urn:switchyard-config:test-validate-java:1.0 +validate_java_1_0.schema=java.xsd +validate_java_1_0.location=/org/switchyard/config/model/switchyard/test/validate/java/ +validate_java_1_0.marshaller=org.switchyard.config.model.switchyard.test.validate.java.JavaMarshaller + +validate_xml_1_0.section=urn:switchyard-config:test-validate-xml +validate_xml_1_0.version=1.0 +validate_xml_1_0.namespace=urn:switchyard-config:test-validate-xml:1.0 +validate_xml_1_0.schema=xml.xsd +validate_xml_1_0.location=/org/switchyard/config/model/switchyard/test/validate/xml/ +validate_xml_1_0.marshaller=org.switchyard.config.model.switchyard.test.validate.xml.XmlMarshaller + +namespacetest_1_0.section=http://a.org/a.xsd +namespacetest_1_0.version=1.0 +namespacetest_1_0.namespace=http://a.org/a.xsd +namespacetest_1_0.schema=bogus.xsd +namespacetest_1_0.location=/org/switchyard/config/model/composite/test/bogus/ +namespacetest_1_0.marshaller=org.switchyard.config.ConfigurationTests$TestMarshaller diff --git a/core/config/src/test/resources/org/switchyard/config/model/property/PropertiesModelTests.xml b/core/config/src/test/resources/org/switchyard/config/model/property/PropertiesModelTests.xml new file mode 100644 index 000000000..3c67b7abd --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/property/PropertiesModelTests.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/property/load.properties b/core/config/src/test/resources/org/switchyard/config/model/property/load.properties new file mode 100644 index 000000000..7bfb1a184 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/property/load.properties @@ -0,0 +1,2 @@ +cat=lion +bird=crow \ No newline at end of file diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/EsbInterfaceTests.xml b/core/config/src/test/resources/org/switchyard/config/model/switchyard/EsbInterfaceTests.xml new file mode 100644 index 000000000..d16285f15 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/EsbInterfaceTests.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/SCABindingTests.xml b/core/config/src/test/resources/org/switchyard/config/model/switchyard/SCABindingTests.xml new file mode 100644 index 000000000..91d703f6e --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/SCABindingTests.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Complete.xml b/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Complete.xml new file mode 100644 index 000000000..d2abd2d9c --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Complete.xml @@ -0,0 +1,94 @@ + + + + + + + ${soapServiceName:SOAPService}/${soapPortName:SOAPPort} + ${soapWsdlName}.wsdl + + + + + + + + + + + + + + + + + + + + + + ${smooksConfig} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Fragment.xml b/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Fragment.xml new file mode 100644 index 000000000..2a888f77f --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Fragment.xml @@ -0,0 +1,29 @@ + + + + + + + ${soapServiceName:SOAPService}/${soapPortName:SOAPPort} + ${soapWsdlName}.wsdl + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Incomplete.xml b/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Incomplete.xml new file mode 100644 index 000000000..4376256ee --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/SwitchYardModelTests-Incomplete.xml @@ -0,0 +1,86 @@ + + + + + + + + + + + + + + + + + + + + + + + + ${smooksConfig} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/ThrottlingExtensionTests.xml b/core/config/src/test/resources/org/switchyard/config/model/switchyard/ThrottlingExtensionTests.xml new file mode 100644 index 000000000..a7644f949 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/ThrottlingExtensionTests.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/ThrottlingExtensionTests2.xml b/core/config/src/test/resources/org/switchyard/config/model/switchyard/ThrottlingExtensionTests2.xml new file mode 100644 index 000000000..f4a96e46a --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/ThrottlingExtensionTests2.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/java/java.xsd b/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/java/java.xsd new file mode 100644 index 000000000..5b747771a --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/java/java.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/smooks/smooks.xsd b/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/smooks/smooks.xsd new file mode 100644 index 000000000..065aab887 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/smooks/smooks.xsd @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/validate/java/java.xsd b/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/validate/java/java.xsd new file mode 100644 index 000000000..16affd016 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/validate/java/java.xsd @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/validate/xml/xml.xsd b/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/validate/xml/xml.xsd new file mode 100644 index 000000000..10eabdfb3 --- /dev/null +++ b/core/config/src/test/resources/org/switchyard/config/model/switchyard/test/validate/xml/xml.xsd @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + DTD. + + + + + + + W3C XML Schema. + + + + + + + RELAX NG. + + + + + + + diff --git a/core/deploy/base/pom.xml b/core/deploy/base/pom.xml new file mode 100644 index 000000000..bf127d202 --- /dev/null +++ b/core/deploy/base/pom.xml @@ -0,0 +1,90 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-deploy + bundle + SwitchYard: Deploy + The Deploy SPI. + http://switchyard.org + + org.switchyard.deploy.*;org.switchyard.standalone.* + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-extensions-java + + + org.switchyard + switchyard-extensions-wsdl + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-security + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard + switchyard-bus-camel + + + + org.mockito + mockito-all + test + + + org.switchyard + switchyard-runtime + test-jar + test + + + diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/Activator.java b/core/deploy/base/src/main/java/org/switchyard/deploy/Activator.java new file mode 100644 index 000000000..b96de5ee6 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/Activator.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy; + +import java.util.Collection; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentModel; + +/** + * Activators allow components to participate in the deployment lifecycle of + * a SwitchYard application. The deployer has a list of activators that map + * to implementation and binding types. During deployment, the deployer will + * build a list of activators for known types and enlist each activator in the + * lifecycle of the application. The deployer takes care of dependency ordering + * between services, references, and bindings and invokes Activator instances + * in the appropriate order. + */ +public interface Activator { + + /** + * Activate a reference or service binding. This is equivalent to a + * create/init for the binding and it's configuration. Validation errors + * with config should be reported from this method. + * @param name name of the service or reference + * @param config binding configuration + * @return a lifecycle-aware service handler used to process exchanges + */ + ServiceHandler activateBinding(QName name, BindingModel config); + /** + * Activate a service implementation. This is equivalent to a + * create/init for the service implementation and it's configuration. + * Validation errors with config should be reported from this method. Note + * that if a service component declares multiple services for a single + * implementation, this method will be called once for each service on + * that implementation. + * @param name name of the service + * @param config component configuration + * @return a lifecycle-aware service handler used to process exchanges + */ + ServiceHandler activateService(QName name, ComponentModel config); + + /** + * Deactivate a binding. This is equivalent to remove/destroy for the + * binding. The handler that was returned from activateBinding() is + * passed as a parameter in case it's needed for callback purposes. + * @param name name of the service or reference binding + * @param handler the handler returned from activateBinding + */ + void deactivateBinding(QName name, ServiceHandler handler); + + /** + * Deactivate a service. This is equivalent to remove/destroy for the + * service. The handler that was returned from activateService() is + * passed as a parameter in case it's needed for callback purposes. Note + * that if a service component declares multiple services for a single + * implementation, this method will be called once for each service on + * that implementation. + * @param name name of the service + * @param handler the handler returned from activateService + */ + void deactivateService(QName name, ServiceHandler handler); + + /** + * Whether the activator can handle a given . + * @param type activation type + * @return true If this Activator can activate the passed-in type. + */ + boolean canActivate(String type); + /** + * Get the types that this Activator can activate. + * @return Collection The activation types that this Activator supports. + */ + Collection getActivationTypes(); + + /** + * Destroys an Activator instance. Called during undeploy and allows the + * activator to perform cleanup of any lingering resources. + */ + void destroy(); +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/ActivatorLoader.java b/core/deploy/base/src/main/java/org/switchyard/deploy/ActivatorLoader.java new file mode 100644 index 000000000..236de3b72 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/ActivatorLoader.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy; + +import java.util.ArrayList; +import java.util.List; + +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.common.util.ProviderRegistry; + +/** + * Contains utilities for creating {@link Activator}s. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public final class ActivatorLoader { + + private static Logger _log = Logger.getLogger(ActivatorLoader.class); + + private ActivatorLoader() { + } + + /** + * Creates a List of component Activators using the ServiceLoader logic. + * + * @param serviceDomain The service domain to be used by the activator. + * @return A List of activators. + */ + public static List createActivators(ServiceDomain serviceDomain) { + List activators = new ArrayList(); + for (Component component : ProviderRegistry.getProviders(Component.class)) { + Activator activator = component.createActivator(serviceDomain); + _log.debug("Registered activator " + activator.getClass()); + activators.add(activator); + } + return activators; + } + + /** + * Creates a List of component Activators using the List of already discovered components. + * + * @param serviceDomain The service domain to be used by the activator. + * @param components The components from which the activators are created. + * @param types List of types to be activated + * @return A List of activators. + */ + public static List createActivators(ServiceDomain serviceDomain, List components, List types) { + List activators = new ArrayList(); + for (Component component : components) { + if (canActivate(component, types)) { + Activator activator = component.createActivator(serviceDomain); + _log.debug("Registered activator " + activator.getClass()); + activators.add(activator); + } + } + return activators; + } + + /** + * Determine if a component is eligible to activate a given set of types. + */ + private static boolean canActivate(Component component, List activationTypes) { + for (String componentType : component.getActivationTypes()) { + if (activationTypes.contains(componentType)) { + return true; + } + } + + return false; + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/BaseActivator.java b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseActivator.java new file mode 100644 index 000000000..ca8e04f87 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseActivator.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.ServiceDomain; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentModel; + +/** + * Base implementation of Activator which provides a convenience implementation + * for declaring activation types. + */ +public abstract class BaseActivator implements Activator { + + private List _activationTypes = new LinkedList(); + private ServiceDomain _serviceDomain; + + protected BaseActivator(String ... types) { + if (types != null) { + _activationTypes.addAll(Arrays.asList(types)); + } + } + + @Override + public ServiceHandler activateBinding(QName name, BindingModel config) { + throw BaseDeployMessages.MESSAGES.activateBindingNotSupported(getClass().getName()); + } + + @Override + public ServiceHandler activateService(QName name, ComponentModel config) { + throw BaseDeployMessages.MESSAGES.activateServiceNotSupported(getClass().getName()); + } + + + @Override + public void deactivateBinding(QName name, ServiceHandler handler) { + throw BaseDeployMessages.MESSAGES.deactivateBindingNotSupported(getClass().getName()); + } + + @Override + public void deactivateService(QName name, ServiceHandler handler) { + throw BaseDeployMessages.MESSAGES.deactivateServiceNotSupported(getClass().getName()); + } + + + /** + * Sets the service domain instance of this activator. + * @param serviceDomain the service domain + */ + public void setServiceDomain(ServiceDomain serviceDomain) { + _serviceDomain = serviceDomain; + } + + /** + * Gets the service domain instance of this activator. + * @return the service domain + */ + public ServiceDomain getServiceDomain() { + return _serviceDomain; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean canActivate(String type) { + return _activationTypes.contains(type); + } + + /** + * {@inheritDoc} + */ + @Override + public Collection getActivationTypes() { + return Collections.unmodifiableList(_activationTypes); + } + + @Override + public void destroy() { + // NOP so that Activator impls don't have to bother with this method + // if they don't have anything to do in destroy(). + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/BaseComponent.java b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseComponent.java new file mode 100644 index 000000000..ec82b44ac --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseComponent.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy; + +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.switchyard.config.Configuration; +import org.switchyard.config.Configurations; + +/** + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public abstract class BaseComponent implements Component { + + private String _name; + private Configuration _config = Configurations.newConfiguration(); + private List _activationTypes = new LinkedList(); + + protected BaseComponent(String ... types) { + if (types != null) { + _activationTypes.addAll(Arrays.asList(types)); + } + } + + /* (non-Javadoc) + * @see org.switchyard.deploy.Component#getName() + */ + @Override + public String getName() { + return _name; + } + + /** + * Sets the name of this component. + * + * @param name the name to set + * @see org.switchyard.deploy.Component#getName() + */ + public void setName(String name) { + _name = name; + } + + /* (non-Javadoc) + * @see org.switchyard.deploy.Component#init(org.switchyard.config.Configuration) + */ + @Override + public void init(Configuration config) { + _config = config; + } + + /** + * Returns the configuration for this component. + * + * @return the configuration used to initialize this component + * @see org.switchyard.deploy.Component#init(org.switchyard.config.Configuration) + */ + public Configuration getConfig() { + return _config; + } + + @Override + public List getActivationTypes() { + return Collections.unmodifiableList(_activationTypes); + } + + /* (non-Javadoc) + * @see org.switchyard.deploy.Component#destroy() + */ + @Override + public void destroy() { + } + + @Override + public void addResourceDependency(Object value) { + // ignore by default + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/BaseDeployLogger.java b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseDeployLogger.java new file mode 100644 index 000000000..b527860e7 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseDeployLogger.java @@ -0,0 +1,91 @@ +package org.switchyard.deploy; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.INFO; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.MessageLogger; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +/** + *

+ * This file is using the subset 12000-12199 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface BaseDeployLogger { + /** + * Default root logger. + */ + BaseDeployLogger ROOT_LOGGER = Logger.getMessageLogger(BaseDeployLogger.class, BaseDeployLogger.class.getPackage().getName()); + + /** + * errorStoppingServiceBinding method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 10900, value="Error stopping service binding.") + void errorStoppingServiceBinding(@Cause Throwable e); + + /** + * errorStoppingServiceBinding method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 10901, value="Error deactivating service binding.") + void errorDeactivatingServiceBinding(@Cause Throwable e); + + + /** + * errorStoppingServiceBinding method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 10902, value="Error stopping service.") + void errorStoppingService(@Cause Throwable e); + + /** + * errorStoppingServiceBinding method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 10903, value="Error deactivating service.") + void errorDeactivatingService(@Cause Throwable e); + + + /** + * errorStoppingReferenceBinding method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 10904, value="Error stopping reference binding.") + void errorStoppingReferenceBinding(@Cause Throwable e); + + /** + * errorDeactivatingReferenceBinding method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 10905, value="Error deactivating reference binding.") + void errorDeactivatingReferenceBinding(@Cause Throwable e); + + /** + * enforcingInteractionPolicyDependency method definition. + * @param dependency dependency + * @param subject subject + */ + @LogMessage(level = INFO) + @Message(id = 10906, value="Enforcing %s interaction policy as a dependency of %s") + void enforcingInteractionPolicyDependency(String dependency, String subject); + + /** + * enforcingImplementationPolicyDependency method definition. + * @param dependency dependency + * @param subject subject + */ + @LogMessage(level = INFO) + @Message(id = 10907, value="Enforcing %s implementation policy as a dependency of %s") + void enforcingImplementationPolicyDependency(String dependency, String subject); +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/BaseDeployMessages.java b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseDeployMessages.java new file mode 100644 index 000000000..2a75f1d25 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseDeployMessages.java @@ -0,0 +1,263 @@ +package org.switchyard.deploy; + +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; +/** + *

+ * This file is using the subset 12200-12399 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface BaseDeployMessages { + /** + * Default messages. + */ + BaseDeployMessages MESSAGES = Messages.getBundle(BaseDeployMessages.class); + + /** + * usagePath method definition. + * @param path path + * @return Localized string + */ + @Message(id = 12200, value = "Usage: %s path-to-switchyard-config") + String usagePath(String path); + + /** + * notValidConfigFile method definition. + * @param arg arg + * @return Localized string + */ + @Message(id = 12201, value = "'%s' is not a valid SwitchYard configuration file.") + String notValidConfigFile(String arg); + + /** + * activateBindingNotSupported method definition. + * @param className className + * @return UnsupportedOperationException + */ + @Message(id = 12202 , value = "activateBinding() not supported by %s") + UnsupportedOperationException activateBindingNotSupported(String className); + + /** + * activateServiceNotSupported method definition. + * @param className className + * @return UnsupportedOperationException + */ + @Message(id = 12203 , value = "activateService() not supported by %s") + UnsupportedOperationException activateServiceNotSupported(String className); + + /** + * deactivateBindingNotSupported method definition. + * @param className className + * @return UnsupportedOperationException + */ + @Message(id = 12204 , value = "deactivateBinding() not supported by %s") + UnsupportedOperationException deactivateBindingNotSupported(String className); + + /** + * deactivateServiceNotSupported method definition. + * @param className className + * @return UnsupportedOperationException + */ + @Message(id = 12205 , value = "deactivateService() not supported by %s") + UnsupportedOperationException deactivateServiceNotSupported(String className); + + /** + * duplicateSecurityConfigurationNames method definition. + * @param key key + * @return IllegalStateException + */ + @Message(id = 12206 , value = "Duplicate security configuration names calculated: %s") + IllegalStateException duplicateSecurityConfigurationNames(String key); + + /** + * invalidHandlerState method definition. + * @return SwitchYardException + */ + @Message(id = 12207 , value = "Invalid handler state.") + SwitchYardException invalidHandlerState(); + + /** + * stateCannotBeNull method definition. + * @return SwitchYardException + */ + @Message(id = 12208 , value = "state cannot be null.") + SwitchYardException stateCannotBeNull(); + + /** + * activatorNotFoundForType method definition. + * @param type type + * @return SwitchYardException + */ + @Message(id = 12209 , value = "Activator not found for type: %s") + SwitchYardException activatorNotFoundForType(String type); + + /** + * componentDefNoImpl method definition. + * @param componentName componentName + * @return SwitchYardException + */ + @Message(id = 12210 , value = "Component defintion %s does not included an implementation definition.") + SwitchYardException componentDefNoImpl(String componentName); + + /** + * failedToLoadServiceInterface method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id = 12211 , value = "Failed to load Service interface class '%s'.") + SwitchYardException failedToLoadServiceInterface(String className); + + /** + * inputTypeRequired method definition. + * @param esbInterface esbInterface + * @return SwitchYardException + */ + @Message(id = 12212 , value = "inputType required on ESB interface definition: %s") + SwitchYardException inputTypeRequired(String esbInterface); + + /** + * faultTypeNeedsOutputType method definition. + * @param esbInterface esbInterface + * @return SwitchYardException + */ + @Message(id = 12213 , value = "faultType must be acommpanied by outputType in ESB interface: %s") + SwitchYardException faultTypeNeedsOutputType(String esbInterface); + + /** + * componentReferenceBindingsNotAllowed method definition. + * @param model model + * @param reference reference + * @return SwitchYardException + */ + @Message(id = 12215 , value = "Component Reference bindings are not allowed. Found %s on reference %s") + SwitchYardException componentReferenceBindingsNotAllowed(String model, String reference); + + /** + * unableCollectRequirements method definition. + * @param reference reference + * @param e e + * @return SwitchYardException + */ + @Message(id = 12216 , value = "Unable to collect requirements for %s") + SwitchYardException unableCollectRequirements(String reference, @Cause Exception e); + + + /** + * multipleServicesFound method definition. + * @param componentName componentName + * @return SwitchYardException + */ + @Message(id = 12217 , value = "Multiple services in the Component '%s' - Just one service is allowed") + SwitchYardException multipleServicesFound(String componentName); + + + /** + * componentServiceBindingsNotAllowed method definition. + * @param model model + * @param service service + * @return SwitchYardException + */ + @Message(id = 12218 , value = "Component Service bindings are not allowed. Found %s on service %s") + SwitchYardException componentServiceBindingsNotAllowed(String model, String service); + + + + + /** + * policyNotInteraction method definition. + * @param policyType policyType + * @return SwitchYardException + */ + @Message(id = 12219 , value = "Policy '%s' is not an interaction policy.") + SwitchYardException policyNotInteraction(String policyType); + + /** + * interactionPolicyShouldBeRequestedWith method definition. + * @param policy policy + * @param required required + * @return SwitchYardException + */ + @Message(id = 12220 , value = "Interaction Policy '%s' should be requested with '%s'") + SwitchYardException interactionPolicyShouldBeRequestedWith(String policy, String required); + + /** + * interactionPolicyRequiresImplPolicy method definition. + * @param policy policy + * @param required required + * @param implementation implementation + * @return SwitchYardException + */ + @Message(id = 12221 , value = "Interaction Policy '%s' requires '%s' Implementation Policy, but it does not exist. %s") + SwitchYardException interactionPolicyRequiresImplPolicy(String policy, String required, String implementation); + + /** + * interactionPolicyNotCompatible method definition. + * @param policy policy + * @param policyTwo policyTwo + * @return SwitchYardException + */ + @Message(id = 12222 , value = "Interaction Policy '%s' and '%s' are not compatible.") + SwitchYardException interactionPolicyNotCompatible(String policy, String policyTwo); + + /** + * policyNotImplementationPolicy method definition. + * @param policy policy + * @return SwitchYardException + */ + @Message(id = 12223 , value = "Policy '%s' is not an implementation policy.") + SwitchYardException policyNotImplementationPolicy(String policy); + + /** + * implementationPolicyShouldBeRequestedWith method definition. + * @param policy policy + * @param required required + * @return SwitchYardException + */ + @Message(id = 12224 , value = "Implementation Policy '%s' should be requested with '%s'") + SwitchYardException implementationPolicyShouldBeRequestedWith(String policy, String required); + + /** + * implementationPolicyRequiresInterPolicy method definition. + * @param policy policy + * @param required required + * @param interaction interaction + * @return SwitchYardException + */ + @Message(id = 12225 , value = "Implementation Policy '%s' requires '%s' Interaction Policy, but it does not exist. %s") + SwitchYardException implementationPolicyRequiresInterPolicy(String policy, String required, String interaction); + + /** + * implementationPolicyNotCompatible method definition. + * @param policy policy + * @param policyTwo policyTwo + * @return SwitchYardException + */ + @Message(id = 12226 , value = "Implementation Policy '%s' and '%s' are not compatible.") + SwitchYardException implementationPolicyNotCompatible(String policy, String policyTwo); + + /** + * implementationPolicyNotCompatibleWithInteraction method definition. + * @param policy policy + * @param policyTwo policyTwo + * @return SwitchYardException + */ + @Message(id = 12227 , value = "Implementation Policy '%s' is not compatible with Interaction Policy '%s'.") + SwitchYardException implementationPolicyNotCompatibleWithInteraction(String policy, String policyTwo); + + + /** + * serviceRegHidesService method definition. + * @param name name + * @param service service + * @return SwitchYardException + */ + @Message(id = 12228 , value = "Service registration with name %s hides %s") + SwitchYardException serviceRegHidesService(String name, String service); + + +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/BaseServiceHandler.java b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseServiceHandler.java new file mode 100644 index 000000000..4368e67e9 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/BaseServiceHandler.java @@ -0,0 +1,127 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy; + +import static org.switchyard.deploy.internal.AbstractDeployment.CLASSLOADER_PROPERTY; + +import org.switchyard.BaseHandler; +import org.switchyard.ServiceDomain; + +/** + * NOP implementation of ServiceHandler. + */ +public class BaseServiceHandler extends BaseHandler implements ServiceHandler { + + private State _state = State.NONE; + + final private ServiceDomain _domain; + + /** + * Creates a service handler that will not override the context class loader + * used when start/stop are invoked. + */ + public BaseServiceHandler() { + this(null); + } + + protected BaseServiceHandler(ServiceDomain domain) { + _domain = domain; + } + + @Override + public synchronized void start() { + if (_state == State.STARTED) { + // already started + return; + } else if (_state != State.NONE) { + throw BaseDeployMessages.MESSAGES.invalidHandlerState(); + } + final ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader(); + try { + final ClassLoader deploymentCL = getDeploymentClassLoader(); + if (deploymentCL != null) { + Thread.currentThread().setContextClassLoader(deploymentCL); + } + setState(State.STARTING); + try { + doStart(); + setState(State.STARTED); + } catch (RuntimeException e) { + setState(State.NONE); + throw e; + } + } finally { + Thread.currentThread().setContextClassLoader(oldTCCL); + } + } + + protected void doStart() { + } + + @Override + public synchronized void stop() { + if (_state == State.NONE) { + // already stopped + return; + } else if (_state != State.STARTED) { + throw BaseDeployMessages.MESSAGES.invalidHandlerState(); + } + final ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader(); + try { + final ClassLoader deploymentCL = getDeploymentClassLoader(); + if (deploymentCL != null) { + Thread.currentThread().setContextClassLoader(deploymentCL); + } + setState(State.STOPPING); + try { + doStop(); + setState(State.NONE); + } catch (RuntimeException e) { + setState(State.STARTED); + throw e; + } + } finally { + Thread.currentThread().setContextClassLoader(oldTCCL); + } + } + + protected void doStop() { + } + + @Override + public State getState() { + return _state; + } + + /** + * @param newState the new state of the service handler. + */ + protected void setState(State newState) { + if (newState == null) { + throw BaseDeployMessages.MESSAGES.stateCannotBeNull(); + } + _state = newState; + } + + /** + * @return the class loader for the deployment using this handler. + */ + protected ClassLoader getDeploymentClassLoader() { + return _domain == null + ? null + : (ClassLoader) _domain.getProperty(CLASSLOADER_PROPERTY); + } + +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/Binding.java b/core/deploy/base/src/main/java/org/switchyard/deploy/Binding.java new file mode 100644 index 000000000..eea9f8c26 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/Binding.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy; + +import java.util.LinkedList; +import java.util.List; + +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.metadata.Registrant; + +/** + * Represents binding metadata for a service or reference. + */ +public class Binding implements Registrant { + + private List _configs = new LinkedList(); + + /** + * Create a new Binding instance. + * @param configs list of binding configs + */ + public Binding(List configs) { + if (configs != null) { + _configs.addAll(configs); + } + } + + /** + * Create a new Binding instance. + * @param config binding configuration + */ + public Binding(BindingModel config) { + _configs.add(config); + } + + @Override + public boolean isBinding() { + return true; + } + + @Override + public boolean isImplementation() { + return false; + } + + @SuppressWarnings("unchecked") + @Override + public List getConfig() { + return _configs; + } + +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/Component.java b/core/deploy/base/src/main/java/org/switchyard/deploy/Component.java new file mode 100644 index 000000000..46fd67e30 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/Component.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy; + +import java.util.List; + +import org.switchyard.ServiceDomain; +import org.switchyard.config.Configuration; + +/** + * Components allow components to participate in the deployment and configuration lifecycle of + * a SwitchYard runtime. Components are initialized during boot strap process at system startup. + * There is exactly one instance of a particular SwitchYard Component per SwitchYard runtime. + */ +public interface Component { + /** + * Creates and configures an Activator associated with this Component. + * Component instances should attempt to use the domain passed + * to configure the Activator associated with them. + * @param domain The SwitchYard Service Domain. + * @return An Activator instance that will be used by deployments. + */ + Activator createActivator(ServiceDomain domain); + + /** + * Get the activator types that this Component can create. + * @return List The activation types that this Component supports. + */ + List getActivationTypes(); + + /** + * Returns the name of the Component instance. + * @return The name. + */ + String getName(); + /** + * Initialize a component based on the supplied environment/global + * configuration. Component instances should attempt to use the + * configuration passed when necessary to configure the Activator + * associated with them. + * @param config switchyard environment/global configuration for the component + */ + void init(Configuration config); + /** + * Destroy the specified Component. Component implementations should + * use this lifecyle method to clean up any resources used by Activators. + */ + void destroy(); + + /** + * @return the configuration used by this component. + * @see #init(Configuration) + */ + Configuration getConfig(); + + /** + * Inject a resource dependency on Component. + * + * TODO This API should be changed to more generic& configurable way + * https://issues.jboss.org/browse/SWITCHYARD-833 + * + * @param value resource instance + */ + void addResourceDependency(Object value); +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/ComponentNames.java b/core/deploy/base/src/main/java/org/switchyard/deploy/ComponentNames.java new file mode 100644 index 000000000..bb7723173 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/ComponentNames.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy; + +import javax.xml.namespace.QName; + +import org.switchyard.ServiceReference; + +/** + * Utility class for constructing and parsing service and reference names + * qualified with a service component name. + */ +public final class ComponentNames { + + private ComponentNames() { + + } + + /** + * Construct a qualified reference name based on the specified component and reference name. + * @param componentName service component name + * @param referenceName reference name + * @return qualified name + */ + public static QName qualify(QName componentName, QName referenceName) { + return qualify(componentName.getLocalPart(), + referenceName.getLocalPart(), componentName.getNamespaceURI()); + } + + /** + * Construct a qualified reference name based on the specified component, reference name + * and namespace. + * @param componentName service component name + * @param referenceName reference name + * @param namespaceURI namespace URI + * @return qualified name + */ + public static QName qualify(String componentName, String referenceName, String namespaceURI) { + return new QName(namespaceURI, componentName + "/" + referenceName); + } + + /** + * Return an unqualified name from the given service reference, removing the name of the + * service component. + * @param reference service reference + * @return name without service component name included + */ + public static QName unqualify(ServiceReference reference) { + return unqualify(reference.getName()); + } + + /** + * Return an unqualified name from the given service reference name, removing the name of the + * service component. + * @param refName service reference name + * @return name without service component name included + */ + public static QName unqualify(QName refName) { + if (refName.getLocalPart().contains("/")) { + String name = refName.getLocalPart().split("/")[1]; + refName = new QName(refName.getNamespaceURI(), name); + } + return refName; + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/Implementation.java b/core/deploy/base/src/main/java/org/switchyard/deploy/Implementation.java new file mode 100644 index 000000000..be0d7e720 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/Implementation.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy; + +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.metadata.Registrant; + +/** + * Represents implementation metadata for a service or reference. + */ +public class Implementation implements Registrant { + + private ComponentImplementationModel _config; + + /** + * Create a new Implementation instance. + * @param config implementation configuration + */ + public Implementation(ComponentImplementationModel config) { + _config = config; + } + + @Override + public boolean isBinding() { + return false; + } + + @Override + public boolean isImplementation() { + return true; + } + + @SuppressWarnings("unchecked") + @Override + public ComponentImplementationModel getConfig() { + return _config; + } + +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/Lifecycle.java b/core/deploy/base/src/main/java/org/switchyard/deploy/Lifecycle.java new file mode 100644 index 000000000..28dc56bcb --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/Lifecycle.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy; + +/** + * Lifecycle + *

+ * Provides common lifecycle methods. + */ +public interface Lifecycle { + + /** + * Represents the current state of a Lifecycle object. + */ + public enum State { + /** No state. */ + NONE, + /** + * In the process of starting, i.e. start() has been invoked, but has + * not yet completed. + */ + STARTING, + /** + * The object has been started and is running, i.e. start() has been + * invoked and has successfully completed. + */ + STARTED, + /** + * In the process of stopping, i.e. stop() has been invoked, but has not + * yet completed. + */ + STOPPING; + } + + /** + * Start processing. + */ + void start(); + + /** + * Stop processing. + */ + void stop(); + + /** + * @return the current state of this object. + */ + State getState(); +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/ServiceDomainManager.java b/core/deploy/base/src/main/java/org/switchyard/deploy/ServiceDomainManager.java new file mode 100644 index 000000000..5bb424a61 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/ServiceDomainManager.java @@ -0,0 +1,186 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceSecurity; +import org.switchyard.bus.camel.CamelExchangeBus; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.config.model.domain.DomainModel; +import org.switchyard.config.model.domain.SecuritiesModel; +import org.switchyard.config.model.domain.SecurityModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.internal.DefaultServiceRegistry; +import org.switchyard.internal.DomainImpl; +import org.switchyard.internal.EventManager; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.internal.validate.BaseValidatorRegistry; +import org.switchyard.security.service.DefaultServiceDomainSecurity; +import org.switchyard.security.service.DefaultServiceSecurity; +import org.switchyard.security.service.ServiceDomainSecurity; +import org.switchyard.security.system.SystemSecurity; +import org.switchyard.spi.ServiceRegistry; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.validate.ValidatorRegistry; + +/** + * {@link org.switchyard.ServiceDomain} manager class. + *

+ * Currently supports a flat ServiceDomain model with a ServiceDomain per application/deployment, + * all managed from this container level bean. Deployments are supplied with a {@link DomainProxy} + * instance which can first delegate service lookup to the application's own domain, but on lookup + * failure, can then delegate to this class in order to continue the lookup across all application + * ServiceDomain's managed by the container. + *

+ * This model does not yet support the notion of multiple isolated ServiceDomains. This class will + * change or go away. + * + * @author tom.fennelly@gmail.com + */ +public class ServiceDomainManager { + + /** + * Root domain property. + */ + public static final QName ROOT_DOMAIN = new QName("org.switchyard.domains.root"); + + // Share the same service registry and bus across domains to give visibility + // to registered services across application domains + private ServiceRegistry _registry = new DefaultServiceRegistry(); + private EventManager _eventManager = new EventManager(); + private final SystemSecurity _systemSecurity; + + /** + * Constructs a new ServiceDomainManager. + */ + public ServiceDomainManager() { + this(SystemSecurity.DEFAULT); + } + + /** + * Constructs a new ServiceDomainManager with the specified SystemSecurity. + * @param systemSecurity the SystemSecurity + */ + public ServiceDomainManager(SystemSecurity systemSecurity) { + _systemSecurity = systemSecurity; + } + + /** + * Create a ServiceDomain instance. + *

+ * Uses {@link #ROOT_DOMAIN} as the domain name. + * @return The ServiceDomain instance. + */ + public ServiceDomain createDomain() { + return createDomain(ROOT_DOMAIN, null); + } + + /** + * Create a ServiceDomain instance. + * @param domainName The domain name. + * @param switchyardConfig The SwitchYard configuration. + * @return The ServiceDomain instance. + */ + public ServiceDomain createDomain(QName domainName, SwitchYardModel switchyardConfig) { + TransformerRegistry transformerRegistry = new BaseTransformerRegistry(); + ValidatorRegistry validatorRegistry = new BaseValidatorRegistry(); + + SwitchYardCamelContextImpl camelContext = new SwitchYardCamelContextImpl(); + CamelExchangeBus bus = new CamelExchangeBus(camelContext); + + ServiceDomainSecurity serviceDomainSecurity = getServiceDomainSecurity(switchyardConfig); + + DomainImpl domain = new DomainImpl( + domainName, _registry, bus, transformerRegistry, validatorRegistry, _eventManager, serviceDomainSecurity); + camelContext.setServiceDomain(domain); + + // set properties on the domain + Map properties = getDomainProperties(switchyardConfig); + for (Map.Entry property : properties.entrySet()) { + domain.setProperty(property.getKey(), property.getValue()); + } + + // now that all resources and properties are set, init the domain + domain.init(); + return domain; + } + + /** + * Return the shared EventManager used for all ServiceDomain instances. + * @return EventManager instance + */ + public EventManager getEventManager() { + return _eventManager; + } + + /** + * Return the shared ServiceRegistry used for all ServiceDomain instance. + * @return ServiceRegistry instance + */ + public ServiceRegistry getRegistry() { + return _registry; + } + + protected ServiceDomainSecurity getServiceDomainSecurity(SwitchYardModel switchyard) { + Map serviceSecurities = new HashMap(); + if (switchyard != null) { + DomainModel domain = switchyard.getDomain(); + if (domain != null) { + SecuritiesModel securities = domain.getSecurities(); + if (securities != null) { + for (SecurityModel security : securities.getSecurities()) { + if (security != null) { + PropertiesModel properties = security.getProperties(); + ServiceSecurity value = new DefaultServiceSecurity() + .setName(security.getName()) + .setCallbackHandler(security.getCallbackHandler(getClass().getClassLoader())) + .setProperties(properties != null ? properties.toMap() : null) + .setRolesAllowed(security.getRolesAllowed()) + .setRunAs(security.getRunAs()) + .setSecurityDomain(security.getSecurityDomain()); + String key = value.getName(); + if (!serviceSecurities.containsKey(key)) { + serviceSecurities.put(key, value); + } else { + throw BaseDeployMessages.MESSAGES.duplicateSecurityConfigurationNames(key); + } + } + } + } + } + } + return new DefaultServiceDomainSecurity(serviceSecurities, _systemSecurity); + } + + protected Map getDomainProperties(SwitchYardModel config) { + if (config != null) { + DomainModel domain = config.getDomain(); + if (domain != null) { + PropertiesModel properties = domain.getProperties(); + if (properties != null) { + return properties.toMap(); + } + } + } + return Collections.emptyMap(); + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/ServiceHandler.java b/core/deploy/base/src/main/java/org/switchyard/deploy/ServiceHandler.java new file mode 100644 index 000000000..32db75ddc --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/ServiceHandler.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy; + +import org.switchyard.ExchangeHandler; + +/** + * Lifecycle-aware version of ExchangeHandler. The deployer will invoke + * start() and stop() in accordance with the deployment's lifecycle. + */ +public interface ServiceHandler extends ExchangeHandler, Lifecycle { + +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/event/ApplicationDeployedEvent.java b/core/deploy/base/src/main/java/org/switchyard/deploy/event/ApplicationDeployedEvent.java new file mode 100644 index 000000000..748ca7d21 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/event/ApplicationDeployedEvent.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.event; + +import java.util.EventObject; + +import org.switchyard.deploy.internal.AbstractDeployment; + +/** + * Fired when a SwitchYard application is deployed. + */ +public class ApplicationDeployedEvent extends EventObject { + + private static final long serialVersionUID = 8389754361920353347L; + + /** + * Creates a new ApplicationDeployedEvent event. + * @param deployment the application deployment + */ + public ApplicationDeployedEvent(AbstractDeployment deployment) { + super(deployment); + } + + /** + * Gets the deployed application. + * @return application deployment + */ + public AbstractDeployment getDeployment() { + return (AbstractDeployment)getSource(); + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/event/ApplicationUndeployedEvent.java b/core/deploy/base/src/main/java/org/switchyard/deploy/event/ApplicationUndeployedEvent.java new file mode 100644 index 000000000..d7a404a03 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/event/ApplicationUndeployedEvent.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.event; + +import java.util.EventObject; + +import org.switchyard.deploy.internal.AbstractDeployment; + +/** + * Fired when a SwitchYard application is undeployed. + */ +public class ApplicationUndeployedEvent extends EventObject { + + private static final long serialVersionUID = 8389754361920353347L; + + /** + * Creates a new ApplicationUndeployedEvent event. + * @param deployment the application deployment + */ + public ApplicationUndeployedEvent(AbstractDeployment deployment) { + super(deployment); + } + + /** + * Gets the undeployed application. + * @return application deployment + */ + public AbstractDeployment getDeployment() { + return (AbstractDeployment)getSource(); + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/internal/AbstractDeployment.java b/core/deploy/base/src/main/java/org/switchyard/deploy/internal/AbstractDeployment.java new file mode 100644 index 000000000..657162f2a --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/internal/AbstractDeployment.java @@ -0,0 +1,216 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.internal; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.Lifecycle; +import org.switchyard.transform.internal.TransformerRegistryLoader; +import org.switchyard.validate.internal.ValidatorRegistryLoader; + +/** + * Abstract SwitchYard application deployment. + * + * @author tom.fennelly@gmail.com + */ +public abstract class AbstractDeployment { + /** + * Default classpath location for the switchyard configuration. + */ + public static final String SWITCHYARD_XML = "/META-INF/switchyard.xml"; + + /** + * Deployment classloader property name. + */ + public static final String CLASSLOADER_PROPERTY = + "org.switchyard.deployment.DeploymentClassLoader"; + + /** + * Parent deployment. + */ + private AbstractDeployment _parentDeployment; + /** + * The Service Domain. + */ + private ServiceDomain _serviceDomain; + /** + * Transform registry loaded for the deployment. + */ + private TransformerRegistryLoader _transformerRegistryLoader; + /** + * Validate registry loaded for the deployment. + */ + private ValidatorRegistryLoader _validatorRegistryLoader; + /** + * SwitchYard configuration. + */ + private SwitchYardModel _switchyardConfig; + /** + * The name for this deployment. + */ + private QName _name; + + /** + * Flag to indicate whether or not deployment should fail if an activator is not available. + */ + private boolean _failOnMissingActivator = true; + + /** + * Create a new instance of a deployment from a configuration model. + * @param configModel switchyard config model + */ + protected AbstractDeployment(SwitchYardModel configModel) { + _switchyardConfig = configModel; + } + + /** + * Set the parent deployment. + *

+ * This must be called before calling {@link #init(org.switchyard.ServiceDomain,List)}. + * @param parentDeployment The parent deployment. + */ + public void setParentDeployment(AbstractDeployment parentDeployment) { + this._parentDeployment = parentDeployment; + } + + /** + * Should the deployment fail on a missing Activator. + * @return {@code true} if the deployment should fail, otherwise {@code false}. + */ + public boolean failOnMissingActivator() { + return _failOnMissingActivator; + } + + /** + * Set whether or not the deployment should fail on a missing Activator. + * @param failOnMissingActivator {@code true} if the deployment should fail, otherwise {@code false}. + */ + public void setFailOnMissingActivator(boolean failOnMissingActivator) { + this._failOnMissingActivator = failOnMissingActivator; + } + + /** + * Initialise the deployment. + * @param appServiceDomain The ServiceDomain for the application. + * @param activators The list of SwitchYard component activators. + */ + public final void init(ServiceDomain appServiceDomain, List activators) { + if (appServiceDomain == null) { + throw new IllegalArgumentException("null 'appServiceDomain' argument."); + } + + // initialize deployment name + if (getConfig() != null) { + _name = getConfig().getQName(); + if (_name == null) { + // initialize to composite name if config name is missing + if (getConfig().getComposite() != null) { + _name = getConfig().getComposite().getQName(); + } + } + } + + _serviceDomain = appServiceDomain; + _serviceDomain.setProperty(CLASSLOADER_PROPERTY, Classes.getTCCL()); + _transformerRegistryLoader = new TransformerRegistryLoader(appServiceDomain); + _transformerRegistryLoader.loadOOTBTransforms(); + + _validatorRegistryLoader = new ValidatorRegistryLoader(appServiceDomain.getValidatorRegistry()); + _validatorRegistryLoader.loadOOTBValidates(); + + doInit(activators); + } + + + /** + * This field is not available until after the deployment has been + * initialized. + * + * @return the name for this deployment; may be null. + */ + public QName getName() { + return _name; + } + + /** + * Get the {@link ServiceDomain} associated with the deployment. + * @return The domain instance. + */ + public ServiceDomain getDomain() { + if (_parentDeployment == null) { + return _serviceDomain; + } else { + return _parentDeployment.getDomain(); + } + } + + /** + * Get the {@link TransformerRegistryLoader} associated with the deployment. + * @return The TransformerRegistryLoader instance. + */ + public TransformerRegistryLoader getTransformerRegistryLoader() { + return _transformerRegistryLoader; + } + + /** + * Get the {@link ValidatorRegistryLoader} associated with the deployment. + * @return The ValidatorRegistryLoader instance. + */ + public ValidatorRegistryLoader getValidatorRegistryLoader() { + return _validatorRegistryLoader; + } + + /** + * Initialize the deployment + */ + protected abstract void doInit(List activators); + + /** + * Start/un-pause the deployment. + */ + public abstract void start(); + + /** + * Stop/pause the deployment. + */ + public abstract void stop(); + + /** + * Destroy the deployment. + */ + public abstract void destroy(); + + /** + * Retrieves the Lifecycle for the specified gateway. + * + * @param serviceName the name of the service or reference providing the gateway. + * @param bindingName the name of the gateway (binding) + * @return the Lifecycle object associated with the gateway. + */ + public abstract Lifecycle getGatwayLifecycle(QName serviceName, String bindingName); + + /** + * @return the SwitchYard configuration for this deployment. + */ + public SwitchYardModel getConfig() { + return _switchyardConfig; + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/deploy/internal/Deployment.java b/core/deploy/base/src/main/java/org/switchyard/deploy/internal/Deployment.java new file mode 100644 index 000000000..5b42e8f0b --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/deploy/internal/Deployment.java @@ -0,0 +1,898 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.Service; +import org.switchyard.ServiceMetadata; +import org.switchyard.ServiceReference; +import org.switchyard.SwitchYardException; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.ComponentReferenceModel; +import org.switchyard.config.model.composite.ComponentServiceModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.composite.ExtensionsModel; +import org.switchyard.config.model.composite.InterfaceModel; +import org.switchyard.config.model.switchyard.EsbInterfaceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.ThrottlingModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.model.validate.ValidatesModel; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseDeployLogger; +import org.switchyard.deploy.BaseDeployMessages; +import org.switchyard.deploy.Binding; +import org.switchyard.deploy.ComponentNames; +import org.switchyard.deploy.Implementation; +import org.switchyard.deploy.Lifecycle; +import org.switchyard.deploy.ServiceHandler; +import org.switchyard.deploy.event.ApplicationDeployedEvent; +import org.switchyard.deploy.event.ApplicationUndeployedEvent; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.extensions.wsdl.WSDLReaderException; +import org.switchyard.extensions.wsdl.WSDLService; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.metadata.ServiceMetadataBuilder; +import org.switchyard.metadata.qos.Throttling; +import org.switchyard.policy.Policy; +import org.switchyard.policy.Policy.PolicyType; +import org.switchyard.policy.PolicyFactory; + +/** + * Deployment is a framework-independent representation of a deployed SwitchYard + * application. At this point, a deployment is 1:1 with a SwitchYard domain, but + * this will change to allow multiple deployments to participate in a single, + * shared domain. + * @author tom.fennelly@gmail.com + */ +public class Deployment extends AbstractDeployment { + + private static Logger _log = Logger.getLogger(Deployment.class); + + private Map _activators = new HashMap(); + private List _components = new LinkedList(); + private List _serviceBindings = new LinkedList(); + private List _referenceBindings = new LinkedList(); + + /** + * Create a new instance of Deployer from a configuration stream. + * @param configStream stream containing switchyard config + * @throws IOException Error reading configuration model. + */ + public Deployment(InputStream configStream) throws IOException { + super(new ModelPuller().pull(configStream)); + } + + /** + * Create a new instance of Deployer from a configuration model. + * @param configModel switchyard config model + */ + public Deployment(SwitchYardModel configModel) { + super(configModel); + } + + /** + * Initialize the deployment. + * + * @param activators The list of component activators. + */ + protected void doInit(List activators) { + _log.debug("Initializing deployment " + getName()); + // create a new domain and load transformer , validator and activator instances for lifecycle + registerTransformers(); + registerValidators(); + if (activators != null) { + for (Activator activator : activators) { + Collection activationTypes = activator.getActivationTypes(); + if (activationTypes != null) { + for (String type : activationTypes) { + _log.debug("Registered activation type " + type + + " for activator " + activator.getClass() + " on deployment " + getName()); + _activators.put(type, activator); + } + } + } + } + + getDomain().getEventPublisher().publish(new ApplicationDeployedEvent(this)); + } + + /** + * Starts the deployment. All services are registered and the appropriate + * activators are triggered. + */ + public void start() { + _log.debug("Starting deployment " + getName()); + // ordered startup lifecycle + try { + deployReferenceBindings(); + deployImplementations(); + deployServiceBindings(); + } catch (RuntimeException e1) { + // Undo partial deployment... + _log.debug("Undeploying partially deployed artifacts of failed deployment " + getConfig().getQName()); + try { + stop(); + } catch (RuntimeException e2) { + // Nothing we can do... + _log.debug("Failed to properly undeploy a partial/failed deployment " + getConfig().getQName(), e2); + } + // Rethrow the exception... + throw e1; + } + } + + /** + * Stops the deployment. All services are unregistered and the appropriate + * activators are triggered. + */ + public void stop() { + _log.debug("Stopping deployment " + getName()); + undeployServiceBindings(); + undeployImplementations(); + undeployReferenceBindings(); + } + + /** + * Tear everything down. + */ + public void destroy() { + _log.debug("Destroying deployment " + getName()); + + // Clean up our list of activations, just in case something's left + _serviceBindings.clear(); + _components.clear(); + _referenceBindings.clear(); + + getValidatorRegistryLoader().unregisterValidators(); + getTransformerRegistryLoader().unregisterTransformers(); + + getDomain().getEventPublisher().publish(new ApplicationUndeployedEvent(this)); + getDomain().destroy(); + } + + @Override + public Lifecycle getGatwayLifecycle(final QName serviceName, final String bindingName) { + // TODO: look at a more efficient way of doing this + for (Activation binding : _serviceBindings) { + if (bindingName.equals(binding.getBindingModel().getName()) && serviceName.equals(binding.getName())) { + return binding.getHandler(); + } + } + for (Activation binding : _referenceBindings) { + if (bindingName.equals(binding.getBindingModel().getName()) && serviceName.equals(binding.getName())) { + return binding.getHandler(); + } + } + return null; + } + + /** + * Find the deployment activator for the specified type. + * + * @param type The activator component type. + * @return Activator the Activator instance, or null if no activator exists for the specified type. + * @throws SwitchYardException if the component definition does not contain + * an implementation type + */ + public Activator findActivator(String type) throws SwitchYardException { + if (_activators.containsKey(type)) { + return _activators.get(type); + } else if (failOnMissingActivator()) { + throw BaseDeployMessages.MESSAGES.activatorNotFoundForType(type); + } else { + return null; + } + } + + /** + * Returns a list of activator types required by this deployment. The list + * is built from implementation, service binding, and reference binding + * types in the application. + * @return list of activator type names + */ + public List getActivationTypes() { + HashSet types = new HashSet(); + CompositeModel composite = getConfig().getComposite(); + if (composite != null) { + // reference bindings + for (CompositeReferenceModel reference : composite.getReferences()) { + for (BindingModel binding : reference.getBindings()) { + types.add(binding.getType()); + } + } + // service bindings + for (CompositeServiceModel service : composite.getServices()) { + for (BindingModel binding : service.getBindings()) { + types.add(binding.getType()); + } + } + // implementations + for (ComponentModel component : composite.getComponents()) { + if (component.getImplementation() != null) { + types.add(component.getImplementation().getType()); + } + } + } + + return new ArrayList(types); + } + + /** + * Finds an activator that handles the component implementation type. + * @throws SwitchYardException if the component definition does not contain + * an implementation type + */ + private Activator findActivator(ComponentModel component) throws SwitchYardException { + if (component.getImplementation() == null) { + throw BaseDeployMessages.MESSAGES.componentDefNoImpl(component.getName()); + } + return findActivator(component.getImplementation().getType()); + } + + private void registerTransformers() { + _log.debug("Registering configured Transformers for deployment " + getName()); + TransformsModel transforms = getConfig().getTransforms(); + getTransformerRegistryLoader().registerTransformers(transforms); + } + + private void registerValidators() { + _log.debug("Registering configured Validators for deployment " + getName()); + ValidatesModel validates = getConfig().getValidates(); + getValidatorRegistryLoader().registerValidators(validates); + } + + private void deployReferenceBindings() { + _log.debug("Deploying reference bindings for deployment " + getName()); + // activate bindings for each service + CompositeModel composite = getConfig().getComposite(); + if (composite == null) { + return; + } + for (CompositeReferenceModel reference : composite.getReferences()) { + int bindingCount = 0; + for (BindingModel binding : reference.getBindings()) { + QName refQName = reference.getQName(); + ++bindingCount; + if (binding.getName() == null) { + _log.debug("Initializing binding name for binding " + bindingCount + " for reference " + + reference.getQName() + " for deployment " + getName()); + binding.setName("_" + reference.getName() + "_" + binding.getType() + "_" + bindingCount); + } + _log.debug("Deploying binding " + binding.getName() + " for reference " + + reference.getQName() + " for deployment " + getName()); + + Activator activator = findActivator(binding.getType()); + if (activator == null) { + continue; + } + + ServiceHandler handler = activator.activateBinding(reference.getQName(), binding); + Activation activation = new Activation(activator, reference.getQName(), binding, handler); + ServiceInterface si = getCompositeReferenceInterface(reference); + Binding bindingMetadata = new Binding(binding); + validateServiceRegistration(refQName); + ServiceMetadata metadata = ServiceMetadataBuilder.create().registrant(bindingMetadata).build(); + Service svc = getDomain().registerService(refQName, si, handler, metadata); + activation.addService(svc); + _referenceBindings.add(activation); + + handler.start(); + } + } + } + + private ServiceInterface getCompositeReferenceInterface(CompositeReferenceModel compositeRefModel) { + ServiceInterface serviceInterface = null; + if (hasCompositeReferenceInterface(compositeRefModel)) { + serviceInterface = loadServiceInterface(compositeRefModel.getInterface()); + } else { + List componentRefModels = compositeRefModel.getComponentReferences(); + switch (componentRefModels.size()) { + case 0: + break; + case 1: + ComponentReferenceModel componentRefModel = componentRefModels.iterator().next(); + if (hasComponentReferenceInterface(componentRefModel)) { + serviceInterface = loadServiceInterface(componentRefModel.getInterface()); + } + break; + default: + throw new SwitchYardException("A composite reference interface must be defined if promoting more than one component reference."); + } + } + return serviceInterface; + } + + private ServiceInterface getCompositeServiceInterface(CompositeServiceModel compositeServiceModel) { + ServiceInterface serviceInterface = null; + if (hasCompositeServiceInterface(compositeServiceModel)) { + serviceInterface = loadServiceInterface(compositeServiceModel.getInterface()); + } else if (hasComponentServiceInterface(compositeServiceModel.getComponentService())) { + serviceInterface = loadServiceInterface(compositeServiceModel.getComponentService().getInterface()); + } + return serviceInterface; + } + + private Throttling getCompositeServiceThrottling(CompositeServiceModel compositeServiceModel) { + final ExtensionsModel extensions = compositeServiceModel.getExtensions(); + if (extensions == null) { + return null; + } + final ThrottlingModel throttling = extensions.getThrottling(); + if (throttling == null) { + return null; + } + final Long timePeriod = throttling.getTimePeriod(); + final Throttling retVal = new Throttling(); + retVal.setMaxRequests(throttling.getMaxRequests()); + if (timePeriod != null) { + retVal.setTimePeriod(timePeriod); + } + return retVal; + } + + private boolean hasComponentReferenceInterface(ComponentReferenceModel componentRef) { + return componentRef != null && componentRef.getInterface() != null; + } + + private boolean hasCompositeReferenceInterface(CompositeReferenceModel compositeRef) { + return compositeRef != null && compositeRef.getInterface() != null; + } + + private boolean hasComponentServiceInterface(ComponentServiceModel componentService) { + return componentService != null && componentService.getInterface() != null; + } + + private boolean hasCompositeServiceInterface(CompositeServiceModel compositeService) { + return compositeService != null && compositeService.getInterface() != null; + } + + private ServiceInterface getComponentReferenceInterface(ComponentReferenceModel reference) { + ServiceInterface referenceInterface = null; + + if (reference != null && reference.getInterface() != null) { + referenceInterface = loadServiceInterface(reference.getInterface()); + } + return referenceInterface; + } + + private ServiceInterface getComponentServiceInterface(ComponentServiceModel service) { + ServiceInterface serviceInterface = null; + + if (service != null && service.getInterface() != null) { + serviceInterface = loadServiceInterface(service.getInterface()); + } + return serviceInterface; + } + + private ServiceInterface loadServiceInterface(InterfaceModel intfModel) { + ServiceInterface serviceInterface = null; + + if (intfModel != null) { + if (isJavaInterface(intfModel.getType())) { + String interfaceClass = intfModel.getInterface(); + Class serviceInterfaceType = loadClass(interfaceClass); + + if (serviceInterfaceType == null) { + throw BaseDeployMessages.MESSAGES.failedToLoadServiceInterface(interfaceClass); + } + serviceInterface = JavaService.fromClass(serviceInterfaceType); + } else if (InterfaceModel.WSDL.equals(intfModel.getType())) { + try { + serviceInterface = WSDLService.fromWSDL(intfModel.getInterface()); + } catch (WSDLReaderException wsdlre) { + throw new SwitchYardException(wsdlre); + } + } else if (EsbInterfaceModel.ESB.equals(intfModel.getType())) { + EsbInterfaceModel esbIntf = (EsbInterfaceModel)intfModel; + validateEsbInterface(esbIntf); + if (esbIntf.getOutputType() == null) { + serviceInterface = new InOnlyService(new InOnlyOperation( + ServiceInterface.DEFAULT_OPERATION, esbIntf.getInputType())); + } else { + serviceInterface = new InOutService(new InOutOperation( + ServiceInterface.DEFAULT_OPERATION, + esbIntf.getInputType(), esbIntf.getOutputType(), esbIntf.getFaultType())); + } + } + } + + return serviceInterface; + } + + // Checks for invalid input/output/fault combinations on ESB interfaces. + private void validateEsbInterface(EsbInterfaceModel esbIntf) { + if (esbIntf.getInputType() == null) { + throw BaseDeployMessages.MESSAGES.inputTypeRequired(esbIntf.toString()); + } + + if (esbIntf.getFaultType() != null && esbIntf.getOutputType() == null) { + throw BaseDeployMessages.MESSAGES.faultTypeNeedsOutputType(esbIntf.toString()); + } + } + + private boolean isJavaInterface(final String type) { + return InterfaceModel.JAVA.equals(type); + } + + private void deployImplementations() { + if (getConfig().getComposite() == null) { + return; + } + for (ComponentModel component : getConfig().getComposite().getComponents()) { + Activator activator = findActivator(component); + if (activator == null) { + continue; + } + + List requiresImpl = null; + try { + requiresImpl = getPolicyRequirements(component.getImplementation()); + } catch (Exception e) { + throw new SwitchYardException(e); + } + + Implementation impl = new Implementation(component.getImplementation()); + List references = new LinkedList(); + + // register a reference for each one declared in the component + for (ComponentReferenceModel reference : component.getReferences()) { + // Create the reference name qualified with component name to ensure uniqueness + QName refName = ComponentNames.qualify(component.getQName(), reference.getQName()); + + _log.debug("Registering reference " + refName + " for component " + + component.getImplementation().getType() + " for deployment " + getName()); + + // Component Reference bindings not allowed, check to see if we find one and throw an exception + List models = reference.getModelChildren(); + for (Model model : models) { + if (BindingModel.class.isAssignableFrom(model.getClass())) { + throw BaseDeployMessages.MESSAGES.componentReferenceBindingsNotAllowed(model.toString(), reference.toString()); + } + } + List requires = null; + try { + requires = getPolicyRequirements(reference); + } catch (Exception e) { + throw BaseDeployMessages.MESSAGES.unableCollectRequirements(reference.toString(), e); + } + processPolicyDependency(requires, requiresImpl); + validatePolicy(requires, requiresImpl); + + ServiceInterface refIntf = getComponentReferenceInterface(reference); + ServiceMetadata metadata = ServiceMetadataBuilder.create() + .security(getDomain().getServiceSecurity(reference.getSecurity())) + .requiredPolicies(requires).registrant(impl) + .build(); + ServiceReference svcRef = getDomain().registerServiceReference(refName, refIntf, null, metadata); + + boolean wired = false; + // wire a reference if the name is different from promoted name + compositeReferenceLoop: for (CompositeReferenceModel compositeReference : getConfig().getComposite().getReferences()) { + for (ComponentReferenceModel componentReference : compositeReference.getComponentReferences()) { + if (componentReference != null && componentReference.equals(reference)) { + if (!componentReference.getQName().equals(compositeReference.getQName())) { + svcRef.wire(compositeReference.getQName()); + wired = true; + break compositeReferenceLoop; + } + } + } + } + + // if we didn't wire to a promoted reference, then default to unqualified service name + if (!wired) { + svcRef.wire(ComponentNames.unqualify(svcRef)); + } + references.add(svcRef); + } + + // register a service for each one declared in the component + if (component.getServices().size() > 1) { + throw BaseDeployMessages.MESSAGES.multipleServicesFound(component.getName()); + } else if (component.getServices().size() == 1) { + ComponentServiceModel service = component.getServices().get(0); + _log.debug("Registering service " + service.getQName() + + " for component " + component.getImplementation().getType() + " for deployment " + getName()); + + + // Component Service bindings not allowed, check to see if we find one and throw an exception + List models = service.getModelChildren(); + for (Model model : models) { + if (BindingModel.class.isAssignableFrom(model.getClass())) { + throw BaseDeployMessages.MESSAGES.componentServiceBindingsNotAllowed(model.toString(), service.toString()); + } + } + + + List requires = null; + try { + requires = getPolicyRequirements(service); + processPolicyDependency(requires, requiresImpl); + validatePolicy(requires, requiresImpl); + } catch (Exception e) { + throw new SwitchYardException(e); + } + requires.addAll(requiresImpl); + + ServiceHandler handler = activator.activateService(service.getQName(), component); + Activation activation = new Activation(activator, component.getQName(), null, handler); + ServiceInterface serviceIntf = getComponentServiceInterface(service); + ServiceMetadata metadata = ServiceMetadataBuilder.create() + .security(getDomain().getServiceSecurity(service.getSecurity())) + .requiredPolicies(requires) + .registrant(impl) + .build(); + + Service svc = getDomain().registerService(service.getQName(), serviceIntf, handler, metadata); + activation.addService(svc); + activation.addReferences(references); + + // register any service promotions + for (CompositeServiceModel compositeService : getConfig().getComposite().getServices()) { + ComponentServiceModel componentService = compositeService.getComponentService(); + if (componentService != null && componentService.equals(service)) { + // avoid duplicates + if (!service.getQName().equals(compositeService.getQName())) { + validateServiceRegistration(compositeService.getQName()); + Service promotedService = getDomain().registerService( + compositeService.getQName(), serviceIntf, handler, metadata); + activation.addPromotion(promotedService); + } + } + } + + _components.add(activation); + handler.start(); + + } else { + // we don't have a distinct call for activateReference right now, + // so this catches cases where an implementation has one or more + // references, but no services. (this is pretty crappy) + _log.debug("Activating component " + component.getQName()); + activator.activateService(null, component); + // while this is not a service, it will ensure that the component is deactivated + Activation activation = new Activation(activator, component.getQName(), null, null); + activation.addReferences(references); + _components.add(activation); + } + } + } + + private void deployServiceBindings() { + _log.debug("Deploying service bindings for deployment " + getName()); + if (getConfig().getComposite() == null) { + return; + } + // activate bindings for each service + for (CompositeServiceModel service : getConfig().getComposite().getServices()) { + // Create the reference for the composite service + ServiceMetadata metadata = ServiceMetadataBuilder.create() + .throttling(getCompositeServiceThrottling(service)) + .registrant(new Binding(service.getBindings())) + .build(); + ServiceReference reference = getDomain().registerServiceReference( + service.getQName(), getCompositeServiceInterface(service), null, metadata); + + int bindingCount = 0; + for (BindingModel binding : service.getBindings()) { + ++bindingCount; + if (binding.getName() == null) { + _log.debug("Initializing binding name for binding " + bindingCount + " for service " + + service.getQName() + " for deployment " + getName()); + binding.setName("_" + service.getName() + "_" + binding.getType() + "_" + bindingCount); + } + _log.debug("Deploying binding " + binding.getName() + " for service " + + service.getQName() + " for deployment " + getName()); + + Activator activator = findActivator(binding.getType()); + if (activator == null) { + continue; + } + + ServiceHandler handler = activator.activateBinding(service.getQName(), binding); + Activation activation = new Activation(activator, service.getQName(), binding, handler); + activation.addReference(reference); + _serviceBindings.add(activation); + + handler.start(); + } + } + } + + private void undeployServiceBindings() { + _log.debug("Undeploying service bindings for deployment " + getName()); + try { + for (Activation activation : _serviceBindings) { + try { + activation.getHandler().stop(); + } catch (Throwable e) { + BaseDeployLogger.ROOT_LOGGER.errorStoppingServiceBinding(e); + } + try { + activation.getActivator().deactivateBinding(activation.getName(), activation.getHandler()); + } catch (Throwable e) { + BaseDeployLogger.ROOT_LOGGER.errorDeactivatingServiceBinding(e); + } + + for (ServiceReference reference : activation.getReferences()) { + reference.unregister(); + } + + } + } finally { + _serviceBindings.clear(); + } + } + + private void undeployImplementations() { + _log.debug("Undeploying services for deployment " + getName()); + try { + for (Activation activation : _components) { + _log.debug("Deactivating " + activation.getName()); + final ServiceHandler handler = activation.getHandler(); + if (handler != null) { + try { + handler.stop(); + } catch (Throwable e) { + BaseDeployLogger.ROOT_LOGGER.errorStoppingService(e); + } + } + + for (Service service : activation.getServices()) { + try { + activation.getActivator().deactivateService(service.getName(), activation.getHandler()); + } catch (Throwable e) { + BaseDeployLogger.ROOT_LOGGER.errorDeactivatingService(e); + } + service.unregister(); + } + + for (ServiceReference reference : activation.getReferences()) { + reference.unregister(); + } + + for (Service service : activation.getPromotions()) { + service.unregister(); + } + } + } finally { + _components.clear(); + } + } + + private void undeployReferenceBindings() { + _log.debug("Undeploying reference bindings for deployment " + getName()); + try { + for (Activation activation : _referenceBindings) { + try { + activation.getHandler().stop(); + } catch (Throwable e) { + BaseDeployLogger.ROOT_LOGGER.errorStoppingReferenceBinding(e); + } + try { + activation.getActivator().deactivateBinding(activation.getName(), activation.getHandler()); + } catch (Throwable e) { + BaseDeployLogger.ROOT_LOGGER.errorDeactivatingReferenceBinding(e); + } + + for (Service service : activation.getServices()) { + service.unregister(); + } + } + } finally { + _referenceBindings.clear(); + } + } + + private Class loadClass(String className) { + return Classes.forName(className, getClass()); + } + + private List getPolicyRequirements(ComponentServiceModel serviceModel) throws Exception { + LinkedList requires = new LinkedList(); + for (QName policyQName : serviceModel.getPolicyRequirements()) { + requires.add(PolicyFactory.getPolicy(policyQName)); + } + return requires; + } + + private List getPolicyRequirements(ComponentImplementationModel implModel) throws Exception { + LinkedList requires = new LinkedList(); + for (QName policyQName : implModel.getPolicyRequirements()) { + requires.add(PolicyFactory.getPolicy(policyQName)); + } + return requires; + } + + private List getPolicyRequirements(ComponentReferenceModel referenceModel) throws Exception { + LinkedList requires = new LinkedList(); + for (QName policyQName : referenceModel.getPolicyRequirements()) { + requires.add(PolicyFactory.getPolicy(policyQName)); + } + return requires; + } + + private void processPolicyDependency(List interaction, List implementation) { + if (interaction == null || implementation == null) { + return; // Just to avoid findbugs error + } + + List implToAdd = new LinkedList(); + List interactToAdd = new LinkedList(); + for (int i=0; i interaction, List implementation) { + for (int i=0; interaction != null && i _services = new LinkedList(); + private List _promotions = new LinkedList(); + private List _references = new LinkedList(); + + Activation(Activator activator, QName name, BindingModel bindingModel, ServiceHandler handler) { + _activator = activator; + _name = name; + _bindingModel = bindingModel; + _handler = handler; + } + + Activator getActivator() { + return _activator; + } + + QName getName() { + return _name; + } + + BindingModel getBindingModel() { + return _bindingModel; + } + + ServiceHandler getHandler() { + return _handler; + } + + Activation addService(Service service) { + _services.add(service); + return this; + } + + Activation addReferences(List references) { + _references.addAll(references); + return this; + } + + Activation addReference(ServiceReference reference) { + _references.add(reference); + return this; + } + + Activation addPromotion(Service service) { + _promotions.add(service); + return this; + } + + List getReferences() { + return _references; + } + + List getServices() { + return _services; + } + + List getPromotions() { + return _promotions; + } +} diff --git a/core/deploy/base/src/main/java/org/switchyard/standalone/SwitchYard.java b/core/deploy/base/src/main/java/org/switchyard/standalone/SwitchYard.java new file mode 100644 index 000000000..c2dbf65d7 --- /dev/null +++ b/core/deploy/base/src/main/java/org/switchyard/standalone/SwitchYard.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.standalone; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.ActivatorLoader; +import org.switchyard.deploy.BaseDeployMessages; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.internal.AbstractDeployment; +import org.switchyard.deploy.internal.Deployment; + +/** + * SwitchYard main. + *

+ * Standalone bootstrap class. + * + * @author tom.fennelly@gmail.com + */ +public class SwitchYard { + + private static Logger _logger = Logger.getLogger(SwitchYard.class); + private List _activatorList; + private ServiceDomain _domain; + private Deployment _deployment; + + /** + * Create a new SwitchYard runtime from the specified config. + * @param config Switchyard configuration. + * @throws IOException Error reading configuration. + */ + public SwitchYard(InputStream config) throws IOException { + _deployment = new Deployment(config); + _domain = new ServiceDomainManager().createDomain( + _deployment.getConfig().getQName(), _deployment.getConfig()); + _activatorList = ActivatorLoader.createActivators(_domain); + } + + /** + * Start the SwitchYard application. + */ + public void start() { + _logger.debug("Starting SwitchYard application '" + _deployment.getConfig().getQName() + "'."); + + _deployment.init(_domain, _activatorList); + _deployment.start(); + _logger.debug("SwitchYard application '" + _deployment.getConfig().getQName() + "' started."); + } + + /** + * Stop the SwitchYard application. + */ + public void stop() { + _logger.debug("Stopping SwitchYard application '" + _deployment.getConfig().getQName() + "'."); + _deployment.stop(); + _logger.debug("SwitchYard application '" + _deployment.getConfig().getQName() + "' stopped."); + } + + /** + * Returns a reference to the activator list used by this runtime instance. + * @return the activator list + */ + public List getActivatorList() { + return _activatorList; + } + + /** + * Sets the list of activators used by the runtime instance. + * @param activators the list of activators to use for this runtime instance + */ + public void setActivatorList(List activators) { + _activatorList = activators; + } + + /** + * Main method. + * @param args startup args. + * @throws Exception Error starting SwitchYard application. + */ + public static void main(String[] args) throws Exception { + InputStream configStream; + + if (args.length == 0) { + configStream = SwitchYard.class.getResourceAsStream(AbstractDeployment.SWITCHYARD_XML); + + if (configStream == null) { + System.out.println(BaseDeployMessages.MESSAGES.usagePath(SwitchYard.class.getName())); + System.exit(1); + } + } else { + File configFile = new File(args[0]); + + if (!configFile.isFile()) { + System.out.println(BaseDeployMessages.MESSAGES.notValidConfigFile(args[0])); + System.exit(1); + } + + configStream = new FileInputStream(configFile); + } + + final SwitchYard switchyard; + try { + switchyard = new SwitchYard(configStream); + } finally { + configStream.close(); + } + + switchyard.start(); + + Runtime.getRuntime().addShutdownHook( + new Thread() { + public void run() { + switchyard.stop(); + switchyard.notify(); + } + } + ); + + switchyard.wait(); + System.exit(0); + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/SwitchYardTest.java b/core/deploy/base/src/test/java/org/switchyard/SwitchYardTest.java new file mode 100644 index 000000000..30aadfe4c --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/SwitchYardTest.java @@ -0,0 +1,106 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import java.io.InputStream; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.deploy.ServiceHandler; +import org.switchyard.standalone.SwitchYard; + +public class SwitchYardTest { + + @Test + public void getActivators() throws Exception { + InputStream config = Classes.getResourceAsStream("/switchyard-config-mock-01.xml", getClass()); + SwitchYard sy = new SwitchYard(config); + config.close(); + + Assert.assertEquals(1, sy.getActivatorList().size()); + } + + @Test + public void replaceActivator() throws Exception { + InputStream config = Classes.getResourceAsStream("/switchyard-config-mock-01.xml", getClass()); + SwitchYard sy = new SwitchYard(config); + + // Remove the old activator if it exists + Iterator activators = sy.getActivatorList().iterator(); + while (activators.hasNext()) { + Activator activator = activators.next(); + if (activator.canActivate("mock")) { + activators.remove(); + } + } + + // Add new activator + MockActivator mock = new MockActivator(); + sy.getActivatorList().add(mock); + + sy.start(); + Assert.assertTrue(mock.activationCalled); + + config.close(); + } + + @Test + public void customActivatorList() throws Exception { + InputStream config = Classes.getResourceAsStream("/switchyard-config-mock-01.xml", getClass()); + SwitchYard sy = new SwitchYard(config); + + // Add new activator + MockActivator mock = new MockActivator(); + List activatorList = new LinkedList(); + activatorList.add(mock); + sy.setActivatorList(activatorList); + + sy.start(); + Assert.assertTrue(mock.activationCalled); + + config.close(); + } +} + +class MockActivator extends BaseActivator { + boolean activationCalled; + + public MockActivator() { + super("mock"); + } + + @Override + public ServiceHandler activateService(QName name, ComponentModel config) { + activationCalled = true; + return new BaseServiceHandler(); + } + + @Override + public ServiceHandler activateBinding(QName name, BindingModel config) { + return new BaseServiceHandler(); + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/BaseActivatorTest.java b/core/deploy/base/src/test/java/org/switchyard/deploy/BaseActivatorTest.java new file mode 100644 index 000000000..6b010db8a --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/BaseActivatorTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.switchyard.deploy; + +import junit.framework.Assert; + +import org.junit.Test; + +public class BaseActivatorTest { + + @Test + public void testNullCtor() { + SimpleActivator activator = new SimpleActivator((String)null); + Assert.assertNotNull(activator.getActivationTypes()); + Assert.assertFalse(activator.canActivate("foo")); + } + + @Test + public void testSingleActivationType() { + SimpleActivator activator = new SimpleActivator("bar"); + Assert.assertEquals(1, activator.getActivationTypes().size()); + Assert.assertTrue(activator.canActivate("bar")); + } + + + @Test + public void testMultipleActivationTypes() { + SimpleActivator activator = new SimpleActivator( + new String[] {"abc", "xyz"}); + Assert.assertEquals(2, activator.getActivationTypes().size()); + Assert.assertTrue(activator.canActivate("abc")); + Assert.assertTrue(activator.canActivate("xyz")); + } +} + +class SimpleActivator extends BaseActivator { + + SimpleActivator(String ... types) { + super(types); + } + +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/ComponentNamesTest.java b/core/deploy/base/src/test/java/org/switchyard/deploy/ComponentNamesTest.java new file mode 100644 index 000000000..6cceb281f --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/ComponentNamesTest.java @@ -0,0 +1,56 @@ +package org.switchyard.deploy; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.ServiceReference; +import org.switchyard.internal.ServiceReferenceImpl; + +public class ComponentNamesTest { + + private static final QName COMPONENT_NAME = new QName("urn:foo", "componentName"); + private static final QName SERVICE_NAME = new QName("urn:foo", "serviceName"); + + @Test + public void testQualifyQNames() { + QName qualified = ComponentNames.qualify(COMPONENT_NAME, SERVICE_NAME); + Assert.assertEquals(COMPONENT_NAME.getNamespaceURI(), qualified.getNamespaceURI()); + Assert.assertEquals( + COMPONENT_NAME.getLocalPart() + "/" + SERVICE_NAME.getLocalPart(), + qualified.getLocalPart()); + } + + @Test + public void testQualifyStrings() { + QName qualified = ComponentNames.qualify( + COMPONENT_NAME.getLocalPart(), + SERVICE_NAME.getLocalPart(), + COMPONENT_NAME.getNamespaceURI()); + + Assert.assertEquals(COMPONENT_NAME.getNamespaceURI(), qualified.getNamespaceURI()); + Assert.assertEquals( + COMPONENT_NAME.getLocalPart() + "/" + SERVICE_NAME.getLocalPart(), + qualified.getLocalPart()); + } + + @Test + public void testUnqualifyReference() { + ServiceReference reference = new ServiceReferenceImpl( + ComponentNames.qualify(COMPONENT_NAME, SERVICE_NAME), null, null, null); + + QName unqualified = ComponentNames.unqualify(reference); + + Assert.assertEquals(COMPONENT_NAME.getNamespaceURI(), unqualified.getNamespaceURI()); + Assert.assertEquals(SERVICE_NAME, unqualified); + } + + @Test + public void testUnqualifyQName() { + QName qualified = ComponentNames.qualify(COMPONENT_NAME, SERVICE_NAME); + QName unqualified = ComponentNames.unqualify(qualified); + + Assert.assertEquals(COMPONENT_NAME.getNamespaceURI(), unqualified.getNamespaceURI()); + Assert.assertEquals(SERVICE_NAME, unqualified); + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/ServiceDomainManagerTest.java b/core/deploy/base/src/test/java/org/switchyard/deploy/ServiceDomainManagerTest.java new file mode 100644 index 000000000..be34196f1 --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/ServiceDomainManagerTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.ServiceDomain; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * @author tom.fennelly@gmail.com + */ +public class ServiceDomainManagerTest { + + @Test + public void testHandlerRegistration() throws Exception { + SwitchYardModel switchyard = new ModelPuller().pull( + "/switchyard-config-properties-01.xml", getClass()); + + ServiceDomain domain = new ServiceDomainManager().createDomain( + new QName("test"), switchyard); + + Assert.assertEquals("abc-value", domain.getProperty("abc")); + Assert.assertEquals("xyz-value", domain.getProperty("xyz")); + Assert.assertNull(domain.getProperty("nothing")); + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/components/MockActivator.java b/core/deploy/base/src/test/java/org/switchyard/deploy/components/MockActivator.java new file mode 100644 index 000000000..b37d7209c --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/components/MockActivator.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.components; + +import javax.xml.namespace.QName; + +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.deploy.BaseActivator; +import org.switchyard.deploy.BaseServiceHandler; +import org.switchyard.deploy.ServiceHandler; + +public class MockActivator extends BaseActivator { + + public static final String ACTIVATION_TYPE = "mock"; + + private boolean _activateBindingCalled; + private boolean _activateServiceCalled; + private boolean _deactivateBindingCalled; + private boolean _deactivateServiceCalled; + private boolean _startCalled; + private boolean _stopCalled; + + private ServiceHandler _handler = new MockServiceHandler(); + + public MockActivator() { + super(ACTIVATION_TYPE); + } + + @Override + public ServiceHandler activateBinding(QName serviceName, BindingModel config) { + _activateBindingCalled = true; + return _handler; + } + + @Override + public ServiceHandler activateService(QName serviceName, ComponentModel config) { + _activateServiceCalled = true; + return _handler; + } + + + @Override + public void deactivateBinding(QName name, ServiceHandler handler) { + _deactivateBindingCalled = true; + } + + @Override + public void deactivateService(QName name, ServiceHandler handler) { + _deactivateServiceCalled = true; + } + + public boolean startCalled() { + return _startCalled; + } + + public boolean stopCalled() { + return _stopCalled; + } + + public boolean activateBindingCalled() { + return _activateBindingCalled; + } + + public boolean activateServiceCalled() { + return _activateServiceCalled; + } + + public boolean deactivateBindingCalled() { + return _deactivateBindingCalled; + } + + public boolean deactivateServiceCalled() { + return _deactivateServiceCalled; + } + + class MockServiceHandler extends BaseServiceHandler { + @Override + public void doStart() { + _startCalled = true; + } + + @Override + public void doStop() { + _stopCalled = true; + } + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/components/MockComponent.java b/core/deploy/base/src/test/java/org/switchyard/deploy/components/MockComponent.java new file mode 100644 index 000000000..56c397c2a --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/components/MockComponent.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.components; + +import org.switchyard.ServiceDomain; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.BaseComponent; + +/** + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class MockComponent extends BaseComponent { + + public MockComponent() { + setName("Mockcomponent"); + } + + @Override + public Activator createActivator(ServiceDomain domain) { + return new MockActivator(); + } + +} \ No newline at end of file diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/MockBindingModel.java b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/MockBindingModel.java new file mode 100644 index 000000000..ee1ff529f --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/MockBindingModel.java @@ -0,0 +1,22 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.switchyard.deploy.components.config; + +import org.switchyard.config.model.composite.BindingModel; + +public interface MockBindingModel extends BindingModel { + public String TYPE = "mock"; +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/MockImplementationModel.java b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/MockImplementationModel.java new file mode 100644 index 000000000..1647e917f --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/MockImplementationModel.java @@ -0,0 +1,22 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.switchyard.deploy.components.config; + +import org.switchyard.config.model.composite.ComponentImplementationModel; + +public interface MockImplementationModel extends ComponentImplementationModel { + public String TYPE = "mock"; +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockBindingModel.java b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockBindingModel.java new file mode 100644 index 000000000..b87d62332 --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockBindingModel.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package org.switchyard.deploy.components.config.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1BindingModel; +import org.switchyard.deploy.components.config.MockBindingModel; + +public class V1MockBindingModel extends V1BindingModel implements MockBindingModel { + + /** + * Create a new V1MockBindingModel + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1MockBindingModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(); + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockImplementationModel.java b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockImplementationModel.java new file mode 100644 index 000000000..b20080aee --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockImplementationModel.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.components.config.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.composite.v1.V1ComponentImplementationModel; +import org.switchyard.deploy.components.config.MockImplementationModel; + +public class V1MockImplementationModel extends V1ComponentImplementationModel implements MockImplementationModel { + + /** + * Create a new MockImplementationModel v1 instance. + * @param config The switchyard configuration instance. + * @param desc The switchyard descriptor instance. + */ + public V1MockImplementationModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockModelMarshaller.java b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockModelMarshaller.java new file mode 100644 index 000000000..600933d15 --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/components/config/v1/V1MockModelMarshaller.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.components.config.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentImplementationModel; + +public class V1MockModelMarshaller extends BaseMarshaller { + + /** + * Create a new MockModel marshaller. + * @param desc The switchyard descriptor. + */ + public V1MockModelMarshaller(final Descriptor desc) { + super(desc); + } + + @Override + public Model read(final Configuration config) { + Model model = null; + if (config.getName().startsWith(BindingModel.BINDING)) { + model = new V1MockBindingModel(config, getDescriptor()); + } else if (config.getName().startsWith(ComponentImplementationModel.IMPLEMENTATION)) { + model = new V1MockImplementationModel(config, getDescriptor()); + } + return model; + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/handler/DummyHandler.java b/core/deploy/base/src/test/java/org/switchyard/deploy/handler/DummyHandler.java new file mode 100644 index 000000000..bc1fdcc3b --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/handler/DummyHandler.java @@ -0,0 +1,21 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.handler; + +import org.switchyard.BaseHandler; + +public class DummyHandler extends BaseHandler { + +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/internal/DeploymentTest.java b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/DeploymentTest.java new file mode 100644 index 000000000..c464cdf76 --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/DeploymentTest.java @@ -0,0 +1,491 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.SwitchYardException; +import org.switchyard.bus.camel.CamelExchangeBus; +import org.switchyard.common.camel.CamelContextConfigurator; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.switchyard.EsbInterfaceModel; +import org.switchyard.deploy.ActivatorLoader; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.components.MockActivator; +import org.switchyard.deploy.components.config.MockBindingModel; +import org.switchyard.deploy.internal.transformers.ABTransformer; +import org.switchyard.deploy.internal.transformers.CDTransformer; +import org.switchyard.deploy.internal.validators.AValidator; +import org.switchyard.deploy.internal.validators.BValidator; +import org.switchyard.extensions.wsdl.WSDLService; +import org.switchyard.internal.DomainImpl; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.policy.TransactionPolicy; +import org.switchyard.spi.ServiceRegistry; +import org.switchyard.transform.Transformer; +import org.switchyard.validate.Validator; + +/** + * @author tom.fennelly@gmail.com + */ +public class DeploymentTest { + + @Test + public void testEmptySwitchYardConfiguration() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-empty-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + deployment.destroy(); + } + + @Test + public void testComponentReferenceBinding() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-component-reference-binding-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + + boolean result = false; + try { + deployment.start(); + } catch (SwitchYardException sye) { + Assert.assertTrue(sye.getMessage().contains("Component Reference bindings are not allowed. Found ")); + result = true; + } catch (Exception e) { + Assert.fail("Expected to catch a SwitchYardException on deploy."); + } + Assert.assertTrue("Expected to catch a SwitchYardException on deploy.", result); + } + + @Test + public void testComponentServiceBinding() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-component-service-binding-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + boolean result = false; + try { + deployment.start(); + } catch (SwitchYardException sye) { + Assert.assertTrue(sye.getMessage().contains("Component Service bindings are not allowed. Found")); + result = true; + } catch (Exception e) { + Assert.fail("Expected to catch a SwitchYardException on deploy."); + } + Assert.assertTrue("Expected to catch a SwitchYardException on deploy.", result); + } + + + @Test + public void testRegistrants() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-mock-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + deployment.start(); + + // check metadata is included for services and references + Service implService = deployment.getDomain().getServices( + new QName("urn:test:config-mock-binding:1.0", "TestService")).get(0); + Assert.assertNotNull(implService.getServiceMetadata().getRegistrant()); + Assert.assertTrue(implService.getServiceMetadata().getRequiredPolicies().contains(TransactionPolicy.MANAGED_TRANSACTION_GLOBAL)); + Assert.assertTrue(implService.getServiceMetadata().getRequiredPolicies().contains(TransactionPolicy.PROPAGATES_TRANSACTION)); + Assert.assertTrue(implService.getServiceMetadata().getRegistrant().getConfig() instanceof ComponentImplementationModel); + + Service promotedService = deployment.getDomain().getServices( + new QName("urn:test:config-mock-binding:1.0", "PromotedTestService")).get(0); + Assert.assertNotNull(promotedService.getServiceMetadata().getRegistrant()); + Assert.assertTrue(promotedService.getServiceMetadata().getRequiredPolicies().contains(TransactionPolicy.MANAGED_TRANSACTION_GLOBAL)); + Assert.assertTrue(promotedService.getServiceMetadata().getRequiredPolicies().contains(TransactionPolicy.PROPAGATES_TRANSACTION)); + Assert.assertTrue(promotedService.getServiceMetadata().getRegistrant().getConfig() instanceof ComponentImplementationModel); + + Service bindingService = deployment.getDomain().getServices( + new QName("urn:test:config-mock-binding:1.0", "TestReference")).get(0); + Assert.assertNotNull(bindingService.getServiceMetadata().getRegistrant()); + List svcBindings = bindingService.getServiceMetadata().getRegistrant().getConfig(); + Assert.assertEquals(1, svcBindings.size()); + + ServiceReference implReference = deployment.getDomain().getServiceReference( + new QName("urn:test:config-mock-binding:1.0", "TestService/TestReference")); + Assert.assertNotNull(implReference.getServiceMetadata().getRegistrant()); + Assert.assertTrue(implReference.getServiceMetadata().getRegistrant().getConfig() instanceof ComponentImplementationModel); + + ServiceReference bindingReference = deployment.getDomain().getServiceReference( + new QName("urn:test:config-mock-binding:1.0", "PromotedTestService")); + Assert.assertNotNull(bindingReference.getServiceMetadata().getRegistrant()); + List refBindings = bindingReference.getServiceMetadata().getRegistrant().getConfig(); + Assert.assertEquals(2, refBindings.size()); + + // SWITCHYARD-1686 + ServiceReference compReference = deployment.getDomain().getServiceReference( + new QName("urn:test:config-mock-binding:1.0", "NoService/TestReference")); + Assert.assertNotNull(compReference.getServiceMetadata().getRegistrant()); + Assert.assertTrue(compReference.getServiceMetadata().getRegistrant().getConfig() instanceof ComponentImplementationModel); + + ServiceRegistry registry = ((DomainImpl) deployment.getDomain()).getServiceRegistry(); + deployment.stop(); + // ensure we're cleaning up after ourselves. + Assert.assertEquals(0, registry.getServices().size()); + Assert.assertEquals(0, registry.getServiceReferences().size()); + deployment.destroy(); + } + + @Test + public void testActivators() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-mock-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + + // Grab a reference to our activators + MockActivator activator = (MockActivator) + deployment.findActivator(MockBindingModel.TYPE); + deployment.start(); + deployment.stop(); + deployment.destroy(); + + // Verify the activators were poked + Assert.assertTrue(activator.activateServiceCalled()); + Assert.assertTrue(activator.activateBindingCalled()); + Assert.assertTrue(activator.startCalled()); + Assert.assertTrue(activator.stopCalled()); + Assert.assertTrue(activator.deactivateServiceCalled()); + Assert.assertTrue(activator.deactivateBindingCalled()); + } + + @Test + public void testActivationTypes() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-mock-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + List types = deployment.getActivationTypes(); + Assert.assertEquals(1, types.size()); + Assert.assertEquals("mock", types.iterator().next()); + } + + @Test + public void test_transform_registration() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-transform-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + + // Check that the transformers are deployed... + ServiceDomain domain = deployment.getDomain(); + Transformer abTransformer = domain.getTransformerRegistry().getTransformer(new QName("A"), new QName("B")); + Transformer cdTransformer = domain.getTransformerRegistry().getTransformer(new QName("C"), new QName("D")); + + Assert.assertTrue(abTransformer instanceof ABTransformer); + Assert.assertTrue(cdTransformer instanceof CDTransformer); + + deployment.destroy(); + + // Check that the transformers are undeployed... + } + + @Test + public void test_validate_registration() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-validate-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + + // Check that the validators are deployed... + ServiceDomain domain = deployment.getDomain(); + Validator aValidator = domain.getValidatorRegistry().getValidator(new QName("A")); + Validator bValidator = domain.getValidatorRegistry().getValidator(new QName("B")); + + Assert.assertTrue(aValidator instanceof AValidator); + Assert.assertTrue(bValidator instanceof BValidator); + + deployment.destroy(); + + // Check that the validators are undeployed... + } + + @Test + public void interfaceWSDL() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-interface-wsdl-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + deployment.start(); + + Service service = serviceDomain.getServiceRegistry().getServices( + new QName("urn:switchyard-interface-wsdl", "HelloService")).get(0); + Assert.assertNotNull(service); + ServiceInterface iface = service.getInterface(); + Assert.assertEquals(WSDLService.TYPE, iface.getType()); + ServiceOperation op = iface.getOperation("sayHello"); + Assert.assertNotNull(op); + Assert.assertEquals(new QName("urn:switchyard-interface-wsdl", "sayHello"), op.getInputType()); + Assert.assertEquals(new QName("urn:switchyard-interface-wsdl", "sayHelloResponse"), op.getOutputType()); + + deployment.stop(); + deployment.destroy(); + + } + + + @Test + public void interfaceESB() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-interface-esb-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + deployment.start(); + + // Test the service + Service service = serviceDomain.getServiceRegistry().getServices( + new QName("urn:switchyard-interface-esb", "HelloService")).get(0); + Assert.assertNotNull(service); + ServiceInterface iface = service.getInterface(); + Assert.assertEquals(EsbInterfaceModel.ESB, iface.getType()); + ServiceOperation op = iface.getOperation(ServiceInterface.DEFAULT_OPERATION); + Assert.assertNotNull(op); + Assert.assertEquals(ExchangePattern.IN_ONLY, op.getExchangePattern()); + + // Test the reference + ServiceReference reference = serviceDomain.getServiceReference( + new QName("urn:switchyard-interface-esb", "HelloService/SomeOtherService")); + Assert.assertNotNull(reference); + Assert.assertEquals(EsbInterfaceModel.ESB, service.getInterface().getType()); + ServiceOperation rop = reference.getInterface().getOperation(ServiceInterface.DEFAULT_OPERATION); + Assert.assertNotNull(rop); + Assert.assertEquals(ExchangePattern.IN_OUT, rop.getExchangePattern()); + + deployment.stop(); + deployment.destroy(); + + } + + @Test + public void nonExistentActivatorThrowsException() throws Exception { + InputStream swConfigStream = null; + SwitchYardException exception = null; + + // Load an app config which references a mock component, but provide no activator + try { + swConfigStream = Classes.getResourceAsStream("/switchyard-config-activator-01.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + deployment.start(); + } catch (SwitchYardException sye) { + exception = sye; + System.err.println(sye.toString()); + } finally { + if (swConfigStream != null) { + swConfigStream.close(); + } + } + + Assert.assertNotNull("Missing activator did not trigger SwitchYardException!", exception); + } + + @Test + public void testUnknownInterfaceClassName() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-unknown-interface.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + try { + deployment.start(); + Assert.fail("Expected SwitchYardException"); + } catch (SwitchYardException e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD012211"); + Assert.assertTrue(exceptionMatches); + } + } + + @Test + public void componentServiceMultiplePromotions() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-multiple-promotions.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + deployment.start(); + + // verify that two promotions with different names have been registered + List test1svcs = deployment.getDomain().getServices( + new QName("urn:test:config-mock-binding:1.0", "Test1")); + Assert.assertEquals(1, test1svcs.size()); + List test2svcs = deployment.getDomain().getServices( + new QName("urn:test:config-mock-binding:1.0", "Test2")); + Assert.assertEquals(1, test2svcs.size()); + + // make sure there's only one registration when component service name equals composite service name + List testsvcs = deployment.getDomain().getServices( + new QName("urn:test:config-mock-binding:1.0", "TestService")); + Assert.assertEquals(1, testsvcs.size()); + } + + @Test + public void testDuplicateReference() throws Exception { + deployWithFail("/naming/duplicate-reference.xml"); + } + + @Test + public void testReferencePromotion() throws Exception { + deployWithoutFail("/naming/reference-promotion.xml"); + } + + @Test + public void testDuplicatePromotion() throws Exception { + deployWithFail("/naming/duplicate-promotion.xml"); + } + + @Test + public void testPromotedService() throws Exception { + deployWithoutFail("/naming/promoted-service.xml"); + } + + /** + * This test is similar to a version in the bus-camel module, but has one important + * difference: the config is loaded from switchyard.xml and throttling is set via + * the deployer vs. setting it directly on the bus as in the ExchangeDispatcherTest. + * This test confirms the fix for SWITCHYARD-2306. + */ + @Test + public void throttleWithTimePeriod() throws Exception { + final QName svcName = new QName("urn:test:config-throttling:1.0", "TestService"); + // read the app config with throttling + InputStream syConfigStream = Classes.getResourceAsStream("/switchyard-config-throttling-01.xml", getClass()); + Deployment deployment = new Deployment(syConfigStream); + syConfigStream.close(); + + + // initialize the deployment + ServiceDomain domain = new ServiceDomainManager().createDomain(); + domain.setProperty(CamelContextConfigurator.SHUTDOWN_TIMEOUT, "10"); + deployment.init(domain, ActivatorLoader.createActivators(domain)); + deployment.start(); + + // we want to invoke a mock so we can check for messages received + final ServiceReference reference = domain.getServiceReference(svcName); + domain.getServices(svcName).get(0).unregister(); + final MockHandler service = new MockHandler(); + domain.registerService(svcName, new InOnlyService(), service); + + + final int NUM_SENDS = 5; + for (int i = 0; i < NUM_SENDS; i++) { + new Thread(new Runnable() { + public void run() { + Exchange exchange = reference.createExchange(); + Message message = exchange.createMessage(); + exchange.send(message); + } + }).start(); + } + + Thread.sleep(4000); + Assert.assertEquals("Received more than one message per minute - throttling policy violated!", + 1, service.getMessages().size()); + } + + @Test + public void testManagedLocalTxPolicyDependency() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("/switchyard-config-policy-tx-managedLocal.xml", getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + deployment.start(); + + Service implService = deployment.getDomain().getServices( + new QName("urn:test:config-mock-binding:1.0", "TestService")).get(0); + Assert.assertNotNull(implService.getServiceMetadata().getRegistrant()); + Assert.assertTrue(implService.getServiceMetadata().getRequiredPolicies().contains(TransactionPolicy.MANAGED_TRANSACTION_LOCAL)); + Assert.assertTrue(implService.getServiceMetadata().getRequiredPolicies().contains(TransactionPolicy.SUSPENDS_TRANSACTION)); + + ServiceReference implReference = deployment.getDomain().getServiceReference( + new QName("urn:test:config-mock-binding:1.0", "TestService/TestReference")); + Assert.assertNotNull(implReference.getServiceMetadata().getRegistrant()); + Assert.assertTrue(implReference.getServiceMetadata().getRequiredPolicies().contains(TransactionPolicy.SUSPENDS_TRANSACTION)); + deployment.destroy(); + } + + @Test + public void testManagedLocalTxPolicyDependencyInvalid() throws Exception { + deployWithFail("/switchyard-config-policy-tx-managedLocal-invalid.xml"); + } + + // helper methods + private void deployWithoutFail(String name) throws IOException { + InputStream swConfigStream = Classes.getResourceAsStream(name, getClass()); + Deployment deployment = new Deployment(swConfigStream); + swConfigStream.close(); + + MockDomain serviceDomain = new MockDomain(); + deployment.init(serviceDomain, ActivatorLoader.createActivators(serviceDomain)); + deployment.start(); + deployment.stop(); + } + + private void deployWithFail(String name) { + try { + deployWithoutFail(name); + Assert.fail("Unexpected success of deployment " + name); + } catch (IOException e) { + Assert.fail("Can not read configuration " + name); + } catch (SwitchYardException e) { + // this is expected + e.getMessage(); + } + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/internal/transformers/ABTransformer.java b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/transformers/ABTransformer.java new file mode 100644 index 000000000..d648ceba1 --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/transformers/ABTransformer.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.internal.transformers; + +import javax.xml.namespace.QName; + +import org.switchyard.transform.BaseTransformer; + +/** + * @author tom.fennelly@gmail.com + */ +public class ABTransformer extends BaseTransformer { + + public ABTransformer() { + super(new QName("A"), new QName("B")); + } + + @Override + public Object transform(Object from) { + return from; + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/internal/transformers/CDTransformer.java b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/transformers/CDTransformer.java new file mode 100644 index 000000000..e9e88cbe6 --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/transformers/CDTransformer.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.internal.transformers; + +import org.switchyard.transform.BaseTransformer; + +import javax.xml.namespace.QName; + +/** + * @author tom.fennelly@gmail.com + */ +public class CDTransformer extends BaseTransformer { + + public CDTransformer() { + super(new QName("C"), new QName("D")); + } + + @Override + public Object transform(Object from) { + return from; + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/internal/validators/AValidator.java b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/validators/AValidator.java new file mode 100644 index 000000000..cc0beaf0f --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/validators/AValidator.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.internal.validators; + +import javax.xml.namespace.QName; + +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; + +/** + * @author Tomohisa Igarashi + */ +public class AValidator extends BaseValidator { + + public AValidator() { + super(new QName("A")); + } + + @Override + public ValidationResult validate(Object obj) { + if (obj != null) { + return validResult(); + } else { + return invalidResult("obj == null"); + } + } +} diff --git a/core/deploy/base/src/test/java/org/switchyard/deploy/internal/validators/BValidator.java b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/validators/BValidator.java new file mode 100644 index 000000000..b1c9a9f87 --- /dev/null +++ b/core/deploy/base/src/test/java/org/switchyard/deploy/internal/validators/BValidator.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.internal.validators; + +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; + +import javax.xml.namespace.QName; + +/** + * @author Tomohisa Igarashi + */ +public class BValidator extends BaseValidator { + + public BValidator() { + super(new QName("B")); + } + + @Override + public ValidationResult validate(Object obj) { + if (obj != null) { + return validResult(); + } else { + return invalidResult("obj == null"); + } + } +} diff --git a/core/deploy/base/src/test/resources/Hello.wsdl b/core/deploy/base/src/test/resources/Hello.wsdl new file mode 100644 index 000000000..c98464956 --- /dev/null +++ b/core/deploy/base/src/test/resources/Hello.wsdl @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/META-INF/services/org.switchyard.deploy.Component b/core/deploy/base/src/test/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..fe821a464 --- /dev/null +++ b/core/deploy/base/src/test/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1 @@ +org.switchyard.deploy.components.MockComponent diff --git a/core/deploy/base/src/test/resources/log4j.xml b/core/deploy/base/src/test/resources/log4j.xml new file mode 100644 index 000000000..fe8c248ca --- /dev/null +++ b/core/deploy/base/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/naming/duplicate-promotion.xml b/core/deploy/base/src/test/resources/naming/duplicate-promotion.xml new file mode 100644 index 000000000..eb34ac212 --- /dev/null +++ b/core/deploy/base/src/test/resources/naming/duplicate-promotion.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/naming/duplicate-reference.xml b/core/deploy/base/src/test/resources/naming/duplicate-reference.xml new file mode 100644 index 000000000..3bd288660 --- /dev/null +++ b/core/deploy/base/src/test/resources/naming/duplicate-reference.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/naming/promoted-service.xml b/core/deploy/base/src/test/resources/naming/promoted-service.xml new file mode 100644 index 000000000..da4333a52 --- /dev/null +++ b/core/deploy/base/src/test/resources/naming/promoted-service.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/naming/reference-promotion.xml b/core/deploy/base/src/test/resources/naming/reference-promotion.xml new file mode 100644 index 000000000..9cde1b1e4 --- /dev/null +++ b/core/deploy/base/src/test/resources/naming/reference-promotion.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/org/switchyard/component/mock/config/model/v1/mock_1_0.xsd b/core/deploy/base/src/test/resources/org/switchyard/component/mock/config/model/v1/mock_1_0.xsd new file mode 100644 index 000000000..23cb25b77 --- /dev/null +++ b/core/deploy/base/src/test/resources/org/switchyard/component/mock/config/model/v1/mock_1_0.xsd @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/org/switchyard/config/model/descriptor.properties b/core/deploy/base/src/test/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..0d0bf3972 --- /dev/null +++ b/core/deploy/base/src/test/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,18 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +mock_1_0.section=urn:switchyard-component-mock:config +mock_1_0.version=1.0 +mock_1_0.namespace=urn:switchyard-component-mock:config:1.0 +mock_1_0.schema=mock_1_0.xsd +mock_1_0.location=/org/switchyard/deploy/components/config/v1/ +mock_1_0.marshaller=org.switchyard.deploy.components.config.v1.V1MockModelMarshaller diff --git a/core/deploy/base/src/test/resources/switchyard-config-activator-01.xml b/core/deploy/base/src/test/resources/switchyard-config-activator-01.xml new file mode 100644 index 000000000..55261a78f --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-activator-01.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-component-reference-binding-01.xml b/core/deploy/base/src/test/resources/switchyard-config-component-reference-binding-01.xml new file mode 100644 index 000000000..50d5e6fed --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-component-reference-binding-01.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-component-service-binding-01.xml b/core/deploy/base/src/test/resources/switchyard-config-component-service-binding-01.xml new file mode 100644 index 000000000..41853bec9 --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-component-service-binding-01.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-empty-01.xml b/core/deploy/base/src/test/resources/switchyard-config-empty-01.xml new file mode 100644 index 000000000..7d331e22e --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-empty-01.xml @@ -0,0 +1,16 @@ + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-interface-esb-01.xml b/core/deploy/base/src/test/resources/switchyard-config-interface-esb-01.xml new file mode 100644 index 000000000..be5a3ed3c --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-interface-esb-01.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-interface-wsdl-01.xml b/core/deploy/base/src/test/resources/switchyard-config-interface-wsdl-01.xml new file mode 100644 index 000000000..6dccbbf6a --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-interface-wsdl-01.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-mock-01.xml b/core/deploy/base/src/test/resources/switchyard-config-mock-01.xml new file mode 100644 index 000000000..67401f47c --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-mock-01.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-multiple-promotions.xml b/core/deploy/base/src/test/resources/switchyard-config-multiple-promotions.xml new file mode 100644 index 000000000..072345190 --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-multiple-promotions.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-policy-tx-managedLocal-invalid.xml b/core/deploy/base/src/test/resources/switchyard-config-policy-tx-managedLocal-invalid.xml new file mode 100644 index 000000000..82251e540 --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-policy-tx-managedLocal-invalid.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-policy-tx-managedLocal.xml b/core/deploy/base/src/test/resources/switchyard-config-policy-tx-managedLocal.xml new file mode 100644 index 000000000..97e42e211 --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-policy-tx-managedLocal.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-properties-01.xml b/core/deploy/base/src/test/resources/switchyard-config-properties-01.xml new file mode 100644 index 000000000..d1b592e44 --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-properties-01.xml @@ -0,0 +1,22 @@ + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-throttling-01.xml b/core/deploy/base/src/test/resources/switchyard-config-throttling-01.xml new file mode 100644 index 000000000..b8869902c --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-throttling-01.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-transform-01.xml b/core/deploy/base/src/test/resources/switchyard-config-transform-01.xml new file mode 100644 index 000000000..fcc4edded --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-transform-01.xml @@ -0,0 +1,20 @@ + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-unknown-interface.xml b/core/deploy/base/src/test/resources/switchyard-config-unknown-interface.xml new file mode 100644 index 000000000..686689f38 --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-unknown-interface.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/core/deploy/base/src/test/resources/switchyard-config-validate-01.xml b/core/deploy/base/src/test/resources/switchyard-config-validate-01.xml new file mode 100644 index 000000000..968d385c8 --- /dev/null +++ b/core/deploy/base/src/test/resources/switchyard-config-validate-01.xml @@ -0,0 +1,20 @@ + + + + + + + + diff --git a/core/deploy/cdi/pom.xml b/core/deploy/cdi/pom.xml new file mode 100644 index 000000000..ff235dbac --- /dev/null +++ b/core/deploy/cdi/pom.xml @@ -0,0 +1,56 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-deploy-cdi + jar + SwitchYard: CDI Deployer + CDI-Based Deployer + http://switchyard.org + + + + javax.enterprise + cdi-api + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-deploy + + + + diff --git a/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/CDIDeployLogger.java b/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/CDIDeployLogger.java new file mode 100644 index 000000000..c97a7a377 --- /dev/null +++ b/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/CDIDeployLogger.java @@ -0,0 +1,18 @@ +package org.switchyard.deploy.cdi; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 12400-15999 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface CDIDeployLogger { + /** + * Default root logger. + */ + CDIDeployLogger ROOT_LOGGER = Logger.getMessageLogger(CDIDeployLogger.class, CDIDeployLogger.class.getPackage().getName()); +} diff --git a/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/CDIDeployMessages.java b/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/CDIDeployMessages.java new file mode 100644 index 000000000..bdb3aabfe --- /dev/null +++ b/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/CDIDeployMessages.java @@ -0,0 +1,30 @@ +package org.switchyard.deploy.cdi; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 12600-12799 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface CDIDeployMessages { + /** + * Default messages. + */ + CDIDeployMessages MESSAGES = Messages.getBundle(CDIDeployMessages.class); + + /** + * failedReadingConfig method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id = 12600, value = "Failed while reading config stream.") + SwitchYardException failedReadingConfig(@Cause Exception e); +} diff --git a/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/SwitchYardCDIDeployer.java b/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/SwitchYardCDIDeployer.java new file mode 100644 index 000000000..3edb7b21a --- /dev/null +++ b/core/deploy/cdi/src/main/java/org/switchyard/deploy/cdi/SwitchYardCDIDeployer.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.cdi; + +import java.io.IOException; +import java.io.InputStream; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.spi.AfterDeploymentValidation; +import javax.enterprise.inject.spi.BeforeShutdown; +import javax.enterprise.inject.spi.Extension; + +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; +import org.switchyard.deploy.ActivatorLoader; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.internal.AbstractDeployment; +import org.switchyard.deploy.internal.Deployment; + +/** + * Deployer implemented as a CDI extension. The deployer kicks in after all + * switchyard services and references have been discovered by the Bean component + * CDI extension. + * @author tom.fennelly@gmail.com + */ +@ApplicationScoped +public class SwitchYardCDIDeployer implements Extension { + + private Deployment _deployment; + + /** + * {@link AfterDeploymentValidation} CDI event observer. + * + * @param event CDI Event instance. + */ + public void afterDeploymentValidation(@Observes AfterDeploymentValidation event) { + InputStream swConfigStream; + try { + swConfigStream = Classes.getResourceAsStream(AbstractDeployment.SWITCHYARD_XML, getClass()); + } catch (IOException ioe) { + swConfigStream = null; + } + + if (swConfigStream != null) { + try { + _deployment = new Deployment(swConfigStream); + } catch (java.io.IOException ioEx) { + throw CDIDeployMessages.MESSAGES.failedReadingConfig(ioEx); + } finally { + try { + swConfigStream.close(); + } catch (IOException ioEx) { + ioEx.getMessage(); // keeps checkstyle happy + } + } + ServiceDomain domain = new ServiceDomainManager().createDomain(); + _deployment.init(domain, ActivatorLoader.createActivators(domain)); + _deployment.start(); + } + } + + /** + * {@link BeforeShutdown} CDI event observer. + * + * @param event CDI Event instance. + */ + public void beforeShutdown(@Observes BeforeShutdown event) { + if (_deployment != null) { + _deployment.stop(); + _deployment.destroy(); + } + } +} diff --git a/core/deploy/cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/core/deploy/cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension new file mode 100644 index 000000000..6ac68252b --- /dev/null +++ b/core/deploy/cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension @@ -0,0 +1 @@ +org.switchyard.deploy.cdi.SwitchYardCDIDeployer \ No newline at end of file diff --git a/core/deploy/webapp/pom.xml b/core/deploy/webapp/pom.xml new file mode 100644 index 000000000..c7959c923 --- /dev/null +++ b/core/deploy/webapp/pom.xml @@ -0,0 +1,44 @@ + + + + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + 4.0.0 + switchyard-deploy-webapp + jar + SwitchYard: JEE Web Application Deployer + JEE Web Application Deployer Implementation + http://switchyard.org + + + org.switchyard + switchyard-deploy + + + org.jboss.spec.javax.servlet + jboss-servlet-api_2.5_spec + provided + + + org.switchyard + switchyard-test + test + + + diff --git a/core/deploy/webapp/src/main/java/org/switchyard/deployment/WebApplicationDeployer.java b/core/deploy/webapp/src/main/java/org/switchyard/deployment/WebApplicationDeployer.java new file mode 100644 index 000000000..f9ad8f79e --- /dev/null +++ b/core/deploy/webapp/src/main/java/org/switchyard/deployment/WebApplicationDeployer.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deployment; + +import org.jboss.logging.Logger; +import org.switchyard.standalone.SwitchYard; +import org.switchyard.deploy.internal.AbstractDeployment; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import java.io.IOException; +import java.io.InputStream; + +/** + * SwitchYard Web Application Deployer. + *

+ * {@link ServletContextListener} implementation that allows SwitchYard be deployed as part of + * a JEE Web Application. + * + * @author tom.fennelly@gmail.com + */ +public class WebApplicationDeployer implements ServletContextListener { + + private static Logger _logger = Logger.getLogger(WebApplicationDeployer.class); + + private SwitchYard _switchyard; + + @Override + public void contextInitialized(ServletContextEvent sce) { + ServletContext servletContext = sce.getServletContext(); + InputStream switchYardConfig = servletContext.getResourceAsStream("WEB-INF/classes/" + AbstractDeployment.SWITCHYARD_XML); + + if (switchYardConfig != null) { + try { + _switchyard = new SwitchYard(switchYardConfig); + _switchyard.start(); + } catch (IOException e) { + _logger.debug("Error deploying SwitchYard within Web Application '" + servletContext.getServletContextName() + "'. SwitchYard not deployed.", e); + } + } else { + _logger.debug("No SwitchYard configuration found at '" + AbstractDeployment.SWITCHYARD_XML + "' in Web Application '" + servletContext.getServletContextName() + "'. SwitchYard not deployed."); + } + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + if (_switchyard != null) { + _switchyard.stop(); + } + } +} diff --git a/core/extensions/java/pom.xml b/core/extensions/java/pom.xml new file mode 100644 index 000000000..058570e39 --- /dev/null +++ b/core/extensions/java/pom.xml @@ -0,0 +1,47 @@ + + + + 4.0.0 + switchyard-extensions-java + bundle + SwitchYard: API Extensions - Java + The SwitchYard Java API Extension + http://switchyard.org + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + + org.switchyard.extensions.java + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + + junit + junit + + + diff --git a/core/extensions/java/src/main/java/org/switchyard/extensions/java/JavaService.java b/core/extensions/java/src/main/java/org/switchyard/extensions/java/JavaService.java new file mode 100644 index 000000000..34d8f7919 --- /dev/null +++ b/core/extensions/java/src/main/java/org/switchyard/extensions/java/JavaService.java @@ -0,0 +1,211 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.extensions.java; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.APIMessages; +import org.switchyard.annotations.OperationTypes; +import org.switchyard.common.type.Classes; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.metadata.ServiceOperation; + +/** + * An implementation of ServiceInterface for Java classes. The + * fromClass() method can be used to create a ServiceInterface + * representation from a Java class or interface. A ServiceOperation will be + * created for each public methods on the Java interface. Inherited + * superclass methods are not included to avoid polluting + * the ServiceInterface with methods from java.lang.Object, java.io.Serializable, + * etc. + *

+ * Operation names are mapped directly from the method names on the Java class. + *

+ * Message names are created using the FQ class name. A prefix of + * JavaService.TYPE is used to produce a name of the format + * java:[class.getName()], e.g. java:org.example.MyType. + */ +public final class JavaService extends BaseService { + + /** + * Interface type for Java service contracts. + */ + public static final String TYPE = "java"; + + // Java class used to create this ServiceInterface + private Class _serviceInterface; + + /** + * Private ctor for creating a new ServiceInterface. Clients of the API + * should use fromClass() to create a ServiceInterface from a Java class. + * @param operations list of operations on the service interface + * @param serviceInterface the java class used to derive the interface + */ + private JavaService(Set operations, Class serviceInterface) { + super(operations, TYPE); + _serviceInterface = serviceInterface; + } + + /** + * Creates a ServiceInterface from the specified Java class or interface. + * This is the equivalent of fromClass(serviceInterface, null). + * @param serviceInterface class or interface representing the service + * interface + * @return ServiceInterface representing the Java class + */ + public static JavaService fromClass(Class serviceInterface) { + HashSet ops = new HashSet(); + // Use all methods in type hierarchy for interfaces, but avoid this + // for classes which can drag in garbage from java.lang.Object, etc. + Method[] methods = serviceInterface.isInterface() + ? serviceInterface.getMethods() + : serviceInterface.getDeclaredMethods(); + for (Method m : methods) { + // We only consider public methods + if (Modifier.isPublic(m.getModifiers())) { + // At this point, we only accept methods with a single + // parameter which maps to the input message + Class[] params = m.getParameterTypes(); + if (params.length > 1) { + throw APIMessages.MESSAGES.serviceOpNeedOneParamater(); + } + + // Create the appropriate service operation and add it to the list + OperationTypeQNames operationTypeNames = new OperationTypeQNames(m); + if (m.getReturnType().equals(Void.TYPE)) { + ops.add(new InOnlyOperation(m.getName(), operationTypeNames.in())); + } else { + ops.add(new InOutOperation(m.getName(), operationTypeNames.in(), operationTypeNames.out(), operationTypeNames.fault())); + } + } + } + + return new JavaService(ops, serviceInterface); + } + + /** + * Returns the Java class or interface used to create this ServiceInterface. + * representation + * @return Java class or interface + */ + public Class getJavaInterface() { + return _serviceInterface; + } + + + + /** + * Tries to parse the passed in {@link QName} and load the class of that + * type. + * + * @param type The {@link QName} of the Java type to parse + * @return Class The Java class type or null if the {@link QName} passed in was null, + * or if the passed in type {@link QName} does not have the {@value #TYPE_PREFIX} + */ + public static Class parseType(final QName type) { + if (type == null) { + return null; + } + + final String localPart = type.getLocalPart(); + int indexOf = localPart.indexOf(':'); + if (indexOf != -1) { + return Classes.forName(localPart.substring(indexOf + 1)); + } else { + return null; + } + } + + /** + * Constructs QNames for method parameter and return types. + */ + public final static class OperationTypeQNames { + + private Method _operationMethod; + private OperationTypes _methodTypeNames; + + /** + * Construct am OperationTypeQNames. + * + * @param operationMethod the method that needs to pruned + */ + public OperationTypeQNames(Method operationMethod) { + this._operationMethod = operationMethod; + this._methodTypeNames = operationMethod.getAnnotation(OperationTypes.class); + } + + /** + * Construct QName for method parameter. + * + * @return the QName + */ + public QName in() { + if (_operationMethod.getParameterTypes().length > 0) { + Class inputType = _operationMethod.getParameterTypes()[0]; + + if (_methodTypeNames != null && _methodTypeNames.in().length() != 0) { + return QName.valueOf(_methodTypeNames.in()); + } + + return JavaTypes.toMessageType(inputType); + } else { + return null; + } + } + + /** + * Construct QName for method return type. + * + * @return the QName + */ + public QName out() { + if (_methodTypeNames != null && _methodTypeNames.out().length() != 0) { + return QName.valueOf(_methodTypeNames.out()); + } + + return JavaTypes.toMessageType(_operationMethod.getReturnType()); + } + + /** + * Construct QName for exception thrown from method. + * + * @return the QName + */ + public QName fault() { + Class[] exceptions = _operationMethod.getExceptionTypes(); + + if (exceptions.length == 0) { + return null; + } + if (exceptions.length > 1) { + throw APIMessages.MESSAGES.serviceOpOnlyOneParameter(); + } + + if (_methodTypeNames != null && _methodTypeNames.fault().length() != 0) { + return QName.valueOf(_methodTypeNames.fault()); + } + + return JavaTypes.toMessageType(exceptions[0]); + } + } +} diff --git a/core/extensions/java/src/test/java/org/switchyard/extensions/java/JavaServiceTest.java b/core/extensions/java/src/test/java/org/switchyard/extensions/java/JavaServiceTest.java new file mode 100644 index 000000000..aca933da8 --- /dev/null +++ b/core/extensions/java/src/test/java/org/switchyard/extensions/java/JavaServiceTest.java @@ -0,0 +1,198 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.extensions.java; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.ExchangePattern; +import org.switchyard.annotations.OperationTypes; +import org.switchyard.metadata.ServiceOperation; + +public class JavaServiceTest { + + static final QName METHOD1_INPUT = new QName( + "java:org.switchyard.extensions.java.MyStuff"); + static final QName METHOD2_INPUT = new QName( + "java:java.lang.Object"); + static final QName METHOD2_OUTPUT = new QName( + "java:org.switchyard.extensions.java.MyStuff"); + + @Test + public void testJavaInterfaceAsService() throws Exception { + JavaService js = JavaService.fromClass(JavaInterface.class); + // There should be two operations + Assert.assertEquals(2, js.getOperations().size()); + + // method1 is InOnly + ServiceOperation method1 = js.getOperation("method1"); + Assert.assertNotNull(method1); + Assert.assertEquals(method1.getInputType(), METHOD1_INPUT); + Assert.assertEquals(method1.getExchangePattern(), ExchangePattern.IN_ONLY); + + //method2 is InOut + ServiceOperation method2 = js.getOperation("method2"); + Assert.assertNotNull(method2); + Assert.assertEquals(method2.getInputType(), METHOD2_INPUT); + Assert.assertEquals(method2.getOutputType(), METHOD2_OUTPUT); + Assert.assertEquals(method2.getExchangePattern(), ExchangePattern.IN_OUT); + } + + @Test + public void testJavaClassAsService() throws Exception { + JavaService js = JavaService.fromClass(JavaClassOnly.class); + // There should be one operation + Assert.assertEquals(1, js.getOperations().size()); + // meh() is InOnly + ServiceOperation method = js.getOperation("meh"); + Assert.assertNotNull(method); + } + + @Test + public void testJavaClassImplementsInterfaceAsService() throws Exception { + JavaService js = JavaService.fromClass(JavaClassImplementsInterface.class); + // There should be one operation + Assert.assertEquals(3, js.getOperations().size()); + // meh() is InOnly + ServiceOperation method = js.getOperation("another"); + Assert.assertNotNull(method); + } + + @Test + public void testJavaClassExtendsClass() throws Exception { + JavaService js = JavaService.fromClass(JavaClassExtendsClass.class); + // There should be one operation + Assert.assertEquals(1, js.getOperations().size()); + // meh() is InOnly + ServiceOperation method = js.getOperation("blorg"); + Assert.assertNotNull(method); + } + + @Test + public void testInterfaceExtension() throws Exception { + JavaService js = JavaService.fromClass(InheritsInterface.class); + // There should be three operations + Assert.assertEquals(3, js.getOperations().size()); + // Check direct and one inherited method + Assert.assertNotNull(js.getOperation("oneMore")); + Assert.assertNotNull(js.getOperation("method1")); + } + + @Test + public void testInterfaceWithBadSignature() throws Exception { + Exception error = null; + + try { + JavaService.fromClass(JavaInterfaceBadSig.class); + } + catch (Exception ex) { error = ex; } + + Assert.assertNotNull(JavaInterfaceBadSig.class.getName() + + " shoud not be accepted as a valid ServiceInterface", error); + } + + @Test + public void testOperationTypes() { + JavaService service = JavaService.fromClass(TyepAnnotatedServiceClass.class); + + testOperationTypes("op1", service, QName.valueOf("A"), QName.valueOf("B"), null); + testOperationTypes("op2", service, QName.valueOf("java:java.lang.String"), null, null); + testOperationTypes("op3", service, QName.valueOf("java:java.lang.String"), QName.valueOf("java:java.lang.String"), QName.valueOf("C")); + testOperationTypes("op4", service, QName.valueOf("java:java.lang.String"), QName.valueOf("java:java.lang.String"), null); + } + + @Test + public void testParseType() { + final QName intType = new QName("java:java.lang.Integer"); + final Class intClass = JavaService.parseType(intType); + Assert.assertEquals(Integer.class, intClass); + } + + @Test + public void testParseTypeNull() { + final Class intClass = JavaService.parseType(null); + Assert.assertEquals(null, intClass); + } + + @Test + public void testParseTypeMissingJavaPrefix() { + final QName missingPrefix = new QName("java.lang.Integer"); + final Class intClass = JavaService.parseType(missingPrefix); + Assert.assertEquals(null, intClass); + } + + private void testOperationTypes(String opName, JavaService service, QName in, QName out, QName fault) { + ServiceOperation operation = service.getOperation(opName); + Assert.assertEquals(in, operation.getInputType()); + Assert.assertEquals(out, operation.getOutputType()); + Assert.assertEquals(fault, operation.getFaultType()); + } + + public interface TyepAnnotatedServiceClass { + + @OperationTypes(in = "A", out = "B") + public String op1(String input); + + @OperationTypes(out = "B") // Should have no effect since there's no return value + public void op2(String input); + + @OperationTypes(fault = "C") + public String op3(String input) throws RuntimeException; + + @OperationTypes(fault = "C") // Should have no effect since there's no exception + public String op4(String input); + } +} + +// This interface has two methods eligible for service operations +interface JavaInterface { + void method1(MyStuff param); + MyStuff method2(Object param); +} + +interface InheritsInterface extends JavaInterface { + void oneMore(String foo); +} + +// Method with no parameter +interface JavaInterfaceBadSig { + void method1(Object foo, Object bar); +} + +// This class has one method eligible for service operation +class JavaClassOnly { + public void meh(Object obj) {}; + void packageMeh() {}; + @SuppressWarnings("unused") + private void privateMeh() {}; +} + + +// This class has one method eligible for service operation; the inherited method +// from the base class is *not* included +class JavaClassExtendsClass extends JavaClassOnly { + public void blorg(Object obj) {}; +} + +// This class has three methods eligible; one from the class and two from the +// interface +class JavaClassImplementsInterface implements JavaInterface { + public void another(Object obj) {} + public void method1(MyStuff param) {} + public MyStuff method2(Object param) {return null;} +} + +class MyStuff { }; diff --git a/core/extensions/wsdl/pom.xml b/core/extensions/wsdl/pom.xml new file mode 100644 index 000000000..04c3dc1fa --- /dev/null +++ b/core/extensions/wsdl/pom.xml @@ -0,0 +1,47 @@ + + + + 4.0.0 + switchyard-extensions-wsdl + bundle + SwitchYard: API Extensions - WSDL + The SwitchYard WSDL API Extension + http://switchyard.org + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + + org.switchyard.extensions.wsdl + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + + junit + junit + + + diff --git a/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLExtensionsLogger.java b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLExtensionsLogger.java new file mode 100644 index 000000000..59d01e0f7 --- /dev/null +++ b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLExtensionsLogger.java @@ -0,0 +1,18 @@ +package org.switchyard.extensions.wsdl; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 13200-13399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface WSDLExtensionsLogger { + /** + * Default root logger. + */ + WSDLExtensionsLogger ROOT_LOGGER = Logger.getMessageLogger(WSDLExtensionsLogger.class, WSDLExtensionsLogger.class.getPackage().getName()); +} diff --git a/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLExtensionsMessages.java b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLExtensionsMessages.java new file mode 100644 index 000000000..284c4303e --- /dev/null +++ b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLExtensionsMessages.java @@ -0,0 +1,76 @@ +package org.switchyard.extensions.wsdl; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 12800-13000 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface WSDLExtensionsMessages { + /** + * Default messages. + */ + WSDLExtensionsMessages MESSAGES = Messages.getBundle(WSDLExtensionsMessages.class); + + /** + * unableFindPort method definition. + * @param portType port type + * @return WSDLReaderException + */ + @Message(id = 12800, value = "Unable to find portType with name %s") + WSDLReaderException unableFindPort(String portType); + + /** + * wsdlInterfaceNeedsOneParameter method definition. + * @return WSDLReaderException + */ + @Message(id = 12801, value = "Service operations on a WSDL interface must have exactly one parameter.") + WSDLReaderException wsdlInterfaceNeedsOneParameter(); + + /** + * unableResolveWSDL method definition. + * @param wsdlURI wsdlURI + * @param e e + * @return WSDLReaderException + */ + @Message(id = 12802, value = "Unable to resolve WSDL document at %s") + WSDLReaderException unableResolveWSDL(String wsdlURI, @Cause Exception e); + + /** + * invalidWSDLInterfacePart method definition. + * @param wsdlLocationURI wsdlLocationURI + * @return WSDLReaderException + */ + @Message(id = 12803, value = "Invalid WSDL interface part %s") + WSDLReaderException invalidWSDLInterfacePart(String wsdlLocationURI); + + /** + * invalidWSDLInterface method definition. + * @param wsdlLocationURI wsdlLocationURI + * @return WSDLReaderException + */ + @Message(id = 12804, value = "Invalid WSDL interface %s") + WSDLReaderException invalidWSDLInterface(String wsdlLocationURI); + + /** + * messageNameMissing method definition. + * @return WSDLReaderException + */ + @Message(id = 12805, value = "Message name missing.") + WSDLReaderException messageNameMissing(); + + /** + * missingOperationForMessage method definition. + * @param localName localName + * @return WSDLReaderException + */ + @Message(id = 12806, value = "Missing operation for message %s") + WSDLReaderException missingOperationForMessage(String localName); + +} diff --git a/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLReader.java b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLReader.java new file mode 100644 index 000000000..f9622d437 --- /dev/null +++ b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLReader.java @@ -0,0 +1,526 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.extensions.wsdl; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; + +import org.jboss.logging.Logger; +import org.switchyard.common.type.Classes; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * A utility class that creates ServiceOperation from a WSDL port definition. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class WSDLReader { + + private static final Logger LOGGER = Logger.getLogger(WSDLReader.class); + + private static final String SOAP11_URI = "http://schemas.xmlsoap.org/wsdl/soap/"; + private static final String SOAP12_URI = "http://schemas.xmlsoap.org/wsdl/soap12/"; + private static final String WSDLNS_URI = "http://schemas.xmlsoap.org/wsdl/"; + private static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; + private static final String ATTR_ELEMENT = "element"; + private static final String ATTR_LOCATION = "location"; + private static final String ATTR_MESSAGE = "message"; + private static final String ATTR_NAME = "name"; + private static final String ATTR_TARGET_NS = "targetNamespace"; + private static final String ATTR_XMLNS = "xmlns"; + private static final String ATTR_STYLE = "style"; + private static final String ATTR_TYPE = "type"; + private static final QName IMPORT = new QName(WSDLNS_URI, "import"); + private static final QName PORT_TYPE = new QName(WSDLNS_URI, "portType"); + private static final QName OPERATION = new QName(WSDLNS_URI, "operation"); + private static final QName INPUT = new QName(WSDLNS_URI, "input"); + private static final QName OUTPUT = new QName(WSDLNS_URI, "output"); + private static final QName FAULT = new QName(WSDLNS_URI, "fault"); + private static final QName MESSAGE = new QName(WSDLNS_URI, "message"); + private static final QName PART = new QName(WSDLNS_URI, "part"); + private static final QName BINDING = new QName(WSDLNS_URI, "binding"); + private static final QName SOAP11_BINDING = new QName(SOAP11_URI, "binding"); + private static final QName SOAP12_BINDING = new QName(SOAP12_URI, "binding"); + private static final String DOCUMENT = "document"; + private static final String RESPONSE = "Response"; + + private Boolean _documentStyle; + private String _wsdlURI; + + /** + * Read the WSDL document accessible via the specified + * URI into a WSDL definition. + * + * @param wsdlURI a URI (can be a filename or URL) pointing to a WSDL XML definition. + * @param portName the port name to match with + * @return the ServiceOperations. + * @throws WSDLReaderException if the wsdl cannot be read or is improper + */ + public HashSet readWSDL(final String wsdlURI, final String portName) throws WSDLReaderException { + + Element defEl = readWSDL(wsdlURI); + Map namespaces = parseNamespaces(defEl); + Element portType = getPortType(defEl, portName, namespaces); + if (portType == null) { + throw WSDLExtensionsMessages.MESSAGES.unableFindPort(portName); + } + String style = getStyle(defEl, portType, namespaces); + _documentStyle = style.equals(DOCUMENT) ? true : false; + Map parts = getParts(defEl, portType, namespaces); + HashSet ops = new HashSet(); + List operations = getOperations(portType); + int size = operations.size(); + for (int i = 0; i < size; i++) { + ops.add(createServiceOperation(operations.get(i), parts, namespaces)); + } + + return ops; + } + + /** + * Obtains the WSDL document located at the URI. + * + * @param wsdlURI a URI (can be a filename or URL) pointing to a WSDL XML definition. + * @return the WSDL document + * @throws WSDLReaderException if the wsdl cannot be read or is improper + */ + public Element readWSDL(final String wsdlURI) throws WSDLReaderException { + try { + // this is a hack, but it's necessary to avoid making breaking changes to + // the API by requiring the WSDL URI in the constructor + if (_wsdlURI == null) { + _wsdlURI = wsdlURI; + } + LOGGER.trace("Retrieving document at '" + wsdlURI + "'"); + URL url = getURL(wsdlURI); + InputStream inputStream = url.openStream(); + InputSource inputSource = new InputSource(inputStream); + inputSource.setSystemId(url.toString()); + Document doc = XMLHelper.getDocument(inputSource); + + inputStream.close(); + + return doc.getDocumentElement(); + + } catch (IOException e) { + throw WSDLExtensionsMessages.MESSAGES.unableResolveWSDL(wsdlURI, e); + } catch (ParserConfigurationException pce) { + throw new WSDLReaderException(pce); + } catch (SAXException se) { + throw new WSDLReaderException(se); + } + } + + /** + * Parse a WSDL definition for imports. + * + * @param defEl the definition element. + * @return the imported WSDL Locations. + */ + private List getImports(final Element defEl) { + Element tempEl = XMLHelper.getFirstChildElement(defEl); + List imports = new ArrayList(); + + while (tempEl != null) { + QName qname = new QName(tempEl.getNamespaceURI(), tempEl.getLocalName()); + if (IMPORT.equals(qname)) { + imports.add(tempEl.getAttribute(ATTR_LOCATION)); + } + tempEl = XMLHelper.getNextSiblingElement(tempEl); + } + return imports; + } + + /** + * Parse a WSDL definition for a given port name. + * + * @param defEl the definition element. + * @param portName the porttype name. + * @param namespaces the namespaces map. + * @return the porttype element. + * @throws WSDLReaderException if the wsdl cannot be read or is improper + */ + private Element getPortType(Element defEl, final String portName, Map namespaces) throws WSDLReaderException { + Element tempEl = XMLHelper.getFirstChildElement(defEl); + Element portType = null; + + while (tempEl != null) { + QName qname = new QName(tempEl.getNamespaceURI(), tempEl.getLocalName()); + if (PORT_TYPE.equals(qname)) { + if (portName != null + && tempEl.hasAttribute(ATTR_NAME) + && !tempEl.getAttribute(ATTR_NAME).equals(portName)) { + tempEl = XMLHelper.getNextSiblingElement(tempEl); + continue; + } + portType = tempEl; + break; + } + tempEl = XMLHelper.getNextSiblingElement(tempEl); + } + if (portType == null) { + List wsdlImports = getImports(defEl); + int size = wsdlImports.size(); + for (int i = 0; i < size; i++) { + Element importedDefEl = readWSDL(wsdlImports.get(i)); + namespaces.putAll(parseNamespaces(importedDefEl)); + portType = getPortType(importedDefEl, portName, namespaces); + if (portType != null) { + break; + } + } + } + return portType; + } + + /** + * Find the style of a WSDL port. + * + * @param defEl the definition element. + * @param portType the porttype element. + * @param namespaces a map of namespaceURIs + * @return the style, can be 'document' or 'rpc'. + * @throws WSDLReaderException if the wsdl cannot be read or is improper + */ + private String getStyle(final Element defEl, final Element portType, Map namespaces) throws WSDLReaderException { + Element tempEl = XMLHelper.getFirstChildElement(defEl); + QName portTypeName = getQName(portType.getAttributeNode(ATTR_NAME).getValue(), namespaces); + String style = DOCUMENT; + + while (tempEl != null) { + QName qname = new QName(tempEl.getNamespaceURI(), tempEl.getLocalName()); + if (BINDING.equals(qname)) { + QName bindingType = getQName(tempEl.getAttributeNode(ATTR_TYPE).getValue(), namespaces); + if (bindingType.equals(portTypeName)) { + Element tempEl2 = XMLHelper.getFirstChildElement(tempEl); + while (tempEl2 != null) { + QName qname2 = new QName(tempEl2.getNamespaceURI(), tempEl2.getLocalName()); + if ((SOAP11_BINDING.equals(qname2) || SOAP12_BINDING.equals(qname2)) && tempEl2.hasAttribute(ATTR_STYLE)) { + style = tempEl2.getAttributeNode(ATTR_STYLE).getValue(); + break; + } + tempEl2 = XMLHelper.getNextSiblingElement(tempEl2); + } + break; + } + } + tempEl = XMLHelper.getNextSiblingElement(tempEl); + } + if (style == null) { + List wsdlImports = getImports(defEl); + int size = wsdlImports.size(); + for (int i = 0; i < size; i++) { + Element importedDefEl = readWSDL(wsdlImports.get(i)); + namespaces.putAll(parseNamespaces(importedDefEl)); + style = getStyle(importedDefEl, portType, namespaces); + if (style != null) { + break; + } + } + } + return style; + } + + /** + * Parse a port type element and return all operations defined in it. + * + * @param portEl the portType element. + * @return a list of operation elements. + */ + private List getOperations(final Element portEl) { + Element tempEl = XMLHelper.getFirstChildElement(portEl); + List operations = new ArrayList(); + + while (tempEl != null) { + QName qname = new QName(tempEl.getNamespaceURI(), tempEl.getLocalName()); + if (OPERATION.equals(qname)) { + operations.add(tempEl); + } + tempEl = XMLHelper.getNextSiblingElement(tempEl); + } + return operations; + } + + /** + * Parse a port element and return the operation element matching the message element. + * + * @param portEl the portType element. + * @param msgEl the message element. + * @param namespaces a map of namespaceURIs + * @return the operation element. + */ + private Element getOperationByInput(final Element portEl, final Element msgEl, final Map namespaces) { + Element tempEl = XMLHelper.getFirstChildElement(portEl); + Element operation = null; + QName msgQName = getQName(msgEl.getAttribute(ATTR_NAME), namespaces); + +outer: while (tempEl != null) { + QName qname = new QName(tempEl.getNamespaceURI(), tempEl.getLocalName()); + if (OPERATION.equals(qname)) { + Element inputEl = XMLHelper.getFirstChildElement(tempEl); + while (inputEl != null) { + QName inputElQName = new QName(inputEl.getNamespaceURI(), inputEl.getLocalName()); + if (INPUT.equals(inputElQName)) { + QName inputMessageQName = getQName(inputEl.getAttribute(ATTR_MESSAGE), namespaces); + if (inputMessageQName.equals(msgQName)) { + operation = tempEl; + break outer; + } + } + inputEl = XMLHelper.getNextSiblingElement(inputEl); + } + } + tempEl = XMLHelper.getNextSiblingElement(tempEl); + } + return operation; + } + + /** + * Parse a port element and return the operation element matching the message element. + * + * @param portEl the portType element. + * @param msgEl the message element. + * @param namespaces a map of namespaceURIs + * @return the operation element. + */ + private Element getOperationByOutput(final Element portEl, final Element msgEl, final Map namespaces) { + Element tempEl = XMLHelper.getFirstChildElement(portEl); + Element operation = null; + QName msgQName = getQName(msgEl.getAttribute(ATTR_NAME), namespaces); + +outer: while (tempEl != null) { + QName qname = new QName(tempEl.getNamespaceURI(), tempEl.getLocalName()); + if (OPERATION.equals(qname)) { + Element inputEl = XMLHelper.getFirstChildElement(tempEl); + while (inputEl != null) { + QName inputElQName = new QName(inputEl.getNamespaceURI(), inputEl.getLocalName()); + if (OUTPUT.equals(inputElQName)) { + QName inputMessageQName = getQName(inputEl.getAttribute(ATTR_MESSAGE), namespaces); + if (inputMessageQName.equals(msgQName)) { + operation = tempEl; + break outer; + } + } + inputEl = XMLHelper.getNextSiblingElement(inputEl); + } + } + tempEl = XMLHelper.getNextSiblingElement(tempEl); + } + return operation; + } + + /** + * Parse a definition element and return all message parts defined in it. + * + * @param defEl the definition element. + * @param portType the portType element. + * @param namespaces a map of namespaceURIs + * @return a map of message parts. + * @throws WSDLReaderException if the wsdl operation is improper + */ + private Map getParts(final Element defEl, final Element portType, Map namespaces) throws WSDLReaderException { + NodeList messages = defEl.getElementsByTagNameNS(MESSAGE.getNamespaceURI(), MESSAGE.getLocalPart()); + int msgSize = messages.getLength(); + Map parts = new HashMap(); + for (int i = 0; i < msgSize; i++) { + Element msgEl = (Element) messages.item(i); + NodeList partEls = msgEl.getElementsByTagNameNS(PART.getNamespaceURI(), PART.getLocalPart()); + if (_documentStyle && (partEls.getLength() != 1)) { + throw WSDLExtensionsMessages.MESSAGES.wsdlInterfaceNeedsOneParameter(); + } + if (_documentStyle) { + Element partEl = (Element) partEls.item(0); + parts.put(getQName(msgEl.getAttribute(ATTR_NAME), namespaces), getQName(partEl.getAttribute(ATTR_ELEMENT), namespaces)); + } else { + if (!msgEl.hasAttribute(ATTR_NAME)) { + throw WSDLExtensionsMessages.MESSAGES.messageNameMissing(); + } + Element operationEl = getOperationByInput(portType, msgEl, namespaces); + if (operationEl != null) { + // request + // Create a fictional wrapper with the operation name + parts.put(getQName(msgEl.getAttribute(ATTR_NAME), namespaces), getQName(operationEl.getAttribute(ATTR_NAME), namespaces)); + } else { + // response + operationEl = getOperationByOutput(portType, msgEl, namespaces); + if (operationEl != null) { + // Create a fictional wrapper with the operation name + Response suffix + parts.put(getQName(msgEl.getAttribute(ATTR_NAME), namespaces), getQName(operationEl.getAttribute(ATTR_NAME) + RESPONSE, namespaces)); + } else { + WSDLExtensionsMessages.MESSAGES.missingOperationForMessage(msgEl.getLocalName()); + } + } + } + } + if (parts.isEmpty()) { + List wsdlImports = getImports(defEl); + int size = wsdlImports.size(); + for (int i = 0; i < size; i++) { + Element importedDefEl = readWSDL(wsdlImports.get(i)); + namespaces.putAll(parseNamespaces(importedDefEl)); + parts = getParts(importedDefEl, portType, namespaces); + if (!parts.isEmpty()) { + break; + } + } + } + return parts; + } + + /** + * Parse and create a Service Operation. + * + * @param opEl the operation element. + * @param parts a map of message parts. + * @param namespaces a map of namespaceURIs + * @return a ServiceOperation. + */ + private ServiceOperation createServiceOperation(final Element opEl, final Map parts, final Map namespaces) { + Element tempEl = XMLHelper.getFirstChildElement(opEl); + QName inputType = null; + QName outputType = null; + QName faultType = null; + + while (tempEl != null) { + QName qname = new QName(tempEl.getNamespaceURI(), tempEl.getLocalName()); + if (INPUT.equals(qname)) { + // input + inputType = parts.get(getQName(tempEl.getAttribute(ATTR_MESSAGE), namespaces)); + } else if (OUTPUT.equals(qname)) { + // output + outputType = parts.get(getQName(tempEl.getAttribute(ATTR_MESSAGE), namespaces)); + } else if (FAULT.equals(qname)) { + // fault + faultType = parts.get(getQName(tempEl.getAttribute(ATTR_MESSAGE), namespaces)); + } + tempEl = XMLHelper.getNextSiblingElement(tempEl); + } + if (outputType == null) { + return new InOnlyOperation(opEl.getAttribute(ATTR_NAME), inputType); + } else { + return new InOutOperation(opEl.getAttribute(ATTR_NAME), inputType, outputType, faultType); + } + } + + /** + * Parse and create a list of namespace declarations. + * + * @param defEl the definitions element. + * @return the list of namespaces. + */ + private Map parseNamespaces(final Element defEl) { + Map namespaces = new HashMap(); + String targetNamespace = defEl.getAttribute(ATTR_TARGET_NS); + namespaces.put(null, targetNamespace); + NamedNodeMap attrs = defEl.getAttributes(); + int size = attrs.getLength(); + + for (int i = 0; i < size; i++) { + Attr attr = (Attr) attrs.item(i); + String namespaceURI = attr.getNamespaceURI(); + String localPart = attr.getLocalName(); + String value = attr.getValue(); + + if (namespaceURI != null && namespaceURI.equals(XMLNS_URI)) { + if (localPart != null && !localPart.equals(ATTR_XMLNS)) { + namespaces.put(localPart, value); + } + } + } + return namespaces; + } + + /** + * Creates a QName with attribute value. + * + * @param value the attribute value. + * @param namespaces a map of namespaceURIs + * @return the fully qualified name. + */ + private QName getQName(final String value, final Map namespaces) { + String name = null; + String namespace = null; + if (value != null) { + int idx = value.lastIndexOf(":"); + name = value.substring(idx + 1, value.length()); + if (idx > 0) { + namespace = value.substring(0, idx); + } + } + return new QName(namespaces.get(namespace), name); + } + + + /** + * Convert a path/uri to a URL. + * + * @param path a path or URI. + * @return the URL. + * @throws MalformedURLException If the url path is not valid + */ + private URL getURL(final String path) throws MalformedURLException { + if (path.startsWith("http://") || path.startsWith("https://") || path.startsWith("file://")) { + return new URL(null, path); + } else { + URL url; + try { + if (_wsdlURI.equals(path)) { + url = Classes.getResource(path, getClass()); + } else { + // we are loading an imported resource, so use relative path + url = Classes.getResource(createRelativePath(_wsdlURI, path), getClass()); + } + } catch (IOException ioe) { + url = null; + } + if (url == null) { + File localFile = new File(path); + url = localFile.toURI().toURL(); + } + return url; + } + } + + // This method creates a relative path for an imported WSDL (path) based on the URI for + // the importing WSDL (baseURI). + String createRelativePath(String baseURI, String path) { + int lastPathIdx = baseURI.lastIndexOf('/'); + if (lastPathIdx > 0) { + return baseURI.substring(0, lastPathIdx + 1) + path; + } else { + return path; + } + } +} diff --git a/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLReaderException.java b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLReaderException.java new file mode 100644 index 000000000..6b6651a32 --- /dev/null +++ b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLReaderException.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.extensions.wsdl; + +/** + * Wrapper for WSDL read exceptions. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class WSDLReaderException extends Exception { + private static final long serialVersionUID = 1L; + + /** + * Public constructor. + * @param message Exception message. + */ + public WSDLReaderException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Exception cause. + */ + public WSDLReaderException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * Public constructor. + * @param cause Exception cause. + */ + public WSDLReaderException(final Throwable cause) { + super(cause); + } +} diff --git a/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLService.java b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLService.java new file mode 100644 index 000000000..e9509ac18 --- /dev/null +++ b/core/extensions/wsdl/src/main/java/org/switchyard/extensions/wsdl/WSDLService.java @@ -0,0 +1,125 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.extensions.wsdl; + +import java.util.HashSet; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.ServiceOperation; + +/** + * An implementation of ServiceInterface for WSDL files. The + * fromWSDL() method can be used to create a ServiceInterface + * representation from a WSDL file. A ServiceOperation will be + * created for each operation declared on the WSDL portType. + * + * Operation names are mapped directly from the operation QName. + * + * Message names are created using the input and output declarations of that operation. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public final class WSDLService extends BaseService { + + /** + * The type returned from ServiceInterface.getType(). + */ + public static final String TYPE = "wsdl"; + + private static final String PORTTYPE = "wsdl.porttype"; + + // WSDL location used to create this ServiceInterface + private String _wsdlLocation; + + // The port type for the ServiceInterface + private QName _portType; + + /** + * Private constructor for creating a new ServiceInterface. Clients of the API + * should use fromWSDL() to create a ServiceInterface from a WSDL. + * + * @param operations list of operations on the service interface + * @param wsdlLocation the WSDL location used to derive the interface + */ + private WSDLService(QName portType, final Set operations, final String wsdlLocation) { + super(operations, TYPE); + _portType = portType; + _wsdlLocation = wsdlLocation; + } + + /** + * Creates a ServiceInterface from the specified WSDL. The first found port definition will be used. + * + * @param wsdlLocationURI the WSDL location with port name used to derive the interface + * @return ServiceInterface representing the WSDL + * @throws WSDLReaderException if the wsdl cannot be read or is improper + */ + public static WSDLService fromWSDL(final String wsdlLocationURI) throws WSDLReaderException { + int index = wsdlLocationURI.indexOf("#"); + if (index > 0) { + String wsdlLocation = wsdlLocationURI.substring(0, index); + String localPart = wsdlLocationURI.substring(index + 1); + String portName = null; + if (localPart.contains(PORTTYPE)) { + portName = localPart.substring(PORTTYPE.length() + 1, localPart.length() - 1); + } else { + throw WSDLExtensionsMessages.MESSAGES.invalidWSDLInterfacePart(wsdlLocationURI); + } + return fromWSDL(wsdlLocation, portName); + } else { + throw WSDLExtensionsMessages.MESSAGES.invalidWSDLInterface(wsdlLocationURI); + } + } + + /** + * Creates a ServiceInterface from the specified WSDL. The first matching port definition + * with portName will be used. + * + * @param wsdlLocation the WSDL location used to derive the interface + * @param portName the port name to match with + * @return ServiceInterface representing the WSDL + * @throws WSDLReaderException if the wsdl cannot be read or is improper + */ + public static WSDLService fromWSDL(final String wsdlLocation, final String portName) throws WSDLReaderException { + WSDLReader reader = new WSDLReader(); + HashSet ops = reader.readWSDL(wsdlLocation, portName); + org.w3c.dom.Element wsdl = reader.readWSDL(wsdlLocation); + + QName portType = new QName(wsdl.getAttribute("targetNamespace"), portName); + + return new WSDLService(portType, ops, wsdlLocation); + } + + /** + * Returns the WSDL location used to create this ServiceInterface. + * + * @return WSDL definition location + */ + public String getWSDLLocation() { + return _wsdlLocation; + } + + /** + * Returns the Port Type associated with this ServiceInterface. + * + * @return Port type + */ + public QName getPortType() { + return _portType; + } +} diff --git a/core/extensions/wsdl/src/test/java/org/switchyard/extensions/wsdl/WSDLReaderTest.java b/core/extensions/wsdl/src/test/java/org/switchyard/extensions/wsdl/WSDLReaderTest.java new file mode 100644 index 000000000..389bc47b8 --- /dev/null +++ b/core/extensions/wsdl/src/test/java/org/switchyard/extensions/wsdl/WSDLReaderTest.java @@ -0,0 +1,54 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.extensions.wsdl; + +import java.util.Set; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.metadata.ServiceOperation; + +public class WSDLReaderTest { + + private static final String ORDER_WSDL = "wsdl/OrderService.wsdl"; + private WSDLReader reader; + + @Before + public void setUp() { + reader = new WSDLReader(); + } + + @Test + public void testRelativePaths() { + String base1 = "base.wsdl"; + String base2 = "wsdl/one/base.wsdl"; + String base3 = "wsdl/one/two/base.wsdl"; + String wsdl = "example.wsdl"; + + Assert.assertEquals("example.wsdl", + reader.createRelativePath(base1, wsdl)); + Assert.assertEquals("wsdl/one/example.wsdl", + reader.createRelativePath(base2, wsdl)); + Assert.assertEquals("wsdl/one/two/example.wsdl", + reader.createRelativePath(base3, wsdl)); + } + + @Test + public void importedWSDLs() throws Exception { + Assert.assertNotNull(reader.readWSDL(ORDER_WSDL)); + Set ops = reader.readWSDL(ORDER_WSDL, "OrderService"); + Assert.assertEquals(1, ops.size()); + } +} diff --git a/core/extensions/wsdl/src/test/java/org/switchyard/extensions/wsdl/WSDLServiceTest.java b/core/extensions/wsdl/src/test/java/org/switchyard/extensions/wsdl/WSDLServiceTest.java new file mode 100644 index 000000000..aaf53fe79 --- /dev/null +++ b/core/extensions/wsdl/src/test/java/org/switchyard/extensions/wsdl/WSDLServiceTest.java @@ -0,0 +1,150 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.extensions.wsdl; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.ExchangePattern; +import org.switchyard.extensions.wsdl.WSDLReaderException; +import org.switchyard.extensions.wsdl.WSDLService; +import org.switchyard.metadata.ServiceOperation; + +/** + * Tests for WSDLService + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class WSDLServiceTest { + + static final QName METHOD1_INPUT = new QName("urn:switchyard-metadata-wsdl", "helloWS"); + static final QName METHOD2_INPUT = new QName("urn:switchyard-metadata-wsdl", "sayHello"); + static final QName METHOD2_OUTPUT = new QName("urn:switchyard-metadata-wsdl", "sayHelloResponse"); + static final QName METHOD3_INPUT = new QName("urn:switchyard-metadata-interface", "helloWS"); + + @Test + public void interfaceWSDLService() throws Exception { + WSDLService wsdlService = WSDLService.fromWSDL("HelloWebService.wsdl", "HelloWebService"); + + Assert.assertEquals("{urn:switchyard-metadata-wsdl}HelloWebService", wsdlService.getPortType().toString()); + + // There should be two operations + Assert.assertEquals(2, wsdlService.getOperations().size()); + + // method1 is InOnly + ServiceOperation method1 = wsdlService.getOperation("helloWS"); + Assert.assertNotNull(method1); + Assert.assertEquals(method1.getInputType(), METHOD1_INPUT); + Assert.assertEquals(method1.getExchangePattern(), ExchangePattern.IN_ONLY); + + //method2 is InOut + ServiceOperation method2 = wsdlService.getOperation("sayHello"); + Assert.assertNotNull(method2); + Assert.assertEquals(method2.getInputType(), METHOD2_INPUT); + Assert.assertEquals(method2.getOutputType(), METHOD2_OUTPUT); + Assert.assertEquals(method2.getExchangePattern(), ExchangePattern.IN_OUT); + } + + @Test + public void interfaceWSDLServiceNoPortName() throws Exception { + WSDLService wsdlService = WSDLService.fromWSDL("HelloWebService.wsdl#wsdl.porttype(HelloWebService)"); + + Assert.assertEquals("{urn:switchyard-metadata-wsdl}HelloWebService", wsdlService.getPortType().toString()); + + // There should be two operations + Assert.assertEquals(2, wsdlService.getOperations().size()); + } + + @Test + public void invalidInterface() throws Exception { + try { + WSDLService.fromWSDL("wsdl.porttype(HelloWebService)"); + } catch (WSDLReaderException e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD012804"); + Assert.assertTrue(exceptionMatches); + } + } + + @Test + public void invalidInterface2() throws Exception { + try { + WSDLService.fromWSDL("HelloWebService.wsdl#(HelloWebService)"); + } catch (WSDLReaderException e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD012803"); + Assert.assertTrue(exceptionMatches); + } + } + + @Test + public void nonExistingPort() throws Exception { + try { + WSDLService.fromWSDL("HelloWebService.wsdl", "hello"); + } catch (WSDLReaderException e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD012800"); + Assert.assertTrue(exceptionMatches); + } + } + + @Test + public void nonExistingFile() throws Exception { + try { + WSDLService.fromWSDL("unknown.wsdl", "hello"); + } catch (WSDLReaderException e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD012802"); + Assert.assertTrue(exceptionMatches); + } + } + + @Test + public void improperWSDL() throws Exception { + try { + WSDLService.fromWSDL("HelloWebService2.wsdl", "HelloWebService"); + } catch (WSDLReaderException e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD012801"); + Assert.assertTrue(exceptionMatches); + } + } + + @Test + public void importedWSDL() throws Exception { + WSDLService wsdlService = WSDLService.fromWSDL("HelloWebService3.wsdl", "HelloWebService"); + + Assert.assertEquals("{urn:switchyard-metadata-wsdl}HelloWebService", wsdlService.getPortType().toString()); + // There should be two operations + Assert.assertEquals(2, wsdlService.getOperations().size()); + + // method is InOnly + ServiceOperation method1 = wsdlService.getOperation("helloWS"); + Assert.assertNotNull(method1); + Assert.assertEquals(METHOD3_INPUT, method1.getInputType()); + Assert.assertEquals(ExchangePattern.IN_ONLY, method1.getExchangePattern()); + } + + @Test + public void importedWSDLMulti() throws Exception { + WSDLService wsdlService = WSDLService.fromWSDL("service.wsdl", "HelloWebService"); + + Assert.assertEquals("{urn:switchyard-metadata-wsdl}HelloWebService", wsdlService.getPortType().toString()); + // There should be two operations + Assert.assertEquals(2, wsdlService.getOperations().size()); + + // method is InOnly + ServiceOperation method1 = wsdlService.getOperation("helloWS"); + Assert.assertNotNull(method1); + Assert.assertEquals(METHOD3_INPUT, method1.getInputType()); + Assert.assertEquals(ExchangePattern.IN_ONLY, method1.getExchangePattern()); + } +} diff --git a/core/extensions/wsdl/src/test/resources/HelloInterface.wsdl b/core/extensions/wsdl/src/test/resources/HelloInterface.wsdl new file mode 100644 index 000000000..3675c2bb0 --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/HelloInterface.wsdl @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/extensions/wsdl/src/test/resources/HelloWebService.wsdl b/core/extensions/wsdl/src/test/resources/HelloWebService.wsdl new file mode 100644 index 000000000..0d8b66c7a --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/HelloWebService.wsdl @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/extensions/wsdl/src/test/resources/HelloWebService2.wsdl b/core/extensions/wsdl/src/test/resources/HelloWebService2.wsdl new file mode 100644 index 000000000..6e1a2812d --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/HelloWebService2.wsdl @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/extensions/wsdl/src/test/resources/HelloWebService3.wsdl b/core/extensions/wsdl/src/test/resources/HelloWebService3.wsdl new file mode 100644 index 000000000..167b977d2 --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/HelloWebService3.wsdl @@ -0,0 +1,17 @@ + + + + + + + + + + diff --git a/core/extensions/wsdl/src/test/resources/message.wsdl b/core/extensions/wsdl/src/test/resources/message.wsdl new file mode 100644 index 000000000..d3e482b5b --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/message.wsdl @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/extensions/wsdl/src/test/resources/port.wsdl b/core/extensions/wsdl/src/test/resources/port.wsdl new file mode 100644 index 000000000..1a547a356 --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/port.wsdl @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + diff --git a/core/extensions/wsdl/src/test/resources/service.wsdl b/core/extensions/wsdl/src/test/resources/service.wsdl new file mode 100644 index 000000000..65ae86fdd --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/service.wsdl @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/extensions/wsdl/src/test/resources/wsdl/Common.wsdl b/core/extensions/wsdl/src/test/resources/wsdl/Common.wsdl new file mode 100644 index 000000000..7d8a1397c --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/wsdl/Common.wsdl @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/extensions/wsdl/src/test/resources/wsdl/OrderService.wsdl b/core/extensions/wsdl/src/test/resources/wsdl/OrderService.wsdl new file mode 100644 index 000000000..230675b4d --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/wsdl/OrderService.wsdl @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/extensions/wsdl/src/test/resources/wsdl/OrderTypes.xsd b/core/extensions/wsdl/src/test/resources/wsdl/OrderTypes.xsd new file mode 100644 index 000000000..0f5115a0a --- /dev/null +++ b/core/extensions/wsdl/src/test/resources/wsdl/OrderTypes.xsd @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core/pom.xml b/core/pom.xml new file mode 100644 index 000000000..f88368f94 --- /dev/null +++ b/core/pom.xml @@ -0,0 +1,163 @@ + + + + + org.switchyard + switchyard-parent + 2.1.0-SNAPSHOT + .. + + 4.0.0 + switchyard-core-parent + pom + SwitchYard: Core + SwitchYard Core + + scm:git:https://github.com/jboss-switchyard/core.git + scm:git:ssh://git@github.com:jboss-switchyard/core.git + http://github.com/jboss-switchyard/core + + + build + api + extensions/java + extensions/wsdl + common/core + common/cdi + common/camel + config + serial/base + serial/jackson + + security/base + security/jboss + security/karaf + transform + validate + runtime + remote + admin + bus/camel + test + tools/maven/plugins/switchyard + deploy/base + deploy/cdi + deploy/webapp + tools/maven/archetypes/application + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + https://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + + + + junit + junit + test + true + + + xmlunit + xmlunit + test + true + + + org.jboss.logging + jboss-logging + + + org.jboss.logging + jboss-logging-processor + + provided + true + + + + + javadoc + + false + + javadoc + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + aggregate + + aggregate + + install + + JBoss by Red Hat + true + ${project.build.sourceEncoding} + ${project.build.sourceEncoding} + + SwitchYard Core ${project.version} + ${project.build.sourceEncoding} + *.admin.*:*.bus.*:*.config.*:*.deploy.*:*.deployment.*:*.extensions.*:*.handlers.*:*.internal.*:*.spi.*:*.test.*:*.tools.*:*.transform.ootb.**.transform.xslt.* + + + API + org.switchyard:org.switchyard.annotations*:org.switchyard.composer*:org.switchyard.exception*:org.switchyard.io*:org.switchyard.metadata*:org.switchyard.policy*:org.switchyard.transform* + + + Common + org.switchyard.common* + + + true + + http://docs.oracle.com/javase/6/docs/api/ + + true + true + + + + + + + + + diff --git a/core/remote/pom.xml b/core/remote/pom.xml new file mode 100644 index 000000000..b8857e57d --- /dev/null +++ b/core/remote/pom.xml @@ -0,0 +1,77 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-remote + bundle + SwitchYard: Remote + Library used to communicate with remote SwitchYard instances + http://switchyard.org + + + org.switchyard.remote.* + + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + org.infinispan*;resolution:=optional, + * + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-serial + + + org.switchyard + switchyard-serial-jackson + + + + org.infinispan + infinispan-core + + + org.jboss.marshalling + jboss-marshalling + test + + + org.jboss.marshalling + jboss-marshalling-river + test + + + org.jgroups + jgroups + test + + + diff --git a/core/remote/src/main/java/org/switchyard/remote/RemoteEndpoint.java b/core/remote/src/main/java/org/switchyard/remote/RemoteEndpoint.java new file mode 100644 index 000000000..70921111a --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/RemoteEndpoint.java @@ -0,0 +1,165 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote; + +import javax.xml.namespace.QName; + +import org.switchyard.Service; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.serial.graph.AccessType; +import org.switchyard.serial.graph.Strategy; + +/** + * Represents a service endpoint registered in a distributed registry. + */ +@Strategy(access=AccessType.FIELD) +public class RemoteEndpoint { + + private QName _serviceName; + private QName _domainName; + private String _endpoint; + private String _node; + private ServiceInterface _contract; + + /** + * Creates a new, empty RemoteEndpoint. + */ + public RemoteEndpoint() { + + } + + /** + * Creates a new RemoteEndpoint with the specified attributes. + * @param serviceName the service name + * @param domainName name of the domain where the service is regsitered + * @param endpoint endpoint remote access URL + * @param node the cluster node name where the service resides + * @param contract the contract for the service + */ + public RemoteEndpoint(QName serviceName, + QName domainName, + String endpoint, + String node, + ServiceInterface contract) { + + _serviceName = serviceName; + _domainName = domainName; + _endpoint = endpoint; + _node = node; + _contract = contract; + } + + /** + * Returns the name of the service. + * @return service name + */ + public QName getServiceName() { + return _serviceName; + } + + /** + * Specifies the service name for the endpoint. + * @param serviceName service name + * @return reference to this RemoteEndpoint + */ + public RemoteEndpoint setServiceName(QName serviceName) { + _serviceName = serviceName; + return this; + } + + /** + * Returns the domain name. + * @return domain name. + */ + public QName getDomainName() { + return _domainName; + } + + /** + * Specifies the domain name. + * @param domainName domain name + * @return reference to this RemoteEndpoint + */ + public RemoteEndpoint setDomainName(QName domainName) { + _domainName = domainName; + return this; + } + + /** + * Returns the endpoint address. + * @return endpoint address + */ + public String getEndpoint() { + return _endpoint; + } + + /** + * Specifies the endpoint address. + * @param endpoint endpoint address + * @return reference to this RemoteEndpoint + */ + public RemoteEndpoint setEndpoint(String endpoint) { + _endpoint = endpoint; + return this; + } + + /** + * Returns the service contract. + * @return service contract + */ + public ServiceInterface getContract() { + return _contract; + } + + /** + * Specifies the service contract. + * @param contract service contract + * @return reference to this RemoteEndpoint + */ + public RemoteEndpoint setContract(ServiceInterface contract) { + _contract = contract; + return this; + } + + /** + * Returns the node name. + * @return node name. + */ + public String getNode() { + return _node; + } + + /** + * Specifies the domain name. + * @param node domain name + * @return reference to this RemoteEndpoint + */ + public RemoteEndpoint setNode(String node) { + _node = node; + return this; + } + + /** + * Create a RemoteEndpoint representation from a registered service. + * @param service registered service + * @return reference to this RemoteEndpoint + */ + public static RemoteEndpoint fromService(Service service) { + return new RemoteEndpoint(service.getName(), + service.getDomain().getName(), + null, + null, + RemoteInterface.fromInterface(service.getInterface())); + } +} diff --git a/core/remote/src/main/java/org/switchyard/remote/RemoteInterface.java b/core/remote/src/main/java/org/switchyard/remote/RemoteInterface.java new file mode 100644 index 000000000..940605a0c --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/RemoteInterface.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote; + +import java.util.HashSet; +import java.util.Set; + +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.metadata.ServiceOperation; + +/** + * Remotable contract definition. + */ +public class RemoteInterface extends BaseService { + + /** + * The "remote" type. + */ + public static final String TYPE = "remote"; + + /** + * Create a new RemoteInterface with no operations. + */ + public RemoteInterface() { + super(new HashSet(), TYPE); + } + + /** + * Create a new RemoteInterface with the specified operation and type. + * @param operations the operation set + * @param type the interface type + */ + public RemoteInterface(Set operations, String type) { + super(operations, type); + } + + /** + * Creates a RemoteInterface representation from an existing contract. + * @param contract the existing interface contract + * @return RemoteInterface representation of the specified contract + */ + public static RemoteInterface fromInterface(ServiceInterface contract) { + return new RemoteInterface(contract.getOperations(), TYPE); + } + +} diff --git a/core/remote/src/main/java/org/switchyard/remote/RemoteInvoker.java b/core/remote/src/main/java/org/switchyard/remote/RemoteInvoker.java new file mode 100644 index 000000000..9b34d6651 --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/RemoteInvoker.java @@ -0,0 +1,29 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote; + + +/** + * Client contract for remote service invocation. + */ +public interface RemoteInvoker { + + /** + * Invoke a remote service using the specified RemoteMessage. + * @param request message + * @return reply message or null if the invoked service is in-only + * @throws java.io.IOException remote communication failure + */ + public RemoteMessage invoke(RemoteMessage request) throws java.io.IOException; +} diff --git a/core/remote/src/main/java/org/switchyard/remote/RemoteLogger.java b/core/remote/src/main/java/org/switchyard/remote/RemoteLogger.java new file mode 100644 index 000000000..b9a57f19a --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/RemoteLogger.java @@ -0,0 +1,43 @@ +package org.switchyard.remote; + +import static org.jboss.logging.Logger.Level.INFO; +import static org.jboss.logging.Logger.Level.WARN; + +import java.io.IOException; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 13600-13799 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface RemoteLogger { + /** + * Default root logger. + */ + RemoteLogger ROOT_LOGGER = Logger.getMessageLogger(RemoteLogger.class, RemoteLogger.class.getPackage().getName()); + + /** + * remoteEndpointRegistered method definition. + * @param cacheKey cacheKey + */ + @LogMessage(level = INFO) + @Message(id = 13600, value="Remote endpoint %s is already registered in the cache") + void remoteEndpointRegistered(String cacheKey); + + /** + * failedAddEndpoint method definition. + * @param cacheKey cacheKey + * @param ioEx ioEx + */ + @LogMessage(level = WARN) + @Message(id = 13601, value="Failed to add remote endpoint %s to registry.") + void failedAddEndpoint(String cacheKey, @Cause IOException ioEx); +} diff --git a/core/remote/src/main/java/org/switchyard/remote/RemoteMessage.java b/core/remote/src/main/java/org/switchyard/remote/RemoteMessage.java new file mode 100644 index 000000000..01c2be448 --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/RemoteMessage.java @@ -0,0 +1,150 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote; + +import javax.xml.namespace.QName; + +import org.switchyard.Context; +import org.switchyard.internal.CompositeContext; +import org.switchyard.serial.graph.AccessType; +import org.switchyard.serial.graph.Strategy; + +/** + * Serializable container for context and content used in an invocation. + */ +@Strategy(access=AccessType.FIELD) +public class RemoteMessage { + + private Context _context; + private Object _content; + private QName _service; + private QName _domain; + private String _operation; + private boolean _fault; + + /** + * Create an empty remote message. + */ + public RemoteMessage() { + _context = new CompositeContext(); + } + + /** + * Create a remote message for the specified domain and service. + * @param domain the domain name + * @param service the service name + */ + public RemoteMessage(QName domain, QName service) { + _domain = domain; + _service = service; + } + + /** + * Returns the context properties for the invocation. + * @return context properties + */ + public Context getContext() { + return _context; + } + + /** + * Returns the content for the invocation. + * @return the message content + */ + public Object getContent() { + return _content; + } + + /** + * Specifies the content for the invocation. + * @param content message content + * @return a reference to this RemoteMessage + */ + public RemoteMessage setContent(Object content) { + _content = content; + return this; + } + + /** + * Returns the service name for the invocation. + * @return the service name + */ + public QName getService() { + return _service; + } + + /** + * Specifies the name of the service being invoked. + * @param service service name + * @return a reference to this RemoteMessage + */ + public RemoteMessage setService(QName service) { + _service = service; + return this; + } + + /** + * Returns the name of the domain for the invocation. + * @return a reference to this RemoteMessage + */ + public QName getDomain() { + return _domain; + } + + /** + * Specifies the name of the domain for the invocation. + * @param domain domain name + * @return a reference to this RemoteMessage + */ + public RemoteMessage setDomain(QName domain) { + _domain = domain; + return this; + } + + /** + * Returns the operation being invoked. + * @return operation name + */ + public String getOperation() { + return _operation; + } + + /** + * Specifies the name of the operation being invoked. + * @param operation operation name + * @return a reference to this RemoteMessage + */ + public RemoteMessage setOperation(String operation) { + _operation = operation; + return this; + } + + /** + * Specifies whether this remote message represents a fault. + * @param isFault true if this is a fault, false otherwise + * @return a reference to this RemoteMessage + */ + public RemoteMessage setFault(boolean isFault) { + _fault = isFault; + return this; + } + + /** + * Indicates whether this remote message represents a fault. + * @return true if this is a fault, false otherwise + */ + public boolean isFault() { + return _fault; + } +} diff --git a/core/remote/src/main/java/org/switchyard/remote/RemoteMessages.java b/core/remote/src/main/java/org/switchyard/remote/RemoteMessages.java new file mode 100644 index 000000000..4104e6a67 --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/RemoteMessages.java @@ -0,0 +1,41 @@ +package org.switchyard.remote; + +import java.net.MalformedURLException; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 13400-13599 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface RemoteMessages { + /** + * Default messages. + */ + RemoteMessages MESSAGES = Messages.getBundle(RemoteMessages.class); + + /** + * noRemoteEndpointFound method definition. + * @param service service + * @return SwitchYardException + */ + @Message(id = 13400, value = "No remote endpoints found for service %s") + SwitchYardException noRemoteEndpointFound(String service); + + /** + * invalidURLForEndpoint method definition. + * @param endpoint endpoint + * @param mue mue + * @return IllegalArgumentException + */ + @Message(id = 13401, value = "Invalid URL for remote endpoint: %s") + IllegalArgumentException invalidURLForEndpoint(String endpoint, @Cause MalformedURLException mue); +} diff --git a/core/remote/src/main/java/org/switchyard/remote/RemoteRegistry.java b/core/remote/src/main/java/org/switchyard/remote/RemoteRegistry.java new file mode 100644 index 000000000..c50fe339e --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/RemoteRegistry.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote; + +import java.util.List; + +import javax.xml.namespace.QName; + +/** + * Contract for a distributed registry provider. + */ +public interface RemoteRegistry { + + /** + * Add an endpoint to the registry. If the endpoint already exists then nothing is added. + * @param endpoint the endpoint to add + */ + public void addEndpoint(RemoteEndpoint endpoint); + + /** + * Removes an endpoint from the registry if it exists. + * @param endpoint the endpoint to remove. + */ + public void removeEndpoint(RemoteEndpoint endpoint); + + /** + * Returns a list of all registered endpoints for a given service. + * @param serviceName name of the service + * @return list of registered endpoints + */ + public List getEndpoints(QName serviceName); + +} diff --git a/core/remote/src/main/java/org/switchyard/remote/cluster/BaseStrategy.java b/core/remote/src/main/java/org/switchyard/remote/cluster/BaseStrategy.java new file mode 100644 index 000000000..3378a11e1 --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/cluster/BaseStrategy.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.cluster; + +import org.switchyard.remote.RemoteRegistry; + +/** + * Abstract base class for LoadBalanceStrategy implementations. + */ +public abstract class BaseStrategy implements LoadBalanceStrategy { + + private RemoteRegistry _registry; + + @Override + public RemoteRegistry getRegistry() { + return _registry; + } + + @Override + public void setRegistry(RemoteRegistry registry) { + _registry = registry; + } +} diff --git a/core/remote/src/main/java/org/switchyard/remote/cluster/ClusteredInvoker.java b/core/remote/src/main/java/org/switchyard/remote/cluster/ClusteredInvoker.java new file mode 100644 index 000000000..8b05ef1fc --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/cluster/ClusteredInvoker.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.cluster; + +import java.io.IOException; + +import org.switchyard.remote.RemoteEndpoint; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.RemoteMessages; +import org.switchyard.remote.RemoteRegistry; +import org.switchyard.remote.http.HttpInvoker; + +/** + * Cluster-aware implementation of RemoteInvoker which uses a load balance strategy in + * combination with a remote registry to invoke remote services. + */ +public class ClusteredInvoker implements RemoteInvoker { + + private LoadBalanceStrategy _loadBalancer; + + /** + * Create a new ClusteredInvoker with the default load balance strategy (RoundRobin). + * @param registry remote registry + */ + public ClusteredInvoker(RemoteRegistry registry) { + this(registry, new RoundRobinStrategy()); + } + + /** + * Create a new ClusteredInvoker with the specified load balance strategy. + * @param registry remote registry + * @param loadBalancer load balance strategy + */ + public ClusteredInvoker(RemoteRegistry registry, LoadBalanceStrategy loadBalancer) { + _loadBalancer = loadBalancer; + _loadBalancer.setRegistry(registry); + } + + @Override + public RemoteMessage invoke(RemoteMessage request) throws IOException { + RemoteEndpoint ep = _loadBalancer.selectEndpoint(request.getService()); + if (ep == null) { + throw RemoteMessages.MESSAGES.noRemoteEndpointFound(request.getService().toString()); + } + return new HttpInvoker(ep.getEndpoint()).invoke(request); + } + +} diff --git a/core/remote/src/main/java/org/switchyard/remote/cluster/LoadBalanceStrategy.java b/core/remote/src/main/java/org/switchyard/remote/cluster/LoadBalanceStrategy.java new file mode 100644 index 000000000..02b87b764 --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/cluster/LoadBalanceStrategy.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.cluster; + +import javax.xml.namespace.QName; + +import org.switchyard.remote.RemoteEndpoint; +import org.switchyard.remote.RemoteRegistry; + +/** + * Represents the contract for endpoint selection strategy in a SwitchYard cluster. A + * strategy implementation is initialized with information on remote endpoints + * (e.g. a reference to RemoteRegistry) and selects a service endpoint based on available + * endpoints and its load balance strategy (e.g. RoundRobin, FirstAvailable, etc.). + */ +public interface LoadBalanceStrategy { + /** + * Select an endpoint based on the list of available endpoints and the implementation's + * load balance strategy. + * @param serviceName service name for lookup + * @return selected service endpoint or null if no endpoint was located + */ + RemoteEndpoint selectEndpoint(QName serviceName); + + /** + * Returns a reference to the remote registry used by the load balancing strategy. + * @return remote registry + */ + RemoteRegistry getRegistry(); + + /** + * Specifies the remote registry used by the load balancing strategy. + * @param registry remote registry + */ + void setRegistry(RemoteRegistry registry); +} diff --git a/core/remote/src/main/java/org/switchyard/remote/cluster/RandomStrategy.java b/core/remote/src/main/java/org/switchyard/remote/cluster/RandomStrategy.java new file mode 100644 index 000000000..2e7bc8f0c --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/cluster/RandomStrategy.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.cluster; + +import java.util.List; +import java.util.Random; + +import javax.xml.namespace.QName; + +import org.switchyard.remote.RemoteEndpoint; + +/** + * Random endpoint selection strategy which uses a Java Random with default seed to select an + * available endpoint in the list. + */ +public class RandomStrategy extends BaseStrategy { + + private Random _random = new Random(); + + /** + * Create a new RandomStrategy. + */ + public RandomStrategy() { + super(); + } + + @Override + public RemoteEndpoint selectEndpoint(QName serviceName) { + if (getRegistry() == null) { + return null; + } + + RemoteEndpoint selectedEp = null; + List eps = getRegistry().getEndpoints(serviceName); + if (!eps.isEmpty()) { + int idx = _random.nextInt(Integer.MAX_VALUE) % eps.size(); + selectedEp = eps.get(idx); + } + + return selectedEp; + } + +} diff --git a/core/remote/src/main/java/org/switchyard/remote/cluster/RoundRobinStrategy.java b/core/remote/src/main/java/org/switchyard/remote/cluster/RoundRobinStrategy.java new file mode 100644 index 000000000..3ff39c7dd --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/cluster/RoundRobinStrategy.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.cluster; + +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.namespace.QName; + +import org.switchyard.remote.RemoteEndpoint; + +/** + * Round Robin load balancing strategy. The algorithm used here is pretty naive in that the + * index is decoupled from the list of endpoints returned from the remote registry. This means + * there's potential for a given endpoint to be "skipped" in a given cycle if endpoints are + * removed between selections. This is not harmful, but it means this implementation does not + * guarantee completely uniform distribution in the event of cluster topology changes. + */ +public class RoundRobinStrategy extends BaseStrategy { + + private ConcurrentMap _endpointIdxs = new ConcurrentHashMap(); + + /** + * Create a new RoundRobin strategy. + */ + public RoundRobinStrategy() { + super(); + } + + @Override + public RemoteEndpoint selectEndpoint(QName serviceName) { + if (getRegistry() == null) { + return null; + } + RemoteEndpoint selectedEp = null; + List eps = getRegistry().getEndpoints(serviceName); + if (!eps.isEmpty()) { + _endpointIdxs.putIfAbsent(serviceName, new AtomicInteger(0)); + AtomicInteger idx = _endpointIdxs.get(serviceName); + synchronized (idx) { + idx.set(idx.get() % eps.size()); + selectedEp = eps.get(idx.getAndIncrement()); + } + } + + return selectedEp; + } +} diff --git a/core/remote/src/main/java/org/switchyard/remote/http/HttpInvoker.java b/core/remote/src/main/java/org/switchyard/remote/http/HttpInvoker.java new file mode 100644 index 000000000..c0b8d5857 --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/http/HttpInvoker.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.http; + +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; + +import org.jboss.logging.Logger; +import org.switchyard.Property; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.RemoteMessages; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; + +/** + * Remote service invoker which uses HTTP as a transport. + */ +public class HttpInvoker implements RemoteInvoker { + + /** + * HTTP header used to communicate the domain name for a service invocation. + */ + public static final String SERVICE_HEADER = "switchyard-service"; + + private static Logger _log = Logger.getLogger(HttpInvoker.class); + private Serializer _serializer = SerializerFactory.create(FormatType.JSON, null, true); + private URL _endpoint; + + /** + * Create a new HttpInvoker from the specified URL string. + * @param endpoint url string + */ + public HttpInvoker(String endpoint) { + try { + _endpoint = new URL(endpoint); + } catch (MalformedURLException badURL) { + throw RemoteMessages.MESSAGES.invalidURLForEndpoint(endpoint, badURL); + } + } + + /** + * Create a new HttpInvoker with the specified URL. + * @param endpoint the endpoint URL + */ + public HttpInvoker(URL endpoint) { + _endpoint = endpoint; + } + + @Override + public RemoteMessage invoke(RemoteMessage request) throws java.io.IOException { + RemoteMessage reply = null; + HttpURLConnection conn = null; + + if (_log.isDebugEnabled()) { + _log.debug("Invoking " + request.getService() + " at endpoint " + _endpoint.toString()); + } + + // Initialize HTTP connection + conn = (HttpURLConnection)_endpoint.openConnection(); + conn.setDoOutput(true); + conn.addRequestProperty(SERVICE_HEADER, request.getService().toString()); + for (Property prop : request.getContext().getProperties(HttpInvokerLabel.HEADER.label())) { + conn.addRequestProperty(prop.getName(), prop.getValue().toString()); + } + + conn.connect(); + OutputStream os = conn.getOutputStream(); + try { + // Write the request message + _serializer.serialize(request, RemoteMessage.class, os); + os.flush(); + } finally { + os.close(); + } + + // Check for response and process accordingly + if (conn.getResponseCode() == 200) { + if (_log.isDebugEnabled()) { + _log.debug("Processing reply for service " + request.getService()); + } + InputStream is = conn.getInputStream(); + try { + reply = _serializer.deserialize(is, RemoteMessage.class); + } finally { + is.close(); + } + } + + return reply; + } +} diff --git a/core/remote/src/main/java/org/switchyard/remote/http/HttpInvokerLabel.java b/core/remote/src/main/java/org/switchyard/remote/http/HttpInvokerLabel.java new file mode 100644 index 000000000..c2e608e86 --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/http/HttpInvokerLabel.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.http; + +import org.switchyard.label.Label; + +/** + * Represents httpinvoker labels. + */ +public enum HttpInvokerLabel implements Label { + /** httpinvoker labels. */ + HEADER; + + private final String _label; + + private HttpInvokerLabel() { + _label = Label.Util.toSwitchYardLabel("httpinvoker", name()); + } + + /** + * {@inheritDoc} + */ + @Override + public String label() { + return _label; + } + + /** + * Gets the HttpInvokerLabel enum via case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the HttpInvokerLabel enum + */ + public static final HttpInvokerLabel ofName(String name) { + return Label.Util.ofName(HttpInvokerLabel.class, name); + } + + /** + * Gets the full-form httpinvoker label from the case-insensitive short-name. + * @param name the case-insensitive short-name + * @return the full-form httpinvoker label + */ + public static final String toLabel(String name) { + HttpInvokerLabel label = ofName(name); + return label != null ? label.label() : null; + } + + /** + * Prints all known httpinvoker labels. + * @param args ignored + */ + public static void main(String... args) { + Label.Util.print(values()); + } +} diff --git a/core/remote/src/main/java/org/switchyard/remote/infinispan/InfinispanRegistry.java b/core/remote/src/main/java/org/switchyard/remote/infinispan/InfinispanRegistry.java new file mode 100644 index 000000000..dbbec8c47 --- /dev/null +++ b/core/remote/src/main/java/org/switchyard/remote/infinispan/InfinispanRegistry.java @@ -0,0 +1,171 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.infinispan; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.infinispan.Cache; +import org.infinispan.notifications.Listener; +import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged; +import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; +import org.infinispan.remoting.transport.Address; +import org.switchyard.remote.RemoteEndpoint; +import org.switchyard.remote.RemoteLogger; +import org.switchyard.remote.RemoteRegistry; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; + +/** + * Implementation of a distributed registry based on a replicated cache in Infinispan. + * This class provides an implementation of the RemoteRegistry contract as well as a group + * membership listener to detect node failures and remove endpoint registrations from that node. + */ +public class InfinispanRegistry implements RemoteRegistry { + + private static final QName ROOT_DOMAIN = new QName("all-domains"); + + private static Logger _log = Logger.getLogger(InfinispanRegistry.class); + + private String _nodeName; + private Cache _serviceCache; + private Serializer _serializer; + + /** + * Create a new InfinispanRegistry using the specified replicated cache. + * @param serviceCache the replicated cache to use + */ + public InfinispanRegistry(Cache serviceCache) { + _serviceCache = serviceCache; + _serializer = SerializerFactory.create(FormatType.JSON, null, true); + + serviceCache.getCacheManager().addListener(new MemberDropListener()); + _nodeName = serviceCache.getCacheManager().getAddress().toString(); + } + + @Override + public void addEndpoint(RemoteEndpoint endpoint) { + String cacheKey = createNodeKey(ROOT_DOMAIN, endpoint.getServiceName(), _nodeName); + if (_serviceCache.get(cacheKey) != null) { + RemoteLogger.ROOT_LOGGER.remoteEndpointRegistered(cacheKey); + return; + } + + try { + endpoint.setNode(_nodeName); + String epStr = new String(_serializer.serialize(endpoint, RemoteEndpoint.class)); + _serviceCache.put(cacheKey, epStr); + + if (_log.isDebugEnabled()) { + StringBuilder buf = new StringBuilder() + .append("Added Endpoint:[") + .append("EndpointAddress='").append(endpoint.getEndpoint()).append("'") + .append(", NodeName='").append(endpoint.getNode()).append("'") + .append(", DomainName='").append(endpoint.getDomainName()).append("'") + .append(", ServiceName='").append(endpoint.getServiceName()).append("'") + .append(", ServiceContract='").append(endpoint.getContract()).append("'") + .append("]"); + _log.debug(buf.toString()); + } + } catch (java.io.IOException ioEx) { + RemoteLogger.ROOT_LOGGER.failedAddEndpoint(cacheKey, ioEx); + } + } + + @Override + public void removeEndpoint(RemoteEndpoint endpoint) { + if (_nodeName != null) { + _serviceCache.remove(createNodeKey(ROOT_DOMAIN, endpoint.getServiceName(), _nodeName)); + + if (_log.isDebugEnabled()) { + StringBuilder buf = new StringBuilder() + .append("Removed Endpoint:[") + .append("EndpointAddress='").append(endpoint.getEndpoint()).append("'") + .append(", NodeName='").append(endpoint.getNode()).append("'") + .append(", DomainName='").append(endpoint.getDomainName()).append("'") + .append(", ServiceName='").append(endpoint.getServiceName()).append("'") + .append(", ServiceContract='").append(endpoint.getContract()).append("'") + .append("]"); + _log.debug(buf.toString()); + } + } + } + + @Override + public List getEndpoints(QName serviceName) { + List services = new LinkedList(); + // add remotes and prune the local entry + String serviceKey = createServiceKey(ROOT_DOMAIN, serviceName); + Set nodes = _serviceCache.keySet(); + if (nodes != null) { + for (String node : nodes) { + if (node.startsWith(serviceKey)) { + String epStr = _serviceCache.get(node); + // Catch a race condition where entry has been removed since keySet list was built + if (epStr != null) { + try { + RemoteEndpoint ep = _serializer.deserialize(epStr.getBytes(), RemoteEndpoint.class); + services.add(ep); + } catch (java.io.IOException ioEx) { + _log.warn("Failed to deserialize remote endpoint: " + epStr, ioEx); + } + } + } + } + } + return services; + } + + private String createServiceKey(QName domain, QName service) { + return "/" + domain.toString() + "/" + service.toString(); + } + + private String createNodeKey(QName domain, QName service, String node) { + return createServiceKey(domain, service) + "/" + node; + } + + /** + * Listeners for members which get dropped and removes any endpoint registrations for + * dropped nodes in the registry. + */ + @Listener + public class MemberDropListener { + /** + * Triggered when a view is changed, signaling that a member has joined or dropped from the cluster. + * @param event change details + */ + @ViewChanged + public void viewChanged(ViewChangedEvent event) { + List

dropped = new ArrayList
(event.getOldMembers()); + dropped.removeAll(event.getNewMembers()); + for (Address addr : dropped) { + dropAllServices(addr); + } + } + + void dropAllServices(Address address) { + for (String node : _serviceCache.keySet()) { + if (node.endsWith("/" + address.toString())) { + _serviceCache.remove(node); + } + } + } + } +} diff --git a/core/remote/src/test/java/org/switchyard/remote/RemoteEndpointTest.java b/core/remote/src/test/java/org/switchyard/remote/RemoteEndpointTest.java new file mode 100644 index 000000000..d11edd2dd --- /dev/null +++ b/core/remote/src/test/java/org/switchyard/remote/RemoteEndpointTest.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote; + +import java.io.ByteArrayOutputStream; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; + +public class RemoteEndpointTest { + + private Serializer _serializer; + private ByteArrayOutputStream _sink; + + @Before + public void setUp() throws Exception { + _serializer = SerializerFactory.create(FormatType.JSON); + _sink = new ByteArrayOutputStream(); + } + + @Test + public void emptyService() throws Exception { + RemoteEndpoint ep1 = new RemoteEndpoint(); + _serializer.serialize(ep1, RemoteEndpoint.class, _sink); + RemoteEndpoint ep2 = _serializer.deserialize(_sink.toByteArray(), RemoteEndpoint.class); + Assert.assertNotNull(ep2); + } + + @Test + public void serviceAndDomainAndEndpoint() throws Exception { + RemoteEndpoint ep1 = new RemoteEndpoint(new QName("foo"), new QName("xyz"), "abc", "bar", null); + _serializer.serialize(ep1, RemoteEndpoint.class, _sink); + RemoteEndpoint ep2 = _serializer.deserialize(_sink.toByteArray(), RemoteEndpoint.class); + Assert.assertEquals(ep1.getServiceName(), ep2.getServiceName()); + Assert.assertEquals(ep1.getNode(), ep2.getNode()); + Assert.assertEquals(ep1.getDomainName(), ep2.getDomainName()); + Assert.assertEquals(ep1.getEndpoint(), ep2.getEndpoint()); + } + + @Test + public void withJavaContract() throws Exception { + RemoteInterface contract = RemoteInterface.fromInterface(JavaService.fromClass(MyContract.class)); + RemoteEndpoint ep1 = new RemoteEndpoint(new QName("foo"), new QName("xyz"), "abc", "bar", contract); + _serializer.serialize(ep1, RemoteEndpoint.class, _sink); + RemoteEndpoint ep2 = _serializer.deserialize(_sink.toByteArray(), RemoteEndpoint.class); + Assert.assertEquals(ep1.getServiceName(), ep2.getServiceName()); + Assert.assertEquals(contract.getOperation("submit").getInputType(), + ep2.getContract().getOperation("submit").getInputType()); + Assert.assertEquals(contract.getOperation("reply").getOutputType(), + ep2.getContract().getOperation("reply").getOutputType()); + } +} + +interface MyContract { + void submit(Foo foo); + Bar reply(Foo foo); +} + +class Foo { } + +class Bar { } \ No newline at end of file diff --git a/core/remote/src/test/java/org/switchyard/remote/RemoteMessageTest.java b/core/remote/src/test/java/org/switchyard/remote/RemoteMessageTest.java new file mode 100644 index 000000000..def585747 --- /dev/null +++ b/core/remote/src/test/java/org/switchyard/remote/RemoteMessageTest.java @@ -0,0 +1,108 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote; + +import java.io.StringReader; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; +import org.w3c.dom.Element; + +/** + * Tests RemoteMessage de/serialization scenarios. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class RemoteMessageTest { + + private T serDeser(T object, Class clazz) throws Exception { + Serializer ser = SerializerFactory.create(FormatType.JSON, null, true); + byte[] bytes = ser.serialize(object, clazz); + return ser.deserialize(bytes, clazz); + } + + @Test + public void testDOMProperty() throws Exception { + final String expectedXML = ""; + final Element expectedDOM = new ElementPuller().pull(new StringReader(expectedXML)); + RemoteMessage msg = new RemoteMessage(); + msg.getContext().setProperty("one", expectedDOM); + msg = serDeser(msg, RemoteMessage.class); + final Element actualDOM = (Element)msg.getContext().getProperty("one").getValue(); + final String actualXML = XMLHelper.toString(actualDOM); + Assert.assertEquals(expectedXML, actualXML); + } + + @Test + public void testDOMContent() throws Exception { + final String expectedXML = ""; + final Element expectedDOM = new ElementPuller().pull(new StringReader(expectedXML)); + RemoteMessage msg = new RemoteMessage(); + msg.setContent(expectedDOM); + msg = serDeser(msg, RemoteMessage.class); + final Element actualDOM = (Element)msg.getContent(); + final String actualXML = XMLHelper.toString(actualDOM); + Assert.assertEquals(expectedXML, actualXML); + } + + @Test + public void testThrowableContent() throws Exception { + // create hierarchy + final Exception e_pre = new Exception("e"); + e_pre.fillInStackTrace(); + final HandlerException he1_pre = new HandlerException(e_pre); + he1_pre.fillInStackTrace(); + final RuntimeException re_pre = new RuntimeException("re", he1_pre); + re_pre.fillInStackTrace(); + final SwitchYardException sye_pre = new SwitchYardException("sye", re_pre); + sye_pre.fillInStackTrace(); + final HandlerException he2_pre = new HandlerException("he", sye_pre); + he2_pre.fillInStackTrace(); + // create message + RemoteMessage msg = new RemoteMessage(); + msg.setContent(he2_pre); + // serialize and deserialize + msg = serDeser(msg, RemoteMessage.class); + // get causes + final HandlerException he2_post = (HandlerException)msg.getContent(); + final SwitchYardException sye_post = (SwitchYardException)he2_post.getCause(); + final RuntimeException re_post = (RuntimeException)sye_post.getCause(); + final HandlerException he1_post = (HandlerException)re_post.getCause(); + final Exception e_post = (Exception)he1_post.getCause(); + // test wrapper + Assert.assertEquals(he2_pre.isWrapper(), he2_post.isWrapper()); + Assert.assertEquals(he1_pre.isWrapper(), he1_post.isWrapper()); + // test messages + Assert.assertEquals(he2_pre.getMessage(), he2_post.getMessage()); + Assert.assertEquals(sye_pre.getMessage(), sye_post.getMessage()); + Assert.assertEquals(re_pre.getMessage(), re_post.getMessage()); + Assert.assertEquals(he1_pre.getMessage(), he1_post.getMessage()); + Assert.assertEquals(e_pre.getMessage(), e_post.getMessage()); + // test stack traces + Assert.assertEquals(he2_pre.getStackTrace().length, he2_post.getStackTrace().length); + Assert.assertEquals(sye_pre.getStackTrace().length, sye_post.getStackTrace().length); + Assert.assertEquals(re_pre.getStackTrace().length, re_post.getStackTrace().length); + Assert.assertEquals(he1_pre.getStackTrace().length, he1_post.getStackTrace().length); + Assert.assertEquals(e_pre.getStackTrace().length, e_post.getStackTrace().length); + } + +} diff --git a/core/remote/src/test/java/org/switchyard/remote/cluster/MockRegistry.java b/core/remote/src/test/java/org/switchyard/remote/cluster/MockRegistry.java new file mode 100644 index 000000000..e4e0cf347 --- /dev/null +++ b/core/remote/src/test/java/org/switchyard/remote/cluster/MockRegistry.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.cluster; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.switchyard.remote.RemoteEndpoint; +import org.switchyard.remote.RemoteRegistry; + +/** + * Dummy registry which allows a single service with multiple endpoints. + */ +public class MockRegistry implements RemoteRegistry { + + private Map> endpoints = new HashMap>(); + + @Override + public void addEndpoint(RemoteEndpoint endpoint) { + List eps = endpoints.get(endpoint.getServiceName()); + if (eps == null) { + endpoints.put(endpoint.getServiceName(), + new ArrayList()); + endpoints.get(endpoint.getServiceName()).add(endpoint); + } else { + endpoints.get(endpoint.getServiceName()).add(endpoint); + } + } + + @Override + public void removeEndpoint(RemoteEndpoint endpoint) { + endpoints.remove(endpoint.getServiceName()); + } + + @Override + public List getEndpoints(QName serviceName) { + List eps = endpoints.get(serviceName); + if (eps == null) { + return new ArrayList(); + } + return eps; + } + +} diff --git a/core/remote/src/test/java/org/switchyard/remote/cluster/RandomStrategyTest.java b/core/remote/src/test/java/org/switchyard/remote/cluster/RandomStrategyTest.java new file mode 100644 index 000000000..421d31c0d --- /dev/null +++ b/core/remote/src/test/java/org/switchyard/remote/cluster/RandomStrategyTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.cluster; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.remote.RemoteEndpoint; +import org.switchyard.remote.RemoteRegistry; + +public class RandomStrategyTest { + + private static final QName TEST_SERVICE = new QName("RandomStrategy"); + private RemoteRegistry registry = new MockRegistry(); + private RandomStrategy random = new RandomStrategy(); + + @Before + public void setUp() throws Exception { + random.setRegistry(registry); + } + + @Test + public void noEndpoints() { + Assert.assertNull(random.selectEndpoint(TEST_SERVICE)); + } + + @Test + public void oneEndpoint() { + registry.addEndpoint(new RemoteEndpoint().setServiceName(TEST_SERVICE)); + Assert.assertNotNull(random.selectEndpoint(TEST_SERVICE)); + } + + @Test + public void multipleEndpoints() { + // register two endpoints for the same service + RemoteEndpoint ep1 = new RemoteEndpoint().setServiceName(TEST_SERVICE).setEndpoint("ep1"); + RemoteEndpoint ep2 = new RemoteEndpoint().setServiceName(TEST_SERVICE).setEndpoint("ep2"); + registry.addEndpoint(ep1); + registry.addEndpoint(ep2); + + Map epCounts = new HashMap(); + epCounts.put(ep1.getEndpoint(), new AtomicInteger()); + epCounts.put(ep2.getEndpoint(), new AtomicInteger()); + for (int i = 0; i < 1000; i++) { + RemoteEndpoint ep = random.selectEndpoint(TEST_SERVICE); + epCounts.get(ep.getEndpoint()).incrementAndGet(); + } + + Assert.assertTrue(epCounts.get(ep1.getEndpoint()).get() > 0); + Assert.assertTrue(epCounts.get(ep2.getEndpoint()).get() > 0); + } +} diff --git a/core/remote/src/test/java/org/switchyard/remote/cluster/RoundRobinStrategyTest.java b/core/remote/src/test/java/org/switchyard/remote/cluster/RoundRobinStrategyTest.java new file mode 100644 index 000000000..127d41233 --- /dev/null +++ b/core/remote/src/test/java/org/switchyard/remote/cluster/RoundRobinStrategyTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.cluster; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.remote.RemoteEndpoint; +import org.switchyard.remote.RemoteRegistry; + +public class RoundRobinStrategyTest { + + private static final QName TEST_SERVICE1 = new QName("RoundRobinStrategy1"); + private static final QName TEST_SERVICE2 = new QName("RoundRobinStrategy2"); + + private RemoteRegistry registry = new MockRegistry(); + private RoundRobinStrategy robin = new RoundRobinStrategy(); + + @Before + public void setUp() throws Exception { + robin.setRegistry(registry); + } + + @Test + public void noEndpoints() { + Assert.assertNull(robin.selectEndpoint(TEST_SERVICE1)); + } + + @Test + public void oneEndpoint() { + registry.addEndpoint(new RemoteEndpoint().setServiceName(TEST_SERVICE1)); + Assert.assertNotNull(robin.selectEndpoint(TEST_SERVICE1)); + } + + @Test + public void multipleEndpoints() { + // register endpoints for each service + RemoteEndpoint ep1 = new RemoteEndpoint().setServiceName(TEST_SERVICE1).setEndpoint("ep1"); + RemoteEndpoint ep2 = new RemoteEndpoint().setServiceName(TEST_SERVICE1).setEndpoint("ep2"); + RemoteEndpoint ep3 = new RemoteEndpoint().setServiceName(TEST_SERVICE2).setEndpoint("ep3"); + RemoteEndpoint ep4 = new RemoteEndpoint().setServiceName(TEST_SERVICE2).setEndpoint("ep4"); + registry.addEndpoint(ep1); + registry.addEndpoint(ep2); + registry.addEndpoint(ep3); + registry.addEndpoint(ep4); + + // check to see we get round robin behavior + Assert.assertEquals(ep1, robin.selectEndpoint(TEST_SERVICE1)); + Assert.assertEquals(ep3, robin.selectEndpoint(TEST_SERVICE2)); + Assert.assertEquals(ep2, robin.selectEndpoint(TEST_SERVICE1)); + Assert.assertEquals(ep4, robin.selectEndpoint(TEST_SERVICE2)); + Assert.assertEquals(ep1, robin.selectEndpoint(TEST_SERVICE1)); + } +} diff --git a/core/remote/src/test/java/org/switchyard/remote/infinispan/InfinispanRegistryTest.java b/core/remote/src/test/java/org/switchyard/remote/infinispan/InfinispanRegistryTest.java new file mode 100644 index 000000000..47d3ecf0e --- /dev/null +++ b/core/remote/src/test/java/org/switchyard/remote/infinispan/InfinispanRegistryTest.java @@ -0,0 +1,131 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.remote.infinispan; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.infinispan.Cache; +import org.infinispan.configuration.cache.ConfigurationBuilder; +import org.infinispan.configuration.global.GlobalConfigurationBuilder; +import org.infinispan.manager.DefaultCacheManager; +import org.infinispan.remoting.transport.Address; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.remote.RemoteEndpoint; + +public class InfinispanRegistryTest { + + private InfinispanRegistry _registry; + private DefaultCacheManager _cacheMgr; + + @Before + public void setUp() { + _cacheMgr = new DefaultCacheManager(new GlobalConfigurationBuilder() + .transport().defaultTransport().build()); + + _cacheMgr.defineConfiguration("test-cache", + new ConfigurationBuilder().invocationBatching().enable().build()); + Cache cache = _cacheMgr.getCache("test-cache"); + _registry = new InfinispanRegistry(cache); + } + + @After + public void tearDown() { + _cacheMgr.stop(); + } + + @Test + public void addGetAndRemoveSingle() throws Exception { + RemoteEndpoint ep1 = new RemoteEndpoint() + .setDomainName(new QName("domain1")) + .setServiceName(new QName("service1")); + + // nothing in the registry + Assert.assertEquals(0, _registry.getEndpoints(ep1.getServiceName()).size()); + // add an endpoint + _registry.addEndpoint(ep1); + // should get one now + Assert.assertEquals(1, _registry.getEndpoints(ep1.getServiceName()).size()); + // remove the endpoint + _registry.removeEndpoint(ep1); + // nothing in the registry + Assert.assertEquals(0, _registry.getEndpoints(ep1.getServiceName()).size()); + } + + @Test + public void testNodeFailure() throws Exception { + RemoteEndpoint ep1 = new RemoteEndpoint() + .setDomainName(new QName("domain1")) + .setServiceName(new QName("service1")); + RemoteEndpoint ep2 = new RemoteEndpoint() + .setDomainName(new QName("domain1")) + .setServiceName(new QName("service2")); + + // nothing in the registry + Assert.assertEquals(0, _registry.getEndpoints(ep1.getServiceName()).size()); + // add our endpoints on the same node + _registry.addEndpoint(ep1); + _registry.addEndpoint(ep2); + // signal that the node has failed + InfinispanRegistry.MemberDropListener dropListener = _registry.new MemberDropListener(); + dropListener.dropAllServices(new FakeAddress(ep1.getNode())); + + // check to make sure all endpoints were removed + Assert.assertEquals(0, _registry.getEndpoints(ep1.getServiceName()).size()); + // check to make sure all endpoints were removed + Assert.assertEquals(0, _registry.getEndpoints(ep2.getServiceName()).size()); + + } + + @Test + public void addDuplicate() throws Exception { + RemoteEndpoint ep1 = new RemoteEndpoint() + .setDomainName(new QName("domain1")) + .setServiceName(new QName("service1")); + + // add an endpoint + _registry.addEndpoint(ep1); + // should get one now + Assert.assertEquals(1, _registry.getEndpoints(ep1.getServiceName()).size()); + // attempt to add again + _registry.addEndpoint(ep1); + // still just one in the registry + Assert.assertEquals(1, _registry.getEndpoints(ep1.getServiceName()).size()); + } +} + +class FakeAddress implements Address { + + private String _address; + + public FakeAddress(String address) { + _address = address; + } + + @Override + public String toString() { + return _address; + } + + @Override + public int compareTo(Address address) { + if (address == null) { + return -1; + } + return _address.compareTo(address.toString()); + } +} diff --git a/core/remote/src/test/resources/log4j.properties b/core/remote/src/test/resources/log4j.properties new file mode 100644 index 000000000..02a249c1d --- /dev/null +++ b/core/remote/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootCategory=INFO, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=DEBUG +log4j.appender.CONSOLE.Target=System.out +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n diff --git a/core/runtime/pom.xml b/core/runtime/pom.xml new file mode 100644 index 000000000..ac220a9f2 --- /dev/null +++ b/core/runtime/pom.xml @@ -0,0 +1,89 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-runtime + bundle + SwitchYard: Runtime + The core runtime library. + http://switchyard.org + + + org.switchyard.handlers.*; + org.switchyard.internal.*; + org.switchyard.runtime.*; + org.switchyard.spi.* + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-security + + + org.switchyard + switchyard-serial + + + org.switchyard + switchyard-extensions-java + + + org.switchyard + switchyard-serial-jackson + test + + + + org.jboss.spec.javax.transaction + jboss-transaction-api_1.1_spec + + + log4j + log4j + test + + + diff --git a/core/runtime/src/main/java/org/switchyard/handlers/AddressingHandler.java b/core/runtime/src/main/java/org/switchyard/handlers/AddressingHandler.java new file mode 100644 index 000000000..2f168ef41 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/handlers/AddressingHandler.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.handlers; + +import java.util.List; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.policy.Policy; +import org.switchyard.policy.PolicyUtil; +import org.switchyard.runtime.RuntimeMessages; + +/** + * The AddressingHandler resolves service instances based on a service reference. + */ +public class AddressingHandler extends BaseHandler { + + private ServiceDomain _domain; + + /** + * Create a new AddressingHandler for the specified domain. + * @param domain services available for routing + */ + public AddressingHandler(ServiceDomain domain) { + _domain = domain; + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // only set the provider on the 'IN' phase + if (ExchangePhase.IN != exchange.getPhase()) { + return; + } + + // is a provider already set? + if (exchange.getProvider() != null) { + return; + } + + List services = _domain.getServices(exchange.getConsumer().getTargetServiceName()); + if (services == null || services.isEmpty()) { + throw RuntimeMessages.MESSAGES.noRegisteredService(exchange.getConsumer().getName().toString()); + } + + // At this stage, just pick the first service implementation we find and go with + // it. In the future, it would be nice if we could make this pluggable. + Service service = services.get(0); + ServiceOperation consumerOp = exchange.getContract().getConsumerOperation(); + ServiceOperation providerOp = service.getInterface().getOperation(consumerOp.getName()); + + if (providerOp == null) { + // try for a default operation + if (service.getInterface().getOperations().size() == 1) { + providerOp = service.getInterface().getOperations().iterator().next(); + } else { + throw RuntimeMessages.MESSAGES.operationNotIncluded(consumerOp.getName(), + service.getName().toString()); + } + } + + // set provider contract and details on exchange + exchange.provider(service, providerOp); + for (Policy policy : service.getServiceMetadata().getRequiredPolicies()) { + PolicyUtil.require(exchange, policy); + } + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/handlers/MessageTraceHandler.java b/core/runtime/src/main/java/org/switchyard/handlers/MessageTraceHandler.java new file mode 100644 index 000000000..c5899ee26 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/handlers/MessageTraceHandler.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.handlers; + +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.HandlerException; +import org.switchyard.runtime.util.ExchangeFormatter; + +/** + * Half-baked message tracing implementation. + */ +public class MessageTraceHandler implements ExchangeHandler { + + /** + * Property name used to enable message tracing. + */ + public static final String TRACE_ENABLED = + "org.switchyard.handlers.messageTrace.enabled"; + + private static Logger _log = Logger.getLogger(MessageTraceHandler.class); + + @Override + public void handleFault(Exchange exchange) { + if (_log.isInfoEnabled()) { + _log.info(ExchangeFormatter.format(exchange, true)); + } + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + if (_log.isInfoEnabled()) { + _log.info(ExchangeFormatter.format(exchange, true)); + } + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/handlers/PolicyHandler.java b/core/runtime/src/main/java/org/switchyard/handlers/PolicyHandler.java new file mode 100644 index 000000000..f8668b171 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/handlers/PolicyHandler.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.handlers; + +import java.util.Iterator; +import java.util.Set; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; +import org.switchyard.policy.Policy; +import org.switchyard.policy.PolicyUtil; +import org.switchyard.runtime.RuntimeMessages; + +/** + * Generic policy handler which simply checks to make sure all required policies + * have been provided. This handler should always occur *after* the other + * policy handlers in the handler chain, which allows policy-specific handlers + * to adjust the set of provided/required policies as appropriate. + */ +public class PolicyHandler extends BaseHandler { + + /** + * Create a new PolicyHandler. + */ + public PolicyHandler() {} + + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // only execute on the IN phase + if (ExchangePhase.IN.equals(exchange.getPhase())) { + Set required = PolicyUtil.getRequired(exchange); + Iterator reqIt = required.iterator(); + while (reqIt.hasNext()) { + if (PolicyUtil.isProvided(exchange, reqIt.next())) { + reqIt.remove(); + } + } + if (!required.isEmpty()) { + // Required policies are missing. Format the list for fault message. + Iterator missing = required.iterator(); + StringBuilder requires = new StringBuilder(missing.next().getQName().toString()); + while (missing.hasNext()) { + requires.append(" " + missing.next().getQName().toString()); + } + throw RuntimeMessages.MESSAGES.requiredPolicesNeeded(requires.toString()); + } + } + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/handlers/ProviderHandler.java b/core/runtime/src/main/java/org/switchyard/handlers/ProviderHandler.java new file mode 100644 index 000000000..031e61a9a --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/handlers/ProviderHandler.java @@ -0,0 +1,81 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.handlers; + +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceSecurity; +import org.switchyard.security.SecurityServices; +import org.switchyard.security.context.SecurityContext; +import org.switchyard.security.context.SecurityContextManager; +import org.switchyard.security.provider.SecurityProvider; + +/** + * Handler calling service provider. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class ProviderHandler extends BaseHandler { + + private final SecurityProvider _securityProvider; + private final SecurityContextManager _securityContextManager; + + /** + * Create a new ProviderHandler with the specified ServiceDomain. + * @param serviceDomain the ServiceDomain + */ + public ProviderHandler(ServiceDomain serviceDomain) { + _securityProvider = SecurityServices.getSecurityProvider(); + _securityContextManager = new SecurityContextManager(serviceDomain); + } + + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + final Service service = exchange.getProvider(); + ServiceSecurity serviceSecurity = service.getServiceMetadata().getSecurity(); + if (serviceSecurity != null) { + SecurityContext securityContext = _securityContextManager.getContext(exchange); + PrivilegedExceptionAction action = new PrivilegedExceptionAction() { + public Void run() throws Exception { + service.getProviderHandler().handleMessage(exchange); + return null; + } + }; + try { + _securityProvider.runAs(serviceSecurity, securityContext, action); + } catch (Exception e) { + if (e instanceof PrivilegedActionException) { + e = ((PrivilegedActionException)e).getException(); + } + if (e instanceof HandlerException) { + throw (HandlerException)e; + } else { + throw new HandlerException(e); + } + } + } else { + service.getProviderHandler().handleMessage(exchange); + } + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/handlers/SecurityHandler.java b/core/runtime/src/main/java/org/switchyard/handlers/SecurityHandler.java new file mode 100644 index 000000000..94d279421 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/handlers/SecurityHandler.java @@ -0,0 +1,193 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.handlers; + +import static org.switchyard.policy.PolicyUtil.isProvided; +import static org.switchyard.policy.PolicyUtil.isRequired; +import static org.switchyard.policy.PolicyUtil.provide; +import static org.switchyard.policy.SecurityPolicy.AUTHORIZATION; +import static org.switchyard.policy.SecurityPolicy.CLIENT_AUTHENTICATION; +import static org.switchyard.policy.SecurityPolicy.CONFIDENTIALITY; + +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import org.jboss.logging.Logger; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceSecurity; +import org.switchyard.security.SecurityMetadata; +import org.switchyard.security.SecurityServices; +import org.switchyard.security.context.SecurityContext; +import org.switchyard.security.context.SecurityContextManager; +import org.switchyard.security.credential.ConfidentialityCredential; +import org.switchyard.security.credential.PrincipalCredential; +import org.switchyard.security.provider.SecurityProvider; + +/** + * A security ExchangeHandler implementation. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SecurityHandler extends BaseHandler { + + private static final Logger LOGGER = Logger.getLogger(SecurityHandler.class); + private static final ThreadLocal PROCESS_COUNT = new InheritableThreadLocal(); + + private final SecurityContextManager _securityContextManager; + private final SecurityProvider _securityProvider; + private final SecurityAction _securityAction; + + /** + * What the SecurityHandler should do. + */ + public static enum SecurityAction { + /** Process security. */ + PROCESS, + /** Cleanup security. */ + CLEANUP; + } + + /** + * Constructs a SecurityHandler for the specified ServiceDomain and SecurityAction. + * @param serviceDomain the ServiceDomain + * @param securityAction the SecurityAction + */ + public SecurityHandler(ServiceDomain serviceDomain, SecurityAction securityAction) { + _securityContextManager = new SecurityContextManager(serviceDomain); + _securityProvider = SecurityServices.getSecurityProvider(); + _securityAction = securityAction; + } + + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + ServiceSecurity serviceSecurity = SecurityMetadata.getServiceSecurity(exchange); + if (serviceSecurity == null) { + // nothing to do + return; + } + switch (_securityAction) { + case PROCESS: + process(exchange, serviceSecurity); + break; + case CLEANUP: + cleanup(exchange, serviceSecurity); + break; + } + } + + /** + * {@inheritDoc} + */ + @Override + public void handleFault(Exchange exchange) { + ServiceSecurity serviceSecurity = SecurityMetadata.getServiceSecurity(exchange); + if (serviceSecurity == null) { + // nothing to do + return; + } + try { + cleanup(exchange, serviceSecurity); + } catch (Exception e) { + LOGGER.error(e); + } + } + + private void process(Exchange exchange, ServiceSecurity serviceSecurity) throws HandlerException { + processCount().incrementAndGet(); + SecurityContext securityContext = _securityContextManager.getContext(exchange); + if (isRequired(exchange, CONFIDENTIALITY) && !isProvided(exchange, CONFIDENTIALITY)) { + if (isConfidentialityProvided(securityContext)) { + provide(exchange, CONFIDENTIALITY); + } + } + boolean success = false; + if (isRequired(exchange, CLIENT_AUTHENTICATION) && !isProvided(exchange, CLIENT_AUTHENTICATION)) { + if (isClientAuthenticationProvided(securityContext)) { + provide(exchange, CLIENT_AUTHENTICATION); + success = true; + } else { + boolean authenticated = _securityProvider.authenticate(serviceSecurity, securityContext); + if (authenticated) { + provide(exchange, CLIENT_AUTHENTICATION); + success = true; + } + } + } else { + success = true; + } + if (success) { + _securityProvider.populate(serviceSecurity, securityContext); + } + if (isRequired(exchange, AUTHORIZATION) && !isProvided(exchange, AUTHORIZATION)) { + if (isAuthorizationProvided(serviceSecurity, securityContext)) { + provide(exchange, AUTHORIZATION); + } + } + _securityContextManager.setContext(exchange, securityContext); + } + + private void cleanup(Exchange exchange, ServiceSecurity serviceSecurity) { + int pc = processCount().decrementAndGet(); + if (pc < 1) { + _securityContextManager.setContext(exchange, null); + processCount().set(0); + } + /* + SecurityContext securityContext = _securityContextManager.getContext(exchange); + securityContext.clearCredentials(); + _securityProvider.clear(serviceSecurity, securityContext); + _securityContextManager.setContext(exchange, securityContext); + */ + } + + private boolean isConfidentialityProvided(SecurityContext securityContext) { + Set creds = securityContext.getCredentials(ConfidentialityCredential.class); + for (ConfidentialityCredential cred : creds) { + if (cred.isConfidential()) { + return true; + } + } + return false; + } + + private boolean isClientAuthenticationProvided(SecurityContext securityContext) { + Set creds = securityContext.getCredentials(PrincipalCredential.class); + for (PrincipalCredential cred : creds) { + if (cred.getPrincipal() != null && cred.isTrusted()) { + return true; + } + } + return false; + } + + private boolean isAuthorizationProvided(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + return _securityProvider.checkRolesAllowed(serviceSecurity, securityContext); + } + + private static synchronized AtomicInteger processCount() { + AtomicInteger hic = PROCESS_COUNT.get(); + if (hic == null) { + hic = new AtomicInteger(0); + PROCESS_COUNT.set(hic); + } + return hic; + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/handlers/TransactionHandler.java b/core/runtime/src/main/java/org/switchyard/handlers/TransactionHandler.java new file mode 100644 index 000000000..4df19aad7 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/handlers/TransactionHandler.java @@ -0,0 +1,383 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.handlers; + +import javax.transaction.Status; +import javax.transaction.SystemException; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; + +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.HandlerException; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.policy.PolicyUtil; +import org.switchyard.policy.TransactionPolicy; +import org.switchyard.runtime.RuntimeLogger; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.runtime.util.TransactionManagerLocator; + + +/** + * Interprets transactional policy specified on an exchange and handles + * transactional requirements. + */ +public class TransactionHandler implements ExchangeHandler { + + private static final String SUSPENDED_TRANSACTION_PROPERTY = + "org.switchyard.exchange.transaction.suspended"; + private static final String INITIATED_TRANSACTION_PROPERTY = + "org.switchyard.exchange.transaction.initiated"; + private static final String BEFORE_INVOKED_PROPERTY = + "org.switchyard.exchange.transaction.beforeInvoked"; + + private static Logger _log = Logger.getLogger(TransactionHandler.class); + + private TransactionManager _transactionManager; + + /** + * Create a new TransactionHandler. + */ + public TransactionHandler() { + _transactionManager = TransactionManagerLocator.locateTransactionManager(); + if (_transactionManager == null) { + _log.debug("Unable to find TransactionManager - Transaction Policy handling will not be available."); + } + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // if no TM is available, there's nothing to do + if (_transactionManager == null) { + return; + } + + Property prop = exchange.getContext().getProperty(BEFORE_INVOKED_PROPERTY, Scope.EXCHANGE); + if (prop != null && Boolean.class.cast(prop.getValue())) { + // OUT phase in IN_OUT exchange or 2nd invocation in IN_ONLY exchange + handleAfter(exchange); + } else { + exchange.getContext().setProperty(BEFORE_INVOKED_PROPERTY, Boolean.TRUE, Scope.EXCHANGE).addLabels(BehaviorLabel.TRANSIENT.label()); + handleBefore(exchange); + } + } + + @Override + public void handleFault(Exchange exchange) { + // if no TM is available, there's nothing to do + if (_transactionManager == null) { + return; + } + + try { + Property rollbackOnFaultProperty = exchange.getContext().getProperty(Exchange.ROLLBACK_ON_FAULT); + if (rollbackOnFaultProperty != null && rollbackOnFaultProperty.getValue() != null + && Boolean.class.cast(rollbackOnFaultProperty.getValue())) { + Transaction transaction = getCurrentTransaction(); + if (transaction != null) { + transaction.setRollbackOnly(); + } + } + handleAfter(exchange); + } catch (Exception e) { + _log.error(e); + } + } + + void setTransactionManager(TransactionManager transactionManager) { + _transactionManager = transactionManager; + } + + TransactionManager getTransactionManager() { + return _transactionManager; + } + + private void handleAfter(Exchange exchange) throws HandlerException { + Transaction transaction = null; + try { + // complete the transaction which is initiated by this handler + transaction = (Transaction) exchange.getContext().getPropertyValue(INITIATED_TRANSACTION_PROPERTY); + if (transaction != null) { + endTransaction(); + } + } catch (Exception e) { + throw RuntimeMessages.MESSAGES.failedToCompleteTransaction(e); + } finally { + // resume the transaction which is suspended by this handler + transaction = (Transaction) exchange.getContext().getPropertyValue(SUSPENDED_TRANSACTION_PROPERTY); + if (transaction != null) { + resumeTransaction(transaction); + } + } + } + + private void handleBefore(Exchange exchange) throws HandlerException { + if (!(propagatesRequired(exchange) || suspendsRequired(exchange) || managedGlobalRequired(exchange) + || managedLocalRequired(exchange) || noManagedRequired(exchange))) { + return; + } + + evaluatePolicyCombination(exchange); + evaluateTransactionStatus(exchange); + + if (isEligibleToSuspendTransaction(exchange)) { + suspendTransaction(exchange); + } + + if (isEligibleToStartTransaction(exchange)) { + startTransaction(exchange); + } + + provideRequiredPolicies(exchange); + } + + private void evaluatePolicyCombination(Exchange exchange) throws HandlerException { + // check for incompatible policy definition + if (suspendsRequired(exchange) && propagatesRequired(exchange)) { + throw RuntimeMessages.MESSAGES.invalidTransactionPolicy(TransactionPolicy.SUSPENDS_TRANSACTION.toString(), + TransactionPolicy.PROPAGATES_TRANSACTION.toString()); + } + if (managedGlobalRequired(exchange) && managedLocalRequired(exchange) + || managedGlobalRequired(exchange) && noManagedRequired(exchange) + || managedLocalRequired(exchange) && noManagedRequired(exchange)) { + throw RuntimeMessages.MESSAGES.invalidTransactionPolicy(TransactionPolicy.MANAGED_TRANSACTION_GLOBAL.toString(), + TransactionPolicy.NO_MANAGED_TRANSACTION.toString()); + } + if (propagatesRequired(exchange) && managedLocalRequired(exchange) + || propagatesRequired(exchange) && noManagedRequired(exchange)) { + throw RuntimeMessages.MESSAGES.invalidTransactionPolicyCombo(TransactionPolicy.PROPAGATES_TRANSACTION.toString(), + TransactionPolicy.MANAGED_TRANSACTION_LOCAL.toString(), TransactionPolicy.NO_MANAGED_TRANSACTION.toString()); + } + } + + private void evaluateTransactionStatus(Exchange exchange) throws HandlerException { + Transaction transaction = getCurrentTransaction(); + + if (transaction == null && propagatesRequired(exchange) && !managedGlobalRequired(exchange)) { + throw RuntimeMessages.MESSAGES.invalidTransactionStatus(TransactionPolicy.PROPAGATES_TRANSACTION.toString()); + } + } + + private boolean isEligibleToSuspendTransaction(Exchange exchange) throws HandlerException { + Transaction transaction = getCurrentTransaction(); + if (transaction == null) { + return false; + } + + if (managedLocalRequired(exchange) || noManagedRequired(exchange) || suspendsRequired(exchange)) { + return true; + } + + return false; + } + + private boolean isEligibleToStartTransaction(Exchange exchange) throws HandlerException { + Transaction transaction = getCurrentTransaction(); + + if (managedLocalRequired(exchange)) { + return true; + } else if (managedGlobalRequired(exchange)) { + if (transaction == null) { + return true; + } + } + return false; + } + + private void provideRequiredPolicies(Exchange exchange) { + if (suspendsRequired(exchange)) { + provideSuspends(exchange); + } else if (propagatesRequired(exchange)) { + providePropagates(exchange); + } + + if (managedGlobalRequired(exchange)) { + provideManagedGlobal(exchange); + } else if (managedLocalRequired(exchange)) { + provideManagedLocal(exchange); + } else if (noManagedRequired(exchange)) { + provideNoManaged(exchange); + } + } + + private boolean managedGlobalRequired(Exchange exchange) { + return PolicyUtil.isRequired(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + } + + private boolean managedLocalRequired(Exchange exchange) { + return PolicyUtil.isRequired(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL); + } + + private boolean noManagedRequired(Exchange exchange) { + return PolicyUtil.isRequired(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION); + } + + private boolean suspendsRequired(Exchange exchange) { + return PolicyUtil.isRequired(exchange, TransactionPolicy.SUSPENDS_TRANSACTION); + } + + private boolean propagatesRequired(Exchange exchange) { + return PolicyUtil.isRequired(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + } + + private void providePropagates(Exchange exchange) { + PolicyUtil.provide(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + } + + private void provideSuspends(Exchange exchange) { + PolicyUtil.provide(exchange, TransactionPolicy.SUSPENDS_TRANSACTION); + } + + private void provideManagedGlobal(Exchange exchange) { + PolicyUtil.provide(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + } + + private void provideManagedLocal(Exchange exchange) { + PolicyUtil.provide(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL); + } + + private void provideNoManaged(Exchange exchange) { + PolicyUtil.provide(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION); + } + + private void startTransaction(Exchange exchange) throws HandlerException { + if (_log.isDebugEnabled()) { + printDebugInfo("Creating new transaction"); + } + + int txStatus = getCurrentTransactionStatus(); + + if (txStatus == Status.STATUS_NO_TRANSACTION) { + Transaction transaction = null; + try { + _transactionManager.begin(); + transaction = _transactionManager.getTransaction(); + } catch (Exception e) { + throw RuntimeMessages.MESSAGES.failedCreateNewTransaction(e); + } + + if (transaction != null) { + if (_log.isDebugEnabled()) { + printDebugInfo("Created new transaction"); + } + exchange.getContext().setProperty(INITIATED_TRANSACTION_PROPERTY, transaction, Scope.EXCHANGE).addLabels(BehaviorLabel.TRANSIENT.label()); + } + } else { + throw RuntimeMessages.MESSAGES.transactionAlreadyExists(); + } + } + + private void endTransaction() throws HandlerException { + if (_log.isDebugEnabled()) { + printDebugInfo("Completing transaction"); + } + + int txStatus = getCurrentTransactionStatus(); + + if (txStatus == Status.STATUS_MARKED_ROLLBACK) { + try { + _transactionManager.rollback(); + if (_log.isDebugEnabled()) { + printDebugInfo("Transaction rolled back as it has been marked as RollbackOnly"); + } + } catch (Exception e) { + throw RuntimeMessages.MESSAGES.failedToRollbackTransaction(e); + } + } else if (txStatus == Status.STATUS_ACTIVE) { + try { + _transactionManager.commit(); + if (_log.isDebugEnabled()) { + printDebugInfo("Transaction has been committed"); + } + } catch (Exception e) { + throw RuntimeMessages.MESSAGES.failedToCommitTransaction(e); + } + } else { + throw RuntimeMessages.MESSAGES.failedToCompleteWithStatus(txStatus); + } + } + + private void suspendTransaction(Exchange exchange) { + if (_log.isDebugEnabled()) { + printDebugInfo("Suspending active transaction"); + } + + Transaction transaction = null; + try { + transaction = _transactionManager.suspend(); + } catch (SystemException sysEx) { + RuntimeLogger.ROOT_LOGGER.failedToSuspendTransactionOnExchange(sysEx); + } + if (transaction != null) { + if (_log.isDebugEnabled()) { + printDebugInfo("Suspended active transaction"); + } + exchange.getContext().setProperty(SUSPENDED_TRANSACTION_PROPERTY, transaction, Scope.EXCHANGE).addLabels(BehaviorLabel.TRANSIENT.label()); + } + } + + private void resumeTransaction(Transaction transaction) { + try { + if (_log.isDebugEnabled()) { + printDebugInfo("Resuming suspended transaction"); + } + + _transactionManager.resume(transaction); + + if (_log.isDebugEnabled()) { + printDebugInfo("Resumed suspended transaction"); + } + } catch (Exception ex) { + RuntimeLogger.ROOT_LOGGER.failedToResumeTransaction(ex); + } + } + + private Transaction getCurrentTransaction() throws HandlerException { + try { + return _transactionManager.getTransaction(); + } catch (Exception e) { + throw RuntimeMessages.MESSAGES.failedToRetrieveStatus(e); + } + } + + private int getCurrentTransactionStatus() throws HandlerException { + try { + return _transactionManager.getStatus(); + } catch (Exception e) { + throw RuntimeMessages.MESSAGES.failedToRetrieveStatus(e); + } + } + + private void printDebugInfo(String message) { + StringBuilder buf = new StringBuilder(message); + buf.append(" - [Thread: "); + buf.append(Thread.currentThread().toString()); + buf.append(", Transaction: "); + Transaction currentTx = null; + try { + currentTx = getCurrentTransaction(); + } catch (Exception e) { e.getMessage(); } // ignore + if (currentTx == null) { + buf.append("N/A"); + } else { + buf.append(currentTx.toString()); + } + buf.append(']'); + _log.debug(buf.toString()); + } +} diff --git a/core/runtime/src/main/java/org/switchyard/handlers/TransformHandler.java b/core/runtime/src/main/java/org/switchyard/handlers/TransformHandler.java new file mode 100644 index 000000000..fcd20693b --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/handlers/TransformHandler.java @@ -0,0 +1,188 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.handlers; + +import java.util.Arrays; +import java.util.HashSet; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; +import org.switchyard.Property; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.transform.TransformSequence; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; + +/** + * ExchangeHandler implementation used to introduce transformations to the + * exchange handler chain. The core runtime automatically creates a + * TransformHandler and attaches it to the consumer handler chain for every + * exchange. TransformHandler can also be used in the service provider's + * chain by using the TransformHandler(Transformer) + * constructor. + * + */ +public class TransformHandler extends BaseHandler { + + private static Logger _logger = Logger.getLogger(TransformHandler.class); + + private TransformerRegistry _registry; + + /** + * Create a new TransformHandler. The specified TransformerRegistry will + * be used to locate transformers for each handled exchange. + * @param registry transformation registry to use for lookups of transformer + * instances + */ + public TransformHandler(TransformerRegistry registry) { + _registry = registry; + } + + /** + * Create a new TransformHandler. The specified list of transforms will + * be used in place of a TransformerRegistry to locate transforms for each + * handled exchange. + * @param transforms transform map + */ + public TransformHandler(Transformer ... transforms) { + if (transforms != null && transforms.length > 0) { + _registry = new BaseTransformerRegistry( + new HashSet>(Arrays.asList(transforms))); + } + } + + /** + * Transform the current message on the exchange. + * @param exchange exchange + * @throws HandlerException handler exception + */ + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + // Initialize transform sequence for operation types + if (exchange.getPhase() == ExchangePhase.IN) { + initInTransformSequence(exchange); + } else { + initOutTransformSequence(exchange); + } + + // Apply transforms to the message... + TransformSequence transformSequence = _registry.getTransformSequence(TransformSequence.getCurrentMessageType(exchange), TransformSequence.getTargetMessageType(exchange)); + if (transformSequence != null) { + transformSequence.associateWith(exchange.getMessage()); + } + + TransformSequence.applySequence(exchange, _registry); + if (!TransformSequence.assertTransformsApplied(exchange)) { + QName actualPayloadType = TransformSequence.getCurrentMessageType(exchange); + QName expectedPayloadType = TransformSequence.getTargetMessageType(exchange); + throw RuntimeMessages.MESSAGES.transformationsNotApplied(expectedPayloadType.toString(), + actualPayloadType.toString()); + } + + // Replace the CONTENT_TYPE property to indicate current content type after transform + setContentType(exchange); + } + + @Override + public void handleFault(Exchange exchange) { + // Apply transforms to the fault... + initFaultTransformSequence(exchange); + TransformSequence.applySequence(exchange, _registry); + if (!TransformSequence.assertTransformsApplied(exchange)) { + QName actualPayloadType = TransformSequence.getCurrentMessageType(exchange); + QName expectedPayloadType = TransformSequence.getTargetMessageType(exchange); + + if (_logger.isDebugEnabled()) { + _logger.debug("Transformations not applied. Required payload type of '" + expectedPayloadType + "'. Actual payload type is '" + actualPayloadType + "'. You must define and register a Transformer to transform between these types."); + } + } + + // Replace the CONTENT_TYPE property to indicate current content type after transform + setContentType(exchange); + } + + private void setContentType(Exchange exchange) { + QName currentType = TransformSequence.getCurrentMessageType(exchange); + if (currentType != null) { + exchange.getContext().setProperty(Exchange.CONTENT_TYPE, currentType).addLabels(BehaviorLabel.TRANSIENT.label()); + } else { + // make sure no property is used for current scope + Property p = exchange.getContext().getProperty(Exchange.CONTENT_TYPE); + if (p != null) { + exchange.getContext().removeProperty(p); + } + } + } + + private void initInTransformSequence(Exchange exchange) { + QName exchangeInputType = exchange.getContract().getConsumerOperation().getInputType(); + QName serviceOperationInputType = exchange.getContract().getProviderOperation().getInputType(); + + if (exchangeInputType != null && serviceOperationInputType != null) { + TransformSequence. + from(exchangeInputType). + to(serviceOperationInputType). + associateWith(exchange.getMessage()); + } + } + + private void initOutTransformSequence(Exchange exchange) { + QName serviceOperationOutputType = exchange.getContract().getProviderOperation().getOutputType(); + QName exchangeOutputType = exchange.getContract().getConsumerOperation().getOutputType(); + + if (serviceOperationOutputType != null && exchangeOutputType != null) { + TransformSequence. + from(serviceOperationOutputType). + to(exchangeOutputType). + associateWith(exchange.getMessage()); + } + } + + private void initFaultTransformSequence(Exchange exchange) { + QName exceptionTypeName = null; + ServiceOperation providerOperation = exchange.getContract().getProviderOperation(); + ServiceOperation consumerOperation = exchange.getContract().getConsumerOperation(); + QName invokerFaultTypeName = consumerOperation.getFaultType(); + + if (providerOperation != null) { + exceptionTypeName = providerOperation.getFaultType(); + } + + Object content = exchange.getMessage().getContent(); + if (exceptionTypeName == null && content instanceof Exception) { + exceptionTypeName = JavaTypes.toMessageType(content.getClass()); + } + + if (exceptionTypeName != null && invokerFaultTypeName != null) { + // Set up the type info on the message context so as the exception gets transformed + // appropriately for the invoker... + TransformSequence. + from(exceptionTypeName). + to(invokerFaultTypeName). + associateWith(exchange.getMessage()); + } + } + +} + diff --git a/core/runtime/src/main/java/org/switchyard/handlers/ValidateHandler.java b/core/runtime/src/main/java/org/switchyard/handlers/ValidateHandler.java new file mode 100644 index 000000000..8d5e961ff --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/handlers/ValidateHandler.java @@ -0,0 +1,129 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.handlers; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.SwitchYardException; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.RuntimeLogger; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.Validator; +import org.switchyard.validate.ValidatorRegistry; + +/** + * ExchangeHandler implementation used to introduce validations to the + * exchange handler chain. The core runtime automatically creates a + * ValidateHandler and attaches it to the consumer handler chain for every + * exchange. ValidateHandler can also be used in the service provider's + * chain by using the ValidatorHandler(Validator) + * constructor. + * + */ +public class ValidateHandler extends BaseHandler { + + private static final String KEY_VALIDATED_TYPE = "org.switchyard.validatedType"; + + private static Logger _logger = Logger.getLogger(ValidateHandler.class); + + private ValidatorRegistry _registry; + + /** + * Create a new ValidateHandler. The specified ValidatorRegistry will + * be used to locate validators for each handled exchange. + * @param registry validation registry to use for lookups of validator + */ + public ValidateHandler(ValidatorRegistry registry) { + _registry = registry; + } + + /** + * Validate the current message on the exchange. + * @param exchange exchange + * @throws HandlerException handler exception + */ + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + Validator validator = get(exchange); + if (validator != null) { + try { + ValidationResult result = applyValidator(exchange, validator); + if (!result.isValid()) { + throw RuntimeMessages.MESSAGES.validatorFailed(validator.getClass().getName(), result.getDetail()); + } + } catch (SwitchYardException syEx) { + // Validators which throw SwitchYardException should be reported as HandlerException + throw new HandlerException(syEx.getMessage()); + } + } + } + + @Override + public void handleFault(Exchange exchange) { + Validator validator = get(exchange); + if (validator != null) { + ValidationResult result = applyValidator(exchange, validator); + if (!result.isValid()) { + RuntimeLogger.ROOT_LOGGER.validatorFailed(validator.getClass().getName(), result.getDetail()); + } + } + } + + private Validator get(Exchange exchange) { + Property contentType = exchange.getContext().getProperty(Exchange.CONTENT_TYPE); + Property validatedType = exchange.getContext().getProperty(KEY_VALIDATED_TYPE); + + if (contentType != null) { + if (validatedType != null && contentType.getValue().equals(validatedType.getValue())) { + // Avoid to apply same validator twice. That may occur if any transformer is not applied and + // then the ValidateHandler is triggered twice with same contentType in the same exchange. + return null; + } + return _registry.getValidator((QName)contentType.getValue()); + } else { + return null; + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private ValidationResult applyValidator(Exchange exchange, Validator validator) { + Message message = exchange.getMessage(); + ValidationResult validationResult = null; + if (Message.class.isAssignableFrom(validator.getType())) { + validationResult = validator.validate(message); + } else { + validationResult = validator.validate(message.getContent(validator.getType())); + } + + if (validationResult.isValid()) { + if (_logger.isDebugEnabled()) { + _logger.debug("Validated Message (" + System.identityHashCode(message) + + ") with name '" + validator.getName() + "' using validator type '" + validator.getType() + "'."); + } + } + + exchange.getContext().setProperty(KEY_VALIDATED_TYPE, validator.getType()) + .addLabels(BehaviorLabel.TRANSIENT.label()); + return validationResult; + } +} + diff --git a/core/runtime/src/main/java/org/switchyard/internal/CompositeContext.java b/core/runtime/src/main/java/org/switchyard/internal/CompositeContext.java new file mode 100644 index 000000000..2dcadf382 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/CompositeContext.java @@ -0,0 +1,159 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.internal; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.serial.graph.AccessType; +import org.switchyard.serial.graph.Strategy; + +/** + * Composite context holds multiple scopes mapped to context instances. + */ +@Strategy(access=AccessType.FIELD) +public class CompositeContext implements Context { + + private Map _contexts = new HashMap(); + + /** + * Create a new composite context with empty EXCHANGE and MESSAGE contexts. + */ + public CompositeContext() { + _contexts.put(Scope.EXCHANGE, new DefaultContext(Scope.EXCHANGE)); + _contexts.put(Scope.MESSAGE, new DefaultContext(Scope.MESSAGE)); + } + + /** + * Attach given context to specified scope. + * + * @param scope Scope of context. + * @param context Context instance. + */ + public void setContext(Scope scope, Context context) { + _contexts.put(scope, context); + } + + @Override + public void mergeInto(Context context) { + for (Entry entry : _contexts.entrySet()) { + entry.getValue().mergeInto(context); + } + } + + @Override + public Property getProperty(String name) { + Property property = getProperty(name, Scope.MESSAGE); + return property == null ? getProperty(name, Scope.EXCHANGE) : property; + } + + @Override + public Property getProperty(String name, Scope scope) { + if (!_contexts.containsKey(scope)) { + return null; + } + return _contexts.get(scope).getProperty(name); + } + + @Override + @SuppressWarnings("unchecked") + public T getPropertyValue(String name) { + Property property = getProperty(name); + return property == null ? null : (T) property.getValue(); + } + + @Override + public Set getProperties() { + HashSet properties = new HashSet(); + for (Context ctx : _contexts.values()) { + properties.addAll(ctx.getProperties()); + } + return properties; + } + + @Override + public Set getProperties(Scope scope) { + if (_contexts.containsKey(scope)) { + return _contexts.get(scope).getProperties(); + } + return null; + } + + @Override + public Set getProperties(String label) { + HashSet properties = new HashSet(); + for (Context ctx : _contexts.values()) { + properties.addAll(ctx.getProperties(label)); + } + return properties; + } + + @Override + public void removeProperty(Property property) { + for (Entry entry : _contexts.entrySet()) { + if (entry.getKey() == property.getScope()) { + entry.getValue().removeProperty(property); + } + } + } + + @Override + public void removeProperties() { + for (Context ctx : _contexts.values()) { + ctx.removeProperties(); + } + } + + @Override + public void removeProperties(Scope scope) { + if (_contexts.containsKey(scope)) { + _contexts.get(scope).removeProperties(); + } + } + + @Override + public void removeProperties(String label) { + for (Context ctx : _contexts.values()) { + ctx.removeProperties(label); + } + } + + @Override + public Property setProperty(String name, Object val) { + return setProperty(name, val, Scope.MESSAGE); + } + + @Override + public Property setProperty(String name, Object val, Scope scope) { + if (_contexts.containsKey(scope)) { + return _contexts.get(scope).setProperty(name, val); + } + throw new IllegalArgumentException(scope.name()); + } + + @Override + public Context setProperties(Set properties) { + for (Property property : properties) { + setProperty(property.getName(), property.getValue(), property.getScope()); + } + return this; + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/ContextProperty.java b/core/runtime/src/main/java/org/switchyard/internal/ContextProperty.java new file mode 100644 index 000000000..600315a01 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/ContextProperty.java @@ -0,0 +1,191 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.Collections; +import java.util.Set; +import java.util.TreeSet; + +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.common.lang.Strings; +import org.switchyard.internal.ContextProperty.ContextPropertyFactory; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.serial.graph.AccessType; +import org.switchyard.serial.graph.BaseFactory; +import org.switchyard.serial.graph.Strategy; +import org.switchyard.serial.graph.node.Node; + +/** + * Serializable implementation of Context. + */ +@Strategy(access=AccessType.FIELD, factory=ContextPropertyFactory.class) +public class ContextProperty implements Property { + + private String _name; + private Scope _scope; + private Object _value; + private Set _labels = Collections.synchronizedSet(new TreeSet()); + + // Private ctor used for internal serialization only + private ContextProperty() { + + } + + ContextProperty(String name, Scope scope, Object value) { + if (name == null || scope == null) { + throw RuntimeMessages.MESSAGES.propertyNameAndScopeCannotBeNull(); + } + + _name = name; + _scope = scope; + _value = value; + } + + @Override + public String getName() { + return _name; + } + + @Override + public Scope getScope() { + return _scope; + } + + @Override + public Object getValue() { + return _value; + } + + /** + * Set the value of a context property. + * @param value value to set + */ + public void setValue(Object value) { + _value = value; + } + + /** + * {@inheritDoc} + */ + @Override + public Set getLabels() { + return Collections.unmodifiableSet(_labels); + } + + /** + * {@inheritDoc} + */ + @Override + public Property addLabels(String... labels) { + for (String label : labels) { + label = normalizeLabel(label); + if (label != null) { + _labels.add(label); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Property addLabels(Set labels) { + for (String label : labels) { + label = normalizeLabel(label); + if (label != null) { + _labels.add(label); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Property removeLabels(String... labels) { + for (String label : labels) { + label = normalizeLabel(label); + if (label != null) { + _labels.remove(label); + } + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasLabel(String label) { + label = normalizeLabel(label); + return label != null && _labels.contains(label); + } + + private String normalizeLabel(String label) { + label = Strings.trimToNull(label); + if (label != null) { + label = label.toLowerCase(); + } + return label; + } + + // NOTE: Labels are intentionally not part of equals(Object) or hashCode(). + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof ContextProperty)) { + return false; + } + ContextProperty comp = (ContextProperty)obj; + return _name.equals(comp.getName()) + && _scope.equals(comp.getScope()) + && (_value == null ? comp.getValue() == null : _value.equals(comp.getValue())); + } + + // NOTE: Labels are intentionally not part of equals(Object) or hashCode(). + @Override + public int hashCode() { + int hash = 1; + hash = hash * 31 + _name.hashCode(); + hash = hash * 31 + _scope.hashCode(); + hash = hash * 31 + (_value != null ? _value.hashCode() : 0); + return hash; + } + + @Override + public String toString() { + String labels = Strings.concat(", ", _labels.toArray(new String[_labels.size()])); + labels = "{" + (labels != null ? labels : "") + "}"; + return ("[name=" + _name + ", scope=" + _scope + ", value=" + _value + ", labels=" + labels + "]"); + } + + /** + * The serialization factory for context properties. + */ + public static final class ContextPropertyFactory extends BaseFactory { + /** + * {@inheritDoc} + */ + @Override + public ContextProperty create(Class type, Node node) { + return new ContextProperty(); + } + } +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/ContextUtil.java b/core/runtime/src/main/java/org/switchyard/internal/ContextUtil.java new file mode 100644 index 000000000..ad1ac976e --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/ContextUtil.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.internal; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.runtime.RuntimeMessages; + +/** + * Utility class to handle {@link Context} related operations. + */ +public final class ContextUtil { + + private ContextUtil() { } + + /** + * Copy properties from source context to destination context. Properties with + * TRANSIENT label will be skipped. + * + * @param source Source context. + * @param destination Destination context. + * @return Destination context. + */ + public static Context copy(Context source, Context destination) { + for (Property property : source.getProperties()) { + if (!property.hasLabel(BehaviorLabel.TRANSIENT.label())) { + destination.setProperty(property.getName(), property.getValue()) + .addLabels(property.getLabels()); + } + } + return destination; + } + + /** + * Verify if source scope is same as target scope. If not {@link IllegalArgumentException} will be thrown. + * + * @param source Source scope. + * @param target Target scope. + */ + public static void checkScope(Scope source, Scope target) { + if (source != target) { + throw RuntimeMessages.MESSAGES.scopeDifferent(target.toString(), source.toString()); + } + } +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/DefaultContext.java b/core/runtime/src/main/java/org/switchyard/internal/DefaultContext.java new file mode 100644 index 000000000..d131b1344 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/DefaultContext.java @@ -0,0 +1,175 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import static org.switchyard.internal.ContextUtil.checkScope; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.serial.graph.AccessType; +import org.switchyard.serial.graph.Strategy; + +/** + * Base context implementation. + */ +@Strategy(access=AccessType.FIELD) +public class DefaultContext implements Context { + + private Scope _scope; + private final Map _properties; + + /** + * Create a new DefaultContext instance using the specified property map. + * @param defaultScope Scope handled by context. + * @param properties context properties + */ + public DefaultContext(Scope defaultScope, Map properties) { + _scope = defaultScope; + _properties = properties; + } + + /** + * Creates new context with given scope. + * + * @param defaultScope Scope handled by context. + */ + public DefaultContext(Scope defaultScope) { + this(defaultScope, new HashMap()); + } + + /** + * Creates new context with exchange scope. + */ + public DefaultContext() { + this(Scope.EXCHANGE); + } + + @Override + @SuppressWarnings("unchecked") + public T getPropertyValue(String name) { + Property prop = _properties.get(name); + if (prop != null) { + return (T) prop.getValue(); + } + return null; + } + + @Override + public void removeProperties() { + _properties.clear(); + } + + @Override + public Context setProperties(Set properties) { + for (Property p : properties) { + _properties.put(p.getName(), p); + } + return this; + } + + @Override + public Set getProperties() { + return new HashSet(_properties.values()); + } + + @Override + public void removeProperty(Property property) { + checkScope(_scope, property.getScope()); + _properties.remove(property.getName()); + } + + @Override + public Property getProperty(String name) { + return _properties.get(name); + } + + @Override + public Property setProperty(String name, Object val) { + Property p = new ContextProperty(name, _scope, val); + _properties.put(p.getName(), p); + return p; + } + + @Override + public void mergeInto(Context context) { + ContextUtil.copy(this, context); + } + + @Override + public Set getProperties(String label) { + Set props = new HashSet(); + for (Property p : getProperties()) { + if (p.hasLabel(label)) { + props.add(p); + } + } + return props; + } + + @Override + public void removeProperties(String label) { + for (Property p : getProperties()) { + if (p.hasLabel(label)) { + removeProperty(p); + } + } + } + + @Override + public Property getProperty(String name, Scope scope) { + checkScope(_scope, scope); + return _properties.get(name); + } + + @Override + public Set getProperties(Scope scope) { + checkScope(_scope, scope); + return getProperties(); + } + + @Override + public void removeProperties(Scope scope) { + checkScope(_scope, scope); + _properties.clear(); + } + + @Override + public Property setProperty(String name, Object val, Scope scope) { + checkScope(_scope, scope); + ContextProperty value = new ContextProperty(name, scope, val); + _properties.put(name, value); + return value; + } + + /** + * Allows to specify default scope of this context. + * + * @param scope Scope of this context instance. + */ + public void setScope(Scope scope) { + this._scope = scope; + } + + @Override + public String toString() { + return _properties.toString(); + } +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/DefaultHandlerChain.java b/core/runtime/src/main/java/org/switchyard/internal/DefaultHandlerChain.java new file mode 100644 index 000000000..ca7878d5a --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/DefaultHandlerChain.java @@ -0,0 +1,222 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.jboss.logging.Logger; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.runtime.RuntimeLogger; + +/** + * Default handler chain. + */ +public class DefaultHandlerChain implements HandlerChain { + private static Logger _logger = Logger.getLogger(DefaultHandlerChain.class); + private final LinkedList _chain = new LinkedList(); + + /** + * Create a new handler chain with no handlers in it. + */ + public DefaultHandlerChain() { + } + + /** + * Create a new handler chain with the specified handlers. This ctor + * is not intended for external use - it's used by the clone() method. + * @param handlers + */ + private DefaultHandlerChain(List handlers) { + _chain.addAll(handlers); + } + + /** + * Create a handler chain from a list of ExchangeHandler instances. The + * handlers in the chain are named using the class name of the handler. + * @param handlers list of handlers + * @return new HandlerChain containing the list of handlers in order + */ + public static DefaultHandlerChain fromList(List handlers) { + DefaultHandlerChain chain = new DefaultHandlerChain(); + for (ExchangeHandler handler : handlers) { + chain.addLast(handler.getClass().getName(), handler); + } + return chain; + } + + @Override + public synchronized void addFirst(String handlerName, + ExchangeHandler handler) { + HandlerRef handlerRef = new HandlerRef(handlerName, handler); + + _chain.addFirst(handlerRef); + if (_logger.isDebugEnabled()) { + _logger.debug("Added ExchangeHandler instance at start of Handler Chain: " + handlerRef); + } + } + + @Override + public synchronized void addLast(String handlerName, + ExchangeHandler handler) { + HandlerRef handlerRef = new HandlerRef(handlerName, handler); + + _chain.addLast(handlerRef); + if (_logger.isDebugEnabled()) { + _logger.debug("Added ExchangeHandler instance at end of Handler Chain: " + handlerRef); + } + } + + @Override + public synchronized boolean replace(String handlerName, ExchangeHandler handler) { + for (int i = 0; i < _chain.size(); i++) { + if (_chain.get(i).getName().equals(handlerName)) { + _chain.remove(i); + _chain.add(i, new HandlerRef(handlerName, handler)); + return true; + } + } + + // no handler with the specified name found + return false; + } + + @Override + public synchronized ExchangeHandler remove(String handlerName) { + ExchangeHandler handler = null; + + for (HandlerRef ref : _chain) { + if (ref.getName().equals(handlerName)) { + handler = ref.getHandler(); + _chain.remove(ref); + break; + } + } + + return handler; + } + + @Override + public void handle(Exchange exchange) { + if (exchange.getState() == ExchangeState.FAULT) { + handleFault(exchange); + } else { + handleMessage(exchange); + } + } + + @Override + public void handleFault(Exchange exchange) { + for (HandlerRef ref : listHandlers()) { + try { + if (_logger.isDebugEnabled()) { + _logger.debug("Executing Fault ExchangeHandler (" + ref + ") on message Exchange instance (" + System.identityHashCode(exchange) + ")."); + } + ref.getHandler().handleFault(exchange); + } catch (Exception e) { + RuntimeLogger.ROOT_LOGGER.handlerFailedHandleFault(ref.getName(), e); + } + } + } + + @Override + public void handleMessage(Exchange exchange) { + HandlerRef handlerRef = null; + try { + for (HandlerRef ref : listHandlers()) { + handlerRef = ref; + if (_logger.isDebugEnabled()) { + _logger.debug("Executing ExchangeHandler (" + ref + ") on message Exchange instance (" + System.identityHashCode(exchange) + ")."); + } + ref.getHandler().handleMessage(exchange); + + if (exchange.getState() == ExchangeState.FAULT) { + // Exchange state has changed to FAULT. + // Stop executing handlers.... + break; + } + } + } catch (HandlerException handlerEx) { + StringBuilder errorMsg = new StringBuilder(handlerEx.getClass().getName() + " was thrown by handler(" + handlerRef.getName() + "): " + handlerEx.getMessage()); + Throwable cause = handlerEx; + while ((cause = cause.getCause()) != null) { + errorMsg.append(" --- Caused by " + cause.getClass().getName() + ": " + cause.getMessage()); + } + _logger.error(errorMsg.toString()); + _logger.debug("", handlerEx); + + Message faultMessage = exchange.createMessage().setContent(handlerEx); + exchange.sendFault(faultMessage); + } + } + + @Override + public List getHandlers() { + List handlers = new LinkedList(); + for (HandlerRef hr : listHandlers()) { + handlers.add(hr.getHandler()); + } + return Collections.unmodifiableList(handlers); + } + + /** + * Create a copy of the default handler chain. + * @return copy of the default chain. + */ + public DefaultHandlerChain copy() { + if (_logger.isDebugEnabled()) { + _logger.debug("Cloning DefaultHandlerChain from a its list of Handlers: " + listHandlers()); + } + return new DefaultHandlerChain(listHandlers()); + } + + @Override + public String toString() { + return _chain.toString(); + } + + private synchronized List listHandlers() { + return new LinkedList(_chain); + } + + // sweet little struct + private static final class HandlerRef { + HandlerRef(String name, ExchangeHandler handler) { + _handler = handler; + _name = name; + } + + public String getName() { + return _name; + } + + public ExchangeHandler getHandler() { + return _handler; + } + + @Override + public String toString() { + return "Name '" + _name + "', Class '" + _handler.getClass().getName() + "'"; + } + + private final ExchangeHandler _handler; + private final String _name; + } +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/DefaultMessage.java b/core/runtime/src/main/java/org/switchyard/internal/DefaultMessage.java new file mode 100644 index 000000000..3496b472a --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/DefaultMessage.java @@ -0,0 +1,159 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.HashMap; +import java.util.Map; + +import javax.activation.DataSource; +import javax.xml.namespace.QName; + +import org.switchyard.Context; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; + +/** + * Implementation of Message. + */ +public class DefaultMessage implements Message { + + private TransformerRegistry _transformerRegistry; + private Object _content; + private Map _attachments = + new HashMap(); + private Context _context = new DefaultContext(Scope.MESSAGE); + private boolean _sent; + + /** + * Create a new instance of DefaultMessage. + */ + public DefaultMessage() { + } + + /** + * Set the transformation registry to be used by the Message instance when + * performing payload conversions. + * + * @param transformerRegistry The transformation registry instance. + * @return this Message instance. + */ + public DefaultMessage setTransformerRegistry(TransformerRegistry transformerRegistry) { + _transformerRegistry = transformerRegistry; + return this; + } + + @Override + public DefaultMessage addAttachment(final String name, final DataSource attachment) { + _attachments.put(name, attachment); + return this; + } + + @Override + public DataSource getAttachment(final String name) { + return _attachments.get(name); + } + + @Override + public void removeAttachment(final String name) { + _attachments.remove(name); + } + + @Override + public Map getAttachmentMap() { + return new HashMap(_attachments); + } + + @Override + public Object getContent() { + return _content; + } + + @Override + public Context getContext() { + return _context; + } + + @Override + public T getContent(final Class type) { + if (type == null) { + throw RuntimeMessages.MESSAGES.nullTypeArgument(); + } + if (_content == null) { + return null; + } + if (type.isInstance(_content)) { + return type.cast(_content); + } + if (_transformerRegistry == null) { + throw RuntimeMessages.MESSAGES.noTransformRegistryAvailable(_content.getClass().getName(), type.getName()); + } + + QName fromType = JavaTypes.toMessageType(_content.getClass()); + QName toType = JavaTypes.toMessageType(type); + Transformer transformer = _transformerRegistry.getTransformer(fromType, toType); + if (transformer == null) { + throw RuntimeMessages.MESSAGES.noRegisteredTransformer(_content.getClass().getName(), type.getName(), + fromType.toString(), toType.toString()); + } + + Object transformedContent = transformer.transform(_content); + if (transformedContent == null) { + throw RuntimeMessages.MESSAGES.transformerReturnedNull(_content.getClass().getName(), type.getName(), + transformer.getClass().getName()); + } + if (!type.isInstance(transformedContent)) { + throw RuntimeMessages.MESSAGES.transformerReturnedIncompatibleType(_content.getClass().getName(), type.getName(), transformer.getClass().getName(), + transformedContent.getClass().getName()); + } + + return type.cast(transformedContent); + } + + @Override + public DefaultMessage setContent(final Object content) { + _content = content; + return this; + } + + @Override + public Message copy() { + DefaultMessage message = new DefaultMessage(); + if (_transformerRegistry != null) { + message.setTransformerRegistry(_transformerRegistry); + } + return message.setContent(_content); + } + + /** + * Checks if message was already sent by someone. + * + * @return True if message was already sent. + */ + public boolean isSent() { + return _sent; + } + + /** + * Sets sent flag to true. + */ + public void send() { + _sent = true; + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/DefaultServiceRegistry.java b/core/runtime/src/main/java/org/switchyard/internal/DefaultServiceRegistry.java new file mode 100644 index 000000000..71fd00e0a --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/DefaultServiceRegistry.java @@ -0,0 +1,127 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.Service; +import org.switchyard.ServiceReference; +import org.switchyard.spi.ServiceRegistry; + +/** + * Standalone implementation of ServiceRegistry. + */ +public class DefaultServiceRegistry implements ServiceRegistry { + + private static Logger _logger = Logger.getLogger(DefaultServiceRegistry.class); + + private final Map> _services = + new HashMap>(); + + private ConcurrentHashMap _references = + new ConcurrentHashMap(); + + @Override + public synchronized List getServices() { + List serviceList = new LinkedList(); + for (List services : _services.values()) { + serviceList.addAll(services); + } + + return serviceList; + } + + @Override + public synchronized List getServices(QName serviceName) { + if (!_services.containsKey(serviceName)) { + return Collections.emptyList(); + } + + return new LinkedList(_services.get(serviceName)); + } + + @Override + public synchronized Service registerService(Service service) { + if (!_services.containsKey(service.getName())) { + _services.put(service.getName(), new LinkedList()); + } + _services.get(service.getName()).add(service); + + if (_logger.isDebugEnabled()) { + _logger.debug("Registered Service '" + service.getName() + "'."); + } + + return service; + } + + @Override + public synchronized void unregisterService(Service service) { + List serviceList =_services.get(service.getName()); + if (serviceList != null) { + serviceList.remove(service); + + if (_logger.isDebugEnabled()) { + + QName serviceName = service.getName(); + String domainName = ""; + if ((service.getDomain() != null) && (service.getDomain().getName() != null)) { + domainName = service.getDomain().getName().toString(); + } + _logger.debug("Unregistered Service '" + serviceName + "' from ServiceDomain '" + domainName + "'."); + } + } + } + + @Override + public void registerServiceReference(ServiceReference reference) { + ServiceReference ref = _references.putIfAbsent(reference.getName(), reference); + + if (_logger.isDebugEnabled()) { + _logger.debug("Registered ServiceReference '" + reference.getName() + "', " + + "found previous map value of " + ref + "."); + } + } + + @Override + public void unregisterServiceReference(ServiceReference reference) { + ServiceReference removed = _references.remove(reference.getName()); + if (removed != null && _logger.isDebugEnabled()) { + _logger.debug("Unregistered ServiceReference '" + reference.getName() + "'."); + } + } + + @Override + public List getServiceReferences() { + if (_references.isEmpty()) { + return Collections.emptyList(); + } else { + return new LinkedList(_references.values()); + } + } + + @Override + public ServiceReference getServiceReference(QName serviceName) { + return _references.get(serviceName); + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/DomainImpl.java b/core/runtime/src/main/java/org/switchyard/internal/DomainImpl.java new file mode 100644 index 000000000..88cb45a1a --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/DomainImpl.java @@ -0,0 +1,291 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.EventObject; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.ExchangeHandler; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceMetadata; +import org.switchyard.ServiceReference; +import org.switchyard.ServiceSecurity; +import org.switchyard.event.DomainShutdownEvent; +import org.switchyard.event.DomainStartupEvent; +import org.switchyard.event.EventObserver; +import org.switchyard.event.EventPublisher; +import org.switchyard.event.ReferenceRegistrationEvent; +import org.switchyard.event.ServiceRegistrationEvent; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.internal.validate.BaseValidatorRegistry; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.security.service.DefaultServiceDomainSecurity; +import org.switchyard.security.service.SecureServiceDomain; +import org.switchyard.security.service.ServiceDomainSecurity; +import org.switchyard.spi.Dispatcher; +import org.switchyard.spi.ExchangeBus; +import org.switchyard.spi.ServiceRegistry; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.validate.ValidatorRegistry; + +/** + * Implementation of ServiceDomain. + */ +public class DomainImpl implements SecureServiceDomain { + + private static Logger _logger = Logger.getLogger(DomainImpl.class); + + private final QName _name; + private EventManager _eventManager; + private ServiceRegistry _serviceRegistry; + private ExchangeBus _exchangeBus; + private TransformerRegistry _transformerRegistry; + private ValidatorRegistry _validatorRegistry; + private Map _properties = new ConcurrentHashMap(); + private ServiceDomainSecurity _serviceDomainSecurity; + + /** + * Create a new ServiceDomain. This is a convenience constructor which uses default + * resources and initializes via init() in the constructor. Do not use this in runtime + * code! This is for test/embedded use only. + * @param name name + */ + protected DomainImpl(QName name) { + this(name, + new DefaultServiceRegistry(), + new LocalExchangeBus(), + new BaseTransformerRegistry(), + new BaseValidatorRegistry(), + new EventManager(), + new DefaultServiceDomainSecurity()); + init(); + } + + /** + * Create a new ServiceDomain. + * @param name name + * @param serviceRegistry serviceRegistry + * @param exchangeBus exchangeBus + * @param transformerRegistry transformerRegistry + * @param validatorRegistry validatorRegistry + * @param eventManager eventManager + * @param serviceDomainSecurity serviceDomainSecurity + */ + public DomainImpl(QName name, + ServiceRegistry serviceRegistry, + ExchangeBus exchangeBus, + TransformerRegistry transformerRegistry, + ValidatorRegistry validatorRegistry, + EventManager eventManager, + ServiceDomainSecurity serviceDomainSecurity) { + + _name = name; + _serviceRegistry = serviceRegistry; + _exchangeBus = exchangeBus; + _transformerRegistry = transformerRegistry; + _validatorRegistry = validatorRegistry; + _eventManager = eventManager; + _serviceDomainSecurity = serviceDomainSecurity; + + setEventPublisher(_transformerRegistry); + setEventPublisher(_validatorRegistry); + + if (_logger.isDebugEnabled()) { + _logger.debug("Created SwitchYard ServiceDomain instance '" + name + "'."); + } + } + + @Override + public Service registerService(QName serviceName, ServiceInterface contract, + ExchangeHandler handler) { + return registerService(serviceName, contract, handler, null); + } + + @Override + public Service registerService(QName serviceName, + ServiceInterface contract, ExchangeHandler handler, ServiceMetadata metadata) { + + // If no service interface is provided, we default to InOutService + if (contract == null) { + contract = new InOutService(); + } + // Create the service + Service service = new ServiceImpl(serviceName, contract, this, handler, metadata); + // register the service + _serviceRegistry.registerService(service); + _eventManager.publish(new ServiceRegistrationEvent(service)); + return service; + } + + @Override + public ServiceReference registerServiceReference(QName serviceName, + ServiceInterface contract) { + return registerServiceReference(serviceName, contract, null); + } + + @Override + public ServiceReference registerServiceReference(QName serviceName, + ServiceInterface contract, ExchangeHandler handler) { + return registerServiceReference(serviceName, contract, handler, null); + } + + @Override + public ServiceReference registerServiceReference(QName serviceName, + ServiceInterface contract, ExchangeHandler handler, ServiceMetadata metadata) { + ServiceReferenceImpl reference = new ServiceReferenceImpl(serviceName, contract, this, handler, metadata); + Dispatcher dispatch = _exchangeBus.createDispatcher(reference); + reference.setDispatcher(dispatch); + _serviceRegistry.registerServiceReference(reference); + _eventManager.publish(new ReferenceRegistrationEvent(reference)); + + return reference; + } + + @Override + public ServiceReference getServiceReference(QName serviceName) { + return _serviceRegistry.getServiceReference(serviceName); + } + + @Override + public QName getName() { + return _name; + } + + @Override + public TransformerRegistry getTransformerRegistry() { + return _transformerRegistry; + } + + @Override + public ValidatorRegistry getValidatorRegistry() { + return _validatorRegistry; + } + + @Override + public List getServices() { + return _serviceRegistry.getServices(); + } + + + @Override + public List getServices(QName serviceName) { + return _serviceRegistry.getServices(serviceName); + } + + /** + * Convenient access to the domain's service registry. + * @return service registry + */ + public ServiceRegistry getServiceRegistry() { + return _serviceRegistry; + } + + /** + * Convenient access to the domain's exchange bus. + * @return exchange bus + */ + public ExchangeBus getBus() { + return _exchangeBus; + } + + @Override + public void init() { + _eventManager.publish(new DomainStartupEvent(this)); + _exchangeBus.init(this); + _exchangeBus.start(); + } + + @Override + public void destroy() { + _exchangeBus.stop(); + _eventManager.publish(new DomainShutdownEvent(this)); + } + + @Override + public ServiceDomain addEventObserver(EventObserver observer, Class eventType) { + _eventManager.addObserver(observer, eventType); + return this; + } + + @Override + public EventPublisher getEventPublisher() { + return _eventManager; + } + + @Override + public Map getProperties() { + return Collections.unmodifiableMap(_properties); + } + + @Override + public Object getProperty(String name) { + return _properties.get(name); + } + + @Override + public ServiceDomain setProperty(String name, Object value) { + if (value != null) { + _properties.put(name, value); + } else { + _properties.remove(name); + } + return this; + } + + private void setEventPublisher(Object target) { + if (target == null) { + return; + } + + try { + Method setter = target.getClass().getMethod("setEventPublisher", EventPublisher.class); + setter.invoke(target, _eventManager); + } catch (Exception ex) { + _logger.debug("Attempt to set EventPublisher failed on " + + target.getClass().getCanonicalName(), ex); + } + } + + /** + * {@inheritDoc} + */ + @Override + public ServiceSecurity getServiceSecurity(String name) { + return getServiceDomainSecurity().getServiceSecurity(name); + } + + /** + * {@inheritDoc} + */ + @Override + public ServiceDomainSecurity getServiceDomainSecurity() { + return _serviceDomainSecurity; + } + + @Override + public String toString() { + return "ServiceDomain [name=" + _name + "]"; + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/EventManager.java b/core/runtime/src/main/java/org/switchyard/internal/EventManager.java new file mode 100644 index 000000000..4c0ce36d1 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/EventManager.java @@ -0,0 +1,118 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.Collections; +import java.util.EventObject; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.jboss.logging.Logger; +import org.switchyard.event.EventObserver; +import org.switchyard.event.EventPublisher; + +/** + * Handles registration and publication of events in a ServiceDomain. + */ +public class EventManager implements EventPublisher { + + private static Logger _logger = Logger.getLogger(EventManager.class); + + private Map, List> _observers; + + /** + * Creates a new instance of EventManager. + */ + public EventManager() { + _observers = new ConcurrentHashMap, List>(); + } + + @Override + public void publish(EventObject event) { + if (_logger.isTraceEnabled()) { + _logger.trace("Publishing event " + event); + } + + for (EventObserver observer : getObserversForEvent(event.getClass())) { + try { + observer.notify(event); + } catch (Throwable t) { + // do not propagate errors on event notifications + _logger.debug("Observer threw exception on event " + event.getClass(), t); + } + } + } + + /** + * Returns a list of EventObserver instances for a given event type. + * @param event event type to query for observers + * @return list of EventObservers for the type or an empty list if none are registered + */ + public List getObserversForEvent(Class event) { + if (_observers.containsKey(event)) { + return _observers.get(event); + } else { + return Collections.emptyList(); + } + } + + /** + * Synchronizing this method since adding an observer may lead to a + * new list being created for an event entry and we don't want a race + * condition if multiple threads hit this during deployment/startup. + * @param observer observer instance to add + * @param event the event to register against + * @return a reference to this EventManger for chaining calls + */ + public synchronized EventManager addObserver( + EventObserver observer, Class event) { + + List observerList = _observers.get(event); + if (observerList == null) { + observerList = new LinkedList(); + _observers.put(event, observerList); + } + + observerList.add(observer); + _logger.debug("Observer added for event " + event.getCanonicalName()); + return this; + } + + /** + * Remove all event registrations for a given EventObserver instance. + * @param observer the observer to unregister + */ + public synchronized void removeObserver(EventObserver observer) { + for (List observers : _observers.values()) { + observers.remove(observer); + } + } + + /** + * Remove an EventObserver from a specific event type. + * @param observer the EventObserver to unregister + * @param event the event to unregister + */ + public synchronized void removeObserverForEvent( + EventObserver observer, Class event) { + + List observers = _observers.get(event); + if (observers != null) { + observers.remove(observer); + } + } +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/ExchangeImpl.java b/core/runtime/src/main/java/org/switchyard/internal/ExchangeImpl.java new file mode 100644 index 000000000..ba4a4acee --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/ExchangeImpl.java @@ -0,0 +1,354 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangePhase; +import org.switchyard.ExchangeSecurity; +import org.switchyard.ExchangeState; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.metadata.BaseExchangeContract; +import org.switchyard.metadata.ExchangeContract; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.runtime.RuntimeLogger; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.runtime.event.ExchangeInitiatedEvent; +import org.switchyard.security.context.DefaultExchangeSecurity; +import org.switchyard.spi.Dispatcher; + +/** + * Implementation of Exchange. + */ +public class ExchangeImpl implements Exchange { + + private static Logger _log = Logger.getLogger(ExchangeImpl.class); + + private ExchangePhase _phase; + private Message _message; + private ExchangeState _state = ExchangeState.OK; + private Dispatcher _dispatch; + private ExchangeHandler _replyHandler; + private ServiceDomain _domain; + private Long _startTime; + private Context _context; + private CompositeContext _compositeContext; + private ServiceReference _consumer; + private Service _provider; + private BaseExchangeContract _contract = new BaseExchangeContract(); + private transient ExchangeSecurity _security = null; + + /** + * Create a new exchange with no endpoints initialized. At a minimum, the + * input endpoint must be set before sending an exchange. + * @param domain Service domain for this exchange + * @param dispatcher Exchange dispatcher to use + */ + public ExchangeImpl(ServiceDomain domain, Dispatcher dispatcher) { + this(domain, dispatcher, null); + } + + /** + * Constructor. + * @param domain service domain for this exchange + * @param dispatch exchange dispatcher + * @param replyHandler handler for replies + */ + public ExchangeImpl(ServiceDomain domain, Dispatcher dispatch, ExchangeHandler replyHandler) { + _domain = domain; + _dispatch = dispatch; + _replyHandler = replyHandler; + _context = new DefaultContext(); + _compositeContext = new CompositeContext(); + _compositeContext.setContext(Scope.EXCHANGE, _context); + } + + @Override + public Context getContext() { + return _compositeContext; + } + + @Override + public Context getContext(Message message) { + if (_message != null && _message == message) { + return getContext(); + } + return message.getContext(); + } + + @Override + public Message getMessage() { + return _message; + } + + @Override + public synchronized void send(Message message) { + assertMessageOK(message); + + // Set exchange phase + if (_phase == null) { + _phase = ExchangePhase.IN; + initContentType(message); + } else if (_phase.equals(ExchangePhase.IN)) { + _phase = ExchangePhase.OUT; + initContentType(message); + // set relatesTo header on OUT context + Object propertyValue = _message.getContext().getPropertyValue(MESSAGE_ID); + message.getContext().setProperty(RELATES_TO, propertyValue) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } else { + throw RuntimeMessages.MESSAGES.sendMessageNotAllowed(_phase.toString()); + } + + sendInternal(message); + } + + @Override + public synchronized void sendFault(Message message) { + assertMessageOK(message); + + // You can't send a fault before you send a message + if (_phase == null) { + throw RuntimeMessages.MESSAGES.sendFaultNotAllowed(); + } + + _phase = ExchangePhase.OUT; + _state = ExchangeState.FAULT; + initFaultContentType(); + + // set relatesTo header on OUT context + message.getContext().setProperty(RELATES_TO, _message.getContext().getPropertyValue(MESSAGE_ID)) + .addLabels(BehaviorLabel.TRANSIENT.label()); + + sendInternal(message); + } + + @Override + public ExchangeState getState() { + return _state; + } + + /** + * Get exchange dispatcher. + * @return exchange dispatcher + */ + public Dispatcher getDispatcher() { + return _dispatch; + } + + @Override + public ExchangeHandler getReplyHandler() { + return _replyHandler; + } + + @Override + public ExchangePattern getPattern() { + ExchangePattern pattern = null; + if (getContract() != null) { + pattern = getContract().getConsumerOperation().getExchangePattern(); + } + return pattern; + } + + @Override + public ExchangeSecurity getSecurity() { + if (_security == null) { + _security = new DefaultExchangeSecurity(this); + } + return _security; + } + + /** + * Internal send method common to sendFault and sendMessage. This method + * assumes that the exchange phase has been assigned for the send and that + * the exchange state has been verified (i.e. it's OK to deliver in the + * exchange's current state). + */ + private void sendInternal(Message message) { + if (_startTime == null) { + _startTime = System.nanoTime(); + } + ExchangePhase sendPhase = _phase; + + _message = message; + // assign messageId + _message.getContext().setProperty(MESSAGE_ID, UUID.randomUUID().toString()) + .addLabels(BehaviorLabel.TRANSIENT.label()); + _compositeContext.setContext(Scope.MESSAGE, _message.getContext()); + + if (_log.isDebugEnabled()) { + _log.debug("Sending " + _phase + " Message (" + System.identityHashCode(message) + ") on " + + _contract.getConsumerOperation().getExchangePattern() + + " Exchange (" + instanceHash() + ") for Service '" + _consumer.getName() + + "', operation '" + _contract.getProviderOperation() + "'. Exchange state: " + _state); + } + + // if a fault was thrown by the handler chain and there's no reply chain + // we need to log. + // TODO : stick this in a central fault/error queue + if (ExchangeState.FAULT.equals(_state) && _replyHandler == null) { + // Attempt to convert content to String + String faultContent; + try { + faultContent = _message.getContent(String.class); + } catch (Exception ex) { + // Well, that didn't work. Try the next best thing. + faultContent = _message.getContent().toString(); + } + RuntimeLogger.ROOT_LOGGER.faultGeneratedDuringExchange(faultContent); + } else { + // Publish exchange initiation event + if (ExchangePhase.IN.equals(getPhase())) { + getContext().setProperty(ExchangeInitiatedEvent.EXCHANGE_INITIATED_TIME + ".start", Long.toString(System.nanoTime())); + _domain.getEventPublisher().publish(new ExchangeInitiatedEvent(this)); + } + + _dispatch.dispatch(this); + } + + // Publish exchange completion event + if (isDone(sendPhase)) { + long duration = System.nanoTime() - _startTime; + getContext().setProperty(ExchangeCompletionEvent.EXCHANGE_DURATION, + TimeUnit.MILLISECONDS.convert(duration, TimeUnit.NANOSECONDS)).addLabels(BehaviorLabel.TRANSIENT.label()); + _domain.getEventPublisher().publish(new ExchangeCompletionEvent(this)); + } + } + + private int instanceHash() { + return System.identityHashCode(this); + } + + private void assertMessageOK(Message message) { + if (message == null) { + throw RuntimeMessages.MESSAGES.invalidMessageArgument(); + } + if (_state == ExchangeState.FAULT) { + throw RuntimeMessages.MESSAGES.exchangeInFaultState(); + } + + if (!(message instanceof DefaultMessage)) { + throw RuntimeMessages.MESSAGES.onlyDefaultMessageInstances(); + } + + if (((DefaultMessage) message).isSent()) { + throw RuntimeMessages.MESSAGES.messageOnlySentOnce(); + } + // mark message as sent + ((DefaultMessage) message).send(); + } + + @Override + public Message createMessage() { + DefaultMessage msg = new DefaultMessage(); + if (_domain != null) { + msg.setTransformerRegistry(_domain.getTransformerRegistry()); + } + if (_message == null) { + _compositeContext.setContext(Scope.MESSAGE, msg.getContext()); + } + return msg; + } + + @Override + public ExchangePhase getPhase() { + return _phase; + } + + @Override + public ExchangeContract getContract() { + return _contract; + } + + @Override + public ServiceReference getConsumer() { + return _consumer; + } + + @Override + public Service getProvider() { + return _provider; + } + + @Override + public ExchangeImpl consumer(ServiceReference consumer, ServiceOperation operation) { + if (_phase != null) { + throw RuntimeMessages.MESSAGES.cannotChangeMetaDataAfterMessageSent(); + } + if (_replyHandler == null && operation.getExchangePattern() == ExchangePattern.IN_OUT) { + throw RuntimeMessages.MESSAGES.invalidConsumerContract(); + } + _consumer = consumer; + _contract.setConsumerOperation(operation); + return this; + } + + @Override + public ExchangeImpl provider(Service provider, ServiceOperation operation) { + if (_phase == ExchangePhase.OUT) { + throw RuntimeMessages.MESSAGES.cannotChangeMetadataAfterInvoke(); + } + _provider = provider; + _contract.setProviderOperation(operation); + return this; + } + + protected void setPhase(ExchangePhase phase) { + _phase = phase; + } + + protected void setMessage(Message message) { + _message = message; + } + + private void initContentType(Message message) { + QName exchangeInputType = _contract.getConsumerOperation().getInputType(); + + if (exchangeInputType != null) { + message.getContext().setProperty(Exchange.CONTENT_TYPE, exchangeInputType, Scope.MESSAGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } + } + + private void initFaultContentType() { + if (_contract.getProviderOperation() != null) { + QName serviceOperationFaultType = _contract.getProviderOperation().getFaultType(); + if (serviceOperationFaultType != null) { + _message.getContext().setProperty(Exchange.FAULT_TYPE, serviceOperationFaultType, Scope.MESSAGE) + .addLabels(BehaviorLabel.TRANSIENT.label()); + } + } + } + + private boolean isDone(ExchangePhase phase) { + ExchangePattern mep = _contract.getConsumerOperation().getExchangePattern(); + return (ExchangePhase.IN.equals(phase) && ExchangePattern.IN_ONLY.equals(mep)) + || (ExchangePhase.OUT.equals(phase) && ExchangePattern.IN_OUT.equals(mep)); + } +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/HandlerChain.java b/core/runtime/src/main/java/org/switchyard/internal/HandlerChain.java new file mode 100644 index 000000000..d4a30e029 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/HandlerChain.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.List; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; + +/** + * An ordered list of {@code Handler} instances that can be associated with a + * service or exchange instance. Note that HandlerChain extends ExchangeHandler + * which provides the ability to add a set of handlers instead of a single + * handler to an exchange or service. + */ +public interface HandlerChain extends ExchangeHandler { + + /** + * Reserved name for the service provider handler. This name is used for + * handlers passed to ServiceDomain.createExchange() and + * ServiceDomain.registerService(). + */ + final String PROVIDER_HANDLER = "provider"; + + /** + * Reserved name for the service consumer handler. This name is used for + * the callback handler used by a consumer to process reply messages. + */ + final String CONSUMER_HANDLER = "consumer"; + + /** + * Add a handler to the front of the chain. + * @param handlerName name of the handler to add + * @param handler handler instance + */ + void addFirst(String handlerName, ExchangeHandler handler); + + /** + * Add a handler to the end of the chain. + * @param handlerName name of the handler to add + * @param handler handler instance + */ + void addLast(String handlerName, ExchangeHandler handler); + + /** + * Replaces a specified handler at it's current position in the chain. If + * no handler is found in the chain with the specified name, the new handler + * is *not* added to the chain. + * @param handlerName name of the handler to replace + * @param handler handler instnace to replace + * @return true if the handler was added, false if it was not + */ + boolean replace(String handlerName, ExchangeHandler handler); + + /** + * Remove the named handler from this chain. + * @param handlerName name of the handler to remove + * @return a reference to the removed handler or null if the named handler + * was not present in the chain + */ + ExchangeHandler remove(String handlerName); + + /** + * Triggers the handler chain with the specified exchange. + * @param exchange exchange that needs to be handled + */ + void handle(Exchange exchange); + + /** + * Returns an unmodifiable list of handlers in this chain. + * @return list of handlers in chain + */ + List getHandlers(); + + /** + * Create a shallow copy of the handler chain. The returned chain represents + * a distinct collection from the original, but the individual handler + * instances are identical. + * @return copy of the default chain. + */ + HandlerChain copy(); +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/LocalExchangeBus.java b/core/runtime/src/main/java/org/switchyard/internal/LocalExchangeBus.java new file mode 100644 index 000000000..fe23c77ac --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/LocalExchangeBus.java @@ -0,0 +1,158 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.handlers.AddressingHandler; +import org.switchyard.handlers.PolicyHandler; +import org.switchyard.handlers.ProviderHandler; +import org.switchyard.handlers.SecurityHandler; +import org.switchyard.handlers.SecurityHandler.SecurityAction; +import org.switchyard.handlers.TransactionHandler; +import org.switchyard.handlers.TransformHandler; +import org.switchyard.handlers.ValidateHandler; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.spi.Dispatcher; +import org.switchyard.spi.ExchangeBus; + +/** + * Default endpoint provider. + */ +public class LocalExchangeBus implements ExchangeBus { + + private ConcurrentHashMap _dispatchers = + new ConcurrentHashMap(); + + private HandlerChain _requestChain; + private HandlerChain _replyChain; + private ServiceDomain _domain; + + /** + * Create a new LocalExchangeBus. + */ + public LocalExchangeBus() { + } + + @Override + public void init(ServiceDomain domain) { + _domain = domain; + TransactionHandler transactionHandler = new TransactionHandler(); + TransformHandler transformHandler = new TransformHandler(domain.getTransformerRegistry()); + ValidateHandler validateHandler = new ValidateHandler(domain.getValidatorRegistry()); + + // Build out the request and reply handler chains. + _requestChain = new DefaultHandlerChain(); + _requestChain.addLast("addressing", new AddressingHandler(_domain)); + _requestChain.addLast("transaction-pre-invoke", transactionHandler); + _requestChain.addLast("security-process", new SecurityHandler(_domain, SecurityAction.PROCESS)); + _requestChain.addLast("generic-policy", new PolicyHandler()); + _requestChain.addLast("validation-before-transform", validateHandler); + _requestChain.addLast("transformation", transformHandler); + _requestChain.addLast("validation-after-transform", validateHandler); + _requestChain.addLast("provider", new ProviderHandler(_domain)); + _requestChain.addLast("security-cleanup", new SecurityHandler(_domain, SecurityAction.CLEANUP)); + _requestChain.addLast("transaction-post-invoke", transactionHandler); + + _replyChain = new DefaultHandlerChain(); + _replyChain.addLast("validation-before-transform", validateHandler); + _replyChain.addLast("transformation", transformHandler); + _replyChain.addLast("validation-after-transform", validateHandler); + _replyChain.addLast(HandlerChain.CONSUMER_HANDLER, new BaseHandler()); + } + + @Override + public void start() { + // NOP + } + + @Override + public void stop() { + _dispatchers.clear(); + } + + @Override + public synchronized Dispatcher createDispatcher(ServiceReference reference) { + HandlerChain requestChain = _requestChain.copy(); + HandlerChain replyChain = _replyChain.copy(); + + Dispatcher dispatcher = new LocalDispatcher(_domain, reference, requestChain, replyChain); + _dispatchers.put(reference.getName(), dispatcher); + + return dispatcher; + } + + @Override + public Dispatcher getDispatcher(ServiceReference reference) { + return _dispatchers.get(reference.getName()); + } + +} + +class LocalDispatcher implements Dispatcher { + private HandlerChain _requestChain; + private HandlerChain _replyChain; + private ServiceReference _reference; + private ServiceDomain _domain; + + /** + * Constructor. + * @param _domain + * @param handlerChain handler chain + */ + LocalDispatcher(ServiceDomain domain, final ServiceReference reference, final HandlerChain requestChain, final HandlerChain replyChain) { + this._domain = domain; + _reference = reference; + _requestChain = requestChain; + _replyChain = replyChain; + } + + @Override + public void dispatch(final Exchange exchange) { + switch (exchange.getPhase()) { + case IN: + _requestChain.handle(exchange); + break; + case OUT: + ExchangeHandler replyHandler = ((ExchangeImpl)exchange).getReplyHandler(); + if (replyHandler != null) { + _replyChain.replace(HandlerChain.CONSUMER_HANDLER, replyHandler); + } + _replyChain.handle(exchange); + break; + default: + throw RuntimeMessages.MESSAGES.invalidPhaseForDispatch(exchange.getPhase().toString()); + } + } + + @Override + public ServiceReference getServiceReference() { + return _reference; + } + + @Override + public Exchange createExchange(ExchangeHandler handler, ExchangePattern pattern) { + ExchangeImpl exchangeImpl = new ExchangeImpl(_domain, this, handler); + return exchangeImpl; + } +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/ServiceImpl.java b/core/runtime/src/main/java/org/switchyard/internal/ServiceImpl.java new file mode 100644 index 000000000..654ee9899 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/ServiceImpl.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import javax.xml.namespace.QName; + +import org.switchyard.ExchangeHandler; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceMetadata; +import org.switchyard.event.ServiceUnregistrationEvent; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.metadata.ServiceMetadataBuilder; + +/** + * A service registered in a SwitchYard domain. This is an instance of the + * registered service itself and not a service reference (which is used to + * invoke a service). + */ +public class ServiceImpl implements Service { + + private QName _name; + private ServiceInterface _interface; + private DomainImpl _domain; + private ExchangeHandler _providerHandler; + private ServiceMetadata _metadata; + + /** + * Creates a new Service instance representing a service provider. + * @param name name of the service reference + * @param serviceInterface the service interface + * @param domain domain in which the service is used + * @param providerHandler the exchange handler representing the provider + */ + public ServiceImpl(QName name, + ServiceInterface serviceInterface, + DomainImpl domain, + ExchangeHandler providerHandler) { + this(name, serviceInterface, domain, providerHandler, null); + } + + /** + * Creates a new Service instance representing a service provider. + * @param name name of the service reference + * @param serviceInterface the service interface + * @param domain domain in which the service is used + * @param providerHandler the exchange handler representing the provider + * @param metadata service metadata + */ + public ServiceImpl(QName name, + ServiceInterface serviceInterface, + DomainImpl domain, + ExchangeHandler providerHandler, + ServiceMetadata metadata) { + + _name = name; + _interface = serviceInterface; + _domain = domain; + _providerHandler = providerHandler; + _metadata = metadata != null ? metadata : ServiceMetadataBuilder.create().build(); + } + + @Override + public ServiceInterface getInterface() { + return _interface; + } + + @Override + public QName getName() { + return _name; + } + + @Override + public ServiceDomain getDomain() { + return _domain; + } + + @Override + public void unregister() { + _domain.getServiceRegistry().unregisterService(this); + _domain.getEventPublisher().publish(new ServiceUnregistrationEvent(this)); + } + + + @Override + public ExchangeHandler getProviderHandler() { + return _providerHandler; + } + + @Override + public String toString() { + return "Service [name=" + _name + ", interface=" + _interface + + ", domain=" + _domain + ", metadata=" + _metadata + "]"; + } + + @Override + public ServiceMetadata getServiceMetadata() { + return _metadata; + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/ServiceReferenceImpl.java b/core/runtime/src/main/java/org/switchyard/internal/ServiceReferenceImpl.java new file mode 100644 index 000000000..7e7867d1e --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/ServiceReferenceImpl.java @@ -0,0 +1,204 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceMetadata; +import org.switchyard.ServiceReference; +import org.switchyard.event.ReferenceUnregistrationEvent; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.metadata.ServiceMetadataBuilder; +import org.switchyard.metadata.ServiceOperation; +import org.switchyard.policy.Policy; +import org.switchyard.policy.PolicyUtil; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.security.context.SecurityContextManager; +import org.switchyard.spi.Dispatcher; + +/** + * A reference to a service registered in a SwitchYard domain. The reference + * is a logical representation of a service endpoint, which can be mapped to + * multiple service instances compatible with the service reference metadata. + */ +public class ServiceReferenceImpl implements ServiceReference { + + private QName _name; + private ServiceInterface _interface; + private DomainImpl _domain; + private ExchangeHandler _handler; + private Dispatcher _dispatcher; + private QName _targetServiceName; + private ServiceMetadata _metadata; + private SecurityContextManager _securityContextManager; + + /** + * Creates a new reference to a service. + * @param name name of the service reference + * @param serviceInterface the service interface + * @param domain domain in which the service is used + * @param metadata service metadata + */ + public ServiceReferenceImpl(QName name, + ServiceInterface serviceInterface, + DomainImpl domain, + ServiceMetadata metadata) { + this(name, serviceInterface, domain, null, metadata); + } + + /** + * Creates a new reference to a service. + * @param name name of the service reference + * @param serviceInterface the service interface + * @param domain domain in which the service is used + * @param handler handler used to process reply faults/messages + * @param metadata service metadata + */ + public ServiceReferenceImpl(QName name, + ServiceInterface serviceInterface, + DomainImpl domain, + ExchangeHandler handler, + ServiceMetadata metadata) { + + _name = name; + _interface = serviceInterface; + _handler = handler; + _domain = domain; + _targetServiceName = name; + _metadata = metadata != null ? metadata : ServiceMetadataBuilder.create().build(); + _securityContextManager = new SecurityContextManager(_domain); + } + + @Override + public Exchange createExchange() { + return createExchange(_handler); + } + @Override + public Exchange createExchange(ExchangeHandler handler) { + Set operations = _interface.getOperations(); + if (operations.size() == 0) { + throw RuntimeMessages.MESSAGES.noOperationsInInterfaceForService(_name.toString()); + } else if (operations.size() > 1) { + throw RuntimeMessages.MESSAGES.operationNameRequiredMultipleOps(_name.toString()); + } + + return createExchange(operations.iterator().next().getName(), handler); + } + + @Override + public Exchange createExchange(String operation) { + return createExchange(operation, _handler); + } + + @Override + public Exchange createExchange(String operation, ExchangeHandler handler) { + ServiceOperation op = _interface.getOperation(operation); + if (op == null) { + // try for a default operation + if (ServiceInterface.DEFAULT_TYPE.equals(_interface.getType())) { + op = _interface.getOperations().iterator().next(); + } else { + throw RuntimeMessages.MESSAGES.operationDoesNotExistForService(operation, + _name.toString()); + } + } + + Exchange ex = _dispatcher.createExchange(handler, op.getExchangePattern()); + ex.consumer(this, op); + + // propagate the security context + _securityContextManager.propagateContext(ex); + + for (Policy policy : _metadata.getRequiredPolicies()) { + PolicyUtil.require(ex, policy); + } + for (Policy policy : _metadata.getProvidedPolicies()) { + PolicyUtil.provide(ex, policy); + } + return ex; + } + + @Override + public ServiceInterface getInterface() { + return _interface; + } + + @Override + public QName getName() { + return _name; + } + + @Override + public void unregister() { + _domain.getServiceRegistry().unregisterServiceReference(this); + _domain.getEventPublisher().publish(new ReferenceUnregistrationEvent(this)); + } + + /** + * Specifies the exchange handler to use to process reply messages and faults. + * @param handler exchange handler + * @return this ServiceReference instance + */ + public ServiceReferenceImpl setHandler(ExchangeHandler handler) { + _handler = handler; + return this; + } + + /** + * The domain in which this service reference is registered. + * @return service domain which created this service reference + */ + @Override + public ServiceDomain getDomain() { + return _domain; + } + + /** + * Specifies the exchange bus dispatcher to use for this reference. + * @param dispatcher the exchange dispatcher + * @return this ServiceReference instance + */ + public ServiceReferenceImpl setDispatcher(Dispatcher dispatcher) { + _dispatcher = dispatcher; + return this; + } + + @Override + public void wire(QName serviceName) { + _targetServiceName = serviceName; + } + + @Override + public QName getTargetServiceName() { + return _targetServiceName; + } + + + @Override + public ServiceMetadata getServiceMetadata() { + return _metadata; + } + + @Override + public String toString() { + return "ServiceReference [name=" + _name + ", interface=" + _interface + ", domain=" + _domain + "]"; + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/transform/BaseTransformResolver.java b/core/runtime/src/main/java/org/switchyard/internal/transform/BaseTransformResolver.java new file mode 100644 index 000000000..82f3af7ec --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/transform/BaseTransformResolver.java @@ -0,0 +1,131 @@ +package org.switchyard.internal.transform; + +import java.util.LinkedList; + +import javax.xml.namespace.QName; + +import org.switchyard.transform.TransformResolver; +import org.switchyard.transform.TransformSequence; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; + +/** + * Base implementation of the TransformResolver strategy that facilitates resolving of + * direct/indirect transform sequences. + */ +public class BaseTransformResolver implements TransformResolver { + + /** + * The maximum number of edges to travel in the graph to connect two nodes. + */ + public static final int DEFAULT_HOPS = 2; + + private int _hops = DEFAULT_HOPS; + private TransformerRegistry _registry; + + /** + * Create a new TransformResolver instance. + */ + public BaseTransformResolver() { + + } + + /** + * Create a new transform resolver that will traverse the graph the specified distance + * when searching for transform sequences. + * @param numHops max number of edges to travel when searching for a sequence + */ + public BaseTransformResolver(int numHops) { + _hops = numHops; + } + + /** + * Create a new TransformResolver instance and associate it with a TransformRegistry. + * @param registry registry to use when searching for a transform path + */ + public BaseTransformResolver(TransformerRegistry registry) { + _registry = registry; + } + + /** + * Create a new TransformResolver instance and associate it with a TransformRegistry. + * @param registry set of transformers to add to registry + * @param numHops max number of edges to travel when searching for a sequence + */ + public BaseTransformResolver(TransformerRegistry registry, int numHops) { + _registry = registry; + _hops = numHops; + } + + + @Override + public TransformSequence resolveSequence(QName from, QName to) { + // if either one of these is null then there's no chance a sequence will be found + if (from == null || to == null) { + return null; + } + + // if there's a direct hit, set that and bail + if (_registry.hasTransformer(from, to)) { + return TransformSequence.from(from).to(to); + } + + TransformSequence transformSequence = null; + LinkedList path = new LinkedList(); + + // walk the graph to see if we can resolve the path + if (resolvePath(path, from, to, _hops)) { + transformSequence = TransformSequence.from(from); + for (QName type : path) { + transformSequence.to(type); + } + } + return transformSequence; + } + + /** + * Get the associated TransformerRegistry. + * @return TransformerRegistry. + */ + public TransformerRegistry getRegistry() { + return _registry; + } + + /** + * Sets the TransformerRegistry instance. + * @param registry transformer registry + */ + public void setRegistry(TransformerRegistry registry) { + this._registry = registry; + } + + /** + * Recursive depth-first(ish) search for connected types in the transform registry. There + * is no path weighting applied, so the first connection wins. There is no logic to detect + * cycles since the limit parameter prevents infinite loops. + */ + @SuppressWarnings("rawtypes") + boolean resolvePath(LinkedList path, QName fromType, QName toType, int limit) { + // check search limit + if (limit < 0) { + return false; + } + --limit; + + // have we arrived at our destination? + if (fromType.equals(toType)) { + return true; + } + + // go fish + for (Transformer fromT : _registry.getTransformersFrom(fromType)) { + if (resolvePath(path, fromT.getTo(), toType, limit)) { + path.addFirst(fromT.getTo()); + return true; + } + } + + return false; + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/transform/BaseTransformerRegistry.java b/core/runtime/src/main/java/org/switchyard/internal/transform/BaseTransformerRegistry.java new file mode 100644 index 000000000..bedb606df --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/transform/BaseTransformerRegistry.java @@ -0,0 +1,406 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal.transform; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.EventObject; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.event.EventPublisher; +import org.switchyard.event.TransformerAddedEvent; +import org.switchyard.event.TransformerRemovedEvent; +import org.switchyard.transform.TransformResolver; +import org.switchyard.transform.TransformSequence; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; + +/** + * Maintains a local collection of transformation instances and provides + * facilities to add, query, and remove transforms. + */ +public class BaseTransformerRegistry implements TransformerRegistry { + + private static Logger _log = Logger.getLogger(BaseTransformerRegistry.class); + + /** + * Default hash code. + */ + private static final int DEFAULT_HASHCODE = 32; + + private final ConcurrentHashMap> _transformers = + new ConcurrentHashMap>(); + private final ConcurrentHashMap> _fallbackTransformers = + new ConcurrentHashMap>(); + + private EventPublisher _eventPublisher; + private TransformResolver _transformResolver = new BaseTransformResolver(this); + + /** + * Constructor. + */ + public BaseTransformerRegistry() { + } + + /** + * Create a new TransformRegistry instance and add the list of transformers + * to the registry. + * @param transformers set of transformers to add to registry + */ + public BaseTransformerRegistry(Set> transformers) { + for (Transformer t : transformers) { + addTransformer(t); + } + } + + @Override + public BaseTransformerRegistry addTransformer(Transformer transformer) { + _fallbackTransformers.clear(); + _transformers.put(new NameKey(transformer.getFrom(), + transformer.getTo()), transformer); + publishEvent(new TransformerAddedEvent(transformer)); + return this; + } + + @Override + public TransformerRegistry addTransformer(Transformer transformer, QName from, QName to) { + _fallbackTransformers.clear(); + _transformers.put(new NameKey(from, to), transformer); + publishEvent(new TransformerAddedEvent(transformer)); + return null; + } + + /** + * Sets the EventPublisher instance to be used for transformer events. + * @param eventPublisher event publisher + */ + public void setEventPublisher(EventPublisher eventPublisher) { + _eventPublisher = eventPublisher; + } + + @Override + public Transformer getTransformer(QName from, QName to) { + NameKey nameKey = new NameKey(from, to); + Transformer transformer = _transformers.get(nameKey); + + if (transformer == null) { + transformer = _fallbackTransformers.get(nameKey); + if (transformer == null && QNameUtil.isJavaMessageType(from)) { + transformer = getJavaFallbackTransformer(from, to); + if (transformer != null && _log.isDebugEnabled()) { + _log.debug("Selecting fallback transformer: from '" + transformer.getFrom() + "' to '" + transformer.getTo() + "'. Type: " + transformer.getClass().getName()); + } else if (_log.isDebugEnabled()) { + _log.debug("No compatible transformer registered: from '" + from + "' to '" + to + "'"); + } + } + } else if (_log.isDebugEnabled()) { + _log.debug("Selecting transformer: from '" + transformer.getFrom() + "' to '" + transformer.getTo() + "'. Type: " + transformer.getClass().getName()); + } + + return transformer == NULL_TRANSFORMER ? null : transformer; + } + + @Override + public TransformSequence getTransformSequence(QName from, QName to) { + return _transformResolver.resolveSequence(from, to); + } + + @Override + public boolean hasTransformer(QName from, QName to) { + NameKey nameKey = new NameKey(from, to); + return _transformers.containsKey(nameKey); + } + + private Transformer getJavaFallbackTransformer(QName from, QName to) { + Class javaType = QNameUtil.toJavaMessageType(from); + + if (javaType == null) { + return null; + } + + Set>> entrySet = _transformers.entrySet(); + List fallbackTransforms = new ArrayList(); + for (Map.Entry> entry : entrySet) { + NameKey nameKey = entry.getKey(); + + // "to" must be an exact match... + if (nameKey.getTo().equals(to)) { + if (QNameUtil.isJavaMessageType(nameKey.getFrom())) { + Class candidateType = QNameUtil.toJavaMessageType(nameKey.getFrom()); + if (candidateType != null && candidateType.isAssignableFrom(javaType)) { + fallbackTransforms.add(new JavaSourceFallbackTransformer(candidateType, entry.getValue())); + } + } + } + } + if (fallbackTransforms.size() == 0) { + addFallbackTransformer(NULL_TRANSFORMER, from, to); + return NULL_TRANSFORMER; + } + + if (fallbackTransforms.size() == 1) { + Transformer fallbackTransformer = fallbackTransforms.get(0).getTransformer(); + addFallbackTransformer(fallbackTransformer, from, to); + return fallbackTransformer; + } + + JavaSourceFallbackTransformerComparator comparator = new JavaSourceFallbackTransformerComparator(); + Collections.sort(fallbackTransforms, comparator); + + if (_log.isDebugEnabled()) { + StringBuilder messageBuilder = new StringBuilder(); + + + messageBuilder.append(RuntimeMessages.MESSAGES.multipleFallbackRegistry()); + for (JavaSourceFallbackTransformer t : fallbackTransforms) { + messageBuilder.append("\n\t- from '" + t.getTransformer().getFrom() + "' to '" + t.getTransformer().getTo() + "'"); + } + _log.debug(messageBuilder.toString()); + } + + // Closest super-type will be first in the list.. + Transformer fallbackTransformer = fallbackTransforms.get(0).getTransformer(); + addFallbackTransformer(fallbackTransformer, from, to); + return fallbackTransformer; + } + + private void addFallbackTransformer(Transformer fallbackTransformer, QName from, QName to) { + // Fallback transformers are cached so as to save on lookup times... + _fallbackTransformers.put(new NameKey(from, to), fallbackTransformer); + } + + @Override + public boolean removeTransformer(Transformer transformer) { + _fallbackTransformers.clear(); + boolean removed = _transformers.remove( + new NameKey(transformer.getFrom(), transformer.getTo())) != null; + if (removed) { + publishEvent(new TransformerRemovedEvent(transformer)); + } + + return removed; + } + + @Override + public List> getRegisteredTransformers() { + return new ArrayList>(_transformers.values()); + } + + @Override + public List> getTransformersFrom(QName type) { + List> transforms = new LinkedList>(); + + for (NameKey key : _transformers.keySet()) { + if (key.getFrom() != null && key.getFrom().equals(type)) { + transforms.add(_transformers.get(key)); + } + } + + return transforms; + } + + @Override + public List> getTransformersTo(QName type) { + List> transforms = new LinkedList>(); + + for (NameKey key : _transformers.keySet()) { + if (key.getTo() != null && key.getTo().equals(type)) { + transforms.add(_transformers.get(key)); + } + } + + return transforms; + } + + @Override + public void setTransfomResolver(TransformResolver resolver) { + this._transformResolver = resolver; + } + + // Convenience method to guard against cases when an event publisher has + // not been set. + private void publishEvent(EventObject event) { + if (_eventPublisher != null) { + _eventPublisher.publish(event); + } + } + + private class NameKey extends Key { + NameKey(QName from, QName to) { + super(from, to); + } + } + + private class Key { + private final F _from; + private final T _to; + + Key(F from, T to) { + _from = from; + _to = to; + } + + public F getFrom() { + return _from; + } + + public T getTo() { + return _to; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || !Key.class.isAssignableFrom(obj.getClass())) { + return false; + } + return isEqual(_from, ((Key) obj).getFrom()) + && isEqual(_to, ((Key) obj).getTo()); + } + + @Override + public int hashCode() { + return (_from != null ? _from.hashCode() : (DEFAULT_HASHCODE - 1)) + + (_to != null ? _to.hashCode() : DEFAULT_HASHCODE); + } + + @Override + public String toString() { + return _from + "::" + _to; + } + + // handy method for comparing field refs for equality + private boolean isEqual(Object a, Object b) { + return a == null ? b == null : a.equals(b); + } + } + + /** + * Holder type for Fallback Transformer. + */ + public static class JavaSourceFallbackTransformer { + + private Class _javaType; + private Transformer _transformer; + + /** + * Constructor. + * @param javaType Java type. + * @param transformer Transformer instance. + */ + public JavaSourceFallbackTransformer(Class javaType, Transformer transformer) { + this._javaType = javaType; + this._transformer = transformer; + } + + /** + * Get the Java type. + * @return The Java type. + */ + public Class getJavaType() { + return _javaType; + } + + /** + * Get the Transformer. + * @return The Transformer. + */ + public Transformer getTransformer() { + return _transformer; + } + } + + /** + * Fallback Transformer Sorter. + * @param JavaSourceFallbackTransformer. + */ + @SuppressWarnings("serial") + public static class JavaSourceFallbackTransformerComparator implements Comparator, Serializable { + @Override + public int compare(T t1, T t2) { + if (t1.getJavaType() == t2.getJavaType()) { + return 0; + } else if (t1.getJavaType().isAssignableFrom(t2.getJavaType())) { + return 1; + } else if (t2.getJavaType().isAssignableFrom(t1.getJavaType())) { + return -1; + } else { + // Unrelated types. This means there are branches in the inheritance options, + // which means there are multiple possibilities, therefore it's not uniquely resolvable. + // Marking as equal for now... + return 0; + } + } + } + + + /** + * NULL_TRANSFORMER is a default validator used to prevent searching for + * fallback validators multiple times. Searching for fallback validators is + * expensive because of Class.forName() usage. + */ + private static final Transformer NULL_TRANSFORMER = new Transformer() { + + @Override + public Object transform(Object from) { + return null; + } + + @Override + public Transformer setFrom(QName fromType) { + return null; + } + + @Override + public QName getFrom() { + return null; + } + + @Override + public Transformer setTo(QName toType) { + return null; + } + + @Override + public QName getTo() { + return null; + } + + @Override + public Class getFromType() { + return null; + } + + @Override + public Class getToType() { + return null; + } + + }; + +} diff --git a/core/runtime/src/main/java/org/switchyard/internal/validate/BaseValidatorRegistry.java b/core/runtime/src/main/java/org/switchyard/internal/validate/BaseValidatorRegistry.java new file mode 100644 index 000000000..d8d8c0a17 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/internal/validate/BaseValidatorRegistry.java @@ -0,0 +1,281 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal.validate; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.EventObject; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.event.EventPublisher; +import org.switchyard.event.ValidatorAddedEvent; +import org.switchyard.event.ValidatorRemovedEvent; +import org.switchyard.runtime.RuntimeMessages; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.Validator; +import org.switchyard.validate.ValidatorRegistry; + +/** + * Maintains a local collection of validation instances and provides + * facilities to add, query, and remove validates. + */ +public class BaseValidatorRegistry implements ValidatorRegistry { + + private static Logger _log = Logger.getLogger(BaseValidatorRegistry.class); + + private final ConcurrentHashMap> _validators = + new ConcurrentHashMap>(); + private final ConcurrentHashMap> _fallbackValidators = + new ConcurrentHashMap>(); + + private EventPublisher _eventPublisher; + + /** + * Constructor. + */ + public BaseValidatorRegistry() { + } + + /** + * Create a new ValidatorRegistry instance and add the list of validators + * to the registry. + * @param validators set of validators to add to registry + */ + public BaseValidatorRegistry(Set> validators) { + for (Validator t : validators) { + addValidator(t); + } + } + + @Override + public BaseValidatorRegistry addValidator(Validator validator) { + _fallbackValidators.clear(); + _validators.put(validator.getName(), validator); + publishEvent(new ValidatorAddedEvent(validator)); + return this; + } + + @Override + public ValidatorRegistry addValidator(Validator validator, QName name) { + _fallbackValidators.clear(); + _validators.put(name, validator); + publishEvent(new ValidatorAddedEvent(validator)); + return null; + } + + @Override + public Validator getValidator(QName name) { + Validator validator = _validators.get(name); + + if (validator == null) { + validator = _fallbackValidators.get(name); + if (validator == null && QNameUtil.isJavaMessageType(name)) { + validator = getJavaFallbackValidator(name); + if (validator != null && _log.isDebugEnabled()) { + _log.debug("Selecting fallback validator: name '" + validator.getName() + "'. Type: " + validator.getClass().getName()); + } else if (_log.isDebugEnabled()) { + _log.debug("No compatible validator registered: name '" + name + "'"); + } + } + } else if (_log.isDebugEnabled()) { + _log.debug("Selecting validator: name '" + validator.getName() + "'. Type: " + validator.getClass().getName()); + } + + return validator == NULL_VALIDATOR ? null : validator; + } + + @Override + public boolean hasValidator(QName name) { + return _validators.containsKey(name); + } + + @Override + public boolean removeValidator(Validator validator) { + _fallbackValidators.clear(); + boolean removed = _validators.remove(validator.getName()) != null; + if (removed) { + publishEvent(new ValidatorRemovedEvent(validator)); + } + + return removed; + } + + /** + * Sets the EventPublisher instance to be used for validator events. + * @param eventPublisher event publisher + */ + public void setEventPublisher(EventPublisher eventPublisher) { + _eventPublisher = eventPublisher; + } + + // Convenience method to guard against cases when an event publisher has + // not been set. + private void publishEvent(EventObject event) { + if (_eventPublisher != null) { + _eventPublisher.publish(event); + } + } + + private Validator getJavaFallbackValidator(QName name) { + Class javaType = QNameUtil.toJavaMessageType(name); + + if (javaType == null) { + return null; + } + + Set>> entrySet = _validators.entrySet(); + List fallbackValidates = new ArrayList(); + for (Map.Entry> entry : entrySet) { + QName nameKey = entry.getKey(); + + if (QNameUtil.isJavaMessageType(nameKey)) { + Class candidateType = QNameUtil.toJavaMessageType(nameKey); + if (candidateType != null && candidateType.isAssignableFrom(javaType)) { + fallbackValidates.add(new JavaSourceFallbackValidator(candidateType, entry.getValue())); + } + } + } + + if (fallbackValidates.size() == 0) { + addFallbackValidator(NULL_VALIDATOR, name); + return NULL_VALIDATOR; + } + if (fallbackValidates.size() == 1) { + Validator fallbackValidator = fallbackValidates.get(0).getValidator(); + addFallbackValidator(fallbackValidator, name); + return fallbackValidator; + } + + JavaSourceFallbackValidatorComparator comparator = new JavaSourceFallbackValidatorComparator(); + Collections.sort(fallbackValidates, comparator); + + if (_log.isDebugEnabled()) { + StringBuilder messageBuilder = new StringBuilder(); + + messageBuilder.append(RuntimeMessages.MESSAGES.multipleFallbackValidatorsAvailable()); + for (JavaSourceFallbackValidator t : fallbackValidates) { + messageBuilder.append("\n\t- name '" + t.getValidator().getName() + "'"); + } + _log.debug(messageBuilder.toString()); + } + + // Closest super-type will be first in the list.. + Validator fallbackValidator = fallbackValidates.get(0).getValidator(); + addFallbackValidator(fallbackValidator, name); + return fallbackValidator; + } + + private void addFallbackValidator(Validator fallbackValidator, QName name) { + // Fallback validators are cached so as to save on lookup times... + _fallbackValidators.put(name, fallbackValidator); + } + + /** + * Holder type for Fallback Validator. + */ + public static class JavaSourceFallbackValidator { + + private Class _javaType; + private Validator _validator; + + /** + * Constructor. + * @param javaType Java type. + * @param validator Validator instance. + */ + public JavaSourceFallbackValidator(Class javaType, Validator validator) { + this._javaType = javaType; + this._validator = validator; + } + + /** + * Get the Java type. + * @return The Java type. + */ + public Class getJavaType() { + return _javaType; + } + + /** + * Get the Validator. + * @return The Validator. + */ + public Validator getValidator() { + return _validator; + } + } + + /** + * Fallback Validator Sorter. + * @param JavaSourceFallbackValidator. + */ + @SuppressWarnings("serial") + public static class JavaSourceFallbackValidatorComparator implements Comparator, Serializable { + @Override + public int compare(T t1, T t2) { + if (t1.getJavaType() == t2.getJavaType()) { + return 0; + } else if (t1.getJavaType().isAssignableFrom(t2.getJavaType())) { + return 1; + } else if (t2.getJavaType().isAssignableFrom(t1.getJavaType())) { + return -1; + } else { + // Unrelated types. This means there are branches in the inheritance options, + // which means there are multiple possibilities, therefore it's not uniquely resolvable. + // Marking as equal for now... + return 0; + } + } + } + + /** + * NULL_VALIDATOR is a default validator used to prevent searching for + * fallback validators multiple times. Searching for fallback validators is + * expensive because of Class.forName() usage. + */ + private static final Validator NULL_VALIDATOR = new Validator() { + + @Override + public ValidationResult validate(Object content) { + return null; + } + + @Override + public Validator setName(QName name) { + return null; + } + + @Override + public QName getName() { + return null; + } + + @Override + public Class getType() { + return null; + } + + }; + +} diff --git a/core/runtime/src/main/java/org/switchyard/runtime/RuntimeLogger.java b/core/runtime/src/main/java/org/switchyard/runtime/RuntimeLogger.java new file mode 100644 index 000000000..0c1f2e857 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/runtime/RuntimeLogger.java @@ -0,0 +1,68 @@ +package org.switchyard.runtime; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.WARN; + +import javax.transaction.SystemException; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +/** + *

+ * This file is using the subset 13800-13999 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface RuntimeLogger { + /** + * Default runtime logger. + */ + RuntimeLogger ROOT_LOGGER = Logger.getMessageLogger(RuntimeLogger.class, RuntimeLogger.class.getPackage().getName()); + + /** + * failedToSuspendTransactionOnExchange method definition. + * @param se se + */ + @LogMessage(level = ERROR) + @Message(id = 13800, value = "Failed to suspend transaction on exchange.") + void failedToSuspendTransactionOnExchange(@Cause SystemException se); + + /** + * failedToResumeTransaction method definition. + * @param e e + */ + @LogMessage(level = ERROR) + @Message(id = 13801, value = "Failed to resume transaction after service invocation.") + void failedToResumeTransaction(@Cause Exception e); + + /** + * validatorFailed method definition. + * @param validatorClassName validatorClassName + * @param detail detail + */ + @LogMessage(level = WARN) + @Message(id = 13802, value = "Validator %s failed: %s") + void validatorFailed(String validatorClassName, String detail); + + /** + * faultGeneratedDuringExchange method definition. + * @param faultContent faultContent + */ + @LogMessage(level = WARN) + @Message(id = 13803, value = "Fault generated during exchange without a handler: %s") + void faultGeneratedDuringExchange(String faultContent); + + /** + * handlerFailedHandleFault method definition. + * @param refName refName + * @param e e + */ + @LogMessage(level = WARN) + @Message(id = 13804, value = "Handler '%s' failed to handle fault.") + void handlerFailedHandleFault(String refName, @Cause Exception e); + +} diff --git a/core/runtime/src/main/java/org/switchyard/runtime/RuntimeMessages.java b/core/runtime/src/main/java/org/switchyard/runtime/RuntimeMessages.java new file mode 100644 index 000000000..5b337d8a1 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/runtime/RuntimeMessages.java @@ -0,0 +1,329 @@ +package org.switchyard.runtime; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.HandlerException; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 14000-14199 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface RuntimeMessages { + /** + * Default messages. + */ + RuntimeMessages MESSAGES = Messages.getBundle(RuntimeMessages.class); + + /** + * validatorFailed method definition. + * @param validatorName validatorName + * @param detail detail + * @return HandlerException + */ + @Message(id = 14000, value = "Validator '%s' failed: %s") + HandlerException validatorFailed(String validatorName, String detail); + + /** + * failedToCompleteTransaction method definition. + * @param e e + * @return HandlerException + */ + @Message(id = 14001, value = "TransactionHandler failed to complete a transaction") + HandlerException failedToCompleteTransaction(@Cause Exception e); + + /** + * invalidTransactionPolicy method definition. + * @param policyOne policyOne + * @param policyTwo policyTwo + * @return HandlerException + */ + @Message(id = 14002, value = "Invalid transaction policy : %s and %s cannot be requested simultaneously.") + HandlerException invalidTransactionPolicy(String policyOne, String policyTwo); + + /** + * invalidTransactionPolicyCombo method definition. + * @param policyOne policyOne + * @param policyTwo policyTwo + * @param policyThree policyThree + * @return HandlerException + */ + @Message(id = 14003, value = "Invalid transaction policy : %s cannot be requested with %s nor %s") + HandlerException invalidTransactionPolicyCombo(String policyOne, String policyTwo, String policyThree); + + /** + * invalidTransactionStatus method definition. + * @param policy policy + * @return HandlerException + */ + @Message(id = 14004, value = "Invalid transaction status : %s is required but the transaction doesn't exist") + HandlerException invalidTransactionStatus(String policy); + + /** + * failedCreateNewTransaction method definition. + * @param e e + * @return HandlerException + */ + @Message(id = 14005, value = "Failed to create new transaction") + HandlerException failedCreateNewTransaction(@Cause Exception e); + + /** + * transactionAlreadyExists method definition. + * @return HandlerException + */ + @Message(id = 14006, value = "Transaction already exists") + HandlerException transactionAlreadyExists(); + + /** + * failedToRollbackTransaction method definition. + * @param e e + * @return HandlerException + */ + @Message(id = 14007, value = "Failed to rollback transaction") + HandlerException failedToRollbackTransaction(@Cause Exception e); + + /** + * failedToCommitTransaction method definition. + * @param e e + * @return HandlerException + */ + @Message(id = 14008, value = "Failed to commit transaction") + HandlerException failedToCommitTransaction(@Cause Exception e); + + /** + * failedToCompleteWithStatus method definition. + * @param status status + * @return HandlerException + */ + @Message(id = 14009, value = "Failed to complete transaction due to invalid status - code=%d: " + + "see javax.transaction.Status.") + HandlerException failedToCompleteWithStatus(int status); + + /** + * failedToRetrieveStatus method definition. + * @param e e + * @return HandlerException + */ + @Message(id = 14010, value = "Failed to retrieve transaction status") + HandlerException failedToRetrieveStatus(@Cause Exception e); + + /** + * transformationsNotApplied method definition. + * @param expectedPayload expectedPayload + * @param actualPayload actualPayload + * @return HandlerException + */ + @Message(id = 14011, value = "Transformations not applied. Required payload type of '%s'. " + + "Actual payload type is '%s'. You must define and register a Transformer to transform " + + "between these types.") + HandlerException transformationsNotApplied(String expectedPayload, String actualPayload); + + /** + * noRegisteredService method definition. + * @param serviceName serviceName + * @return SwitchYardException + */ + @Message(id = 14012, value = "No registered service found for %s") + SwitchYardException noRegisteredService(String serviceName); + + /** + * operationNotIncluded method definition. + * @param operationName operationName + * @param serviceName serviceName + * @return HandlerException + */ + @Message(id = 14013, value = "Operation %s is not included in interface for service: %s") + HandlerException operationNotIncluded(String operationName, String serviceName); + + /** + * requiredPolicesNeeded method definition. + * @param requires requires + * @return HandlerException + */ + @Message(id = 14014, value = "Required policies have not been provided: %s") + HandlerException requiredPolicesNeeded(String requires); + + /** + * multipleFallbackValidatorsAvailable method definition. + * @return String + */ + @Message(id = 14015, value = "Multiple possible fallback validators available:") + String multipleFallbackValidatorsAvailable(); + + /** + * multipleFallbackRegistry method definition. + * @return String + */ + @Message(id = 14016, value = "Multiple possible fallback transformers available:") + String multipleFallbackRegistry(); + + /** + * sendFaultNotAllowed method definition. + * @return IllegalStateException + */ + @Message(id = 14017, value = "Send fault not allowed on new exchanges") + IllegalStateException sendFaultNotAllowed(); + + /** + * sendMessageNotAllowed method definition. + * @param phase phase + * @return IllegalStateException + */ + @Message(id = 14018, value = "Send message not allowed for exchange in phase %s") + IllegalStateException sendMessageNotAllowed(String phase); + + /** + * invalidMessageArgument method definition. + * @return IllegalArgumentException + */ + @Message(id = 14019, value = "Invalid null 'message' argument in method call.") + IllegalArgumentException invalidMessageArgument(); + + /** + * exchangeInFaultState method definition. + * @return IllegalStateException + */ + @Message(id = 14020, value = "Exchange instance is in a FAULT state.") + IllegalStateException exchangeInFaultState(); + + /** + * cannotChangeMetaDataAfterMessageSent method definition. + * @return IllegalStateException + */ + @Message(id = 14021, value = "Cannot change consumer metadata after message has been sent on exchange.") + IllegalStateException cannotChangeMetaDataAfterMessageSent(); + + /** + * invalidConsumerContract method definition. + * @return SwitchYardException + */ + @Message(id = 14022, value = "Invalid consumer contract - IN_OUT exchanges require a reply handler.") + SwitchYardException invalidConsumerContract(); + + /** + * cannotChangeMetadataAfterInvoke method definition. + * @return IllegalStateException + */ + @Message(id = 14023, value = "Cannot change provider metadata after provider has been invoked!") + IllegalStateException cannotChangeMetadataAfterInvoke(); + + /** + * nullTypeArgument method definition. + * @return IllegalArgumentException + */ + @Message(id = 14024, value = "Null 'type' argument.") + IllegalArgumentException nullTypeArgument(); + + /** + * noTransformRegistryAvailable method definition. + * @param className className + * @param typeName typeName + * @return SwitchYardException + */ + @Message(id = 14025, value = "Cannot convert from '%s' to '%s'. No TransformRegistry available.") + SwitchYardException noTransformRegistryAvailable(String className, String typeName); + + /** + * noRegisteredTransformer method definition. + * @param className className + * @param typeName typeName + * @param fromType fromType + * @param toType toType + * @return SwitchYardException + */ + @Message(id = 14026, value = "Cannot convert from '%s' to '%s'. No registered Transformer available " + + "for transforming from '%s' to '%s'. A Transformer must be registered.") + SwitchYardException noRegisteredTransformer(String className, String typeName, String fromType, String toType); + + /** + * transformerReturnedNull method definition. + * @param contentClassName contentClassName + * @param typeName typeName + * @param transformerClassName transformerClassName + * @return SwitchYardException + */ + @Message(id = 14027, value = "Error converting from '%s' to '%s'. Transformer '%s' returned null.") + SwitchYardException transformerReturnedNull(String contentClassName, String typeName, String transformerClassName); + + /** + * transformerReturnedIncompatibleType method definition. + * @param contentClassName contentClassName + * @param typeName typeName + * @param transformerClassName transformerClassName + * @param returnedTypeName returnedTypeName + * @return SwitchYardException + */ + @Message(id = 14028, value = "Error converting from '%s' to '%s'. Transformer '%s' returned incompatible type '%s'.") + SwitchYardException transformerReturnedIncompatibleType(String contentClassName, String typeName, + String transformerClassName, String returnedTypeName); + + /** + * propertyNameAndScopeCannotBeNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 14029, value = "Property name and scope must not be null!") + IllegalArgumentException propertyNameAndScopeCannotBeNull(); + + /** + * noOperationsInInterfaceForService method definition. + * @param serviceName serviceName + * @return SwitchYardException + */ + @Message(id = 14030, value = "No operations in interface for service: %s") + SwitchYardException noOperationsInInterfaceForService(String serviceName); + + /** + * operationNameRequiredMultipleOps method definition. + * @param serviceName serviceName + * @return SwitchYardException + */ + @Message(id = 14031, value = "Operation name required - " + + "multiple operations on service interface: %s") + SwitchYardException operationNameRequiredMultipleOps(String serviceName); + + /** + * operationDoesNotExistForService method definition. + * @param operationName operationName + * @param serviceName serviceName + * @return SwitchYardException + */ + @Message(id = 14032, value = "Operation %s does not exist for service %s") + SwitchYardException operationDoesNotExistForService(String operationName, String serviceName); + + /** + * invalidPhaseForDispatch method definition. + * @param phaseName phaseName + * @return IllegalStateException + */ + @Message(id = 14033, value = "Invalid phase for dispatch: %s") + IllegalStateException invalidPhaseForDispatch(String phaseName); + + /** + * onlyDefaultMessageInstances method definition. + * @return IllegalStateException + */ + @Message(id = 14034, value = "This exchange may handle only DefaultMessage instances.") + IllegalStateException onlyDefaultMessageInstances(); + + /** + * messageOnlySentOnce method definition. + * @return IllegalStateException + */ + @Message(id = 14035, value = "Message may be sent only once. Use Message.copy() to re-send same payload.") + IllegalStateException messageOnlySentOnce(); + + /** + * scopeDifferent method definition. + * @param scope scope + * @param source source + * @return IllegalStateException + */ + @Message(id = 14037, value = "Scope %s is different than expected %s") + IllegalArgumentException scopeDifferent(String scope, String source); + +} diff --git a/core/runtime/src/main/java/org/switchyard/runtime/event/ExchangeCompletionEvent.java b/core/runtime/src/main/java/org/switchyard/runtime/event/ExchangeCompletionEvent.java new file mode 100644 index 000000000..f0572aa90 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/runtime/event/ExchangeCompletionEvent.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.runtime.event; + +import java.util.EventObject; + +import org.switchyard.Exchange; + +/** + * Fired when an exchange has completed. For InOnly exchanges, this fires after + * the in message has been processed. For InOut exchanges, this fires after the + * out message has been sent. + */ +public class ExchangeCompletionEvent extends EventObject { + + /** + * Exchange property name used to record the duration of a completed exchange. + */ + public static final String EXCHANGE_DURATION = "org.switchyard.exchangeDurationMS"; + /** + * Exchange property name used to record the name of the gateway being + * invoked, if any. + */ + public static final String GATEWAY_NAME = "org.switchyard.exchangeGatewayName"; + + private static final long serialVersionUID = 1L; + + /** + * Create a new ExchangeCompletionEvent. + * @param exchange the exchange which has completed + */ + public ExchangeCompletionEvent(Exchange exchange) { + super(exchange); + } + + /** + * Gets the completed exchange. + * @return the completed exchange + */ + public Exchange getExchange() { + return (Exchange)getSource(); + } +} diff --git a/core/runtime/src/main/java/org/switchyard/runtime/event/ExchangeInitiatedEvent.java b/core/runtime/src/main/java/org/switchyard/runtime/event/ExchangeInitiatedEvent.java new file mode 100644 index 000000000..bc7366cbd --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/runtime/event/ExchangeInitiatedEvent.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.runtime.event; + +import java.util.EventObject; + +import org.switchyard.Exchange; + +/** + * Fired when an exchange is containing the request is being dispatched for processing. + * For InOnly and InOut exchanges, this event fires before + * the in message has been processed. + */ +public class ExchangeInitiatedEvent extends EventObject { + /** + * Exchange property name used to timestamp the initiation of a dispatched exchange. + */ + public static final String EXCHANGE_INITIATED_TIME = "org.switchyard.exchangeInitiatedNS"; + private static final long serialVersionUID = 1L; + + /** + * Create a new ExchangeInitiatedEvent. + * @param exchange the exchange to be initiated + */ + public ExchangeInitiatedEvent(Exchange exchange) { + super(exchange); + } + + /** + * Gets the initiated exchange. + * @return the initiated exchange + */ + public Exchange getExchange() { + return (Exchange)getSource(); + } +} diff --git a/core/runtime/src/main/java/org/switchyard/runtime/util/ExchangeFormatter.java b/core/runtime/src/main/java/org/switchyard/runtime/util/ExchangeFormatter.java new file mode 100644 index 000000000..ed1fada45 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/runtime/util/ExchangeFormatter.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.runtime.util; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; +import java.util.Comparator; +import java.util.Set; +import java.util.TreeSet; + +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.common.lang.Strings; + +/** + * Implementation class that facilitates print formatting of Switchyard exchanges. + * The Exchange contents (header and body) are formatted to facilitate + * easier display/logging. + */ +public final class ExchangeFormatter { + private static final String INDENT = System.getProperty("line.separator"); + + /** + * Format contents of an incoming exchange. + * + * @param exchange Exchange instance. + * @param printBody boolean. + * + * @return String containing formatted Exchange data. + */ + public static String format(Exchange exchange, boolean printBody) { + StringBuilder summary = new StringBuilder() + .append(indent(0) + "------- Begin Message Trace -------"); + + summary.append(formatHeaders(exchange)); + if (printBody) { + summary.append(formatBody(exchange)); + } + summary.append(indent(0) + "------ End Message Trace -------"); + + return summary.toString(); + } + + private static String formatHeaders(Exchange exchange) { + StringBuilder headers = new StringBuilder() + .append(indent(0) + "Consumer -> " + exchange.getConsumer().getName()) + .append(indent(0) + "Provider -> " + ((exchange.getProvider() == null) ? "[unassigned]" : exchange.getProvider().getName())) + .append(indent(0) + "Operation -> " + exchange.getContract().getConsumerOperation().getName()) + .append(indent(0) + "MEP -> " + + ((exchange.getContract().getConsumerOperation().getExchangePattern() == null) ? "[unassigned]" : exchange.getContract().getConsumerOperation().getExchangePattern())) + .append(indent(0) + "Phase -> " + exchange.getPhase()) + .append(indent(0) + "State -> " + exchange.getState()); + + // Add context properties + headers.append(indent(0) + "Exchange Context -> "); + dumpContext(headers, exchange.getContext().getProperties(Scope.EXCHANGE)); + + headers.append(indent(0) + "Message Context -> "); + dumpContext(headers, exchange.getContext().getProperties(Scope.MESSAGE)); + + return headers.toString(); + } + + private static String formatBody(Exchange exchange) { + StringBuilder body = new StringBuilder(); + + // Add message content + String content = null; + try { + // try to convert the payload to a string + Message msg = exchange.getMessage(); + content = msg.getContent(String.class); + + // check to see if we have to put content back into the message + // after the conversion to string + if (InputStream.class.isAssignableFrom(msg.getContent().getClass())) { + msg.setContent(new ByteArrayInputStream(content.getBytes())); + } else if (Reader.class.isAssignableFrom(msg.getContent().getClass())) { + msg.setContent(new StringReader(content)); + } + } catch (Exception ex) { + // conversion failed, fall back on toString() + if (exchange.getMessage().getContent() != null) { + content = exchange.getMessage().getContent().toString(); + } + } + body.append(indent(0) + "Message Content -> ") + .append(indent(0) + content); + + return body.toString(); + } + + private static void dumpContext(StringBuilder summary, Set properties) { + Set orderedProperties = new TreeSet(new Comparator() { + public int compare(Property p1, Property p2) { + return p1.getName().compareTo(p2.getName()); + } + }); + int maxLength = 0; + for (Property property : properties) { + int curLength = property.getName().length(); + if (curLength > maxLength) { + maxLength = curLength; + } + orderedProperties.add(property); + } + for (Property orderedProperty : orderedProperties) { + String name = orderedProperty.getName(); + int difLength = maxLength - name.length(); + String pad = difLength > 0 ? Strings.repeat(".", difLength) : ""; + summary.append(indent(1) + name + " " + pad + ": " + orderedProperty.getValue()); + } + } + + private static String indent(int column) { + return INDENT + Strings.repeat(" ", column); + } + + private ExchangeFormatter() { + // noop + } + +} diff --git a/core/runtime/src/main/java/org/switchyard/runtime/util/TransactionManagerLocator.java b/core/runtime/src/main/java/org/switchyard/runtime/util/TransactionManagerLocator.java new file mode 100644 index 000000000..fc2cbb0af --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/runtime/util/TransactionManagerLocator.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.runtime.util; + +import javax.naming.InitialContext; +import javax.transaction.TransactionManager; + +import org.jboss.logging.Logger; +import org.switchyard.common.util.ProviderRegistry; + +/** + * A TransactionManagerLocator. + */ +public final class TransactionManagerLocator { + + private static final String JBOSS_JNDI_TRANSACTION_MANAGER = "java:jboss/TransactionManager"; + private static final String OSGI_JNDI_TRANSACTION_MANAGER = "osgi:service/javax.transaction.TransactionManager"; + + private static final Logger LOGGER = Logger.getLogger(TransactionManagerLocator.class); + private TransactionManagerLocator() { + } + + /** + * Lookup TransactionManager. + * @return TransactionManager + */ + public static TransactionManager locateTransactionManager() { + TransactionManager tm = ProviderRegistry.getProvider(TransactionManager.class); + if (tm != null) { + LOGGER.debug("Found a TransactionManager in ProviderRegistry"); + return tm; + } + + InitialContext ic; + try { + ic = new InitialContext(); + } catch (Exception e) { + LOGGER.debug("Failed to create InitialContext - Transaction Policy handling will not be available.", e); + return null; + } + + try { + tm = (TransactionManager) lookupInJndi(ic, JBOSS_JNDI_TRANSACTION_MANAGER); + if (tm != null) { + LOGGER.debug("Found a TransactionManager in JNDI at '" + JBOSS_JNDI_TRANSACTION_MANAGER + "'"); + return tm; + } + + tm = (TransactionManager) lookupInJndi(ic, OSGI_JNDI_TRANSACTION_MANAGER); + if (tm != null) { + LOGGER.debug("Found a TransactionManager in JNDI at '" + OSGI_JNDI_TRANSACTION_MANAGER + "'"); + return tm; + } + } finally { + try { + ic.close(); + } catch (Exception e) { + LOGGER.debug(e); + } + } + LOGGER.debug("No TransactionManager found at '" + JBOSS_JNDI_TRANSACTION_MANAGER + + "' nor '" + OSGI_JNDI_TRANSACTION_MANAGER + "'"); + return null; + } + + private static Object lookupInJndi(InitialContext ic, String name) { + try { + return ic.lookup(name); + } catch (Exception e) { + LOGGER.debug(e); + return null; + } + } +} diff --git a/core/runtime/src/main/java/org/switchyard/spi/Dispatcher.java b/core/runtime/src/main/java/org/switchyard/spi/Dispatcher.java new file mode 100644 index 000000000..f33f087c8 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/spi/Dispatcher.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.spi; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ServiceReference; + +/** + * Dispatches messages to a given service. + */ +public interface Dispatcher { + + /** + * The name of the service. + * @return service reference + */ + ServiceReference getServiceReference(); + + /** + * Creates exchange which is ment to deliver to given operation. + * + * @param handler Handler to handle reply from operation (if any returned). May be null. + * @param pattern Exchange pattern used. + * @return Exchange used to send messages. + */ + Exchange createExchange(ExchangeHandler handler, ExchangePattern pattern); + + /** + * Dispatch given exchange. + * + * @param exchange Exchange to dispatch. + */ + void dispatch(Exchange exchange); + +} diff --git a/core/runtime/src/main/java/org/switchyard/spi/ExchangeBus.java b/core/runtime/src/main/java/org/switchyard/spi/ExchangeBus.java new file mode 100644 index 000000000..5831eaf7b --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/spi/ExchangeBus.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.spi; + +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; + +/** + * An implementation-neutral representation of a message bus. The bus handles + * dispatch for message exchange between service consumer and provider. + */ +public interface ExchangeBus { + + /** + * Create an exchange dispatcher for the specified service reference. + * @param reference service reference + * @return Dispatcher service dispatch reference + */ + Dispatcher createDispatcher(ServiceReference reference); + + /** + * Retrieves a dispatcher for the specified service reference. + * @param reference target reference + * @return dispatcher for the specified service, or null if no dispatcher + * has been created + */ + Dispatcher getDispatcher(ServiceReference reference); + + /** + * Initialize the exchange bus with it's parent service domain. + * @param domain service domain in which this bus will be used + */ + void init(ServiceDomain domain); + + /** + * Start the exchange bus. + */ + void start(); + + /** + * Stop the exchange bus. + */ + void stop(); + +} diff --git a/core/runtime/src/main/java/org/switchyard/spi/ServiceRegistry.java b/core/runtime/src/main/java/org/switchyard/spi/ServiceRegistry.java new file mode 100644 index 000000000..bb0ded4a8 --- /dev/null +++ b/core/runtime/src/main/java/org/switchyard/spi/ServiceRegistry.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.spi; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.Service; +import org.switchyard.ServiceReference; + +/** + * A runtime service registry can be queried for services and references. + */ +public interface ServiceRegistry { + + /** + * Register a service. + * @param service service + * @return registered service + */ + Service registerService(Service service); + /** + * Unregister the service. + * @param service service + */ + void unregisterService(Service service); + + /** + * Register the service reference. + * @param reference service reference + */ + void registerServiceReference(ServiceReference reference); + + /** + * Unregister the service reference. + * @param reference service reference + */ + void unregisterServiceReference(ServiceReference reference); + + /** + * Return the list of services. + * @return services + */ + List getServices(); + + /** + * Get the list of services for the specified service name. + * @param serviceName service name + * @return services + */ + List getServices(QName serviceName); + + /** + * Return the list of service references. + * @return references + */ + List getServiceReferences(); + + /** + * Get a ServiceReference instance for the specified service name. + * @param serviceName service name + * @return reference to the specified service or null if a service reference is not registered. + */ + ServiceReference getServiceReference(QName serviceName); +} diff --git a/core/runtime/src/main/resources/META-INF/services/org.switchyard.spi.ExchangeBus b/core/runtime/src/main/resources/META-INF/services/org.switchyard.spi.ExchangeBus new file mode 100644 index 000000000..ae5b53a87 --- /dev/null +++ b/core/runtime/src/main/resources/META-INF/services/org.switchyard.spi.ExchangeBus @@ -0,0 +1 @@ +org.switchyard.internal.LocalExchangeBus # local exchange bus diff --git a/core/runtime/src/main/resources/META-INF/services/org.switchyard.spi.ServiceRegistry b/core/runtime/src/main/resources/META-INF/services/org.switchyard.spi.ServiceRegistry new file mode 100644 index 000000000..209e340d5 --- /dev/null +++ b/core/runtime/src/main/resources/META-INF/services/org.switchyard.spi.ServiceRegistry @@ -0,0 +1 @@ +org.switchyard.internal.DefaultServiceRegistry # default service registry diff --git a/core/runtime/src/test/java/org/switchyard/MockDomain.java b/core/runtime/src/test/java/org/switchyard/MockDomain.java new file mode 100644 index 000000000..90d7ad7f3 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/MockDomain.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import javax.xml.namespace.QName; + +import org.switchyard.internal.DomainImpl; +import org.switchyard.internal.EventManager; +import org.switchyard.internal.LocalExchangeBus; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.internal.validate.BaseValidatorRegistry; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.security.service.DefaultServiceDomainSecurity; +import org.switchyard.spi.ServiceRegistry; + +public class MockDomain extends DomainImpl { + + public static final QName DEFAULT_DOMAIN = + new QName("urn:switchyard:test", "MockDomain"); + + public MockDomain() { + super(DEFAULT_DOMAIN); + } + + public MockDomain(QName name) { + super(name); + } + + public MockDomain(ServiceRegistry registry) { + super(DEFAULT_DOMAIN, + registry, + new LocalExchangeBus(), + new BaseTransformerRegistry(), + new BaseValidatorRegistry(), + new EventManager(), + new DefaultServiceDomainSecurity()); + init(); + } + + public ServiceReference createInOnlyService(QName serviceName) { + ServiceInterface inOnly = new InOnlyService(); + registerService(serviceName, inOnly, new MockHandler()); + ServiceReference reference = registerServiceReference(serviceName, inOnly); + return reference; + } + + + public ServiceReference createInOnlyService(QName serviceName, ExchangeHandler handler) { + ServiceInterface inOnly = new InOnlyService(); + registerService(serviceName, inOnly, handler); + ServiceReference reference = registerServiceReference(serviceName, inOnly); + return reference; + } + + public ServiceReference createInOutService(QName serviceName) { + ServiceInterface inOut = new InOutService(); + registerService(serviceName, inOut, new MockHandler()); + ServiceReference reference = registerServiceReference(serviceName, inOut); + return reference; + } + + public ServiceReference createInOutService(QName serviceName, ExchangeHandler handler) { + ServiceInterface inOut = new InOutService(); + registerService(serviceName, inOut, handler); + ServiceReference reference = registerServiceReference(serviceName, inOut); + return reference; + } +} diff --git a/core/runtime/src/test/java/org/switchyard/MockExchange.java b/core/runtime/src/test/java/org/switchyard/MockExchange.java new file mode 100644 index 000000000..f7f20756e --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/MockExchange.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import org.switchyard.internal.ExchangeImpl; + +/** + * Dumb implementation of Exchange meant for unit testing. + */ +public class MockExchange extends ExchangeImpl { + + public MockExchange() { + super(new MockDomain(), null); + } + + public void setPhase(ExchangePhase phase) { + super.setPhase(phase); + } + + public void setMessage(Message message) { + super.setMessage(message); + } +} diff --git a/core/runtime/src/test/java/org/switchyard/MockHandler.java b/core/runtime/src/test/java/org/switchyard/MockHandler.java new file mode 100644 index 000000000..9f691ce07 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/MockHandler.java @@ -0,0 +1,183 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard; + +import java.util.concurrent.LinkedBlockingQueue; + +import junit.framework.TestCase; + +/** + * Mock Handler. + * + * @author tom.fennelly@gmail.com + */ +public class MockHandler extends BaseHandler { + /** + * Messages. + */ + private final LinkedBlockingQueue _messages = + new LinkedBlockingQueue(); + + /** + * Faults. + */ + private final LinkedBlockingQueue _faults = + new LinkedBlockingQueue(); + + /** + * Default sleep. + */ + private static final int DEFAULT_SLEEP_MS = 100; + /** + * Default wait timeout. + */ + private static final int DEFAULT_WAIT_TIMEOUT = 5000; + + /** + * Wait timeout value. + */ + private long _waitTimeout = DEFAULT_WAIT_TIMEOUT; // default of 5 seconds + + /** + * Forward input to output flag. + */ + private boolean _forwardInToOut = false; + /** + * Forward input to fault flag. + */ + private boolean _forwardInToFault = false; + + /** + * Constructor. + */ + public MockHandler() { + } + + /** + * @return wait timeout + */ + public long getWaitTimeout() { + return _waitTimeout; + } + + /** + * @param waitTimeout wait timeout + */ + public void setWaitTimeout(long waitTimeout) { + _waitTimeout = waitTimeout; + } + + /** + * Message getter. + * @return messages messages + */ + public LinkedBlockingQueue getMessages() { + return _messages; + } + + /** + * Fault getter. + * @return faults faults + */ + public LinkedBlockingQueue getFaults() { + return _faults; + } + + /** + * Forward input to output. + * @return MockHandler mockhandler + */ + public MockHandler forwardInToOut() { + // An enum would be nicer here !! + _forwardInToOut = true; + _forwardInToFault = false; + return this; + } + + /** + * Forward input to fault. + * @return MockHandler mockhandler + */ + public MockHandler forwardInToFault() { + // An enum would be nicer here !! + _forwardInToOut = false; + _forwardInToFault = true; + return this; + } + + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + _messages.offer(exchange); + if (_forwardInToOut) { + exchange.send(exchange.getMessage().copy()); + } else if (_forwardInToFault) { + exchange.sendFault(exchange.createMessage()); + } + } + + @Override + public void handleFault(final Exchange exchange) { + _faults.offer(exchange); + } + + /** + * Wait for a message. + * @return MockHandler mockhandler + */ + public MockHandler waitForOKMessage() { + waitFor(_messages, 1); + return this; + } + + /** + * Wait for a number of messages. + * @return MockHandler mockhandler + */ + public MockHandler waitForFaultMessage() { + waitFor(_faults, 1); + return this; + } + + /** + * Wait for a number of messages. + * @param eventQueue event queue + * @param numMessages number of messages + */ + private void waitFor(final LinkedBlockingQueue eventQueue, + final int numMessages) { + long start = System.currentTimeMillis(); + + while (System.currentTimeMillis() < start + _waitTimeout) { + if (eventQueue.size() >= numMessages) { + return; + } + sleep(); + } + + TestCase.fail("Timed out waiting on event queue length to be " + + numMessages + " or greater."); + } + + /** + * Sleep. + */ + private void sleep() { + try { + Thread.sleep(DEFAULT_SLEEP_MS); + } catch (InterruptedException e) { + TestCase.fail("Failed to sleep: " + e.getMessage()); + } + } +} diff --git a/core/runtime/src/test/java/org/switchyard/handlers/MessageTraceTest.java b/core/runtime/src/test/java/org/switchyard/handlers/MessageTraceTest.java new file mode 100644 index 000000000..78d380c7f --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/handlers/MessageTraceTest.java @@ -0,0 +1,124 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.handlers; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Exchange; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.ServiceReference; +import org.switchyard.transform.BaseTransformer; + +public class MessageTraceTest { + + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + } + + @Test + public void testInMessageTrace() { + ServiceReference service = _domain.createInOnlyService(new QName("InTrace")); + Exchange exchange = service.createExchange(); + exchange.send(exchange.createMessage()); + } + + @Test + public void testInOutMessageTrace() throws Exception { + ServiceReference service = _domain.createInOutService( + new QName("InOutTrace"), new MockHandler().forwardInToOut()); + Exchange exchange = service.createExchange(new MockHandler()); + exchange.send(exchange.createMessage()); + } + + @Test + public void testInFaultMessageTrace() throws Exception { + ServiceReference service = _domain.createInOutService( + new QName("InFaultTrace"), new MockHandler().forwardInToOut()); + Exchange exchange = service.createExchange(new MockHandler()); + exchange.send(exchange.createMessage()); + } + + @Test + public void testStreamContent() throws Exception { + String contentAsString = "abc-InputStream-xyz"; + MockHandler provider = new MockHandler(); + _domain.getTransformerRegistry().addTransformer(new StreamTransformer()); + ServiceReference service = _domain.createInOnlyService(new QName("StreamTest"), provider); + + InputStream contentAsStream = new ByteArrayInputStream(contentAsString.getBytes()); + Exchange ex = service.createExchange(); + Message msg = ex.createMessage(); + msg.setContent(contentAsStream); + ex.send(msg); + + Message rcvdMsg = provider.getMessages().poll().getMessage(); + Assert.assertTrue(rcvdMsg.getContent(InputStream.class).available() > 0); + + } + + @Test + public void testReaderContent() throws Exception { + String contentAsString = "abc-Reader-xyz"; + MockHandler provider = new MockHandler(); + _domain.getTransformerRegistry().addTransformer(new ReaderTransformer()); + ServiceReference service = _domain.createInOnlyService(new QName("ReaderTest"), provider); + + StringReader contentAsReader = new StringReader(contentAsString); + Exchange ex = service.createExchange(); + Message msg = ex.createMessage(); + msg.setContent(contentAsReader); + ex.send(msg); + + Message rcvdMsg = provider.getMessages().poll().getMessage(); + Assert.assertTrue(rcvdMsg.getContent(Reader.class).read() != -1); + } +} + +class StreamTransformer extends BaseTransformer { + public String transform(InputStream stream) { + try { + byte[] buf = new byte[500]; + int count = stream.read(buf); + return new String(buf, 0, count); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } +} + +class ReaderTransformer extends BaseTransformer { + public String transform(Reader reader) { + try { + char[] buf = new char[500]; + int count = reader.read(buf); + return new String(buf, 0, count); + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/core/runtime/src/test/java/org/switchyard/handlers/PolicyHandlerTest.java b/core/runtime/src/test/java/org/switchyard/handlers/PolicyHandlerTest.java new file mode 100644 index 000000000..34748f933 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/handlers/PolicyHandlerTest.java @@ -0,0 +1,148 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.handlers; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; +import org.switchyard.MockExchange; +import org.switchyard.policy.Policy; +import org.switchyard.policy.PolicyUtil; + +public class PolicyHandlerTest { + + private static final QName FOO_POLICY_QNAME = new QName("foo"); + private static final QName BAR_POLICY_QNAME = new QName("bar"); + + private MockExchange exchange; + private PolicyHandler handler; + + @Before + public void setUp() { + exchange = new MockExchange(); + handler = new PolicyHandler(); + } + + @Test + public void requiredButNotProvided() { + PolicyUtil.require(exchange, new FooPolicy()); + PolicyUtil.require(exchange, new BarPolicy()); + PolicyUtil.provide(exchange, new BarPolicy()); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + // expected + System.out.println(handlerEx.toString()); + return; + } + + Assert.fail("Expected a handler exception due to incompatible policy"); + } + + @Test + public void providedButNotRequired() { + // this should not be an error + PolicyUtil.provide(exchange, new FooPolicy()); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + Assert.fail("Exception not expected when policy is provided but not required: " + handlerEx); + } + } + + @Test + public void requiredAndProvided() { + PolicyUtil.require(exchange, new FooPolicy()); + PolicyUtil.provide(exchange, new FooPolicy()); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + Assert.fail("Exception not expected, required policy is provided: " + handlerEx); + } + } + + private class FooPolicy implements Policy { + @Override + public QName getQName() { + return FOO_POLICY_QNAME; + } + + @Override + public String getName() { + return getQName().getLocalPart(); + } + + @Override + public String toString() { + return getQName().toString(); + } + + @Override + public boolean supports(PolicyType type) { + return type == PolicyType.INTERACTION; + } + + @Override + public boolean isCompatibleWith(Policy target) { + return true; + } + + @Override + public Policy getPolicyDependency() { + return null; + } + } + + private class BarPolicy implements Policy { + @Override + public QName getQName() { + return BAR_POLICY_QNAME; + } + + @Override + public String getName() { + return getQName().getLocalPart(); + } + + @Override + public String toString() { + return getQName().toString(); + } + + @Override + public boolean supports(PolicyType type) { + return type == PolicyType.INTERACTION; + } + + @Override + public boolean isCompatibleWith(Policy target) { + return true; + } + + @Override + public Policy getPolicyDependency() { + return null; + } + } +} diff --git a/core/runtime/src/test/java/org/switchyard/handlers/TransactionHandlerTest.java b/core/runtime/src/test/java/org/switchyard/handlers/TransactionHandlerTest.java new file mode 100644 index 000000000..a1885b205 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/handlers/TransactionHandlerTest.java @@ -0,0 +1,535 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.handlers; + +import java.util.UUID; + +import javax.transaction.HeuristicMixedException; +import javax.transaction.HeuristicRollbackException; +import javax.transaction.InvalidTransactionException; +import javax.transaction.NotSupportedException; +import javax.transaction.RollbackException; +import javax.transaction.Status; +import javax.transaction.Synchronization; +import javax.transaction.SystemException; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; +import javax.transaction.xa.XAResource; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.ExchangePhase; +import org.switchyard.HandlerException; +import org.switchyard.MockExchange; +import org.switchyard.policy.PolicyUtil; +import org.switchyard.policy.TransactionPolicy; + +public class TransactionHandlerTest { + + private MockTransactionManager tm; + private MockExchange exchange; + private TransactionHandler handler; + + @Before + public void setUp() { + tm = new MockTransactionManager(); + exchange = new MockExchange(); + handler = new TransactionHandler(); + handler.setTransactionManager(tm); + } + + /* policy combination error */ + + @Test + public void incompatibleRequirements_PropagatesAndSuspends() { + PolicyUtil.require(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + PolicyUtil.require(exchange, TransactionPolicy.SUSPENDS_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + // expected + System.out.println(handlerEx.toString()); + return; + } + + Assert.fail("Expected a handler exception due to incompatible policy"); + } + + @Test + public void incompatibleRequirements_managedGlobalAndmanagedLocal() { + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + System.out.println(handlerEx.toString()); + return; + } + + Assert.fail("Expected a handler exception due to incompatible policy"); + } + + @Test + public void incompatibleRequirements_managedGlobalAndNoManaged() { + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + PolicyUtil.require(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + // expected + System.out.println(handlerEx.toString()); + return; + } + + Assert.fail("Expected a handler exception due to incompatible policy"); + } + + @Test + public void incompatibleRequirements_managedLocalAndNoManaged() { + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL); + PolicyUtil.require(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + // expected + System.out.println(handlerEx.toString()); + return; + } + + Assert.fail("Expected a handler exception due to incompatible policy"); + } + + @Test + public void incompatibleRequirements_PropagatesAndManagedLocal() { + PolicyUtil.require(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + // expected + System.out.println(handlerEx.toString()); + return; + } + + Assert.fail("Expected a handler exception due to incompatible policy"); + } + + @Test + public void incompatibleRequirements_PropagatesAndNoManaged() { + PolicyUtil.require(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + PolicyUtil.require(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + // expected + System.out.println(handlerEx.toString()); + return; + } + + Assert.fail("Expected a handler exception due to incompatible policy"); + } + + /* invalid transaction status */ + + @Test + public void propagatesRequiredButNoTransaction() { + PolicyUtil.require(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + // expected + System.out.println(handlerEx.toString()); + return; + } + Assert.fail("Expected a handler exception due to invalid policy"); + } + + @Test + public void propagateProvidedButNotRequired() throws Exception { + // We currently view a propagated transaction without a requirement + // as harmless. This tests confirms this behavior and acts as a guard + // in case our behavior changes. + PolicyUtil.provide(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + tm.begin(); + + try { + handler.handleMessage(exchange); + } catch (HandlerException handlerEx) { + Assert.fail("Exception not expected when transaction is provided but not required: " + + handlerEx); + } + } + + /* transaction propagation */ + + @Test + public void propagateRequiredAndProvided() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + PolicyUtil.provide(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + + tm.begin(); + Transaction tx = tm.getTransaction(); + + handler.handleMessage(exchange); + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + + Transaction tx2 = tm.getTransaction(); + Assert.assertEquals(tx, tx2); + Assert.assertEquals(Status.STATUS_ACTIVE, tx2.getStatus()); + } + + @Test + public void propagateRequiredAndProvidedWithManagedGlobalRequired() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + propagateRequiredAndProvided(); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL)); + } + + /* Creates new transaction */ + + @Test + public void propagateRequiredButNotProvidedWithManagedGlobalRequired() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + exchange.setPhase(ExchangePhase.IN); + + Assert.assertEquals(null, tm.getTransaction()); + + handler.handleMessage(exchange); + Transaction tx = tm.getTransaction(); + Assert.assertEquals(Status.STATUS_ACTIVE, tx.getStatus()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.PROPAGATES_TRANSACTION)); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL)); + + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Assert.assertEquals(Status.STATUS_COMMITTED, tx.getStatus()); + } + + @Test + public void managedLocalRequiredWithNoTransactionProvided() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL); + exchange.setPhase(ExchangePhase.IN); + + Assert.assertEquals(null, tm.getTransaction()); + + handler.handleMessage(exchange); + Transaction tx = tm.getTransaction(); + Assert.assertEquals(Status.STATUS_ACTIVE, tx.getStatus()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL)); + + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Assert.assertEquals(Status.STATUS_COMMITTED, tx.getStatus()); + } + + @Test + public void transactionRolledbackByHandler() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.PROPAGATES_TRANSACTION); + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + exchange.setPhase(ExchangePhase.IN); + + Assert.assertEquals(null, tm.getTransaction()); + + handler.handleMessage(exchange); + Transaction tx = tm.getTransaction(); + Assert.assertEquals(Status.STATUS_ACTIVE, tx.getStatus()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.PROPAGATES_TRANSACTION)); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL)); + + tx.setRollbackOnly(); + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Assert.assertEquals(Status.STATUS_ROLLEDBACK, tx.getStatus()); + } + + @Test + public void suspendAndManagedGlobalRequiredButNoTransaction() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.SUSPENDS_TRANSACTION); + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + exchange.setPhase(ExchangePhase.IN); + + handler.handleMessage(exchange); + Transaction tx2 = tm.getTransaction(); + Assert.assertEquals(Status.STATUS_ACTIVE, tx2.getStatus()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.SUSPENDS_TRANSACTION)); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL)); + + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Assert.assertEquals(Status.STATUS_COMMITTED, tx2.getStatus()); + } + + /* Suspends existing transaction and create new transaction */ + + @Test + public void suspendAndManagedGlobalRequired() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.SUSPENDS_TRANSACTION); + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL); + exchange.setPhase(ExchangePhase.IN); + tm.begin(); + Transaction tx1 = tm.getTransaction(); + + handler.handleMessage(exchange); + Transaction tx2 = tm.getTransaction(); + Assert.assertNotSame(tx1, tx2); + Assert.assertEquals(Status.STATUS_ACTIVE, tx1.getStatus()); + Assert.assertEquals(Status.STATUS_ACTIVE, tx2.getStatus()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.SUSPENDS_TRANSACTION)); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.MANAGED_TRANSACTION_GLOBAL)); + + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Assert.assertEquals(tx1, tm.getTransaction()); + Assert.assertEquals(Status.STATUS_ACTIVE, tx1.getStatus()); + Assert.assertEquals(Status.STATUS_COMMITTED, tx2.getStatus()); + } + + @Test + public void suspendsAndManagedLocalRequired() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.SUSPENDS_TRANSACTION); + PolicyUtil.require(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL); + exchange.setPhase(ExchangePhase.IN); + tm.begin(); + Transaction tx1 = tm.getTransaction(); + + handler.handleMessage(exchange); + Transaction tx2 = tm.getTransaction(); + Assert.assertNotSame(tx1, tx2); + Assert.assertEquals(Status.STATUS_ACTIVE, tx1.getStatus()); + Assert.assertEquals(Status.STATUS_ACTIVE, tx2.getStatus()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.SUSPENDS_TRANSACTION)); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.MANAGED_TRANSACTION_LOCAL)); + + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Transaction tx3 = tm.getTransaction(); + Assert.assertEquals(tx1, tx3); + Assert.assertEquals(Status.STATUS_COMMITTED, tx2.getStatus()); + Assert.assertEquals(Status.STATUS_ACTIVE, tx3.getStatus()); + } + + /* Suspends existing transaction and run under no managed transaction */ + + @Test + public void noManagedRequired() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + tm.begin(); + Transaction tx1 = tm.getTransaction(); + + handler.handleMessage(exchange); + Transaction tx2 = tm.getTransaction(); + Assert.assertNotNull(tx1); + Assert.assertNull(tx2); + Assert.assertEquals(Status.STATUS_ACTIVE, tx1.getStatus()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION)); + + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Transaction tx3 = tm.getTransaction(); + Assert.assertEquals(tx1, tx3); + Assert.assertEquals(Status.STATUS_ACTIVE, tx3.getStatus()); + } + + @Test + public void suspendsRequired() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.SUSPENDS_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + tm.begin(); + Transaction tx1 = tm.getTransaction(); + + handler.handleMessage(exchange); + // transaction should be disabled + Assert.assertNull(tm.getTransaction()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.SUSPENDS_TRANSACTION)); + + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Transaction tx2 = tm.getTransaction(); + // transaction should be enabled + Assert.assertEquals(tx1, tx2); + Assert.assertEquals(Status.STATUS_ACTIVE, tx2.getStatus()); + } + + @Test + public void suspendAndNoManagedRequired() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION); + suspendsRequired(); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION)); + } + + /* no transaction */ + + @Test + public void suspendRequiredButNoTransaction() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.SUSPENDS_TRANSACTION); + exchange.setPhase(ExchangePhase.IN); + handler.handleMessage(exchange); + Assert.assertNull(tm.getTransaction()); + exchange.setPhase(ExchangePhase.OUT); + handler.handleMessage(exchange); + Assert.assertNull(tm.getTransaction()); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.SUSPENDS_TRANSACTION)); + } + + @Test + public void suspendAndNoManagedRequiredButNoTransaction() throws Exception { + PolicyUtil.require(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION); + suspendRequiredButNoTransaction(); + Assert.assertTrue(PolicyUtil.isProvided(exchange, TransactionPolicy.NO_MANAGED_TRANSACTION)); + } +} + +class MockTransactionManager implements TransactionManager { + + private ThreadLocal transaction = new ThreadLocal(); + + @Override + public void begin() throws NotSupportedException, SystemException { + transaction.set(new MockTransaction()); + } + + @Override + public void commit() throws RollbackException, HeuristicMixedException, + HeuristicRollbackException, SecurityException, + IllegalStateException, SystemException { + transaction.get().commit(); + transaction.remove(); + } + + @Override + public int getStatus() throws SystemException { + if (transaction.get() != null) { + return transaction.get().getStatus(); + } else { + return Status.STATUS_NO_TRANSACTION; + } + } + + @Override + public MockTransaction getTransaction() throws SystemException { + return transaction.get(); + } + + @Override + public void resume(Transaction arg0) throws InvalidTransactionException, + IllegalStateException, SystemException { + transaction.set(MockTransaction.class.cast(arg0)); + } + + @Override + public void rollback() throws IllegalStateException, SecurityException, + SystemException { + transaction.get().rollback(); + transaction.remove(); + } + + @Override + public void setRollbackOnly() throws IllegalStateException, SystemException { + transaction.get().setRollbackOnly(); + } + + @Override + public void setTransactionTimeout(int arg0) throws SystemException { + // TODO Auto-generated method stub + + } + + @Override + public Transaction suspend() throws SystemException { + MockTransaction t = transaction.get(); + transaction.remove(); + return t; + } +} + +class MockTransaction implements Transaction { + + private int status = Status.STATUS_ACTIVE; + private String uuid; + + public MockTransaction() { + uuid = UUID.randomUUID().toString(); + } + + @Override + public void commit() throws RollbackException, HeuristicMixedException, + HeuristicRollbackException, SecurityException, + IllegalStateException, SystemException { + status = Status.STATUS_COMMITTED; + } + + @Override + public boolean delistResource(XAResource arg0, int arg1) + throws IllegalStateException, SystemException { + return false; + } + + @Override + public boolean enlistResource(XAResource arg0) throws RollbackException, + IllegalStateException, SystemException { + return false; + } + + @Override + public int getStatus() throws SystemException { + return status; + } + + @Override + public void registerSynchronization(Synchronization arg0) + throws RollbackException, IllegalStateException, SystemException { + } + + @Override + public void rollback() throws IllegalStateException, SystemException { + status = Status.STATUS_ROLLEDBACK; + } + + @Override + public void setRollbackOnly() throws IllegalStateException, SystemException { + status = Status.STATUS_MARKED_ROLLBACK; + } + + public String getUUID() { + return uuid; + } + + @Override + public boolean equals(Object obj) { + MockTransaction target = MockTransaction.class.cast(obj); + return uuid.equals(target.getUUID()); + } +} \ No newline at end of file diff --git a/core/runtime/src/test/java/org/switchyard/internal/ContextPropertyTest.java b/core/runtime/src/test/java/org/switchyard/internal/ContextPropertyTest.java new file mode 100644 index 000000000..3a02975e4 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/ContextPropertyTest.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.Scope; + +public class ContextPropertyTest { + + @Test + public void testNullName() { + // null name should not be permitted + try { + new ContextProperty(null, Scope.MESSAGE, "bar"); + Assert.fail("Null property name should not be permitted!"); + } catch (IllegalArgumentException expected) { + // All good + return; + } + } + + @Test + public void testNullScope() { + // null scope should not be permitted + try { + new ContextProperty("foo", null, "bar"); + Assert.fail("Null property scope should not be permitted!"); + } catch (IllegalArgumentException expected) { + // All good + return; + } + } + + @Test + public void testEquals() { + ContextProperty prop1 = new ContextProperty("foo", Scope.MESSAGE, "bar"); + ContextProperty prop2 = new ContextProperty("foo", Scope.MESSAGE, "bar"); + Assert.assertTrue(prop1.equals(prop2)); + } + + @Test + public void testNotEquals() { + ContextProperty propRef = new ContextProperty("foo", Scope.MESSAGE, "bar"); + ContextProperty propDiffName = new ContextProperty("oops", Scope.MESSAGE, "bar"); + ContextProperty propDiffValue = new ContextProperty("foo", Scope.MESSAGE, "nope"); + Assert.assertFalse(propRef.equals(propDiffName)); + Assert.assertFalse(propRef.equals(propDiffValue)); + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/ContextSerializationTest.java b/core/runtime/src/test/java/org/switchyard/internal/ContextSerializationTest.java new file mode 100644 index 000000000..d7524702d --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/ContextSerializationTest.java @@ -0,0 +1,102 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.internal; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import junit.framework.Assert; + +import org.junit.Ignore; +import org.junit.Test; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.serial.CompressionType; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; + +/** + * Tests de/serialization of a Context. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public final class ContextSerializationTest { + + @Test + public void testContextProperty() throws Exception { + assertContextProperty(serDeser(buildContextProperty(), ContextProperty.class)); + } + + @Test + public void testScopedPropertyMap() throws Exception { + assertScopedPropertyMap(serDeser(buildScopedPropertyMap(), Map.class)); + } + + @Test + public void testDefaultContext() throws Exception { + assertDefaultContext(serDeser(buildDefaultContext(), DefaultContext.class)); + } + + private ContextProperty buildContextProperty() { + ContextProperty cp = new ContextProperty("foo", Scope.EXCHANGE, "bar"); + cp.addLabels("baz", "whiz"); + return cp; + } + + private Map buildScopedPropertyMap() { + Map properties = new HashMap(); + ContextProperty property = buildContextProperty(); + properties.put(property.getName(), property); + return properties; + } + + private DefaultContext buildDefaultContext() { + return new DefaultContext(Scope.EXCHANGE, buildScopedPropertyMap()); + } + + private void assertContextProperty(ContextProperty cp) { + Assert.assertNotNull(cp); + Assert.assertEquals("foo", cp.getName()); + Assert.assertSame(Scope.EXCHANGE, cp.getScope()); + Assert.assertEquals("bar", cp.getValue()); + Set labels = cp.getLabels(); + Assert.assertEquals(2, labels.size()); + Assert.assertTrue(labels.contains("baz")); + Assert.assertTrue(labels.contains("whiz")); + Assert.assertFalse(labels.contains("beep")); + } + + private void assertScopedPropertyMap(Map spm) { + Assert.assertNotNull(spm); + assertContextProperty((ContextProperty) spm.values().iterator().next()); + } + + private void assertDefaultContext(DefaultContext dc) { + Assert.assertNotNull(dc); + assertContextProperty((ContextProperty)dc.getProperties().iterator().next()); + } + + private T serDeser(T obj, Class type) throws Exception { + FormatType format = FormatType.JSON; //FormatType.XML_BEAN; //FormatType.SER_OBJECT; + CompressionType compression = null; //CompressionType.ZIP; //CompressionType.GZIP; + Serializer ser = SerializerFactory.create(format, compression, true); + //ser.setPrettyPrint(true); + byte[] bytes = ser.serialize(obj, type); + //System.out.println(new String(bytes)); + return ser.deserialize(bytes, type); + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/DefaultContextTest.java b/core/runtime/src/test/java/org/switchyard/internal/DefaultContextTest.java new file mode 100644 index 000000000..a8444f9fe --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/DefaultContextTest.java @@ -0,0 +1,164 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.Set; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Context; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.label.BehaviorLabel; + +/** + * Tests for context-related operations. + */ +public class DefaultContextTest { + + private static final String TRANSIENT = BehaviorLabel.TRANSIENT.label(); + private static final String PROP_NAME = "foo"; + private static final String PROP_VAL= "bar"; + private DefaultContext _context; + + @Before + public void setUp() { + _context = new DefaultContext(Scope.EXCHANGE); + } + + @Test + public void testGetSet() { + _context.setProperty(PROP_NAME, PROP_VAL); + Assert.assertEquals(PROP_VAL, _context.getProperty(PROP_NAME).getValue()); + } + + @Test + public void testGetPropertyValue() { + final String key = "prop"; + final String value = "exchange"; + _context.setProperty(key, value); + Assert.assertEquals(value, _context.getPropertyValue(key)); + } + + @Test + public void testRemove() { + _context.setProperty(PROP_NAME, PROP_VAL); + Property p = _context.getProperty(PROP_NAME); + Assert.assertEquals(PROP_VAL, p.getValue()); + _context.removeProperty(p); + Assert.assertNull(_context.getProperty(PROP_NAME)); + } + + @Test + public void testRemoveProperites() { + _context.setProperty("out", "bar"); + _context.setProperty("in", "foo"); + _context.setProperty("ex", "psst"); + _context.removeProperties(); + Assert.assertNull(_context.getPropertyValue("in")); + Assert.assertNull(_context.getPropertyValue("out")); + Assert.assertNull(_context.getPropertyValue("ex")); + } + + @Test + public void testNullContextValue() { + _context.setProperty(PROP_NAME, null); + Property p = _context.getProperty(PROP_NAME); + Assert.assertNotNull(p); + Assert.assertNull(p.getValue()); + } + + @Test + public void testSetPropertySet() { + _context.setProperty("one", "bar"); + _context.setProperty("two", "foo"); + Set props = _context.getProperties(); + DefaultContext ctx = new DefaultContext(Scope.MESSAGE); + ctx.setProperties(props); + Assert.assertNotNull(ctx.getPropertyValue("one")); + Assert.assertNotNull(ctx.getPropertyValue("two")); + } + + @Test + public void testGetProperties() { + _context.setProperty(PROP_NAME, PROP_VAL); + Set props = _context.getProperties(); + Assert.assertTrue(props.size() == 1); + Assert.assertEquals(PROP_VAL, props.iterator().next().getValue()); + + // operations to the returned map should *not* be reflected in the context + props.remove(PROP_NAME); + Assert.assertTrue(_context.getProperties().size() == 1); + } + + @Test + public void testGetPropertyLabel() { + _context.setProperty("a", "a").addLabels(TRANSIENT); + _context.setProperty("b", "b").addLabels(TRANSIENT); + _context.setProperty("c", "c").addLabels(TRANSIENT); + _context.setProperty("d", "d").addLabels("foo"); + Assert.assertEquals(3, _context.getProperties(TRANSIENT).size()); + Assert.assertEquals(1, _context.getProperties("foo").size()); + } + + @Test + public void testRemovePropertyLabel() { + _context.setProperty("a", "a").addLabels(TRANSIENT); + _context.setProperty("b", "b").addLabels(TRANSIENT); + _context.setProperty("c", "c").addLabels(TRANSIENT); + _context.setProperty("d", "d").addLabels("foo"); + + _context.removeProperties(TRANSIENT); + Assert.assertEquals(0, _context.getProperties(TRANSIENT).size()); + Assert.assertEquals(1, _context.getProperties("foo").size()); + } + + @Test + public void testCopyClean() { + _context.setProperty("a", "a").addLabels(TRANSIENT); + _context.setProperty("b", "b"); + _context.setProperty("c", "c").addLabels(TRANSIENT); + + Context newCtx = new DefaultContext(Scope.EXCHANGE); + _context.mergeInto(newCtx); + Assert.assertEquals(0, newCtx.getProperties(TRANSIENT).size()); + Assert.assertEquals(1, newCtx.getProperties().size()); + } + + @Test + public void testCopy() { + _context.setProperty("exchange", "val"); + _context.setProperty("in", "val"); + _context.setProperty("out", "val"); + Context ctx = new DefaultContext(Scope.EXCHANGE); + _context.mergeInto(ctx); + // verify that all fields were copied + Assert.assertEquals( + _context.getProperty("exchange"), + ctx.getProperty("exchange")); + Assert.assertEquals( + _context.getProperty("in"), + ctx.getProperty("in")); + Assert.assertEquals( + _context.getProperty("out"), + ctx.getProperty("out")); + // verify that mods to one context do not impact the other + _context.removeProperties(); + Assert.assertNull(_context.getProperty("exchange")); + Assert.assertNotNull(ctx.getProperty("exchange")); + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/DefaultHandlerChainTest.java b/core/runtime/src/test/java/org/switchyard/internal/DefaultHandlerChainTest.java new file mode 100644 index 000000000..c1645342d --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/DefaultHandlerChainTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.ServiceReference; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.spi.Dispatcher; + +public class DefaultHandlerChainTest { + + private HandlerChain _chain; + + @Before + public void setUp() { + _chain = new DefaultHandlerChain(); + } + + @Test + public void faultChainContinuesOnFault() throws Exception { + // This goes first and throws an exception - bad handler! + ExchangeHandler badHandler = new BaseHandler() { + @Override + public void handleFault(Exchange exchange) { + throw new RuntimeException("oops!"); + } + }; + // This goes second and should still be called despite the bad handler + MockHandler goodHandler = new MockHandler(); + + _chain.addFirst("first", badHandler); + _chain.addLast("second", goodHandler); + + MockDomain domain = new MockDomain(); + ServiceReference reference = domain.createInOnlyService(new QName("bar")); + Dispatcher dispatch = domain.getBus().createDispatcher(reference); + Exchange ex = new ExchangeImpl(domain, dispatch).consumer(reference, new InOnlyOperation("foo")); + _chain.handleFault(ex); + Assert.assertNotNull(goodHandler.waitForFaultMessage()); + } + + @Test + public void testReplace() { + MockHandler m1 = new MockHandler(); + MockHandler m2 = new MockHandler(); + MockHandler m3 = new MockHandler(); + MockHandler m4 = new MockHandler(); + + _chain.addFirst("1", m1); + + Assert.assertFalse(_chain.replace("5", m2)); + Assert.assertTrue(_chain.replace("1", m2)); + + Assert.assertTrue(_chain.getHandlers().contains(m2)); + Assert.assertFalse(_chain.getHandlers().contains(m1)); + + // clean up + _chain.remove("1"); + Assert.assertEquals(0, _chain.getHandlers().size()); + + // test replace with multiple handlers + _chain.addFirst("1", m1); + _chain.addFirst("2", m2); + _chain.addFirst("3", m3); + _chain.replace("2", m4); + + Assert.assertEquals(m4, _chain.getHandlers().get(1)); + } +} + + + diff --git a/core/runtime/src/test/java/org/switchyard/internal/DefaultMessageTest.java b/core/runtime/src/test/java/org/switchyard/internal/DefaultMessageTest.java new file mode 100644 index 000000000..61cfaf71e --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/DefaultMessageTest.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Map; + +import javax.activation.DataSource; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Message; + +public class DefaultMessageTest { + + private Message _message; + + @Before + public void setUp() { + _message = new DefaultMessage(); + } + + + @Test + public void testAddAttachment() throws Exception { + _message.addAttachment("attach1", new DummyDS("attach1", "text/xml")); + Assert.assertNotNull(_message.getAttachment("attach1")); + } + + @Test + public void testRemoveAttachment() throws Exception { + _message.addAttachment("attach1", new DummyDS("attach1", "text/xml")); + Assert.assertNotNull(_message.getAttachment("attach1")); + _message.removeAttachment("attach1"); + Assert.assertNull(_message.getAttachment("attach1")); + + } + + @Test + public void testGetAttachmentMap() throws Exception { + _message.addAttachment("attach1", new DummyDS("attach1", "text/xml")); + _message.addAttachment("attach2", new DummyDS("attach1", "text/xml")); + Map attachments = _message.getAttachmentMap(); + // make sure the attachments we added are in the map + Assert.assertTrue(attachments.containsKey("attach1")); + Assert.assertTrue(attachments.containsKey("attach2")); + // make sure that modifications to the map are not reflected in the message + // (i.e.) the returned map is not a direct reference + attachments.remove("attach1"); + Assert.assertNotNull(_message.getAttachment("attach1")); + } + + @Test + public void testContent() throws Exception { + final String message = "Hello There!"; + _message.setContent(message); + Assert.assertEquals(message, _message.getContent()); + // the following tests to make sure casting to same type works + String content = _message.getContent(String.class); + Assert.assertEquals(message, content); + } + +} + +class DummyDS implements DataSource { + + private String _contentType; + private String _name; + + DummyDS(String contentType, String name) { + _contentType = contentType; + _name = name; + } + + @Override + public String getContentType() { + return _contentType; + } + + @Override + public InputStream getInputStream() throws IOException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getName() { + return _name; + } + + @Override + public OutputStream getOutputStream() throws IOException { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/DefaultServiceRegistryTest.java b/core/runtime/src/test/java/org/switchyard/internal/DefaultServiceRegistryTest.java new file mode 100644 index 000000000..89bb8b8d7 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/DefaultServiceRegistryTest.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import static org.hamcrest.CoreMatchers.is; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.Service; + +/** + * Unit test for {@link DefaultServiceRegistry} + *

+ * @author Daniel Bevenius + * + */ +public class DefaultServiceRegistryTest +{ + @Test + public void shouldBePossibleToSearchForNonRegisteredService() + { + DefaultServiceRegistry registry = new DefaultServiceRegistry(); + List services = registry.getServices(new QName("unRegisteredService")); + Assert.assertThat(services.size(), is(0)); + } + + @Test + public void testUnregister() { + final QName serviceName = new QName("Foo"); + DefaultServiceRegistry registry = new DefaultServiceRegistry(); + ServiceImpl service = new ServiceImpl(serviceName, null, null, null); + registry.registerService(service); + Assert.assertTrue(registry.getServices(serviceName).size() > 0); + registry.unregisterService(service); + Assert.assertTrue(registry.getServices(serviceName).size() == 0); + } + + @Test + public void testNullServiceDomainName() { + Logger logger = Logger.getLogger(DefaultServiceRegistry.class); + Level origLevel = logger.getLevel(); + logger.setLevel(Level.DEBUG); + + Assert.assertEquals(logger.getLevel(), Level.DEBUG); + final QName serviceName = new QName("FooBar"); + DefaultServiceRegistry registry = new DefaultServiceRegistry(); + DomainImpl domain = new DomainImpl(null); + ServiceImpl service = new ServiceImpl(serviceName, null, domain, null); + registry.registerService(service); + Assert.assertTrue(service.getDomain().getName() == null); + registry.unregisterService(service); + logger.setLevel(origLevel); + } + + @Test + public void referenceRegistration() { + final QName referenceName = new QName("Bar"); + DefaultServiceRegistry registry = new DefaultServiceRegistry(); + ServiceReferenceImpl reference = new ServiceReferenceImpl(referenceName, null, null, null); + registry.registerServiceReference(reference); + Assert.assertTrue(registry.getServiceReferences().size() > 0); + registry.unregisterServiceReference(reference); + Assert.assertTrue(registry.getServices(referenceName).size() == 0); + } +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/DomainImplTest.java b/core/runtime/src/test/java/org/switchyard/internal/DomainImplTest.java new file mode 100644 index 000000000..afcf26c52 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/DomainImplTest.java @@ -0,0 +1,152 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.EventObject; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; +import org.switchyard.MockHandler; +import org.switchyard.Service; +import org.switchyard.ServiceReference; +import org.switchyard.event.EventObserver; +import org.switchyard.event.ReferenceRegistrationEvent; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceInterface; + +/** + * Unit tests for the DomainImpl class. + */ +public class DomainImplTest { + + private static final QName IN_ONLY_SERVICE = new QName("InOnlyService"); + private static final QName IN_OUT_SERVICE = new QName("InOutService"); + private ServiceReference _inOnlyReference; + private ServiceReference _inOutReference; + private DomainImpl _domain; + + @Before + public void setUp() throws Exception { + _domain = new DomainImpl(new QName("test")); + _domain.registerService(IN_ONLY_SERVICE, new InOnlyService(), new MockHandler()); + _domain.registerService(IN_OUT_SERVICE, new InOutService(), new MockHandler()); + _inOnlyReference = _domain.registerServiceReference(IN_ONLY_SERVICE, new InOnlyService()); + _inOutReference = _domain.registerServiceReference(IN_OUT_SERVICE, new InOutService()); + } + + @Test + public void testCreateExchange() { + Exchange inOnly = _inOnlyReference.createExchange(); + inOnly.consumer(null, new InOnlyOperation("foo")); + Assert.assertEquals(ExchangePattern.IN_ONLY, inOnly.getContract().getConsumerOperation().getExchangePattern()); + Exchange inOut = _inOutReference.createExchange(new MockHandler()); + inOut.consumer(null, new InOutOperation("foo")); + Assert.assertEquals(ExchangePattern.IN_OUT, inOut.getContract().getConsumerOperation().getExchangePattern()); + } + + @Test + public void testRegisterServiceWithoutInterface() { + Service service = _domain.registerService( + new QName("no-interface"), null, new MockHandler()); + // default interface should be used, which has one operation - process() + Assert.assertNotNull(service.getInterface()); + Assert.assertTrue(service.getInterface().getOperations().size() == 1); + Assert.assertNotNull(service.getInterface().getOperation( + ServiceInterface.DEFAULT_OPERATION)); + } + + @Test + public void testRegisterServiceWithInterface() { + Service service = _domain.registerService(new QName("my-interface"), + JavaService.fromClass(MyInterface.class), new MockHandler()); + // default interface should be used, which has one operation - process() + Assert.assertNotNull(service.getInterface()); + Assert.assertTrue(service.getInterface().getOperations().size() == 1); + Assert.assertNotNull(service.getInterface().getOperation("myOperation")); + } + + @Test + public void testGetSetProperties() { + Assert.assertNull(_domain.getProperty("foo")); + _domain.setProperty("foo", "foo-value"); + Assert.assertEquals("foo-value", _domain.getProperty("foo")); + Assert.assertEquals("foo-value", _domain.getProperties().get("foo")); + + // confirm that we can't set properties via getProperties() + try { + _domain.getProperties().put("bar", "bar-value"); + Assert.fail("Should not be able to modify map returned from ServiceDomain.getProperties()"); + } catch (Exception ex) { + Assert.assertEquals(UnsupportedOperationException.class, ex.getClass()); + } + } + + @Test + public void testGetEventPublisher() { + // Test to make sure event manager is initialized in domain + Assert.assertNotNull(_domain.getEventPublisher()); + } + + @Test + public void testAddObserver() { + CountingEventObserver obs = new CountingEventObserver(); + _domain.addEventObserver(obs, ReferenceRegistrationEvent.class); + _domain.getEventPublisher().publish(new ReferenceRegistrationEvent(_inOnlyReference)); + Assert.assertEquals(1, obs.count); + } + +} + +interface MyInterface { + void myOperation(String msg); +} + +class CountingHandler extends BaseHandler { + private int count; + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + ++count; + } + + public int getCount() { + return count; + } + + public void clear() { + count = 0; + } +} + +class CountingEventObserver implements EventObserver { + + public int count; + + public void notify(EventObject event) { + ++count; + } +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/EventManagerTest.java b/core/runtime/src/test/java/org/switchyard/internal/EventManagerTest.java new file mode 100644 index 000000000..a87e3344a --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/EventManagerTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; + +/** + * Unit tests for the EventManager class. + */ +public class EventManagerTest { + + private EventManager _manager; + + @Before + public void setUp() throws Exception { + _manager = new EventManager(); + } + + @Test + public void testSomething() { + } +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/EventsTest.java b/core/runtime/src/test/java/org/switchyard/internal/EventsTest.java new file mode 100644 index 000000000..7c1e9f3a4 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/EventsTest.java @@ -0,0 +1,151 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.EventObject; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.MockDomain; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.event.EventObserver; +import org.switchyard.event.ReferenceRegistrationEvent; +import org.switchyard.event.ReferenceUnregistrationEvent; +import org.switchyard.event.ServiceRegistrationEvent; +import org.switchyard.event.ServiceUnregistrationEvent; +import org.switchyard.event.TransformerAddedEvent; +import org.switchyard.event.TransformerRemovedEvent; +import org.switchyard.event.ValidatorAddedEvent; +import org.switchyard.event.ValidatorRemovedEvent; +import org.switchyard.metadata.InOutService; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.Transformer; +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.Validator; + +/** + * Tests for events generated by the core runtime. + */ +public class EventsTest { + + private ServiceDomain _domain; + private DummyObserver _observer; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + _observer = new DummyObserver(); + } + + @Test + public void testTransformerEvents() { + _domain.addEventObserver(_observer, TransformerAddedEvent.class) + .addEventObserver(_observer, TransformerRemovedEvent.class); + Transformer t = new BaseTransformer() { + public String transform(String from) { + return null; + } + }; + _domain.getTransformerRegistry().addTransformer(t); + Assert.assertTrue(_observer.addTransformerCalled); + _domain.getTransformerRegistry().removeTransformer(t); + Assert.assertTrue(_observer.removeTransformerCalled); + } + + @Test + public void testValidatorEvents() { + _domain.addEventObserver(_observer, ValidatorAddedEvent.class) + .addEventObserver(_observer, ValidatorRemovedEvent.class); + Validator t = new BaseValidator() { + public ValidationResult validate(String name) { + return new ValidationResult() { + public boolean isValid() { + return false; + } + public String getDetail() { + return "error"; + } + }; + } + }; + _domain.getValidatorRegistry().addValidator(t); + Assert.assertTrue(_observer.addValidatorCalled); + _domain.getValidatorRegistry().removeValidator(t); + Assert.assertTrue(_observer.removeValidatorCalled); + } + + @Test + public void testReferenceEvents() { + _domain.addEventObserver(_observer, ReferenceRegistrationEvent.class) + .addEventObserver(_observer, ReferenceUnregistrationEvent.class); + + ServiceReference ref = _domain.registerServiceReference(new QName("test"), new InOutService()); + Assert.assertTrue(_observer.referenceRegistrationCalled); + ref.unregister(); + Assert.assertTrue(_observer.referenceUnregistrationCalled); + } + + @Test + public void testServiceEvents() { + _domain.addEventObserver(_observer, ServiceRegistrationEvent.class) + .addEventObserver(_observer, ServiceUnregistrationEvent.class); + + Service service = _domain.registerService(new QName("test"), new InOutService(), new BaseHandler()); + Assert.assertTrue(_observer.serviceRegistrationCalled); + service.unregister(); + Assert.assertTrue(_observer.serviceUnregistrationCalled); + } +} + + +class DummyObserver implements EventObserver { + + public boolean removeTransformerCalled; + public boolean addTransformerCalled; + public boolean removeValidatorCalled; + public boolean addValidatorCalled; + public boolean referenceRegistrationCalled; + public boolean referenceUnregistrationCalled; + public boolean serviceRegistrationCalled; + public boolean serviceUnregistrationCalled; + + public void notify(EventObject event) { + if (event instanceof TransformerAddedEvent) { + addTransformerCalled = true; + } else if (event instanceof TransformerRemovedEvent) { + removeTransformerCalled = true; + } else if (event instanceof ValidatorAddedEvent) { + addValidatorCalled = true; + } else if (event instanceof ValidatorRemovedEvent) { + removeValidatorCalled = true; + } else if (event instanceof ReferenceRegistrationEvent) { + referenceRegistrationCalled = true; + } else if (event instanceof ReferenceUnregistrationEvent) { + referenceUnregistrationCalled = true; + } else if (event instanceof ServiceRegistrationEvent) { + serviceRegistrationCalled = true; + } else if (event instanceof ServiceUnregistrationEvent) { + serviceUnregistrationCalled = true; + } + } +} \ No newline at end of file diff --git a/core/runtime/src/test/java/org/switchyard/internal/ExchangeImplTest.java b/core/runtime/src/test/java/org/switchyard/internal/ExchangeImplTest.java new file mode 100644 index 000000000..7c50e5478 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/ExchangeImplTest.java @@ -0,0 +1,418 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import java.util.EventObject; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePhase; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.ServiceReference; +import org.switchyard.event.EventObserver; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.runtime.event.ExchangeInitiatedEvent; +import org.switchyard.spi.Dispatcher; +import org.switchyard.transform.BaseTransformer; + +/** + * Unit tests for the ExchangeImpl class. + */ +public class ExchangeImplTest { + + private MockDomain _domain; + private Dispatcher _dispatch; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + ServiceReference reference = _domain.createInOnlyService(new QName("foo")); + _dispatch = _domain.getBus().createDispatcher(reference); + } + + @Test + public void testSendFaultOnNewExchange() { + Exchange exchange = new ExchangeImpl(_domain, _dispatch); + try { + exchange.sendFault(exchange.createMessage()); + Assert.fail("Sending a fault on a new exchange is not allowed"); + } catch (IllegalStateException illEx) { + return; + } + } + + @Test + public void testPhaseIsNullOnNewExchange() { + Exchange exchange = new ExchangeImpl(_domain, _dispatch); + Assert.assertNull(exchange.getPhase()); + } + + @Test + public void testPhaseIsInAfterInputMessage() { + ServiceReference service = _domain.createInOnlyService(new QName("InPhase")); + Exchange exchange = service.createExchange(); + exchange.send(exchange.createMessage()); + Assert.assertEquals(ExchangePhase.IN, exchange.getPhase()); + } + + @Test + public void testPhaseIsOutAfterOutputMessage() { + MockHandler replyHandler = new MockHandler(); + ServiceReference service = _domain.createInOutService( + new QName("OutPhase"), new MockHandler().forwardInToOut()); + Exchange exchange = service.createExchange(replyHandler); + exchange.send(exchange.createMessage()); + replyHandler.waitForOKMessage(); + Assert.assertEquals(ExchangePhase.OUT, exchange.getPhase()); + } + + @Test + public void testPhaseIsOutAfterFaultMessage() { + MockHandler replyHandler = new MockHandler(); + ServiceReference service = _domain.createInOutService( + new QName("FaultPhase"), new MockHandler().forwardInToFault()); + Exchange exchange = service.createExchange(replyHandler); + exchange.send(exchange.createMessage()); + replyHandler.waitForFaultMessage(); + Assert.assertEquals(ExchangePhase.OUT, exchange.getPhase()); + } + + @Test + public void testMessageIdSetOnSend() { + ServiceReference service = _domain.createInOnlyService(new QName("IdTest")); + Exchange exchange = service.createExchange(); + exchange.send(exchange.createMessage()); + Assert.assertNotNull(exchange.getMessage().getContext().getProperty(Exchange.MESSAGE_ID)); + } + + @Test + public void testRelatesToSetOnReply() { + ServiceReference service = _domain.createInOutService( + new QName("ReplyTest"), new MockHandler().forwardInToOut()); + MockHandler replyHandler = new MockHandler(); + Exchange exchange = service.createExchange(replyHandler); + Message message = exchange.createMessage(); + exchange.send(message); + + String requestId = message.getContext().getPropertyValue(Exchange.MESSAGE_ID); + String replyId = exchange.getMessage().getContext().getPropertyValue(Exchange.MESSAGE_ID); + String replyRelatesTo = exchange.getMessage().getContext().getPropertyValue(Exchange.RELATES_TO); + + Assert.assertEquals(requestId, replyRelatesTo); + Assert.assertFalse(requestId.equals(replyId)); + } + + @Test + public void testNullSend() { + Exchange exchange = new ExchangeImpl(_domain, _dispatch); + try { + exchange.send(null); + Assert.fail("Expected IllegalArgumentException."); + } catch (IllegalArgumentException e) { + boolean messageMatch = e.getMessage().contains("SWITCHYARD014019"); + Assert.assertTrue(messageMatch); + } + } + + @Test + public void testNullSendFault() { + Exchange exchange = new ExchangeImpl(_domain, _dispatch); + try { + exchange.sendFault(null); + Assert.fail("Expected IllegalArgumentException."); + } catch (IllegalArgumentException e) { + boolean messageMatch = e.getMessage().contains("SWITCHYARD014019"); + Assert.assertTrue(messageMatch); + } + } + + @Test + public void testExchangeInitiatedEvent() { + EventCounter counter = new EventCounter(); + _domain.addEventObserver(counter, ExchangeInitiatedEvent.class); + + // send in-only and check the count + ServiceReference inOnlyService = _domain.createInOnlyService(new QName("ExchangeInitiatedEvent-1")); + Exchange inOnly = inOnlyService.createExchange(); + inOnly.send(inOnly.createMessage()); + Assert.assertEquals(1, counter.initiatedCount); + + // reset count + counter.initiatedCount = 0; + + // send in-out and check the count + ServiceReference inOutService = _domain.createInOutService( + new QName("ExchangeInitiatedEvent-2"), new MockHandler().forwardInToOut()); + Exchange inOut = inOutService.createExchange(new MockHandler()); + inOut.send(inOut.createMessage()); + Assert.assertEquals(1, counter.initiatedCount); + } + + @Test + public void testExchangeCompletedEvent() { + EventCounter counter = new EventCounter(); + _domain.addEventObserver(counter, ExchangeCompletionEvent.class); + + // send in-only and check the count + ServiceReference inOnlyService = _domain.createInOnlyService(new QName("ExchangeCompleteEvent-1")); + Exchange inOnly = inOnlyService.createExchange(); + inOnly.send(inOnly.createMessage()); + Assert.assertEquals(1, counter.completedCount); + + // reset count + counter.completedCount = 0; + + // send in-out and check the count + ServiceReference inOutService = _domain.createInOutService( + new QName("ExchangeCompleteEvent-2"), new MockHandler().forwardInToOut()); + Exchange inOut = inOutService.createExchange(new MockHandler()); + inOut.send(inOut.createMessage()); + Assert.assertEquals(1, counter.completedCount); + } + + @Test + public void testAllExchangeEventsReceived() throws Exception { + EventCounter counter = new EventCounter(); + _domain.addEventObserver(counter, ExchangeInitiatedEvent.class); + _domain.addEventObserver(counter, ExchangeCompletionEvent.class); + + // send 10 in-only messages and check the counters + for (int i = 0; i < 10; i++) { + ServiceReference inOnlyService = _domain.createInOnlyService(new QName("ExchangeEvent-0" + i)); + Exchange inOnly = inOnlyService.createExchange(); + inOnly.send(inOnly.createMessage()); + } + + Assert.assertEquals(10, counter.initiatedCount); + Assert.assertEquals(10, counter.completedCount); + + // initialize counters + counter.initiatedCount = 0; + counter.completedCount = 0; + + // send 10 in-out and check the count + for (int i = 0; i < 10; i++) { + ServiceReference inOutService = _domain.createInOutService( + new QName("ExchangeEvent-1" + i), new MockHandler().forwardInToOut()); + Exchange inOut = inOutService.createExchange(new MockHandler()); + inOut.send(inOut.createMessage()); + } + + Assert.assertEquals(10, counter.initiatedCount); + Assert.assertEquals(10, counter.completedCount); + } + + /** + * Make sure that the current message is set correctly when an exchange + * is sent. + */ + @Test + public void testGetMessage() throws Exception { + + final QName serviceName = new QName("bleh"); + final String inMsgContent = "in message"; + final String outMsgContent = "out message"; + + // create a handler to test that the in and out content match + // expected result from getMessage() + ExchangeHandler provider = new BaseHandler() { + public void handleMessage(Exchange exchange) { + Assert.assertEquals( + exchange.getMessage().getContent(), + inMsgContent); + + Message outMsg = exchange.createMessage(); + outMsg.setContent(outMsgContent); + try { + exchange.send(outMsg); + } + catch (Exception ex) { + Assert.fail(ex.toString()); + } + } + }; + + ExchangeHandler consumer = new BaseHandler() { + public void handleMessage(Exchange exchange) { + Assert.assertEquals( + exchange.getMessage().getContent(), + outMsgContent); + } + }; + + ServiceReference service = _domain.createInOutService(serviceName, provider); + Exchange exchange = service.createExchange(consumer); + Message inMsg = exchange.createMessage(); + inMsg.setContent(inMsgContent); + exchange.send(inMsg); + } + + @Test + public void testExceptionOnSendOnFaultExchange() throws Exception { + + final QName serviceName = new QName("testExceptionOnSendOnFaultExchange"); + // Provide the service + MockHandler provider = new MockHandler().forwardInToFault(); + ServiceReference service = _domain.createInOutService(serviceName, provider); + + // Consume the service + MockHandler consumer = new MockHandler(); + Exchange exchange = service.createExchange(consumer); + exchange.send(exchange.createMessage()); + + // wait, since this is async + provider.waitForOKMessage(); + consumer.waitForFaultMessage(); + + // Now try send another message on the Exchange... should result in an IllegalStateException... + try { + exchange.send(exchange.createMessage()); + } catch(IllegalStateException e) { + boolean messageMatch = e.getMessage().contains("SWITCHYARD014020"); + Assert.assertTrue(messageMatch); + } + } + + @Test + public void testExceptionOnNoConsumerOnInOut() throws Exception { + + QName serviceName = new QName("testNoNPEOnNoConsumer"); + MockHandler provider = new MockHandler() { + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + throw new HandlerException("explode"); + } + }; + + ServiceReference service = _domain.createInOutService(serviceName, provider); + + try { + // Don't provide a consumer... + service.createExchange(); + Assert.fail("Should not be able to create an InOut without specifying a reply handler"); + } catch (RuntimeException e) { + // exception expected + } + } + + @Test + public void testNoNPEOnInOnlyFault() throws Exception { + + QName serviceName = new QName("testNoNPEOnNoConsumer"); + MockHandler provider = new MockHandler() { + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + throw new HandlerException("explode"); + } + }; + + ServiceReference service = _domain.createInOnlyService(serviceName, provider); + + // Don't provide a consumer... + Exchange exchange = service.createExchange(); + + exchange.send(exchange.createMessage()); + } + + @Test + public void testFaultWithNoHandler() throws Exception { + + final QName serviceName = new QName("testFaultWithNoHandler"); + // Provide the service + MockHandler provider = new MockHandler() { + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + throw new HandlerException("Fault With No Handler!"); + } + }; + ServiceReference service = _domain.createInOnlyService(serviceName, provider); + + // Consume the service + Exchange exchange = service.createExchange(); + exchange.send(exchange.createMessage()); + + // Make sure the exchange is in fault status + Assert.assertEquals(ExchangeState.FAULT, exchange.getState()); + } + + @Test + public void testFaultTransformSequence() throws Exception { + final QName serviceName = new QName("testFaultTransformSequence"); + // Provide the service + MockHandler provider = new MockHandler() { + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + Message fault = exchange.createMessage(); + fault.setContent(new Exception("testFaultTransformSequence")); + exchange.sendFault(fault); + } + }; + InOutOperation providerContract = new InOutOperation("faultOp", + JavaTypes.toMessageType(String.class), // input + JavaTypes.toMessageType(String.class), // output + JavaTypes.toMessageType(Exception.class)); // fault + InOutOperation consumerContract = new InOutOperation("faultOp", + JavaTypes.toMessageType(String.class), // input + JavaTypes.toMessageType(String.class), // output + JavaTypes.toMessageType(String.class)); // fault + _domain.registerService(serviceName, new InOutService(providerContract), provider); + _domain.getTransformerRegistry().addTransformer(new ExceptionToStringTransformer()); + ServiceReference service = _domain.registerServiceReference(serviceName, new InOutService(consumerContract)); + + // Consume the service + Exchange exchange = service.createExchange(new MockHandler()); + exchange.send(exchange.createMessage()); + + // Make sure the exchange is in fault status + Assert.assertEquals(String.class, exchange.getMessage().getContent().getClass()); + Assert.assertEquals(exchange.getMessage().getContent(), "testFaultTransformSequence"); + } + + class EventCounter implements EventObserver { + int initiatedCount; + int completedCount; + public void notify(EventObject event) { + if (event instanceof ExchangeInitiatedEvent) { + ++initiatedCount; + } else if (event instanceof ExchangeCompletionEvent) { + ++completedCount; + } + } + }; + +} + +class ExceptionToStringTransformer extends BaseTransformer { + + @Override + public String transform(Exception from) { + return from.getMessage(); + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/ServiceImplTest.java b/core/runtime/src/test/java/org/switchyard/internal/ServiceImplTest.java new file mode 100644 index 000000000..d8b8e6d14 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/ServiceImplTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.Service; +import org.switchyard.metadata.InOnlyService; + +/** + * Unit tests for the ServiceImpl class. + */ +public class ServiceImplTest { + + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + } + + @Test + public void testUnregister() { + Service service = _domain.registerService(new QName("TestService"), + new InOnlyService(), new MockHandler()); + // test that it was added to the registry + Assert.assertEquals(1, _domain.getServiceRegistry().getServices().size()); + service.unregister(); + // confirm that it was removed + Assert.assertEquals(0, _domain.getServiceRegistry().getServices().size()); + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformResolverTest.java b/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformResolverTest.java new file mode 100644 index 000000000..278a5bdf0 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformResolverTest.java @@ -0,0 +1,133 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal.transform; + +import java.util.LinkedList; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.Transformer; + +public class BaseTransformResolverTest { + + private static final QName A = new QName("a"); + private static final QName B = new QName("b"); + private static final QName C = new QName("c"); + private static final QName D = new QName("d"); + private static final QName E = new QName("e"); + + private Transformer fromAtoB; + private Transformer fromBtoC; + private Transformer fromBtoE; + private Transformer fromCtoD; + + private BaseTransformResolver resolver; + private BaseTransformerRegistry registry; + + public BaseTransformResolverTest() { + fromAtoB = createTransformer(A, B); + fromBtoC = createTransformer(B, C); + fromCtoD = createTransformer(C, D); + fromBtoE = createTransformer(B, E); + } + + @Before + public void setUp() throws Exception { + registry = new BaseTransformerRegistry(); + resolver = new BaseTransformResolver(registry); + } + + @Test + public void AtoCwithTwoHops() { + registry.addTransformer(fromAtoB); + registry.addTransformer(fromBtoC); + registry.addTransformer(fromBtoE); + + LinkedList list = new LinkedList(); + boolean resolved = resolver.resolvePath(list, A, C, 2); + Assert.assertTrue(resolved); + + // Check the path + Assert.assertEquals(B, list.pop()); + Assert.assertEquals(C, list.pop()); + } + + @Test + public void AtoCwithOneHop() { + registry.addTransformer(fromAtoB); + registry.addTransformer(fromBtoC); + LinkedList list = new LinkedList(); + + // This should fail because it requires two hops + boolean resolved = resolver.resolvePath(list, A, C, 1); + Assert.assertFalse(resolved); + } + + @Test + public void AtoDwithThreeHop() { + registry.addTransformer(fromAtoB); + registry.addTransformer(fromBtoC); + registry.addTransformer(fromCtoD); + LinkedList list = new LinkedList(); + + boolean resolved = resolver.resolvePath(list, A, D, 3); + Assert.assertTrue(resolved); + + // Check the path + Assert.assertEquals(B, list.pop()); + Assert.assertEquals(C, list.pop()); + Assert.assertEquals(D, list.pop()); + } + + @Test + public void AtoBwithOneHop() { + registry.addTransformer(fromAtoB); + + LinkedList list = new LinkedList(); + boolean resolved = resolver.resolvePath(list, A, B, 1); + Assert.assertTrue(resolved); + + // Check the path + Assert.assertEquals(B, list.pop()); + } + + @Test + public void AtoEwithCycleAtoA() { + registry.addTransformer(fromAtoB); + registry.addTransformer(createTransformer(A, A)); + registry.addTransformer(createTransformer(B, A)); + + LinkedList list = new LinkedList(); + boolean resolved = resolver.resolvePath(list, A, E, 2); + + // This won't resolve, but we're really just checking to make sure a cycle in + // the graph doesn't produce an infinite loop + Assert.assertFalse(resolved); + } + + @SuppressWarnings("rawtypes") + Transformer createTransformer(QName from, QName to) { + return new BaseTransformer(from, to) { + public Object transform(Object from) { + return null; + } + }; + } +} + diff --git a/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformerRegistryTest.java b/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformerRegistryTest.java new file mode 100644 index 000000000..51e40669c --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformerRegistryTest.java @@ -0,0 +1,171 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal.transform; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.TransformSequence; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; + +public class BaseTransformerRegistryTest { + + private TransformerRegistry _registry; + + @Before + public void setUp() throws Exception { + _registry = new BaseTransformerRegistry(); + } + + @Test + public void testAddGetTransformer() { + final QName fromName = new QName("a"); + final QName toName = new QName("b"); + + BaseTransformer t = + new BaseTransformer(fromName, toName) { + public Integer transform(String from) { + return null; + } + }; + + _registry.addTransformer(t); + Assert.assertEquals(t, _registry.getTransformer(fromName, toName)); + } + + @Test + public void testNullTransformer() { + final QName fromName = new QName("garfield"); + final QName toName = new QName("odie"); + Transformer transformer = _registry.getTransformer(fromName, toName); + + Assert.assertTrue(transformer == null); + } + + @Test + public void test_fallbackTransformerComparator_resolvable() { + List transformersList = new ArrayList(); + + // Mix them up when inserting + transformersList.add(new BaseTransformerRegistry.JavaSourceFallbackTransformer(C.class, null)); + transformersList.add(new BaseTransformerRegistry.JavaSourceFallbackTransformer(E.class, null)); + transformersList.add(new BaseTransformerRegistry.JavaSourceFallbackTransformer(D.class, null)); + transformersList.add(new BaseTransformerRegistry.JavaSourceFallbackTransformer(A.class, null)); + transformersList.add(new BaseTransformerRegistry.JavaSourceFallbackTransformer(B.class, null)); + + BaseTransformerRegistry.JavaSourceFallbackTransformerComparator comparator = new BaseTransformerRegistry.JavaSourceFallbackTransformerComparator(); + Collections.sort(transformersList, comparator); + + // Should be sorted, sub-types first... + Assert.assertTrue(transformersList.get(0).getJavaType() == E.class); + Assert.assertTrue(transformersList.get(1).getJavaType() == D.class); + Assert.assertTrue(transformersList.get(2).getJavaType() == C.class); + Assert.assertTrue(transformersList.get(3).getJavaType() == B.class); + Assert.assertTrue(transformersList.get(4).getJavaType() == A.class); + } + + @Test + public void test_getFallbackTransformer_resolvable() { + addTransformer(B.class); + addTransformer(C.class); + addTransformer(A.class); + + Transformer transformer; + + // Should return no transformer... + transformer = _registry.getTransformer(getType(D.class), new QName("targetX")); + Assert.assertNull(transformer); + + // Should return the C transformer... + transformer = _registry.getTransformer(getType(D.class), new QName("target1")); + Assert.assertNotNull(transformer); + Assert.assertEquals(getType(C.class), transformer.getFrom()); + + transformer = _registry.getTransformer(getType(D.class), new QName("target1")); + } + + @Test + public void testGetTransformSequence() { + final QName A = new QName("a"); + final QName B = new QName("b"); + final QName C = new QName("c"); + + BaseTransformerRegistry _registry = new BaseTransformerRegistry(); + _registry.addTransformer(new TestTransformer2(A, B)); + _registry.addTransformer(new TestTransformer2(B, C)); + + TransformSequence transformSequence = _registry.getTransformSequence(A, C); + DefaultMessage message = new DefaultMessage().setContent(A); + transformSequence.apply(message, _registry); + Assert.assertEquals(C, message.getContent()); + } + + private void addTransformer(Class type) { + QName fromType = getType(type); + QName toType = new QName("target1"); + _registry.addTransformer(new TestTransformer(fromType, toType)); + } + + private QName getType(Class type) { + return JavaTypes.toMessageType(type); + } + + public class A {} + public class B extends A {} + public class C extends B {} + public class D extends C implements I {} + public class E extends D {} + public interface I {} + + public class TestTransformer extends BaseTransformer { + public TestTransformer(QName from, QName to) { + super(from, to); + } + + @Override + public Object transform(Object from) { + return from; + } + } + + private class TestTransformer2 extends BaseTransformer { + + private QName from; + private QName to; + + private TestTransformer2(QName from, QName to) { + super(from, to); + this.from = from; + this.to = to; + } + + @Override + public Object transform(Object from) { + Assert.assertEquals(this.from, from); + return to; + } + } +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformerTest.java b/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformerTest.java new file mode 100644 index 000000000..b906f1ee0 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/transform/BaseTransformerTest.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal.transform; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.transform.BaseTransformer; + +public class BaseTransformerTest { + + @Test + public void testGetName_default_with_generics() { + BaseTransformer intToStr = + new BaseTransformer() { + public String transform(Double from) { + return null; + } + }; + + Assert.assertEquals("java:java.lang.Double", intToStr.getFrom().toString()); + Assert.assertEquals("java:java.lang.String", intToStr.getTo().toString()); + } + + @Test + public void testGetName_default_without_generics() { + // No generics... + BaseTransformer intToStr = + new BaseTransformer() { + public Object transform(Object from) { + return null; + } + }; + + Assert.assertEquals("java:java.lang.Object", intToStr.getFrom().toString()); + Assert.assertEquals("java:java.lang.Object", intToStr.getTo().toString()); + } + + @Test + public void testGetName_specified_with_generics() { + final QName fromName = new QName("string1"); + final QName toName = new QName("string2"); + + BaseTransformer intToStr = + new BaseTransformer(fromName, toName) { + public String transform(String from) { + return null; + } + }; + + Assert.assertEquals(fromName, intToStr.getFrom()); + Assert.assertEquals(toName, intToStr.getTo()); + } + + @Test + public void testGetName_specified_without_generics() { + final QName fromName = new QName("string1"); + final QName toName = new QName("string2"); + + BaseTransformer intToStr = + new BaseTransformer(fromName, toName) { + public Object transform(Object from) { + return null; + } + }; + + Assert.assertEquals(fromName, intToStr.getFrom()); + Assert.assertEquals(toName, intToStr.getTo()); + } +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/transform/TransformSequenceTest.java b/core/runtime/src/test/java/org/switchyard/internal/transform/TransformSequenceTest.java new file mode 100644 index 000000000..29d669a13 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/transform/TransformSequenceTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal.transform; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.TransformSequence; + +/** + * @author tom.fennelly@gmail.com + */ +public class TransformSequenceTest { + + @Test + public void test() { + final QName A = new QName("a"); + final QName B = new QName("b"); + final QName C = new QName("c"); + final QName D = new QName("d"); + + BaseTransformerRegistry xformReg = new BaseTransformerRegistry(); + TransformSequence transSequence = TransformSequence.from(A).to(B).to(C).to(D); + + DefaultMessage message = new DefaultMessage().setContent(A); + + // Apply transform sequence ... no relevant transformers in the reg... nothing should + // happen i.e. content should still be "a"... + transSequence.apply(message, xformReg); + Assert.assertEquals(A, message.getContent()); + + // Add just th "a" to "b" transformer... run again... should transform to "b", but no further... + xformReg.addTransformer(new MockTransformer(A, B)); + transSequence.apply(message, xformReg); + Assert.assertEquals(B, message.getContent()); + + // Add the rest of the transforms now... should transform the last steps in one go... + xformReg.addTransformer(new MockTransformer(B, C)).addTransformer(new MockTransformer(C, D)); + transSequence.apply(message, xformReg); + Assert.assertEquals(D, message.getContent()); + } + + private class MockTransformer extends BaseTransformer { + + private QName from; + private QName to; + + private MockTransformer(QName from, QName to) { + super(from, to); + this.from = from; + this.to = to; + } + + @Override + public Object transform(Object from) { + Assert.assertEquals(this.from, from); + return to; + } + } +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/validate/BaseValidatorRegistryTest.java b/core/runtime/src/test/java/org/switchyard/internal/validate/BaseValidatorRegistryTest.java new file mode 100644 index 000000000..d977a4c62 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/validate/BaseValidatorRegistryTest.java @@ -0,0 +1,140 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal.validate; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.Validator; +import org.switchyard.validate.ValidatorRegistry; + +public class BaseValidatorRegistryTest { + + private ValidatorRegistry _registry; + + @Before + public void setUp() throws Exception { + _registry = new BaseValidatorRegistry(); + } + + @Test + public void testNullValidator() { + final QName name = new QName("notfound"); + + Validator validator = _registry.getValidator(name); + Assert.assertTrue(validator == null); + } + + @Test + public void testAddGetValidator() { + final QName name = new QName("a"); + + BaseValidator t = + new BaseValidator(name) { + public ValidationResult validate(String obj) { + if (obj != null) { + return validResult(); + } else { + return invalidResult("obj == null"); + } + } + }; + + _registry.addValidator(t); + Assert.assertEquals(t, _registry.getValidator(name)); + } + + @Test + public void test_fallbackValidatorComparator_resolvable() { + List validatorsList = new ArrayList(); + + // Mix them up when inserting + validatorsList.add(new BaseValidatorRegistry.JavaSourceFallbackValidator(C.class, null)); + validatorsList.add(new BaseValidatorRegistry.JavaSourceFallbackValidator(E.class, null)); + validatorsList.add(new BaseValidatorRegistry.JavaSourceFallbackValidator(D.class, null)); + validatorsList.add(new BaseValidatorRegistry.JavaSourceFallbackValidator(A.class, null)); + validatorsList.add(new BaseValidatorRegistry.JavaSourceFallbackValidator(B.class, null)); + + BaseValidatorRegistry.JavaSourceFallbackValidatorComparator comparator = new BaseValidatorRegistry.JavaSourceFallbackValidatorComparator(); + Collections.sort(validatorsList, comparator); + + // Should be sorted, sub-types first... + Assert.assertTrue(validatorsList.get(0).getJavaType() == E.class); + Assert.assertTrue(validatorsList.get(1).getJavaType() == D.class); + Assert.assertTrue(validatorsList.get(2).getJavaType() == C.class); + Assert.assertTrue(validatorsList.get(3).getJavaType() == B.class); + Assert.assertTrue(validatorsList.get(4).getJavaType() == A.class); + } + + @Test + public void test_getFallbackValidator_resolvable() { + addValidator(B.class); + addValidator(C.class); + + Validator validator; + + // Should return no validator... + validator = _registry.getValidator(getType(A.class)); + Assert.assertNull(validator); + + // Should return the C validator... + validator = _registry.getValidator(getType(D.class)); + Assert.assertNotNull(validator); + Assert.assertEquals(getType(C.class), validator.getName()); + + } + + private void addValidator(Class type) { + QName name = getType(type); + _registry.addValidator(new TestValidator(name)); + } + + private QName getType(Class type) { + return JavaTypes.toMessageType(type); + } + + public class A {} + public class B extends A {} + public class C extends B {} + public class D extends C implements I {} + public class E extends D {} + public interface I {} + + public class TestValidator extends BaseValidator { + public TestValidator(QName name) { + super(name); + } + + @Override + public ValidationResult validate(Object obj) { + if (obj != null) { + return validResult(); + } else { + return invalidResult("obj != null"); + } + } + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/internal/validate/BaseValidatorTest.java b/core/runtime/src/test/java/org/switchyard/internal/validate/BaseValidatorTest.java new file mode 100644 index 000000000..6af82d708 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/internal/validate/BaseValidatorTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.internal.validate; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; + +public class BaseValidatorTest { + + @Test + public void testGetName_default_with_generics() { + BaseValidator strv = + new BaseValidator() { + public ValidationResult validate(String obj) { + if (obj != null) { + return validResult(); + } else { + return invalidResult("obj == null"); + } + } + }; + + Assert.assertEquals("java:java.lang.String", strv.getName().toString()); + } + + @Test + public void testGetName_default_without_generics() { + // No generics... + BaseValidator strv = + new BaseValidator() { + public ValidationResult validate(Object obj) { + if (obj != null) { + return validResult(); + } else { + return invalidResult("obj == null"); + } + } + }; + + Assert.assertEquals("java:java.lang.Object", strv.getName().toString()); + } + + @Test + public void testGetName_specified_with_generics() { + final QName name = new QName("string1"); + + BaseValidator strv = + new BaseValidator(name) { + public ValidationResult validate(String obj) { + if (obj != null) { + return validResult(); + } else { + return invalidResult("obj == null"); + } + } + }; + + Assert.assertEquals(name, strv.getName()); + } + + @Test + public void testGetName_specified_without_generics() { + final QName name = new QName("string1"); + + BaseValidator strv = + new BaseValidator(name) { + public ValidationResult validate(Object obj) { + if (obj != null) { + return validResult(); + } else { + return invalidResult("obj == null"); + } + } + }; + + Assert.assertEquals(name, strv.getName()); + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/tests/InOnlyTest.java b/core/runtime/src/test/java/org/switchyard/tests/InOnlyTest.java new file mode 100644 index 000000000..719b8437a --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/tests/InOnlyTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.tests; + +import java.util.LinkedList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.MockDomain; +import org.switchyard.ServiceReference; + +public class InOnlyTest { + + private MockDomain _domain; + // event counters used by tests + private List inEvents = new LinkedList(); + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + } + + @After + public void tearDown() throws Exception { + inEvents.clear(); + } + + @Test + public void testInOnlySuccess() throws Exception { + final QName serviceName = new QName("inOnlySuccess"); + + // Provide the service + ExchangeHandler provider = new BaseHandler() { + public void handleMessage(Exchange event) { + inEvents.add(event); + } + }; + + ServiceReference service = _domain.createInOnlyService(serviceName, provider); + + // Consume the service + Exchange exchange = service.createExchange(); + exchange.send(exchange.createMessage()); + + // wait a sec, since this is async + Thread.sleep(200); + Assert.assertTrue(inEvents.size() == 1); + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/tests/InOutTest.java b/core/runtime/src/test/java/org/switchyard/tests/InOutTest.java new file mode 100644 index 000000000..b0e087d34 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/tests/InOutTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.tests; + +import javax.xml.namespace.QName; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Exchange; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.ServiceReference; + +public class InOutTest { + + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + } + + + /** NEW WAY **/ + @Test + public void testInOutSuccess() throws Exception { + final QName serviceName = new QName("inOutSuccess"); + + // Provide the service + MockHandler provider = new MockHandler().forwardInToOut(); + ServiceReference service = _domain.createInOutService(serviceName, provider); + + // Consume the service + MockHandler consumer = new MockHandler(); + Exchange exchange = service.createExchange(consumer); + exchange.send(exchange.createMessage()); + + // wait, since this is async + provider.waitForOKMessage(); + consumer.waitForOKMessage(); + } + + @Test + public void testInOutFault() throws Exception { + + final QName serviceName = new QName("inOutFault"); + // Provide the service + MockHandler provider = new MockHandler().forwardInToFault(); + ServiceReference service = _domain.createInOutService(serviceName, provider); + + // Consume the service + MockHandler consumer = new MockHandler(); + Exchange exchange = service.createExchange(consumer); + exchange.send(exchange.createMessage()); + + // wait, since this is async + provider.waitForOKMessage(); + consumer.waitForFaultMessage(); + + } +} diff --git a/core/runtime/src/test/java/org/switchyard/tests/IndirectTransformationTest.java b/core/runtime/src/test/java/org/switchyard/tests/IndirectTransformationTest.java new file mode 100644 index 000000000..7973a560b --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/tests/IndirectTransformationTest.java @@ -0,0 +1,128 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.tests; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.ServiceReference; +import org.switchyard.handlers.TransformHandler; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.TransformSequence; +import org.switchyard.transform.Transformer; + +/** + * Tests for exercising the TransformationHandler during message exchange. + */ +public class IndirectTransformationTest { + + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + } + + /* Tests to Add : + * - test one level deep transformation + */ + + /** + * Test that the secondary Transform that is one level deep (i.e. A->B, B-C) is applied if the primary Transform (A->C) is not available + */ + @Test + public void testOneLevelDeepTransformInProvider() throws Exception { + final QName serviceName = new QName("nameTransform"); + final QName inType = new QName("fromA"); + final QName indirectDestOutType = new QName("viaB"); + final QName indirectDestInType = new QName("viaB"); + final QName finalDestOutType = new QName("toC"); + + final String input = "Hello"; + + // Add transforms to registry + Transformer transformAtoB = + new BaseTransformer(inType, indirectDestOutType) { + public String transform(String from) { + // transform the input date to the desired output string + return from + " there,"; + } + }; + _domain.getTransformerRegistry().addTransformer(transformAtoB); + + Transformer transformBtoC = + new BaseTransformer(indirectDestInType, finalDestOutType) { + public String transform(String from) { + // transform the input date to the desired output string + return from + " SwitchYard"; + } + }; + _domain.getTransformerRegistry().addTransformer(transformBtoC); + + try { + // Provide the service + TestTransformHandler serviceHandler = new TestTransformHandler(); + ServiceReference service = _domain.createInOnlyService(serviceName, serviceHandler); + + // Create the exchange and invoke the service + MockHandler invokerHandler = new MockHandler(); + Exchange exchange = service.createExchange(invokerHandler); + + // Set the from and to message names. NOTE: setting to the to message + // name will not be necessary once the service definition is available + // at runtime + Message msg = exchange.createMessage().setContent(input); + TransformSequence. + from(inType). + to(finalDestOutType). + associateWith(msg); + + msg.setContent(input); + + exchange.send(msg); + + Assert.assertTrue(serviceHandler.isSuccess()); + } finally { + // Must remove this transformer, otherwise it's there for the following test... will be + // fixed once we get rid of the static service domain. + _domain.getTransformerRegistry().removeTransformer(transformAtoB); + _domain.getTransformerRegistry().removeTransformer(transformBtoC); + } + } + + private class TestTransformHandler extends TransformHandler { + boolean success = false; + + public boolean isSuccess() { + return success; + } + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + String content = (String) exchange.getMessage().getContent(); + if (content.equals("Hello there, SwitchYard")) { + success=true; + } + } + } +} diff --git a/core/runtime/src/test/java/org/switchyard/tests/TransformationTest.java b/core/runtime/src/test/java/org/switchyard/tests/TransformationTest.java new file mode 100644 index 000000000..95cc776e2 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/tests/TransformationTest.java @@ -0,0 +1,140 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.tests; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.ServiceReference; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.TransformSequence; +import org.switchyard.transform.Transformer; + +/** + * Tests for exercising the TransformationHandler during message exchange. + */ +public class TransformationTest { + + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + } + + /* Tests to Add : + * - test failed transformation + * - test transform reply + */ + + /** + * Transformation is loaded from the transformer registry based on the + * message names (from/to). + */ + @Test + public void testTransformationByName() throws Exception { + final QName serviceName = new QName("nameTransform"); + final QName inType = new QName("fromA"); + final QName expectedDestType = new QName("toB"); + final String input = "Hello"; + final String output = "Hello SwitchYard"; + + // Define the transformation and register it + Transformer helloTransform = + new BaseTransformer(inType, expectedDestType) { + public String transform(String from) { + // transform the input date to the desired output string + return from + " SwitchYard"; + } + }; + _domain.getTransformerRegistry().addTransformer(helloTransform); + + try { + // Provide the service + MockHandler provider = new MockHandler(); + ServiceReference service = _domain.createInOnlyService(serviceName, provider); + + // Create the exchange and invoke the service + Exchange exchange = service.createExchange(); + + // Set the from and to message names. NOTE: setting to the to message + // name will not be necessary once the service definition is available + // at runtime + Message msg = exchange.createMessage().setContent(input); + TransformSequence. + from(inType). + to(expectedDestType). + associateWith(msg); + + msg.setContent(input); + exchange.send(msg); + + // wait for message and verify transformation + provider.waitForOKMessage(); + Assert.assertEquals(provider.getMessages().poll().getMessage().getContent(), output); + } finally { + // Must remove this transformer, otherwise it's there for the following test... will be + // fixed once we get rid of the static service domain. + _domain.getTransformerRegistry().removeTransformer(helloTransform); + } + } + + /** + * Test that the TransformHandler throws an exception if transformations are not applied. + */ + @Test + public void testTransformationsNotApplied() throws Exception { + final QName serviceName = new QName("nameTransform"); + final QName inType = new QName("fromA"); + final QName expectedDestType = new QName("toB"); + final String input = "Hello"; + + // Provide the service + MockHandler provider = new MockHandler(); + ServiceReference service = _domain.createInOnlyService(serviceName, provider); + + // Create the exchange and invoke the service + MockHandler invokerHandler = new MockHandler(); + Exchange exchange = service.createExchange(invokerHandler); + + // Set the from and to message names. NOTE: setting to the to message + // name will not be necessary once the service definition is available + // at runtime + Message msg = exchange.createMessage().setContent(input); + TransformSequence. + from(inType). + to(expectedDestType). + associateWith(msg); + + msg.setContent(input); + + exchange.send(msg); + + invokerHandler.waitForFaultMessage(); + Object content = invokerHandler.getFaults().poll().getMessage().getContent(); + Assert.assertTrue(content instanceof HandlerException); + String testString = "Transformations not applied. Required payload type of 'toB'. Actual payload type is 'fromA'. You must define and register a Transformer to transform between these types."; + boolean transformsApplied = ((HandlerException)content).getMessage().contains(testString); + Assert.assertTrue(transformsApplied); + } +} diff --git a/core/runtime/src/test/java/org/switchyard/tests/ValidationTest.java b/core/runtime/src/test/java/org/switchyard/tests/ValidationTest.java new file mode 100644 index 000000000..6c5274a62 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/tests/ValidationTest.java @@ -0,0 +1,145 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.tests; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.Exchange; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.MockDomain; +import org.switchyard.MockHandler; +import org.switchyard.Scope; +import org.switchyard.ServiceReference; +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.Validator; + +/** + * Tests for exercising the ValidationHandler during message exchange. + */ +public class ValidationTest { + + private MockDomain _domain; + + @Before + public void setUp() throws Exception { + _domain = new MockDomain(); + } + + /* Tests to Add : + * - test failed validation + * - test validate reply + */ + + /** + * Validation is loaded from the validator registry based on the + * message name. + */ + @Test + public void testValidationByName() throws Exception { + final QName serviceName = new QName("nameValidate"); + final QName typeName = new QName("A"); + final String input = "Hello"; + + // Define the validation and register it + Validator helloValidate = + new BaseValidator(typeName) { + public ValidationResult validate(String obj) { + if (obj.equals("Hello")) { + return validResult(); + } else { + return invalidResult("obj.equals(\"Hello\") was false"); + } + } + }; + _domain.getValidatorRegistry().addValidator(helloValidate); + + try { + // Provide the service + MockHandler provider = new MockHandler(); + ServiceReference service = _domain.createInOnlyService(serviceName, provider); + + // Create the exchange and invoke the service + Exchange exchange = service.createExchange(); + + // Set the message name. NOTE: setting to the to message + // name will not be necessary once the service definition is available + // at runtime + Message msg = exchange.createMessage().setContent(input); + msg.getContext().setProperty(Exchange.CONTENT_TYPE, typeName); + + msg.setContent(input); + exchange.send(msg); + + // wait for message and verify validation + provider.waitForOKMessage(); + Assert.assertEquals(provider.getMessages().poll().getMessage().getContent(), input); + } finally { + // Must remove this validator, otherwise it's there for the following test... will be + // fixed once we get rid of the static service domain. + _domain.getValidatorRegistry().removeValidator(helloValidate); + } + } + + /** + * Test that the ValidateHandler throws an exception if validations are not applied. + */ + @Test + public void testValidationsFailed() throws Exception { + final QName serviceName = new QName("nameValidate"); + final QName typeName = new QName("A"); + final String input = "Hello"; + + // Define the validation which always fail and register it + Validator failValidate = + new BaseValidator(typeName) { + public ValidationResult validate(String obj) { + return invalidResult("validation fail test"); + } + }; + _domain.getValidatorRegistry().addValidator(failValidate); + + // Provide the service + MockHandler provider = new MockHandler(); + ServiceReference service = _domain.createInOnlyService(serviceName, provider); + + // Create the exchange and invoke the service + MockHandler invokerHandler = new MockHandler(); + Exchange exchange = service.createExchange(invokerHandler); + + // Set the message name. NOTE: setting to the to message + // name will not be necessary once the service definition is available + // at runtime + Message msg = exchange.createMessage().setContent(input); + msg.getContext().setProperty(Exchange.CONTENT_TYPE, typeName); + + msg.setContent(input); + + exchange.send(msg); + + invokerHandler.waitForFaultMessage(); + Object content = invokerHandler.getFaults().poll().getMessage().getContent(); + Assert.assertTrue(content instanceof HandlerException); + + boolean failed = ((HandlerException)content).getMessage().contains("Validator 'org.switchyard.tests.ValidationTest$2' failed: validation fail test"); + Assert.assertTrue(failed); + } + +} diff --git a/core/runtime/src/test/java/org/switchyard/tests/VersionTest.java b/core/runtime/src/test/java/org/switchyard/tests/VersionTest.java new file mode 100644 index 000000000..8135a2967 --- /dev/null +++ b/core/runtime/src/test/java/org/switchyard/tests/VersionTest.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.tests; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertTrue; +import static org.switchyard.common.version.Queries.Projects.SWITCHYARD; +import static org.switchyard.common.version.Queries.Projects.SWITCHYARD_API; +import static org.switchyard.common.version.Queries.Projects.SWITCHYARD_COMMON; +import static org.switchyard.common.version.QueryType.PROJECT_ARTIFACT_ID; +import static org.switchyard.common.version.QueryType.SPECIFICATION_TITLE; + +import java.util.Iterator; +import java.util.Set; +import java.util.TreeSet; + +import org.junit.Test; +import org.switchyard.common.version.Queries.Projects; +import org.switchyard.common.version.Query; +import org.switchyard.common.version.Version; +import org.switchyard.common.version.VersionFactory; +import org.switchyard.common.version.Versions; + +/** + * VersionTest. + * + * @author David Ward <dward@jboss.org> (C) 2012 Red Hat Inc. + */ +public class VersionTest { + + @Test + public void testPrint() { + Versions.printSwitchYardNotification(); + Versions.printSwitchYardVersions(); + } + + @Test + public void testEquals() { + VersionFactory factory = VersionFactory.instance(); + final Version expected = factory.getVersion(SWITCHYARD_COMMON); + Version actual = factory.getVersion(Projects.create("org.switchyard", "switchyard-common")); + assertEquals(expected, actual); + actual = factory.getVersion(SWITCHYARD, new Query(PROJECT_ARTIFACT_ID, "switchyard-common")); + assertEquals(expected, actual); + actual = factory.getVersion(new Query(SPECIFICATION_TITLE, "SwitchYard: Common")); + assertEquals(expected, actual); + } + + @Test + public void testCompare() { + VersionFactory factory = VersionFactory.instance(); + Version api = factory.getVersion(SWITCHYARD_API); + Version common = factory.getVersion(SWITCHYARD_COMMON); + Set set = new TreeSet(); + // add out of order + set.add(common); + set.add(api); + Iterator iter = set.iterator(); + // test compare did ordering + assertTrue("1st version should be api", iter.next() == api); + assertTrue("2nd version should be common", iter.next() == common); + } + +} diff --git a/core/runtime/src/test/resources/log4j.properties b/core/runtime/src/test/resources/log4j.properties new file mode 100644 index 000000000..02a249c1d --- /dev/null +++ b/core/runtime/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootCategory=INFO, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=DEBUG +log4j.appender.CONSOLE.Target=System.out +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n diff --git a/core/security/base/pom.xml b/core/security/base/pom.xml new file mode 100644 index 000000000..197e46793 --- /dev/null +++ b/core/security/base/pom.xml @@ -0,0 +1,50 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-security + bundle + SwitchYard: Security + The base security library. + http://switchyard.org + + + org.switchyard.security.* + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + + org.jboss.spec.javax.servlet + jboss-servlet-api_2.5_spec + provided + + + diff --git a/core/security/base/src/main/java/org/switchyard/security/BaseSecurityLogger.java b/core/security/base/src/main/java/org/switchyard/security/BaseSecurityLogger.java new file mode 100644 index 000000000..d190af00e --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/BaseSecurityLogger.java @@ -0,0 +1,69 @@ +package org.switchyard.security; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.INFO; +import static org.jboss.logging.Logger.Level.WARN; + +import javax.security.auth.login.LoginException; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 14200-14399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface BaseSecurityLogger { + /** + * Default root logger. + */ + BaseSecurityLogger ROOT_LOGGER = Logger.getMessageLogger(BaseSecurityLogger.class, BaseSecurityLogger.class.getPackage().getName()); + + /** + * authenticateLoginException method definition. + * @param message message + * @param le le + */ + @LogMessage(level = ERROR) + @Message(id = 14200, value = "authenticate LoginException: %s") + void authenticateLoginException(String message, @Cause LoginException le); + + /** + * usingSecurityProviderImplementation method definition. + * @param implementationName implementationName + */ + @LogMessage(level = INFO) + @Message(id = 14201, value = "Using SecurityProvider implementation: %s") + void usingSecurityProviderImplementation(String implementationName); + + /** + * charSetNameIllegal method definition. + * @param charsetName charsetName + */ + @LogMessage(level = ERROR) + @Message(id = 14202, value = "charsetName [%s] + is illegal or unsupported; using platform-default") + void charSetNameIllegal(String charsetName); + + /** + * charSetNull method definition. + */ + @LogMessage(level = WARN) + @Message(id = 14203, value = "charsetName is null; using platform-default") + void charSetNull(); + + /** + * configurationNumberFormatException method definition. + * @param name name + * @param value value + * @param nfe nfe + */ + @LogMessage(level = ERROR) + @Message(id = 14204, value = "configuration NumberFormatException: %s=[%s]") + void configurationNumberFormatException(String name, String value, @Cause NumberFormatException nfe); +} diff --git a/core/security/base/src/main/java/org/switchyard/security/BaseSecurityMessages.java b/core/security/base/src/main/java/org/switchyard/security/BaseSecurityMessages.java new file mode 100644 index 000000000..41c048441 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/BaseSecurityMessages.java @@ -0,0 +1,158 @@ +package org.switchyard.security; + +import java.io.IOException; +import java.security.cert.CertificateException; + +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.security.auth.login.LoginException; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 14400-14599 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface BaseSecurityMessages { + /** + * Default messages. + */ + BaseSecurityMessages MESSAGES = Messages.getBundle(BaseSecurityMessages.class); + + /** + * propertiesNotSet method definition. + * @return IllegalStateException + */ + @Message(id = 14401, value="Properties are not set") + IllegalStateException propertiesNotSet(); + + /** + * propertyNotSet method definition. + * @param key key + * @return IllegalStateException + */ + @Message(id = 14402, value="Property [%s] is not set.") + IllegalStateException propertyNotSet(String key); + + /** + * credentialsNotSet method definition. + * @return IllegalStateException + */ + @Message(id = 14403, value="Credentials are not set.") + IllegalStateException credentialsNotSet(); + + /** + * unableToExtractCredentials method definition. + * @param message message + * @param pe pe + * @return RuntimeException + */ + @Message(id = 14404, value="Unable to extract Credentials from SSLSession: %s") + RuntimeException unableToExtractCredentials(String message, @Cause SSLPeerUnverifiedException pe); + + /** + * valueTypeRecognizedNotImplemented method definition. + * @param valueType valueType + * @return IllegalArgumentException + */ + @Message(id = 14405, value="%s not implemented (although recognized)") + IllegalArgumentException valueTypeRecognizedNotImplemented(String valueType); + + /** + * valueTypeNotImplemented method definition. + * @param valueType valueType + * @return IllegalArgumentException + */ + @Message(id = 14406, value="%s not implemented") + IllegalArgumentException valueTypeNotImplemented(String valueType); + + /** + * couldNotCreateCert method definition. + * @param message message + * @param ce ce + * @return RuntimeException + */ + @Message(id = 14407, value="Could not create certificate(s): %s") + RuntimeException couldNotCreateCert(String message, @Cause CertificateException ce); + + /** + * optionsNotSet method definition. + * @param message message + * @param ioe ioe + * @return LoginException + */ + @Message(id = 14408, value="Failed to invoke callback: %s") + LoginException failedInvokeCallback(String message, @Cause IOException ioe); + + /** + * callbackHandlerNoSupport method definition. + * @param handler handler + * @return LoginException + */ + @Message(id = 14410, value="CallbackHandler does not support: %s") + LoginException callbackHandlerNoSupport(String handler); + + /** + * problemAccessingKeystore method definition. + * @param message message + * @return LoginException + */ + @Message(id = 14411, value="Problem accessing KeyStore: %s") + LoginException problemAccessingKeystore(String message); + + /** + * problemVerifyingCallerCert method definition. + * @param message message + * @return LoginException + */ + @Message(id = 14412, value="Problem verifying caller Certificate: %s") + LoginException problemVerifyingCallerCert(String message); + + /** + * noCallerCertificateProvided method definition. + * @return LoginException + */ + @Message(id = 14413, value="No caller X509 Certificate provided") + LoginException noCallerCertificateProvided(); + + /** + * optionsNotSet method definition. + * @return IllegalStateException + */ + @Message(id = 14414, value="Options not set") + IllegalStateException optionsNotSet(); + + /** + * optionNotSet method definition. + * @param name name + * @return IllegalStateException + */ + @Message(id = 14415, value="Option [%s] not set") + IllegalStateException optionNotSet(String name); + + /** + * groupNameCannotBeNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 14416, value="Group name cannot be null") + IllegalArgumentException groupNameCannotBeNull(); + + /** + * roleCannotBeNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 14417, value="Role name cannot be null") + IllegalArgumentException roleCannotBeNull(); + + /** + * userNameCannotBeNull method definition. + * @return IllegalArgumentException + */ + @Message(id = 14418, value="User name cannot be null") + IllegalArgumentException userNameCannotBeNull(); +} diff --git a/core/security/base/src/main/java/org/switchyard/security/SecurityMetadata.java b/core/security/base/src/main/java/org/switchyard/security/SecurityMetadata.java new file mode 100644 index 000000000..9cf263d83 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/SecurityMetadata.java @@ -0,0 +1,120 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security; + +import org.switchyard.Exchange; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.ServiceSecurity; + +/** + * SecurityMetadata. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public final class SecurityMetadata { + + private final Source _source; + private final ServiceDomain _serviceDomain; + private final ServiceSecurity _serviceSecurity; + + private SecurityMetadata(Source source, ServiceDomain serviceDomain, ServiceSecurity serviceSecurity) { + _source = source; + _serviceDomain = serviceDomain; + _serviceSecurity = serviceSecurity; + } + + /** + * If the source is the provider Service. + * @return if true + */ + public boolean isProvider() { + return _source == Source.PROVIDER; + } + + /** + * If the source is the consumer ServiceReference. + * @return if true + */ + public boolean isConsumer() { + return _source == Source.CONSUMER; + } + + /** + * Gets the ServiceDomain. + * @return the ServiceDomain + */ + public ServiceDomain getServiceDomain() { + return _serviceDomain; + } + + /** + * Gets the ServiceSecurity. + * @return the ServiceSecurity + */ + public ServiceSecurity getServiceSecurity() { + return _serviceSecurity; + } + + /** + * Gets the ServiceDomain from the Exchange. + * @param exchange the Exchange + * @return the ServiceDomain + */ + public static final ServiceDomain getServiceDomain(Exchange exchange) { + return getSecurityMetadata(exchange).getServiceDomain(); + } + + /** + * Gets the ServiceSecurity from the Exchange. + * @param exchange the Exchange + * @return the ServiceSecurity + */ + public static final ServiceSecurity getServiceSecurity(Exchange exchange) { + return getSecurityMetadata(exchange).getServiceSecurity(); + } + + /** + * Gets the SecurityMetadata from the Exchange. + * @param exchange the Exchange + * @return the SecurityMetadata + */ + public static final SecurityMetadata getSecurityMetadata(Exchange exchange) { + Source source = null; + ServiceDomain serviceDomain = null; + ServiceSecurity serviceSecurity = null; + Service service = exchange.getProvider(); + if (service != null) { + source = Source.PROVIDER; + serviceDomain = service.getDomain(); + serviceSecurity = service.getServiceMetadata().getSecurity(); + } + if (serviceSecurity == null) { + ServiceReference serviceReference = exchange.getConsumer(); + if (serviceReference != null) { + source = Source.CONSUMER; + serviceDomain = serviceReference.getDomain(); + serviceSecurity = serviceReference.getServiceMetadata().getSecurity(); + } + } + return new SecurityMetadata(source, serviceDomain, serviceSecurity); + } + + private static enum Source { + PROVIDER, + CONSUMER; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/SecurityServices.java b/core/security/base/src/main/java/org/switchyard/security/SecurityServices.java new file mode 100644 index 000000000..084f03556 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/SecurityServices.java @@ -0,0 +1,53 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security; + +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.security.credential.extractor.DefaultServletRequestCredentialExtractor; +import org.switchyard.security.credential.extractor.ServletRequestCredentialExtractor; +import org.switchyard.security.provider.DefaultSecurityProvider; +import org.switchyard.security.provider.SecurityProvider; + +/** + * SecurityServices. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public final class SecurityServices { + + private SecurityServices() {} + + /** + * Gets the SecurityProvider. + * @return the SecurityProvider + */ + public static final SecurityProvider getSecurityProvider() { + SecurityProvider sp = getProvider(SecurityProvider.class); + return sp != null ? sp : new DefaultSecurityProvider(); + } + + /** + * Gets the ServletRequestCredentialExtractor. + * @return the ServletRequestCredentialExtractor + */ + public static final ServletRequestCredentialExtractor getServletRequestCredentialExtractor() { + ServletRequestCredentialExtractor srce = getProvider(ServletRequestCredentialExtractor.class); + return srce != null ? srce : new DefaultServletRequestCredentialExtractor(); + } + + private static final T getProvider(Class clazz) { + return ProviderRegistry.getProvider(clazz, clazz.getClassLoader()); + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/callback/CertificateCallback.java b/core/security/base/src/main/java/org/switchyard/security/callback/CertificateCallback.java new file mode 100644 index 000000000..ee5b7b87f --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/callback/CertificateCallback.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.callback; + +import java.security.cert.Certificate; +import java.util.LinkedHashSet; +import java.util.Set; + +import javax.security.auth.callback.Callback; + +/** + * CertificateCallback. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class CertificateCallback implements Callback { + + private Set _certificates = new LinkedHashSet(); + + /** + * Constructs a new CertificateCallback. + */ + public CertificateCallback() {} + + /** + * Gets the Certificates. + * @return the Certificates + */ + public Set getCertificates() { + Set copy = new LinkedHashSet(); + copy.addAll(_certificates); + return copy; + } + + /** + * Adds a Certificate. + * @param certificate the Certificate to add + */ + public void addCertificate(Certificate certificate) { + if (certificate != null) { + _certificates.add(certificate); + } + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/callback/handler/CertificateCallbackHandler.java b/core/security/base/src/main/java/org/switchyard/security/callback/handler/CertificateCallbackHandler.java new file mode 100644 index 000000000..bf2b2f3e5 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/callback/handler/CertificateCallbackHandler.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.callback.handler; + +import java.io.IOException; +import java.util.Set; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; + +import org.switchyard.security.BaseSecurityMessages; +import org.switchyard.security.callback.CertificateCallback; +import org.switchyard.security.credential.CertificateCredential; +import org.switchyard.security.credential.Credential; + +/** + * CertificateCallbackHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class CertificateCallbackHandler extends SwitchYardCallbackHandler { + + /** + * Constructs a new CertificateCallbackHandler. + */ + public CertificateCallbackHandler() {} + + /** + * {@inheritDoc} + */ + @Override + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + String alias = getProperty("alias", true); + String keyPassword = getProperty("keyPassword", false); + Set credentials = getCredentials(); + if (credentials == null) { + throw BaseSecurityMessages.MESSAGES.credentialsNotSet(); + } + for (Callback cb : callbacks) { + if (cb instanceof NameCallback) { + ((NameCallback)cb).setName(alias); + } else if (cb instanceof PasswordCallback && keyPassword != null) { + ((PasswordCallback)cb).setPassword(keyPassword.toCharArray()); + } else if (cb instanceof CertificateCallback) { + CertificateCallback cert_cb = (CertificateCallback)cb; + for (Credential cred : credentials) { + if (cred instanceof CertificateCredential) { + cert_cb.addCertificate(((CertificateCredential)cred).getCertificate()); + } + } + } + } + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/callback/handler/NamePasswordCallbackHandler.java b/core/security/base/src/main/java/org/switchyard/security/callback/handler/NamePasswordCallbackHandler.java new file mode 100644 index 000000000..55b2ad108 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/callback/handler/NamePasswordCallbackHandler.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.callback.handler; + +import java.io.IOException; +import java.util.Set; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; + +import org.switchyard.security.BaseSecurityMessages; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.NameCredential; +import org.switchyard.security.credential.PasswordCredential; + +/** + * NamePasswordCallbackHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class NamePasswordCallbackHandler extends SwitchYardCallbackHandler { + + /** + * Constructs a new NamePasswordCallbackHandler. + */ + public NamePasswordCallbackHandler() {} + + /** + * {@inheritDoc} + */ + @Override + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + Set credentials = getCredentials(); + if (credentials == null) { + throw BaseSecurityMessages.MESSAGES.credentialsNotSet(); + } + for (Callback cb : callbacks) { + if (cb instanceof NameCallback) { + for (Credential cred : credentials) { + if (cred instanceof NameCredential) { + ((NameCallback)cb).setName(((NameCredential)cred).getName()); + } + } + } else if (cb instanceof PasswordCallback) { + for (Credential cred : credentials) { + if (cred instanceof PasswordCredential) { + ((PasswordCallback)cb).setPassword(((PasswordCredential)cred).getPassword()); + } + } + } + } + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/callback/handler/SwitchYardCallbackHandler.java b/core/security/base/src/main/java/org/switchyard/security/callback/handler/SwitchYardCallbackHandler.java new file mode 100644 index 000000000..82f5f9599 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/callback/handler/SwitchYardCallbackHandler.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.callback.handler; + +import java.util.Map; +import java.util.Set; + +import javax.security.auth.callback.CallbackHandler; + +import org.switchyard.security.BaseSecurityMessages; +import org.switchyard.security.credential.Credential; + +/** + * SwitchYardCallbackHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class SwitchYardCallbackHandler implements CallbackHandler { + + private Map _properties; + private Set _credentials; + + /** + * Gets the Properties. + * @return the Properties + */ + public Map getProperties() { + return _properties; + } + + /** + * Gets a property value with the specified name. + * @param name the specified name + * @return the property value, or null if not set + */ + public String getProperty(String name) { + return getProperty(name, false); + } + + /** + * Gets a property value with the specified name. + * @param name the specified name + * @param required if the property is required to have been set + * @return the property value + */ + public String getProperty(String name, boolean required) { + Map properties = getProperties(); + if (properties == null) { + if (required) { + throw BaseSecurityMessages.MESSAGES.propertiesNotSet(); + } + } else { + String value = properties.get(name); + if (value == null && required) { + throw BaseSecurityMessages.MESSAGES.propertyNotSet(name); + } + return value; + } + return null; + } + + /** + * Sets the Properties. + * @param properties the Properties + * @return this instance (useful for chaining) + */ + public SwitchYardCallbackHandler setProperties(Map properties) { + _properties = properties; + return this; + } + + /** + * Gets the Credentials. + * @return the Credentials + */ + public Set getCredentials() { + return _credentials; + } + + /** + * Sets the Credentials. + * @param credentials the Credentials + * @return this instance (useful for chaining) + */ + public SwitchYardCallbackHandler setCredentials(Set credentials) { + _credentials = credentials; + return this; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/context/DefaultExchangeSecurity.java b/core/security/base/src/main/java/org/switchyard/security/context/DefaultExchangeSecurity.java new file mode 100644 index 000000000..0bd74fb86 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/context/DefaultExchangeSecurity.java @@ -0,0 +1,94 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.context; + +import java.security.Principal; + +import javax.security.auth.Subject; + +import org.switchyard.Exchange; +import org.switchyard.ExchangeSecurity; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceSecurity; +import org.switchyard.security.SecurityMetadata; + +/** + * Default ExchangeSecurity implementation. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class DefaultExchangeSecurity implements ExchangeSecurity { + + private final Exchange _exchange; + private final String _securityDomain; + private final SecurityContextManager _securityContextManager; + + /** + * Creates a new ExchangeUtil for the specified Exchange. + * @param exchange the Exchange + */ + public DefaultExchangeSecurity(Exchange exchange) { + _exchange = exchange; + SecurityMetadata securityMetadata = SecurityMetadata.getSecurityMetadata(exchange); + ServiceSecurity serviceSecurity = securityMetadata.getServiceSecurity(); + _securityDomain = serviceSecurity != null ? serviceSecurity.getSecurityDomain() : null; + ServiceDomain serviceDomain = securityMetadata.getServiceDomain(); + _securityContextManager = serviceDomain != null ? new SecurityContextManager(serviceDomain) : null; + } + + /** + * Gets the security context. This method is not exposed in the public API. + * @return the security context + */ + public SecurityContext getSecurityContext() { + if (_securityContextManager != null) { + return _securityContextManager.getContext(_exchange); + } + return null; + } + + /** + * Gets the subject. This method is not exposed in the public API. + * @return the subject + */ + public Subject getSubject() { + if (_securityContextManager != null) { + return _securityContextManager.getContext(_exchange).getSubject(_securityDomain); + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Principal getCallerPrincipal() { + if (_securityContextManager != null) { + return _securityContextManager.getContext(_exchange).getCallerPrincipal(_securityDomain); + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isCallerInRole(String roleName) { + if (_securityContextManager != null) { + return _securityContextManager.getContext(_exchange).isCallerInRole(roleName, _securityDomain); + } + return false; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/context/DefaultSecurityContext.java b/core/security/base/src/main/java/org/switchyard/security/context/DefaultSecurityContext.java new file mode 100644 index 000000000..c3a3ec491 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/context/DefaultSecurityContext.java @@ -0,0 +1,260 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.context; + +import static org.switchyard.security.principal.GroupPrincipal.CALLER_PRINCIPAL; +import static org.switchyard.security.principal.GroupPrincipal.ROLES; + +import java.security.Principal; +import java.security.acl.Group; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; + +import javax.security.auth.Subject; + +import org.switchyard.security.credential.Credential; +import org.switchyard.security.principal.UserPrincipal; +import org.switchyard.security.system.SystemSecurity; + +/** + * DefaultSecurityContext. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class DefaultSecurityContext implements SecurityContext { + + private static final long serialVersionUID = -5672423874298035845L; + private static final String FORMAT = DefaultSecurityContext.class.getSimpleName() + "@%s[systemUUID=%s, expirationMillis=%s, credentials=%s, securityDomainsToSubjects=%s]"; + + private final UUID _systemUUID; + private final long _expirationMillis; // this is not included in equals() and hashCode() + private final Set _credentials = Collections.synchronizedSet(new LinkedHashSet()); + private final Map _securityDomainsToSubjects = Collections.synchronizedMap(new TreeMap()); + + /** + * Constructs a new DefaultSecurityContext with no timeout. + */ + DefaultSecurityContext() { + this(null, null); + } + + /** + * Constructs a new DefaultSecurityContext with the specified system UUID and timeout in milliseconds. + * @param systemUUID the system UUID + * @param timeoutMillis the timeout in milliseconds + */ + DefaultSecurityContext(UUID systemUUID, Long timeoutMillis) { + _systemUUID = systemUUID != null ? systemUUID : SystemSecurity.DEFAULT.getUUID(); + long em = 0; + if (timeoutMillis != null) { + long tm = timeoutMillis.longValue(); + if (tm > 0) { + em = System.currentTimeMillis() + tm; + } + } + _expirationMillis = em; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isValid(UUID systemUUID) { + return (_systemUUID.equals(systemUUID)) && (_expirationMillis == 0 || _expirationMillis > System.currentTimeMillis()); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getCredentials() { + return _credentials; + } + + /** + * {@inheritDoc} + */ + @Override + public Set getCredentials(Class clazz) { + Set matches = new HashSet(); + for (Credential credential : getCredentials()) { + if (credential != null && clazz.isAssignableFrom(credential.getClass())) { + matches.add(clazz.cast(credential)); + } + } + return matches; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized void clearCredentials() { + synchronized (_credentials) { + _credentials.clear(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Subject getSubject(String securityDomain) { + return getSubject(securityDomain, true); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized Subject getSubject(String securityDomain, boolean create) { + Subject subject = _securityDomainsToSubjects.get(securityDomain); + if (subject == null && create) { + subject = new Subject(); + _securityDomainsToSubjects.put(securityDomain, subject); + } + return subject; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized void clearSubject(String securityDomain) { + synchronized (_securityDomainsToSubjects) { + _securityDomainsToSubjects.remove(securityDomain); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Principal getCallerPrincipal(String securityDomain) { + Principal callerPrincipal = null; + Subject subject = getSubject(securityDomain, false); + if (subject != null) { + outerLoop : for (Principal principal : subject.getPrincipals()) { + if (principal instanceof Group) { + Group group = (Group)principal; + if (group.getName().equalsIgnoreCase(CALLER_PRINCIPAL)) { + Enumeration members = group.members(); + while (members.hasMoreElements()) { + callerPrincipal = members.nextElement(); + break outerLoop; + } + } + } else if (callerPrincipal == null && principal != null) { + // the second case (the simple name comparison) is here to support Karaf + if (principal instanceof UserPrincipal || principal.getClass().getSimpleName().equals("UserPrincipal")) { + callerPrincipal = principal; + } + } + } + } + return callerPrincipal; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isCallerInRole(String roleName, String securityDomain) { + Subject subject = getSubject(securityDomain, false); + if (subject != null) { + for (Principal principal : subject.getPrincipals()) { + if (principal instanceof Group) { + Group group = (Group)principal; + if (group.getName().equalsIgnoreCase(ROLES)) { + Enumeration roles = group.members(); + while (roles.hasMoreElements()) { + Principal role = roles.nextElement(); + if (role.getName().equals(roleName)) { + return true; + } + } + } + } + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _systemUUID, _expirationMillis, _credentials, _securityDomainsToSubjects); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_systemUUID == null) ? 0 : _systemUUID.hashCode()); + result = prime * result + ((_credentials == null) ? 0 : _credentials.hashCode()); + result = prime * result + ((_securityDomainsToSubjects == null) ? 0 : _securityDomainsToSubjects.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + DefaultSecurityContext other = (DefaultSecurityContext)obj; + if (_systemUUID == null) { + if (other._systemUUID != null) { + return false; + } + } else if (!_systemUUID.equals(other._systemUUID)) { + return false; + } + if (_credentials == null) { + if (other._credentials != null) { + return false; + } + } else if (!_credentials.equals(other._credentials)) { + return false; + } + if (_securityDomainsToSubjects == null) { + if (other._securityDomainsToSubjects != null) { + return false; + } + } else if (!_securityDomainsToSubjects.equals(other._securityDomainsToSubjects)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/context/SecurityContext.java b/core/security/base/src/main/java/org/switchyard/security/context/SecurityContext.java new file mode 100644 index 000000000..4605d7195 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/context/SecurityContext.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.context; + +import java.io.Serializable; +import java.security.Principal; +import java.util.Set; +import java.util.UUID; + +import javax.security.auth.Subject; + +import org.switchyard.security.credential.Credential; + +/** + * SecurityContext. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface SecurityContext extends Serializable { + + /** + * Whether this security context is valid, within the current system and without having expired. + * @param systemUUID the system security universally unique identifier + * @return whether this security context is valid + */ + public boolean isValid(UUID systemUUID); + + /** + * Gets the Credentials. + * @return the Credentials + */ + public Set getCredentials(); + + /** + * Gets the Credentials that match the type. + * @param the type + * @param clazz the class + * @return the Credentials that match the type + */ + public Set getCredentials(Class clazz); + + /** + * Clears the credentials. + */ + public void clearCredentials(); + + /** + * Gets the Subject for the security domain, creating one if one did not already exist. + * @param securityDomain the security domain + * @return the Subject for the security domain + */ + public Subject getSubject(String securityDomain); + + /** + * Gets the Subject for the security domain. + * @param securityDomain the security domain + * @param create create one if one did not already exist + * @return the Subject for the security domain, or null if create is false and one didn't already exist + */ + public Subject getSubject(String securityDomain, boolean create); + + /** + * Clears the Subject for the security domain. + * @param securityDomain the security domain + */ + public void clearSubject(String securityDomain); + + /** + * Gets the caller Principal for the security domain. + * @param securityDomain the security domain + * @return the caller Principal + */ + public Principal getCallerPrincipal(String securityDomain); + + /** + * Is the caller in the role name for the security domain. + * @param roleName the role name + * @param securityDomain the security domain + * @return successful check + */ + public boolean isCallerInRole(String roleName, String securityDomain); + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/context/SecurityContextManager.java b/core/security/base/src/main/java/org/switchyard/security/context/SecurityContextManager.java new file mode 100644 index 000000000..bf30fb07b --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/context/SecurityContextManager.java @@ -0,0 +1,161 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.context; + +import java.io.Serializable; +import java.util.Set; +import java.util.UUID; + +import javax.crypto.SealedObject; + +import org.switchyard.Exchange; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.label.BehaviorLabel; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.crypto.PrivateCrypto; +import org.switchyard.security.service.SecureServiceDomain; +import org.switchyard.security.service.ServiceDomainSecurity; +import org.switchyard.security.system.SystemSecurity; + +/** + * SecurityContextManager. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class SecurityContextManager { + + private static final String FORMAT = SecurityContextManager.class.getSimpleName() + "@%s[systemSecurity=%s]"; + private static final String EXCHANGE_PROPERTY = SecurityContext.class.getName(); + private static final ThreadLocal THREAD_LOCAL = new InheritableThreadLocal(); + + private SystemSecurity _systemSecurity = null; + + /** + * Creates a new SecurityContextManager for the specified ServiceDomain. + * @param serviceDomain the ServiceDomain + */ + public SecurityContextManager(ServiceDomain serviceDomain) { + if (serviceDomain instanceof SecureServiceDomain) { + ServiceDomainSecurity serviceDomainSecurity = ((SecureServiceDomain)serviceDomain).getServiceDomainSecurity(); + if (serviceDomainSecurity != null) { + _systemSecurity = serviceDomainSecurity.getSystemSecurity(); + } + } + if (_systemSecurity == null) { + _systemSecurity = SystemSecurity.DEFAULT; + } + } + + /** + * Gets the security context from the exchange, creating it if one did not already exist in the exchange or if it was not still valid. + * @param exchange the exchange + * @return the security context + */ + public SecurityContext getContext(Exchange exchange) { + return getContext(exchange, true); + } + + /** + * Gets the security context from the exchange. + * @param exchange the exchange + * @param create create a new security context if one does not already exist in the exchange or if it is not still valid + * @return the security context, or null if create is false and one didn't already exist or was not valid + */ + public SecurityContext getContext(Exchange exchange, boolean create) { + SecurityContext securityContext = null; + Property property = exchange.getContext().getProperty(EXCHANGE_PROPERTY, Scope.EXCHANGE); + if (property != null) { + Object object = property.getValue(); + if (object instanceof SecurityContext) { + securityContext = (SecurityContext)object; + } else if (object instanceof SealedObject) { + PrivateCrypto privateCrypto = _systemSecurity.getPrivateCrypto(); + if (privateCrypto == null) { + throw new IllegalStateException("privateCrypto == null"); + } + securityContext = (SecurityContext)privateCrypto.unseal((SealedObject)object); + } else if (object != null) { + throw new IllegalArgumentException(object.getClass().getName() + " != " + EXCHANGE_PROPERTY); + } + } + UUID systemUUID = _systemSecurity.getUUID(); + if ((securityContext == null || !securityContext.isValid(systemUUID)) && create) { + Long timeoutMillis = _systemSecurity.getSecurityContextTimeoutMillis(); + securityContext = new DefaultSecurityContext(systemUUID, timeoutMillis); + } + return securityContext; + } + + /** + * Sets the security context on the exchange. + * @param exchange the exchange + * @param securityContext the security context + */ + public void setContext(Exchange exchange, SecurityContext securityContext) { + THREAD_LOCAL.set(securityContext); + Serializable object = securityContext; + if (object != null) { + PrivateCrypto privateCrypto = _systemSecurity.getPrivateCrypto(); + if (privateCrypto != null) { + object = privateCrypto.seal(object); + } + } + Property property = exchange.getContext().setProperty(EXCHANGE_PROPERTY, object, Scope.EXCHANGE); + if (property != null) { + property.addLabels(BehaviorLabel.TRANSIENT.label()); + } + } + + /** + * Adds credentials to the security context in the exchange. + * @param exchange the exchange + * @param credentials the credentials + */ + public void addCredentials(Exchange exchange, Set credentials) { + if (credentials != null && credentials.size() > 0) { + SecurityContext securityContext = getContext(exchange); + securityContext.getCredentials().addAll(credentials); + setContext(exchange, securityContext); + } + } + + /** + * Propagates the security context from a thread-local to the destination exchange. + * @param toExchange the destination exchange + */ + public void propagateContext(Exchange toExchange) { + SecurityContext securityContext = THREAD_LOCAL.get(); + setContext(toExchange, securityContext); + } + + /** + * Propagates the security context from one exchange to another. + * @param fromExchange the source exchange + * @param toExchange the destination exchange + */ + public void propagateContext(Exchange fromExchange, Exchange toExchange) { + setContext(toExchange, getContext(fromExchange, false)); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _systemSecurity); + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/AssertionCredential.java b/core/security/base/src/main/java/org/switchyard/security/credential/AssertionCredential.java new file mode 100644 index 000000000..9df343a79 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/AssertionCredential.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential; + +import org.switchyard.common.xml.XMLHelper; +import org.w3c.dom.Element; + +/** + * AssertionCredential. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class AssertionCredential implements Credential { + + private static final long serialVersionUID = -6370905027144656543L; + private static final String FORMAT = AssertionCredential.class.getSimpleName() + "@%s[assertion=%s]"; + + private final Element _assertion; + private final String _assertionXML; + + /** + * Constructs a AssertionCredential with the specified assertion. + * @param assertion the specified assertion + */ + public AssertionCredential(Element assertion) { + _assertion = assertion; + _assertionXML = _assertion != null ? XMLHelper.toString(_assertion).trim() : null; + } + + /** + * Gets the assertion Element. + * @return the assertion Element + */ + public Element getAssertion() { + return _assertion; + } + + /** + * Gets the assertion XML. + * @return the assertion XML + */ + public String getAssertionXML() { + return _assertionXML; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _assertionXML); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_assertionXML == null) ? 0 : _assertionXML.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + AssertionCredential other = (AssertionCredential)obj; + if (_assertionXML == null) { + if (other._assertionXML != null) { + return false; + } + } else if (!_assertionXML.equals(other._assertionXML)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/CertificateCredential.java b/core/security/base/src/main/java/org/switchyard/security/credential/CertificateCredential.java new file mode 100644 index 000000000..0fc84a9f5 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/CertificateCredential.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential; + +import java.security.cert.Certificate; + +/** + * CertificateCredential. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class CertificateCredential implements Credential { + + private static final long serialVersionUID = 7827609156599212693L; + private static final String FORMAT = CertificateCredential.class.getSimpleName() + "@%s[certificate=%s]"; + + private final Certificate _certificate; + + /** + * Constructs a CertificateCredential with the specified Certificate. + * @param certificate the specified Certificate + */ + public CertificateCredential(Certificate certificate) { + _certificate = certificate; + } + + /** + * Gets the Certificate. + * @return the certificate + */ + public Certificate getCertificate() { + return _certificate; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _certificate); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_certificate == null) ? 0 : _certificate.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + CertificateCredential other = (CertificateCredential)obj; + if (_certificate == null) { + if (other._certificate != null) { + return false; + } + } else if (!_certificate.equals(other._certificate)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/ConfidentialityCredential.java b/core/security/base/src/main/java/org/switchyard/security/credential/ConfidentialityCredential.java new file mode 100644 index 000000000..f3d218c4a --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/ConfidentialityCredential.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential; + +/** + * ConfidentialityCredential. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class ConfidentialityCredential implements Credential { + + private static final long serialVersionUID = -7520434970909546852L; + private static final String FORMAT = ConfidentialityCredential.class.getSimpleName() + "@%s[confidential=%s]"; + + private final boolean _confidential; + + /** + * Constructs a ConfidentialityCredential with the specified confidential flag. + * @param confidential the specified confidential flag + */ + public ConfidentialityCredential(boolean confidential) { + _confidential = confidential; + } + + /** + * Gets the confidential flag. + * @return the confidential flag + */ + public boolean isConfidential() { + return _confidential; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _confidential); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (_confidential ? 1231 : 1237); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ConfidentialityCredential other = (ConfidentialityCredential)obj; + if (_confidential != other._confidential) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/Credential.java b/core/security/base/src/main/java/org/switchyard/security/credential/Credential.java new file mode 100644 index 000000000..bd2b1c4c0 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/Credential.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential; + +import java.io.Serializable; + +/** + * Credential. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface Credential extends Serializable {} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/NameCredential.java b/core/security/base/src/main/java/org/switchyard/security/credential/NameCredential.java new file mode 100644 index 000000000..38ac82749 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/NameCredential.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential; + +/** + * NameCredential. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class NameCredential implements Credential { + + private static final long serialVersionUID = 192266830898823549L; + private static final String FORMAT = NameCredential.class.getSimpleName() + "@%s[name=%s]"; + + private final String _name; + + /** + * Constructs a NameCredential with the specified name. + * @param name the specified name + */ + public NameCredential(String name) { + _name = name; + } + + /** + * Gets the name. + * @return the name + */ + public String getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _name); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_name == null) ? 0 : _name.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + NameCredential other = (NameCredential)obj; + if (_name == null) { + if (other._name != null) { + return false; + } + } else if (!_name.equals(other._name)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/PasswordCredential.java b/core/security/base/src/main/java/org/switchyard/security/credential/PasswordCredential.java new file mode 100644 index 000000000..729f34381 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/PasswordCredential.java @@ -0,0 +1,109 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential; + +import java.util.Arrays; + +/** + * PasswordCredential. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class PasswordCredential implements Credential { + + private static final long serialVersionUID = -680454653305310122L; + private static final String FORMAT = PasswordCredential.class.getSimpleName() + "@%s[password=%s]"; + + private final char[] _password; + private final String _mask; + + /** + * Constructs a PasswordCredential with the specified password. + * @param password the specified password + */ + public PasswordCredential(String password) { + _password = password != null ? password.toCharArray() : null; + _mask = mask(); + } + + /** + * Constructs a PasswordCredential with the specified password. + * @param password the specified password + */ + public PasswordCredential(char[] password) { + _password = password; + _mask = mask(); + } + + private String mask() { + StringBuilder masked = new StringBuilder(); + if (_password != null) { + for (int i=0; i < _password.length; i++) { + masked.append('*'); + } + } else { + masked.append("null"); + } + return masked.toString(); + } + + /** + * Gets the password. + * @return the password + */ + public char[] getPassword() { + return _password; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _mask); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(_password); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PasswordCredential other = (PasswordCredential)obj; + if (!Arrays.equals(_password, other._password)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/PrincipalCredential.java b/core/security/base/src/main/java/org/switchyard/security/credential/PrincipalCredential.java new file mode 100644 index 000000000..1742cb432 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/PrincipalCredential.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential; + +import java.security.Principal; + +/** + * PrincipalCredential. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class PrincipalCredential implements Credential { + + private static final long serialVersionUID = 904862054504518758L; + private static final String FORMAT = PrincipalCredential.class.getSimpleName() + "@%s[principal=%s, trusted=%s]"; + + private final Principal _principal; + private final boolean _trusted; + + /** + * Constructs an untrusted PrincipalCredential with the specified Principal. + * @param principal the specified Principal + */ + public PrincipalCredential(Principal principal) { + this(principal, false); + } + + /** + * Constructs a PrincipalCredentail with the specified principal and trusted flag. + * @param principal the specified Principal + * @param trusted the trusted flag + */ + public PrincipalCredential(Principal principal, boolean trusted) { + _principal = principal; + _trusted = trusted; + } + + /** + * Gets the Principal. + * @return the Principal + */ + public Principal getPrincipal() { + return _principal; + } + + /** + * Gets the trusted flag. + * @return the trusted flag + */ + public boolean isTrusted() { + return _trusted; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _principal, _trusted); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_principal == null) ? 0 : _principal.hashCode()); + result = prime * result + (_trusted ? 1231 : 1237); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PrincipalCredential other = (PrincipalCredential)obj; + if (_principal == null) { + if (other._principal != null) { + return false; + } + } else if (!_principal.equals(other._principal)) { + return false; + } + if (_trusted != other._trusted) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/SubjectCredential.java b/core/security/base/src/main/java/org/switchyard/security/credential/SubjectCredential.java new file mode 100644 index 000000000..ae1764126 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/SubjectCredential.java @@ -0,0 +1,90 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential; + +import javax.security.auth.Subject; + +/** + * SubjectCredential. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class SubjectCredential implements Credential { + + private static final long serialVersionUID = -2683242579779692195L; + private static final String FORMAT = SubjectCredential.class.getSimpleName() + "@%s[subject=%s]"; + + private final Subject _subject; + + /** + * Constructs a SubjectCredentail with the specified subject. + * @param subject the specified Subject + */ + public SubjectCredential(Subject subject) { + _subject = subject; + } + + /** + * Gets the Subject. + * @return the Subject + */ + public Subject getSubject() { + return _subject; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _subject); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_subject == null) ? 0 : _subject.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + SubjectCredential other = (SubjectCredential)obj; + if (_subject == null) { + if (other._subject != null) { + return false; + } + } else if (!_subject.equals(other._subject)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractor.java b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractor.java new file mode 100644 index 000000000..c825e61a6 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractor.java @@ -0,0 +1,128 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.switchyard.common.codec.Base64; +import org.switchyard.common.lang.Strings; +import org.switchyard.security.BaseSecurityLogger; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.NameCredential; +import org.switchyard.security.credential.PasswordCredential; + +/** + * AuthorizationHeaderCredentialExtractor. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class AuthorizationHeaderCredentialExtractor implements CredentialExtractor { + + private final Charset _charset; + + /** + * Constructs a new AuthorizationHeaderCredentialsExtractor, with the platform-dependent charset. + */ + public AuthorizationHeaderCredentialExtractor() { + _charset = Charset.defaultCharset(); + } + + /** + * Constructs a new AuthorizationHeaderCredentialsExtractor, with the specified charset name. + * @param charsetName the specified charset name + */ + public AuthorizationHeaderCredentialExtractor(String charsetName) { + if (charsetName != null) { + Charset charset; + try { + charset = Charset.forName(charsetName); + } catch (Throwable t) { + BaseSecurityLogger.ROOT_LOGGER.charSetNameIllegal(charsetName); + charset = Charset.defaultCharset(); + } + _charset = charset; + } else { + BaseSecurityLogger.ROOT_LOGGER.charSetNull(); + _charset = Charset.defaultCharset(); + } + } + + /** + * Constructs a new AuthorizationHeaderCredentialsExtractor, with the specified charset. + * @param charset the specified charset + */ + public AuthorizationHeaderCredentialExtractor(Charset charset) { + if (charset != null) { + _charset = charset; + } else { + BaseSecurityLogger.ROOT_LOGGER.charSetNull(); + _charset = Charset.defaultCharset(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Set extract(String source) { + Set credentials = new HashSet(); + if (source != null) { + if (source.startsWith("Basic ")) { + String encoded = source.substring(6, source.length()); + String decoded = Base64.decodeToString(encoded, _charset); + if (decoded.indexOf(':') != -1) { + String[] split = decoded.split(":", 2); + String name = split.length > 0 ? split[0] : null; + if (name != null) { + credentials.add(new NameCredential(name)); + } + String password = split.length > 1 ? split[1] : null; + if (password != null) { + credentials.add(new PasswordCredential(password)); + } + } + } else if (source.startsWith("Digest ")) { + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + // https://issues.jboss.org/browse/SWITCHYARD-1082 + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + Map map = new HashMap(); + String everything = source.substring(6, source.length()).trim(); + List list = Strings.splitTrimToNull(everything, ",\n"); + for (String pair : list) { + String[] split = pair.split("=", 2); + String key = split.length > 0 ? split[0] : null; + String value = split.length > 1 ? split[1] : null; + if (key != null && value != null) { + if (value.startsWith("\"") && value.endsWith("\"")) { + value = value.substring(1, value.length() - 1); + } + map.put(key, value); + } + } + String username = map.get("username"); + if (username != null) { + credentials.add(new NameCredential(username)); + } + // TODO: complete per SWITCHYARD-1082 + } + } + return credentials; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/extractor/CredentialExtractor.java b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/CredentialExtractor.java new file mode 100644 index 000000000..de3595f76 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/CredentialExtractor.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import java.util.Set; + +import org.switchyard.security.credential.Credential; + +/** + * CredentialExtractor. + * + * @param the type of the specified source + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface CredentialExtractor { + + /** + * Extracts Credentials from the specified source. + * @param source the specified source + * @return the Credentials + */ + public Set extract(T source); + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/extractor/DefaultServletRequestCredentialExtractor.java b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/DefaultServletRequestCredentialExtractor.java new file mode 100644 index 000000000..a53825a6f --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/DefaultServletRequestCredentialExtractor.java @@ -0,0 +1,73 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import java.security.Principal; +import java.util.HashSet; +import java.util.Set; + +import javax.servlet.ServletRequest; +import javax.servlet.http.HttpServletRequest; + +import org.switchyard.security.credential.ConfidentialityCredential; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.PrincipalCredential; +import org.switchyard.security.principal.UserPrincipal; + +/** + * DefaultServletRequestCredentialExtractor. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class DefaultServletRequestCredentialExtractor implements ServletRequestCredentialExtractor { + + /** + * Constructs a new DefaultServletRequestCredentialExtractor. + */ + public DefaultServletRequestCredentialExtractor() {} + + /** + * {@inheritDoc} + */ + @Override + public Set extract(ServletRequest source) { + Set credentials = new HashSet(); + if (source != null) { + if (source.isSecure()) { + credentials.add(new ConfidentialityCredential(true)); + } + if (source instanceof HttpServletRequest) { + HttpServletRequest request = (HttpServletRequest)source; + Principal userPrincipal = request.getUserPrincipal(); + if (userPrincipal != null) { + credentials.add(new PrincipalCredential(userPrincipal, true)); + } + String remoteUser = request.getRemoteUser(); + if (remoteUser != null) { + credentials.add(new PrincipalCredential(new UserPrincipal(remoteUser), true)); + } + String charsetName = source.getCharacterEncoding(); + AuthorizationHeaderCredentialExtractor ahce; + if (charsetName != null) { + ahce = new AuthorizationHeaderCredentialExtractor(charsetName); + } else { + ahce = new AuthorizationHeaderCredentialExtractor(); + } + credentials.addAll(ahce.extract(request.getHeader("Authorization"))); + } + } + return credentials; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractor.java b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractor.java new file mode 100644 index 000000000..e162892db --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractor.java @@ -0,0 +1,199 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.security.cert.CertPath; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPEnvelope; +import javax.xml.soap.SOAPException; +import javax.xml.soap.SOAPHeader; +import javax.xml.soap.SOAPHeaderElement; +import javax.xml.soap.SOAPMessage; + +import org.switchyard.common.codec.Base64; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.security.BaseSecurityMessages; +import org.switchyard.security.credential.AssertionCredential; +import org.switchyard.security.credential.CertificateCredential; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.NameCredential; +import org.switchyard.security.credential.PasswordCredential; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * SOAPMessageCredentialExtractor. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class SOAPMessageCredentialExtractor implements CredentialExtractor { + + private static final String WSSE_NS = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; + private static final String WSSE_NS2 = "http://schemas.xmlsoap.org/ws/2002/04/secext"; + private static final String WSSE11_NS = "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"; + private static final String WSSE_LN = "Security"; + private static final QName WSSE_QNAME = new QName(WSSE_NS, WSSE_LN); + private static final QName WSSE_2_QNAME = new QName(WSSE_NS2, WSSE_LN); + private static final QName WSSE_11_QNAME = new QName(WSSE11_NS, WSSE_LN); + + private static final String X509V3 = "X509v3"; + private static final String X509PKIPATHV1 = "X509PKIPathv1"; + private static final String PKCS7 = "PKCS7"; + + /** + * Constructs a new SOAPMessageCredentialsExtractor. + */ + public SOAPMessageCredentialExtractor() {} + + /** + * {@inheritDoc} + */ + @Override + public Set extract(SOAPMessage source) { + Set credentials = new HashSet(); + if (source != null) { + try { + SOAPHeaderElement securityHeader = getSecurityHeader(source.getSOAPPart().getEnvelope()); + if (securityHeader != null) { + Iterator iter = securityHeader.getChildElements(); + while (iter.hasNext()) { + Node securityTokenNode = (Node)iter.next(); + if (securityTokenNode.getNodeType() == Node.ELEMENT_NODE) { + String securityTokenNodeName = XMLHelper.nameOf(securityTokenNode); + if ("Assertion".equalsIgnoreCase(securityTokenNodeName)) { + credentials.add(new AssertionCredential((Element)securityTokenNode)); + } else if ("UsernameToken".equalsIgnoreCase(securityTokenNodeName)) { + NodeList usernameChildElements = securityTokenNode.getChildNodes(); + for (int i=0; i < usernameChildElements.getLength(); i++) { + Node usernameChildNode = usernameChildElements.item(i); + String usernameChildeNodeName = XMLHelper.nameOf(usernameChildNode); + if ("Username".equalsIgnoreCase(usernameChildeNodeName)) { + String name = XMLHelper.valueOf(usernameChildNode.getFirstChild()); + if (name != null) { + credentials.add(new NameCredential(name)); + } + } else if ("Password".equalsIgnoreCase(usernameChildeNodeName)) { + String password = XMLHelper.valueOf(usernameChildNode.getFirstChild()); + if (password != null) { + credentials.add(new PasswordCredential(password)); + } + } + } + } else if ("BinarySecurityToken".equalsIgnoreCase(securityTokenNodeName)) { + NamedNodeMap attributes = securityTokenNode.getAttributes(); + String encodingType = stripNS(XMLHelper.valueOf(attributes.getNamedItem("EncodingType"))); + String valueType = stripNS(XMLHelper.valueOf(attributes.getNamedItem("ValueType"))); + String certString = XMLHelper.valueOf(securityTokenNode.getFirstChild()); + byte[] certBytes = null; + if ("Base64Binary".equalsIgnoreCase(encodingType)) { + certBytes = Base64.decode(certString); + } else { + certBytes = certString.getBytes(); + } + try { + CertificateFactory factory = CertificateFactory.getInstance(certificateMatch(valueType)); + InputStream certStream = new ByteArrayInputStream(certBytes); + if (X509PKIPATHV1.equals(valueType)) { + CertPath path = factory.generateCertPath(certStream); + for (Certificate certificate : path.getCertificates()) { + credentials.add(new CertificateCredential(certificate)); + } + } else if (X509V3.equals(valueType)) { + Certificate certificate = factory.generateCertificate(certStream); + credentials.add(new CertificateCredential(certificate)); + } else if (PKCS7.equals(valueType)) { + throw BaseSecurityMessages.MESSAGES.valueTypeRecognizedNotImplemented(valueType); + } else { + throw BaseSecurityMessages.MESSAGES.valueTypeNotImplemented(valueType); + } + } catch (CertificateException ce) { + throw BaseSecurityMessages.MESSAGES.couldNotCreateCert(ce.getMessage(), ce); + } + } + } + } + } + } catch (SOAPException se) { + throw new RuntimeException(se); + } + } + return credentials; + } + + private SOAPHeaderElement getSecurityHeader(SOAPEnvelope envelope) throws SOAPException { + if (envelope != null) { + SOAPHeader header = envelope.getHeader(); + if (header != null) { + Iterator iter = header.getChildElements(WSSE_QNAME); + if (iter.hasNext()) { + return (SOAPHeaderElement)iter.next(); + } + iter = header.getChildElements(WSSE_2_QNAME); + if (iter.hasNext()) { + return (SOAPHeaderElement)iter.next(); + } + iter = header.getChildElements(WSSE_11_QNAME); + if (iter.hasNext()) { + return (SOAPHeaderElement)iter.next(); + } + } + } + return null; + } + + private String stripNS(String value) { + if (value != null) { + if (value.startsWith("http")) { + int idx = value.indexOf('#'); + if (idx > 0) { + value = value.substring(idx + 1); + } + } else { + int idx = value.indexOf(':'); + if (idx > 0) { + value = value.substring(idx + 1); + } + } + } + return value; + } + + private String certificateMatch(String valueType) { + if (valueType.startsWith("X509")) { + return "X.509"; + } + return valueType; + } + + /* + private String pathMatch(String valueType) { + if (valueType.startsWith("")) { + return "PkiPath"; + } + return "PKCS7"; + } + */ + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/extractor/SSLSessionCredentialExtractor.java b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/SSLSessionCredentialExtractor.java new file mode 100644 index 000000000..db63639c8 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/SSLSessionCredentialExtractor.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import java.util.HashSet; +import java.util.Set; + +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; + +import org.switchyard.security.BaseSecurityMessages; +import org.switchyard.security.credential.CertificateCredential; +import org.switchyard.security.credential.ConfidentialityCredential; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.PrincipalCredential; + +/** + * CredentialExtractor which extracts {@link Credential}s from a given {@link SSLSession}. + */ +public class SSLSessionCredentialExtractor implements CredentialExtractor { + + /** + * Constructs a new SSLSessionCredentialExtractor. + */ + public SSLSessionCredentialExtractor() {} + + /** + * {@inheritDoc} + */ + @Override + public Set extract(SSLSession source) { + Set credentials = new HashSet(); + try { + credentials.add(new ConfidentialityCredential(source.isValid())); + credentials.add(new PrincipalCredential(source.getPeerPrincipal())); + credentials.add(new CertificateCredential(source.getPeerCertificates()[0])); + } catch (SSLPeerUnverifiedException e) { + throw BaseSecurityMessages.MESSAGES.unableToExtractCredentials(e.getMessage(), e); + } + return credentials; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/extractor/ServletRequestCredentialExtractor.java b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/ServletRequestCredentialExtractor.java new file mode 100644 index 000000000..15160f73a --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/ServletRequestCredentialExtractor.java @@ -0,0 +1,23 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import javax.servlet.ServletRequest; + +/** + * ServletRequestCredentialExtractor. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public interface ServletRequestCredentialExtractor extends CredentialExtractor {} diff --git a/core/security/base/src/main/java/org/switchyard/security/credential/extractor/WebServiceContextCredentialExtractor.java b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/WebServiceContextCredentialExtractor.java new file mode 100644 index 000000000..2ead085b4 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/credential/extractor/WebServiceContextCredentialExtractor.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import java.security.Principal; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.ws.WebServiceContext; + +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.PrincipalCredential; + +/** + * WebServiceContextCredentialExtractor. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class WebServiceContextCredentialExtractor implements CredentialExtractor { + + /** + * Constructs a new WebServiceContextCredentialsExtractor. + */ + public WebServiceContextCredentialExtractor() {} + + /** + * {@inheritDoc} + */ + @Override + public Set extract(WebServiceContext source) { + Set credentials = new HashSet(); + if (source != null) { + Principal userPrincipal = source.getUserPrincipal(); + if (userPrincipal != null) { + credentials.add(new PrincipalCredential(userPrincipal, true)); + } + } + return credentials; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/crypto/PrivateCrypto.java b/core/security/base/src/main/java/org/switchyard/security/crypto/PrivateCrypto.java new file mode 100644 index 000000000..d31c44fe2 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/crypto/PrivateCrypto.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.crypto; + +import java.io.Serializable; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Properties; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SealedObject; +import javax.crypto.SecretKey; + +import org.switchyard.SwitchYardException; +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.lang.Strings; +import org.switchyard.security.BaseSecurityLogger; + +/** + * PrivateCrypto. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class PrivateCrypto { + + private static final String FORMAT = PrivateCrypto.class.getSimpleName() + "@%s[sealAlgorithm=%s, secretKey=%s]"; + + /** The sealAlgorithm property. */ + public static final String SEAL_ALGORITHM = "sealAlgorithm"; + /** The sealKeySize property. */ + public static final String SEAL_KEY_SIZE = "sealKeySize"; + + private String _sealAlgorithm = null; + private SecretKey _secretKey = null; + + /** + * Creates a new PrivateCrypto with the specified properties. + * @param sealAlgorithm the sealAlgorithm + * @param sealKeySize the sealKeySize + */ + public PrivateCrypto(String sealAlgorithm, int sealKeySize) { + init(sealAlgorithm, sealKeySize); + } + + /** + * Creates a new PrivateCrypto with the specified map. + * @param map the map + */ + public PrivateCrypto(Map map) { + this(new PropertiesPuller().pull(map)); + } + + /** + * Creates a new PrivateCrypto with the specified properties. + * @param properties the properties. + */ + public PrivateCrypto(Properties properties) { + String sealAlgorithm = Strings.trimToNull(properties.getProperty(SEAL_ALGORITHM)); + int sealKeySize = -1; + String sealKeySizeProperty = Strings.trimToNull(properties.getProperty(SEAL_KEY_SIZE)); + if (sealKeySizeProperty != null) { + try { + sealKeySize = Integer.parseInt(sealKeySizeProperty); + } catch (NumberFormatException nfe) { + BaseSecurityLogger.ROOT_LOGGER.configurationNumberFormatException(SEAL_KEY_SIZE, sealKeySizeProperty, nfe); + } + } + init(sealAlgorithm, sealKeySize); + } + + private void init(String sealAlgorithm, int sealKeySize) { + if (sealAlgorithm == null || sealKeySize < 1) { + return; + } + _sealAlgorithm = sealAlgorithm; + try { + KeyGenerator keyGenerator = KeyGenerator.getInstance(_sealAlgorithm); + keyGenerator.init(sealKeySize); + _secretKey = keyGenerator.generateKey(); + } catch (NoSuchAlgorithmException nsae) { + throw new SwitchYardException(nsae); + } + } + + /** + * Seals the specified object. + * @param object the object + * @return the sealed object + */ + public SealedObject seal(Serializable object) { + try { + Cipher cipher = Cipher.getInstance(_sealAlgorithm); + cipher.init(Cipher.ENCRYPT_MODE, _secretKey); + return new SealedObject(object, cipher); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + /** + * Unseals the specified sealed object. + * @param object the sealed object + * @return the unsealed object + */ + public Serializable unseal(SealedObject object) { + try { + Cipher cipher = Cipher.getInstance(_sealAlgorithm); + cipher.init(Cipher.DECRYPT_MODE, _secretKey); + return (Serializable)object.getObject(cipher); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _sealAlgorithm, _secretKey); + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/crypto/PublicCrypto.java b/core/security/base/src/main/java/org/switchyard/security/crypto/PublicCrypto.java new file mode 100644 index 000000000..bd5f13bb0 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/crypto/PublicCrypto.java @@ -0,0 +1,217 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.crypto; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.util.Map; +import java.util.Properties; + +import javax.crypto.Cipher; + +import org.switchyard.SwitchYardException; +import org.switchyard.common.io.Buffers; +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.io.pull.Puller.PathType; +import org.switchyard.common.lang.Strings; +import org.switchyard.security.pull.KeyStorePuller; + +/** + * PublicCrypto. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class PublicCrypto { + + private static final String FORMAT = PublicCrypto.class.getSimpleName() + "@%s[key=%s, publicKey=%s, keyTransformation=%s]"; + + /** The keyStoreLocation property. */ + public static final String KEYSTORE_LOCATION = "keyStoreLocation"; + /** The keyStoreType property. */ + public static final String KEYSTORE_TYPE = "keyStoreType"; + /** The keyStorePassword property. */ + public static final String KEYSTORE_PASSWORD = "keyStorePassword"; + /** The keyAlias property. */ + public static final String KEY_ALIAS = "keyAlias"; + /** The keyPassword property. */ + public static final String KEY_PASSWORD = "keyPassword"; + /** The keyTransformation property. */ + public static final String KEY_TRANSFORMATION = "keyTransformation"; + + private Key _key = null; + private PublicKey _publicKey = null; + private String _keyTransformation = null; + + /** + * Creates a new PublicCrypto with the specified properties. + * @param keyStoreLocation the keyStoreLocation + * @param keyStoreType the keyStoreType + * @param keyStorePassword the keyStorePassword + * @param keyAlias the keyAlias + * @param keyPassword the keyPassword + * @param keyTransformation the keyTransformation + */ + public PublicCrypto(String keyStoreLocation, String keyStoreType, char[] keyStorePassword, String keyAlias, char[] keyPassword, String keyTransformation) { + init(keyStoreLocation, keyStoreType, keyStorePassword, keyAlias, keyPassword, keyTransformation); + } + + /** + * Creates a new PublicCrypto with the specified map. + * @param map the map + */ + public PublicCrypto(Map map) { + this(new PropertiesPuller().pull(map)); + } + + /** + * Creates a new PublicCrypto with the specified properties. + * @param properties the properties. + */ + public PublicCrypto(Properties properties) { + String keyStoreLocation = Strings.trimToNull(properties.getProperty(KEYSTORE_LOCATION)); + String keyStoreType = Strings.trimToNull(properties.getProperty(KEYSTORE_TYPE)); + String keyStorePasswordProperty = properties.getProperty(KEYSTORE_PASSWORD); + char[] keyStorePassword = keyStorePasswordProperty != null ? keyStorePasswordProperty.toCharArray() : null; + String keyAlias = Strings.trimToNull(properties.getProperty(KEY_ALIAS)); + String keyPasswordProperty = properties.getProperty(KEY_PASSWORD); + char[] keyPassword = keyPasswordProperty != null ? keyPasswordProperty.toCharArray() : null; + String keyTransformation = Strings.trimToNull(properties.getProperty(KEY_TRANSFORMATION)); + init(keyStoreLocation, keyStoreType, keyStorePassword, keyAlias, keyPassword, keyTransformation); + } + + private void init(String keyStoreLocation, String keyStoreType, char[] keyStorePassword, String keyAlias, char[] keyPassword, String keyTransformation) { + if (keyStoreLocation == null) { + return; + } + KeyStorePuller keyStorePuller = new KeyStorePuller(keyStoreType, keyStorePassword); + KeyStore keyStore = keyStorePuller.pullPath(keyStoreLocation, getClass(), PathType.values()); + try { + Certificate certificate = keyStore.getCertificate(keyAlias); + _publicKey = certificate.getPublicKey(); + _keyTransformation = keyTransformation != null ? keyTransformation : _publicKey.getAlgorithm(); + } catch (KeyStoreException kse) { + throw new SwitchYardException(kse); + } + } + + /** + * Encrypts the specified object. + * @param object the object + * @return the encrypted bytes + */ + public byte[] encrypt(Serializable object) { + try { + ByteArrayOutputStream encOut = new ByteArrayOutputStream(); + ByteArrayInputStream objIn = new ByteArrayInputStream(toBytes(object)); + byte[] buf = Buffers.newDefaultBuffer(); + int bufLength; + Cipher cipher = Cipher.getInstance(_keyTransformation); + cipher.init(Cipher.ENCRYPT_MODE, _publicKey); + while ((bufLength = objIn.read(buf)) != -1) { + byte[] encBytes = cipher.doFinal(copyBytes(buf, bufLength)); + encOut.write(encBytes); + } + encOut.flush(); + return encOut.toByteArray(); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + /** + * Decrypts the specified encrypted bytes. + * @param bytes the encrypted bytes + * @return the decrypted object + */ + public Serializable decrypt(byte[] bytes) { + try { + ByteArrayInputStream encIn = new ByteArrayInputStream(bytes); + ByteArrayOutputStream decOut = new ByteArrayOutputStream(); + byte[] buf = Buffers.newDefaultBuffer(); + int bufLength; + Cipher cipher = Cipher.getInstance(_keyTransformation); + cipher.init(Cipher.DECRYPT_MODE, _key); + while ((bufLength = encIn.read(buf)) != -1) { + byte[] decBytes = cipher.doFinal(copyBytes(buf, bufLength)); + decOut.write(decBytes); + } + decOut.flush(); + return toSerializable(decOut.toByteArray()); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } + + private byte[] copyBytes(byte[] src, int length) { + if (src.length == length) { + return src; + } + byte[] dest = new byte[length]; + System.arraycopy(src, 0, dest, 0, length); + return dest; + } + + private byte[] toBytes(Serializable object) throws IOException { + ObjectOutputStream oos = null; + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(baos); + oos.writeObject(object); + oos.flush(); + return baos.toByteArray(); + } finally { + if (oos != null) { + try { + oos.close(); + } catch (Throwable t) { + t.getMessage(); + } + } + } + } + + private Serializable toSerializable(byte[] bytes) throws IOException, ClassNotFoundException { + ObjectInputStream ois = null; + try { + ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); + return (Serializable)ois.readObject(); + } finally { + if (ois != null) { + try { + ois.close(); + } catch (Throwable t) { + t.getMessage(); + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _key, _publicKey, _keyTransformation); + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/login/CertificateLoginModule.java b/core/security/base/src/main/java/org/switchyard/security/login/CertificateLoginModule.java new file mode 100644 index 000000000..7427d79e4 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/login/CertificateLoginModule.java @@ -0,0 +1,168 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.login; + +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.Principal; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Properties; +import java.util.Set; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.auth.login.LoginException; + +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.common.io.pull.PropertiesPuller.PropertiesType; +import org.switchyard.common.io.pull.Puller.PathType; +import org.switchyard.common.lang.Strings; +import org.switchyard.security.BaseSecurityMessages; +import org.switchyard.security.callback.CertificateCallback; +import org.switchyard.security.principal.GroupPrincipal; +import org.switchyard.security.principal.RolePrincipal; +import org.switchyard.security.principal.UserPrincipal; +import org.switchyard.security.pull.KeyStorePuller; + +/** + * CertificateLoginModule. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class CertificateLoginModule extends SwitchYardLoginModule { + + private X509Certificate _verifiedCallerCertificate; + + /** + * Constructs a new CertificateLoginModule. + */ + public CertificateLoginModule() {} + + /** + * {@inheritDoc} + */ + @Override + public boolean login() throws LoginException { + NameCallback aliasCallback = new NameCallback("alias"); + //PasswordCallback keyPasswordCallback = new PasswordCallback("keyPassword", false); + CertificateCallback certificateCallback = new CertificateCallback(); + try { + //getCallbackHandler().handle(new Callback[]{aliasCallback, keyPasswordCallback, certificateCallback}); + getCallbackHandler().handle(new Callback[]{aliasCallback, certificateCallback}); + } catch (IOException ioe) { + throw BaseSecurityMessages.MESSAGES.failedInvokeCallback(ioe.getMessage(), ioe); + } catch (UnsupportedCallbackException uce) { + throw BaseSecurityMessages.MESSAGES.callbackHandlerNoSupport(uce.getCallback().toString()); + } + X509Certificate callerCertificate = getCallerCertificate(certificateCallback); + KeyStore keyStore = getKeyStore(); + String alias = aliasCallback.getName(); + //char[] keyPassword = keyPasswordCallback.getPassword(); + Certificate switchyardCertificate; + try { + switchyardCertificate = keyStore.getCertificate(alias); + } catch (KeyStoreException kse) { + throw BaseSecurityMessages.MESSAGES.problemAccessingKeystore(kse.getMessage()); + } + try { + callerCertificate.verify(switchyardCertificate.getPublicKey()); + } catch (Exception e) { + throw BaseSecurityMessages.MESSAGES.problemVerifyingCallerCert(e.getMessage()); + } + _verifiedCallerCertificate = callerCertificate; + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean commit() throws LoginException { + if (_verifiedCallerCertificate == null) { + return false; + } else { + Set principals = getSubject().getPrincipals(); + String userName = _verifiedCallerCertificate.getSubjectX500Principal().getName(); + // get the CN from the DN. + userName = userName.substring(userName.indexOf('=') + 1, userName.indexOf(',')); + UserPrincipal authenticatedPrincipal = new UserPrincipal(userName); + principals.add(authenticatedPrincipal); + // maybe add roles + Properties rolesProperties = getRolesProperties(); + if (rolesProperties != null) { + Set groups = getSubject().getPrincipals(GroupPrincipal.class); + Set roleNames = Strings.uniqueSplitTrimToNull(rolesProperties.getProperty(userName), ","); + for (String roleName : roleNames) { + RolePrincipal role = new RolePrincipal(roleName); + if (groups.isEmpty()) { + GroupPrincipal rolesGroup = new GroupPrincipal(GroupPrincipal.ROLES); + rolesGroup.addMember(role); + getSubject().getPrincipals().add(rolesGroup); + } else { + for (GroupPrincipal group : groups) { + if (GroupPrincipal.ROLES.equals(group.getName())) { + group.addMember(role); + } + } + } + } + } + return true; + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean logout() throws LoginException { + _verifiedCallerCertificate = null; + return true; + } + + private X509Certificate getCallerCertificate(CertificateCallback certificateCallback) throws LoginException { + X509Certificate x509cert = null; + for (Certificate cert : certificateCallback.getCertificates()) { + if (cert instanceof X509Certificate) { + x509cert = (X509Certificate)cert; + break; + } + } + if (x509cert == null) { + throw BaseSecurityMessages.MESSAGES.noCallerCertificateProvided(); + } + return x509cert; + } + + private KeyStore getKeyStore() throws LoginException { + String keyStoreLocation = getOption("keyStoreLocation", true); + String keyStoreType = getOption("keyStoreType", false); + String keyStorePassword = getOption("keyStorePassword", false); + KeyStorePuller keyStorePuller = new KeyStorePuller(keyStoreType, keyStorePassword != null ? keyStorePassword.toCharArray() : null); + return keyStorePuller.pullPath(keyStoreLocation, getClass(), PathType.values()); + } + + private Properties getRolesProperties() { + String rolesPropertiesFile = getOption("rolesProperties", false); + if (rolesPropertiesFile != null) { + PropertiesType propertiesType = rolesPropertiesFile.endsWith(".xml") ? PropertiesType.XML : PropertiesType.PROPERTIES; + return new PropertiesPuller(propertiesType).pullPath(rolesPropertiesFile, getClass(), PathType.values()); + } + return null; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/login/SwitchYardLoginModule.java b/core/security/base/src/main/java/org/switchyard/security/login/SwitchYardLoginModule.java new file mode 100644 index 000000000..8ec8c0467 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/login/SwitchYardLoginModule.java @@ -0,0 +1,145 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.login; + +import java.util.Map; + +import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.login.LoginException; +import javax.security.auth.spi.LoginModule; + +import org.switchyard.common.lang.Strings; +import org.switchyard.security.BaseSecurityMessages; + +/** + * SwitchYardLoginModule. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class SwitchYardLoginModule implements LoginModule { + + private Subject _subject; + private CallbackHandler _callbackHandler; + private Map _sharedState; + private Map _options; + + /** + * Gets the initialized Subject. + * @return the Subject + */ + public Subject getSubject() { + return _subject; + } + + /** + * Gets the initialized CallbackHandler. + * @return the CallbackHandler + */ + public CallbackHandler getCallbackHandler() { + return _callbackHandler; + } + + /** + * Gets the initialized shared state. + * @return the shared state + */ + public Map getSharedState() { + return _sharedState; + } + + /** + * Gets the initialized options. + * @return the options + */ + public Map getOptions() { + return _options; + } + + /** + * Gets an option value with the specified name, as a String. + * @param name the specified name + * @return the option value + */ + public String getOption(String name) { + return getOption(name, false); + } + + /** + * Gets an option value with the specified name, as a String. + * @param name the specified name + * @param required if the option is required to have been set + * @return the option value + */ + public String getOption(String name, boolean required) { + Map options = getOptions(); + if (options == null) { + if (required) { + throw BaseSecurityMessages.MESSAGES.optionsNotSet(); + } + } else { + Object value = options.get(name); + if (value != null) { + return Strings.replaceSystemAndTestProperties(String.valueOf(value)); + } else if (required) { + throw BaseSecurityMessages.MESSAGES.optionNotSet(name); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { + _subject = subject; + _callbackHandler = callbackHandler; + _sharedState = sharedState; + _options = options; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean login() throws LoginException { + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean commit() throws LoginException { + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean abort() throws LoginException { + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean logout() throws LoginException { + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/principal/GroupPrincipal.java b/core/security/base/src/main/java/org/switchyard/security/principal/GroupPrincipal.java new file mode 100644 index 000000000..77b887c85 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/principal/GroupPrincipal.java @@ -0,0 +1,152 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.principal; + +import java.io.Serializable; +import java.security.Principal; +import java.security.acl.Group; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Set; + +import org.switchyard.security.BaseSecurityMessages; + +/** + * GroupPrincipal. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class GroupPrincipal implements Group, Serializable { + + private static final long serialVersionUID = -909127780618924905L; + private static final String FORMAT = GroupPrincipal.class.getSimpleName() + "@%s[name=%s, members=%s]"; + + /** + * The "CallerPrincipal" group name. + */ + public static final String CALLER_PRINCIPAL = "CallerPrincipal"; + + /** + * The "Roles" group name. + */ + public static final String ROLES = "Roles"; + + private final String _name; + private final Set _members = new HashSet(); + + /** + * Constructs a GroupPrincipal with the specified name. + * @param name the specified name + */ + public GroupPrincipal(String name) { + if (name == null) { + throw BaseSecurityMessages.MESSAGES.groupNameCannotBeNull(); + } + _name = name; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean addMember(Principal user) { + return _members.add(user); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isMember(Principal member) { + return _members.contains(member); + } + + /** + * {@inheritDoc} + */ + @Override + public Enumeration members() { + return Collections.enumeration(_members); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean removeMember(Principal user) { + return _members.remove(user); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _name, _members); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_members == null) ? 0 : _members.hashCode()); + result = prime * result + ((_name == null) ? 0 : _name.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + GroupPrincipal other = (GroupPrincipal)obj; + if (_members == null) { + if (other._members != null) { + return false; + } + } else if (!_members.equals(other._members)) { + return false; + } + if (_name == null) { + if (other._name != null) { + return false; + } + } else if (!_name.equals(other._name)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/principal/RolePrincipal.java b/core/security/base/src/main/java/org/switchyard/security/principal/RolePrincipal.java new file mode 100644 index 000000000..ff29a3b13 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/principal/RolePrincipal.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.principal; + +import java.io.Serializable; +import java.security.Principal; + +import org.switchyard.security.BaseSecurityMessages; + +/** + * RolePrincipal. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class RolePrincipal implements Principal, Serializable { + + private static final long serialVersionUID = 7278196575770196005L; + private static final String FORMAT = RolePrincipal.class.getSimpleName() + "@%s[name=%s]"; + + private final String _name; + + /** + * Constructs a RolePrincipal with the specified name. + * @param name the specified name + */ + public RolePrincipal(String name) { + if (name == null) { + throw BaseSecurityMessages.MESSAGES.roleCannotBeNull(); + } + _name = name; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _name); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_name == null) ? 0 : _name.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + RolePrincipal other = (RolePrincipal)obj; + if (_name == null) { + if (other._name != null) { + return false; + } + } else if (!_name.equals(other._name)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/principal/UserPrincipal.java b/core/security/base/src/main/java/org/switchyard/security/principal/UserPrincipal.java new file mode 100644 index 000000000..b7e034058 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/principal/UserPrincipal.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.principal; + +import java.io.Serializable; +import java.security.Principal; + +import org.switchyard.security.BaseSecurityMessages; + +/** + * UserPrincipal. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class UserPrincipal implements Principal, Serializable { + + private static final long serialVersionUID = 1931117417458834463L; + private static final String FORMAT = UserPrincipal.class.getSimpleName() + "@%s[name=%s]"; + + private final String _name; + + /** + * Constructs a UserPrincipal with the specified name. + * @param name the specified name + */ + public UserPrincipal(String name) { + if (name == null) { + throw BaseSecurityMessages.MESSAGES.userNameCannotBeNull(); + } + _name = name; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _name); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((_name == null) ? 0 : _name.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + UserPrincipal other = (UserPrincipal)obj; + if (_name == null) { + if (other._name != null) { + return false; + } + } else if (!_name.equals(other._name)) { + return false; + } + return true; + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/provider/DefaultSecurityProvider.java b/core/security/base/src/main/java/org/switchyard/security/provider/DefaultSecurityProvider.java new file mode 100644 index 000000000..74e3284b5 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/provider/DefaultSecurityProvider.java @@ -0,0 +1,261 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.provider; + +import java.security.AccessController; +import java.security.Principal; +import java.security.PrivilegedActionException; +import java.security.PrivilegedExceptionAction; +import java.security.acl.Group; +import java.util.Collections; +import java.util.Set; + +import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; + +import org.switchyard.ServiceSecurity; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.security.BaseSecurityLogger; +import org.switchyard.security.callback.handler.NamePasswordCallbackHandler; +import org.switchyard.security.callback.handler.SwitchYardCallbackHandler; +import org.switchyard.security.context.SecurityContext; +import org.switchyard.security.credential.SubjectCredential; +import org.switchyard.security.principal.GroupPrincipal; +import org.switchyard.security.principal.RolePrincipal; + +/** + * JaasSecurityProvider. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class DefaultSecurityProvider implements SecurityProvider { + + /** + * Constructs a new JaasSecurityProvider. + */ + public DefaultSecurityProvider() {} + + /** + * {@inheritDoc} + */ + @Override + public boolean authenticate(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + boolean success = false; + Class ch_clazz = serviceSecurity.getCallbackHandler(); + if (ch_clazz == null) { + ch_clazz = NamePasswordCallbackHandler.class; + } + CallbackHandler ch = (CallbackHandler)Construction.construct(ch_clazz); + if (ch instanceof SwitchYardCallbackHandler) { + SwitchYardCallbackHandler sych = (SwitchYardCallbackHandler)ch; + sych.setProperties(serviceSecurity.getProperties()); + sych.setCredentials(securityContext.getCredentials()); + } + String securityDomain = serviceSecurity.getSecurityDomain(); + Subject subject = securityContext.getSubject(securityDomain); + try { + new LoginContext(securityDomain, subject, ch).login(); + success = true; + } catch (LoginException le) { + BaseSecurityLogger.ROOT_LOGGER.authenticateLoginException(le.getMessage(), le); + } + return success; + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + String securityDomain = serviceSecurity.getSecurityDomain(); + Subject toSubject = securityContext.getSubject(securityDomain); + Set subjectCredentials = securityContext.getCredentials(SubjectCredential.class); + for (SubjectCredential subjectCredential : subjectCredentials) { + Subject fromSubject = subjectCredential.getSubject(); + transfer(fromSubject, toSubject); + } + } + + /** + * Transfers Principals, private credentials, and public credentials from one Subject to another. + * @param fromSubject the from Subject + * @param toSubject the to Subject + */ + protected void transfer(Subject fromSubject, Subject toSubject) { + if (toSubject != null && fromSubject != null && toSubject != fromSubject && !toSubject.equals(fromSubject)) { + Set toPrincipals = toSubject.getPrincipals(); + Group toRolesGroup = null; + for (Principal fromPrincipal : fromSubject.getPrincipals()) { + if (fromPrincipal instanceof Group && GroupPrincipal.ROLES.equals(fromPrincipal.getName())) { + Group fromRolesGroup = (Group)fromPrincipal; + if (toRolesGroup == null) { + toRolesGroup = getRolesGroup(toSubject); + } + if (toRolesGroup == fromRolesGroup) { + continue; + } + for (Principal fromRole : Collections.list(fromRolesGroup.members())) { + RolePrincipal toRole = fromRole instanceof RolePrincipal ? (RolePrincipal)fromRole : new RolePrincipal(fromRole.getName()); + toRolesGroup.addMember(toRole); + } + } else { + toPrincipals.add(fromPrincipal); + } + } + toSubject.getPrivateCredentials().addAll(fromSubject.getPrivateCredentials()); + toSubject.getPublicCredentials().addAll(fromSubject.getPublicCredentials()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean checkRolesAllowed(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + Set rolesAllowed = serviceSecurity.getRolesAllowed(); + if (rolesAllowed.isEmpty()) { + return true; + } + String securityDomain = serviceSecurity.getSecurityDomain(); + for (String roleName : rolesAllowed) { + boolean isInRole = securityContext.isCallerInRole(roleName, securityDomain); + if (isInRole) { + return true; + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public T runAs(ServiceSecurity serviceSecurity, SecurityContext securityContext, PrivilegedExceptionAction action) throws Exception { + T t = null; + final String securityDomain = serviceSecurity.getSecurityDomain(); + final Subject subject = securityContext.getSubject(securityDomain); + final Principal principal = securityContext.getCallerPrincipal(securityDomain); + final Group rolesGroup = getRolesGroup(subject); + RolePrincipal runAsPrincipal = null; + boolean runAsAdded = false; + final String runAs = serviceSecurity.getRunAs(); + if (runAs != null) { + runAsPrincipal = new RolePrincipal(runAs); + if (!rolesGroup.isMember(runAsPrincipal)) { + rolesGroup.addMember(runAsPrincipal); + runAsAdded = true; + } + } + Object previous = null; + try { + previous = doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws Exception { + return setContainerContext(securityDomain, subject, principal, rolesGroup, runAs); + } + }); + t = Subject.doAsPrivileged(subject, action, null); + } finally { + if (runAsAdded) { + rolesGroup.removeMember(runAsPrincipal); + } + final Object p = previous; + doPrivileged(new PrivilegedExceptionAction() { + public Object run() throws Exception { + resetContainerContext(p); + return null; + } + }); + } + return t; + } + + /** + * Runs a PrivilegedExceptionAction. + * @param action PrivilegedExceptionAction + * @return the result of the action + * @throws Exception if a problem occurs + */ + private final T doPrivileged(PrivilegedExceptionAction action) throws Exception { + if (System.getSecurityManager() != null) { + try { + return AccessController.doPrivileged(action); + } catch (PrivilegedActionException pae) { + throw pae.getException(); + } + } else { + return action.run(); + } + } + + /** + * Sets a container-specific security context, if necessary. + * @param securityDomain the security domain + * @param subject the subject + * @param principal the principal + * @param rolesGroup the Roles group + * @param runAs the run as + * @return the previous container-specific security context, if it existed + * @throws Exception if a problem occurs + */ + protected Object setContainerContext(String securityDomain, Subject subject, Principal principal, Group rolesGroup, String runAs) throws Exception { + // override in sub-classes + return null; + } + + /** + * Resets a container-specific security context to its previous state, if necessary. + * @param previous the previous state + * @throws Exception if a problem occurs + */ + protected void resetContainerContext(Object previous) throws Exception { + // override in sub-classes + } + + /** + * Gets the Group with the name "Roles" from the specified Subject, creating one if not pre-existent. + * @param subject the subject + * @return the "Roles" Group + */ + private Group getRolesGroup(Subject subject) { + Group rolesGroup = null; + Set groups = subject.getPrincipals(Group.class); + for (Group group : groups) { + if (GroupPrincipal.ROLES.equals(group.getName())) { + rolesGroup = group; + break; + } + } + if (rolesGroup == null) { + rolesGroup = new GroupPrincipal(GroupPrincipal.ROLES); + subject.getPrincipals().add(rolesGroup); + } + return rolesGroup; + } + + /** + * {@inheritDoc} + */ + @Override + public void clear(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + if (serviceSecurity != null) { + String securityDomain = serviceSecurity.getSecurityDomain(); + if (securityDomain != null) { + securityContext.clearSubject(securityDomain); + } + } + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/provider/SecurityProvider.java b/core/security/base/src/main/java/org/switchyard/security/provider/SecurityProvider.java new file mode 100644 index 000000000..69b94c919 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/provider/SecurityProvider.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.provider; + +import java.security.PrivilegedExceptionAction; + +import org.switchyard.ServiceSecurity; +import org.switchyard.security.context.SecurityContext; + +/** + * SecurityProvider. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface SecurityProvider { + + /** + * Performs a login with the SecurityContext for the ServiceSecurity. + * @param serviceSecurity the ServiceSecurity + * @param securityContext the SecurityContext + * @return whether authentication was successful + */ + public boolean authenticate(ServiceSecurity serviceSecurity, SecurityContext securityContext); + + /** + * Populates the SecurityContext with any existing (possibly container-specific) security information. + * @param serviceSecurity the ServiceSecurity + * @param securityContext the SecurityContext + */ + public void populate(ServiceSecurity serviceSecurity, SecurityContext securityContext); + + /** + * Checks if the Subject associated in the SecurityContext has at least one of the allowed roles in the ServiceSecurity. + * @param serviceSecurity the ServiceSecurity + * @param securityContext the SecurityContext + * @return whether the allowed roles check was successful + */ + public boolean checkRolesAllowed(ServiceSecurity serviceSecurity, SecurityContext securityContext); + + /** + * Runs the PrivilegedExceptionAction with the SecurityContext according to the runAs for the ServiceSecurity. + * @param serviceSecurity the ServiceSecurity + * @param securityContext the SecurityContext + * @param action the PrivilegedExceptionAction + * @param the return value type + * @return the return value + * @throws Exception if a problem occurs + */ + public T runAs(ServiceSecurity serviceSecurity, SecurityContext securityContext, PrivilegedExceptionAction action) throws Exception; + + /** + * Clears the SecurityContext and any (possibly container-specific) association. + * @param serviceSecurity the ServiceSecurity + * @param securityContext the SecurityContext + */ + public void clear(ServiceSecurity serviceSecurity, SecurityContext securityContext); + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/pull/KeyStorePuller.java b/core/security/base/src/main/java/org/switchyard/security/pull/KeyStorePuller.java new file mode 100644 index 000000000..aedd8cee0 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/pull/KeyStorePuller.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.pull; + +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.KeyStore; + +import org.switchyard.common.io.pull.Puller; + +/** + * Utility class to safely access ("pull") KeyStores from various sources. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class KeyStorePuller extends Puller { + + private final String _type; + private final char[] _password; + + /** + * Constructs a new KeyStorePuller with the default KeyStore type and null KeyStore password. + */ + public KeyStorePuller() { + this(null, null); + } + + /** + * Constructs a new KeyStorePuller with the specified KeyStore type and null KeyStore password. + * @param type the KeyStore type + */ + public KeyStorePuller(String type) { + this(type, null); + } + + /** + * Constructs a new KeyStorePuller with the default KeyStore type and specified KeyStore password. + * @param password the KeyStore password + */ + public KeyStorePuller(char[] password) { + this(null, password); + } + + /** + * Constructs a new KeyStorePuller with the specified KeyStore type and specified KeyStore password. + * @param type the KeyStore type + * @param password the KeyStore password + */ + public KeyStorePuller(String type, char[] password) { + _type = type != null ? type : KeyStore.getDefaultType(); + _password = password; + } + + /** + * {@inheritDoc} + */ + @Override + public KeyStore pull(InputStream stream) throws IOException { + try { + KeyStore keyStore = KeyStore.getInstance(_type); + keyStore.load(stream, _password); + return keyStore; + } catch (GeneralSecurityException gse) { + throw new IOException(gse); + } + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/service/DefaultServiceDomainSecurity.java b/core/security/base/src/main/java/org/switchyard/security/service/DefaultServiceDomainSecurity.java new file mode 100644 index 000000000..7b4469a71 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/service/DefaultServiceDomainSecurity.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.service; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.switchyard.ServiceSecurity; +import org.switchyard.security.system.SystemSecurity; + +/** + * DefaultServiceDomainSecurity. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class DefaultServiceDomainSecurity implements ServiceDomainSecurity { + + private static final String FORMAT = DefaultServiceDomainSecurity.class.getSimpleName() + "@%s[serviceSecurities=%s, systemSecurity=%s]"; + + private final Map _serviceSecurities; + private final SystemSecurity _systemSecurity; + + /** + * Constructs a new DefaultServiceDomainSecurity with defaults for ServiceSecurity(s) and SystemSecurity. + */ + public DefaultServiceDomainSecurity() { + this(null, null); + } + + /** + * Constructs a new DefaultServiceDomainSecurity with the specified ServiceSecurity(s) and SystemSecurity. + * @param serviceSecurities the ServiceSecurity(s) + * @param systemSecurity the SystemSecurity + */ + public DefaultServiceDomainSecurity(Map serviceSecurities, SystemSecurity systemSecurity) { + Map tmpServiceSecurities = new HashMap(); + if (serviceSecurities != null) { + tmpServiceSecurities.putAll(serviceSecurities); + } + if (!tmpServiceSecurities.containsKey(ServiceSecurity.DEFAULT_NAME)) { + tmpServiceSecurities.put(ServiceSecurity.DEFAULT_NAME, new DefaultServiceSecurity()); + } + _serviceSecurities = Collections.unmodifiableMap(tmpServiceSecurities); + _systemSecurity = systemSecurity != null ? systemSecurity : SystemSecurity.DEFAULT; + } + + /** + * {@inheritDoc} + */ + @Override + public ServiceSecurity getServiceSecurity(String name) { + ServiceSecurity serviceSecurity = name != null ? _serviceSecurities.get(name) : null; + if (serviceSecurity == null) { + serviceSecurity = _serviceSecurities.get(ServiceSecurity.DEFAULT_NAME); + } + return serviceSecurity; + } + + /** + * {@inheritDoc} + */ + @Override + public SystemSecurity getSystemSecurity() { + return _systemSecurity; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _serviceSecurities, _systemSecurity); + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/service/DefaultServiceSecurity.java b/core/security/base/src/main/java/org/switchyard/security/service/DefaultServiceSecurity.java new file mode 100644 index 000000000..2f2f281de --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/service/DefaultServiceSecurity.java @@ -0,0 +1,167 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.service; + +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import org.switchyard.ServiceSecurity; + +/** + * DefaultServiceSecurity. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class DefaultServiceSecurity implements ServiceSecurity { + + private static final String FORMAT = DefaultServiceSecurity.class.getSimpleName() + "@%s[name=%s, callbackHandler=%s, properties=%s, rolesAllowed=%s, runAs=%s, securityDomain=%s]"; + + private String _name; + private Class _callbackHandler; + private Map _properties = new LinkedHashMap(); + private Set _rolesAllowed = new LinkedHashSet(); + private String _runAs; + private String _securityDomain; + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + if (_name != null) { + return _name; + } + return DEFAULT_NAME; + } + + /** + * Sets the name. + * @param name the name + * @return this instance (useful for chaining) + */ + public DefaultServiceSecurity setName(String name) { + _name = name; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Class getCallbackHandler() { + return _callbackHandler; + } + + /** + * Sets the CallbackHandler class. + * @param callbackHandler the CallbackHandler class + * @return this instance (useful for chaining) + */ + public DefaultServiceSecurity setCallbackHandler(Class callbackHandler) { + _callbackHandler = callbackHandler; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Map getProperties() { + return _properties; + } + + /** + * Sets the properties. + * @param properties the properties + * @return this instance (useful for chaining) + */ + public DefaultServiceSecurity setProperties(Map properties) { + _properties.clear(); + if (properties != null) { + _properties.putAll(properties); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public Set getRolesAllowed() { + return _rolesAllowed; + } + + /** + * Sets the roles allowed. + * @param rolesAllowed the roles allowed + * @return this instance (useful for chaining) + */ + public DefaultServiceSecurity setRolesAllowed(Set rolesAllowed) { + _rolesAllowed.clear(); + if (rolesAllowed != null) { + _rolesAllowed.addAll(rolesAllowed); + } + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getRunAs() { + return _runAs; + } + + /** + * Sets the run as. + * @param runAs the run as + * @return this instance (useful for chaining) + */ + public DefaultServiceSecurity setRunAs(String runAs) { + _runAs = runAs; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getSecurityDomain() { + if (_securityDomain != null) { + return _securityDomain; + } + return DEFAULT_SECURITY_DOMAIN; + } + + /** + * Sets the security domain. + * @param securityDomain the security domain + * @return this instance (useful for chaining) + */ + public DefaultServiceSecurity setSecurityDomain(String securityDomain) { + _securityDomain = securityDomain; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), getName(), _callbackHandler, _properties, _rolesAllowed, _runAs, getSecurityDomain()); + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/service/SecureServiceDomain.java b/core/security/base/src/main/java/org/switchyard/security/service/SecureServiceDomain.java new file mode 100644 index 000000000..f972b89f7 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/service/SecureServiceDomain.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.service; + +import org.switchyard.ServiceDomain; + +/** + * SecureServiceDomain. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface SecureServiceDomain extends ServiceDomain { + + /** + * Gets the ServiceDomainSecurity. + * @return the ServiceDomainSecurity + */ + public ServiceDomainSecurity getServiceDomainSecurity(); + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/service/ServiceDomainSecurity.java b/core/security/base/src/main/java/org/switchyard/security/service/ServiceDomainSecurity.java new file mode 100644 index 000000000..4b7761c15 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/service/ServiceDomainSecurity.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.service; + +import org.switchyard.ServiceSecurity; +import org.switchyard.security.system.SystemSecurity; + +/** + * SecureServiceDomain. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface ServiceDomainSecurity { + + /** + * Gets a ServiceSecurity by name. + * @param name the name + * @return the ServiceSecurity + */ + public ServiceSecurity getServiceSecurity(String name); + + /** + * Gets the SystemSecurity. + * @return the SystemSecurity + */ + public SystemSecurity getSystemSecurity(); + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/system/DefaultSystemSecurity.java b/core/security/base/src/main/java/org/switchyard/security/system/DefaultSystemSecurity.java new file mode 100644 index 000000000..0c3f9c721 --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/system/DefaultSystemSecurity.java @@ -0,0 +1,137 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.system; + +import java.util.UUID; + +import org.switchyard.security.crypto.PrivateCrypto; +import org.switchyard.security.crypto.PublicCrypto; + +/** + * DefaultSystemSecurity. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class DefaultSystemSecurity implements SystemSecurity { + + private static final String FORMAT = DefaultSystemSecurity.class.getSimpleName() + "@%s[uuid=%s, securityContextTimeoutMillis=%s, privateCrypto=%s, publicCrypto=%s]"; + + private final UUID _uuid; + private Long _securityContextTimeoutMillis; + private PrivateCrypto _privateCrypto; + private PublicCrypto _publicCrypto; + + /** + * Constructs a new DefaultSystemSecurity with null properties. + */ + public DefaultSystemSecurity() { + this(null, null, null); + } + + /** + * Constructs a new DefaultSystemSecurity with specified properties. + * @param securityContextTimeoutMillis the security context timeout in milliseconds + * @param privateCrypto the private crypto + * @param publicCrypto the public crypto + */ + public DefaultSystemSecurity(Long securityContextTimeoutMillis, PrivateCrypto privateCrypto, PublicCrypto publicCrypto) { + _uuid = UUID.randomUUID(); + _securityContextTimeoutMillis = securityContextTimeoutMillis; + _privateCrypto = privateCrypto; + _publicCrypto = publicCrypto; + } + + /** + * {@inheritDoc} + */ + @Override + public UUID getUUID() { + return _uuid; + } + + /** + * {@inheritDoc} + */ + @Override + public Long getSecurityContextTimeoutMillis() { + return _securityContextTimeoutMillis; + } + + /** + * Sets the security context timeout in milliseconds. + * @param securityContextTimeoutMillis the security context timeout in milliseconds + */ + public void setSecurityContextTimeoutMillis(Long securityContextTimeoutMillis) { + _securityContextTimeoutMillis = securityContextTimeoutMillis; + } + + /** + * {@inheritDoc} + */ + @Override + public PrivateCrypto getPrivateCrypto() { + return _privateCrypto; + } + + /** + * Sets the private crypto. + * @param privateCrypto the private crypto + */ + public void setPrivateCrypto(PrivateCrypto privateCrypto) { + _privateCrypto = privateCrypto; + } + + /** + * {@inheritDoc} + */ + @Override + public PublicCrypto getPublicCrypto() { + return _publicCrypto; + } + + /** + * Sets the public crypto. + * @param publicCrypto the public crypto + */ + public void setPublicCrypto(PublicCrypto publicCrypto) { + _publicCrypto = publicCrypto; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format(FORMAT, System.identityHashCode(this), _uuid, _securityContextTimeoutMillis, _privateCrypto, _publicCrypto); + } + + /** + * An immutable DefaultSystemSecurity. + */ + static final class ImmutableDefaultSystemSecurity extends DefaultSystemSecurity { + @Override + public void setSecurityContextTimeoutMillis(Long securityContextTimeoutMillis) { + throw new UnsupportedOperationException(); + } + @Override + public void setPrivateCrypto(PrivateCrypto privateCrypto) { + throw new UnsupportedOperationException(); + } + @Override + public void setPublicCrypto(PublicCrypto publicCrypto) { + throw new UnsupportedOperationException(); + } + } + +} diff --git a/core/security/base/src/main/java/org/switchyard/security/system/SystemSecurity.java b/core/security/base/src/main/java/org/switchyard/security/system/SystemSecurity.java new file mode 100644 index 000000000..58f8da98f --- /dev/null +++ b/core/security/base/src/main/java/org/switchyard/security/system/SystemSecurity.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.system; + +import java.util.UUID; + +import org.switchyard.security.crypto.PrivateCrypto; +import org.switchyard.security.crypto.PublicCrypto; + +/** + * SystemSecurity. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public interface SystemSecurity { + + /** + * The shared/immutable/default SystemSecurity, for when one is not configured by a container. + */ + public static final SystemSecurity DEFAULT = new DefaultSystemSecurity.ImmutableDefaultSystemSecurity(); + + /** + * Gets the universally unique identifier of this SystemSecurity. + * @return the UUID + */ + public UUID getUUID(); + + /** + * Gets the security context timeout in milliseconds. + * @return the security context timeout in milliseconds + */ + public Long getSecurityContextTimeoutMillis(); + + /** + * Gets the private crypto. + * @return the private crypto + */ + public PrivateCrypto getPrivateCrypto(); + + /** + * Gets the public crypto. + * @return the public crypto + */ + public PublicCrypto getPublicCrypto(); + +} diff --git a/core/security/base/src/test/java/org/switchyard/security/context/SecurityContextTests.java b/core/security/base/src/test/java/org/switchyard/security/context/SecurityContextTests.java new file mode 100644 index 000000000..296dd8cc0 --- /dev/null +++ b/core/security/base/src/test/java/org/switchyard/security/context/SecurityContextTests.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.context; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.io.StringReader; +import java.util.LinkedHashSet; +import java.util.Set; + +import javax.crypto.SealedObject; +import javax.security.auth.Subject; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.security.credential.AssertionCredential; +import org.switchyard.security.credential.ConfidentialityCredential; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.NameCredential; +import org.switchyard.security.credential.PasswordCredential; +import org.switchyard.security.credential.PrincipalCredential; +import org.switchyard.security.credential.SubjectCredential; +import org.switchyard.security.credential.extractor.SOAPMessageCredentialExtractorTests; +import org.switchyard.security.crypto.PrivateCrypto; +import org.switchyard.security.principal.GroupPrincipal; +import org.switchyard.security.principal.RolePrincipal; +import org.switchyard.security.principal.UserPrincipal; + +/** + * SecurityContext tests. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SecurityContextTests { + + @Test + public void testCredentialsSerializable() throws Exception { + for (Credential expected : getCredentials()) { + Credential actual = (Credential)serDeser(expected); + Assert.assertEquals(expected, actual); + } + } + + @Test + public void testCredentialsSealable() throws Exception { + for (Credential expected : getCredentials()) { + Credential actual = (Credential)sealUnseal(expected); + Assert.assertEquals(expected, actual); + } + } + + @Test + public void testContextSerializable() throws Exception { + SecurityContext expected = getContext(); + SecurityContext actual = (SecurityContext)serDeser(expected); + Assert.assertEquals(expected, actual); + } + + @Test + public void testContextSealable() throws Exception { + SecurityContext expected = getContext(); + SecurityContext actual = (SecurityContext)sealUnseal(expected); + Assert.assertEquals(expected, actual); + } + + private SecurityContext getContext() throws Exception { + SecurityContext context = new DefaultSecurityContext(); + Subject subject = context.getSubject("testSecurityDomain"); + subject.getPrincipals().add(new UserPrincipal("testUser")); + context.getCredentials().addAll(getCredentials()); + return context; + } + + private Set getCredentials() throws Exception { + UserPrincipal user = new UserPrincipal("testUser"); + RolePrincipal role = new RolePrincipal("testRole"); + GroupPrincipal parentGroup = new GroupPrincipal("testParentGroup"); + parentGroup.addMember(user); + GroupPrincipal childGroup = new GroupPrincipal("testChildGroup"); + childGroup.addMember(role); + parentGroup.addMember(childGroup); + Set creds = new LinkedHashSet(); + creds.add(new AssertionCredential(new ElementPuller().pull(new StringReader("")))); + creds.add(SOAPMessageCredentialExtractorTests.getBinarySecurityTokenCertificateCredential()); + creds.add(new ConfidentialityCredential(true)); + creds.add(new ConfidentialityCredential(false)); + creds.add(new NameCredential("testName")); + creds.add(new PasswordCredential("testPassword")); + creds.add(new PrincipalCredential(user, true)); + creds.add(new PrincipalCredential(role, false)); + creds.add(new PrincipalCredential(childGroup, true)); + creds.add(new PrincipalCredential(parentGroup, false)); + Subject childSubject = new Subject(); + childSubject.getPrincipals().add(new UserPrincipal("childUser")); + creds.add(new SubjectCredential(childSubject)); + return creds; + } + + private Object serDeser(Serializable o) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(o); + oos.flush(); + oos.close(); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(bais); + o = (Serializable)ois.readObject(); + ois.close(); + return o; + } + + private Object sealUnseal(Serializable o) throws Exception { + PrivateCrypto pc = new PrivateCrypto("TripleDES", 168); + SealedObject so = pc.seal(o); + o = pc.unseal(so); + return o; + } + +} diff --git a/core/security/base/src/test/java/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests.java b/core/security/base/src/test/java/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests.java new file mode 100644 index 000000000..c94a5f5d4 --- /dev/null +++ b/core/security/base/src/test/java/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import java.util.Set; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.NameCredential; +import org.switchyard.security.credential.PasswordCredential; + +/** + * AuthorizationHeaderCredentialExtractor tests. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class AuthorizationHeaderCredentialExtractorTests { + + private static final String BASE_PATH = "/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests-"; + private static final String BASIC_TXT = BASE_PATH + "Basic.txt"; + private static final String DIGEST_TXT = BASE_PATH + "Digest.txt"; + + @Test + public void testBasic() throws Exception { + String source = new StringPuller().pull(BASIC_TXT, AuthorizationHeaderCredentialExtractorTests.class); + Set creds = new AuthorizationHeaderCredentialExtractor().extract(source); + boolean foundName = false; + boolean foundPassword = false; + for (Credential cred : creds) { + if (cred instanceof NameCredential) { + foundName = true; + String name = ((NameCredential)cred).getName(); + Assert.assertEquals("Aladdin", name); + } else if (cred instanceof PasswordCredential) { + foundPassword = true; + String password = new String(((PasswordCredential)cred).getPassword()); + Assert.assertEquals("open sesame", password); + } + } + if (!foundName) { + Assert.fail("name not found"); + } + if (!foundPassword) { + Assert.fail("password not found"); + } + } + + @Test + public void testDigest() throws Exception { + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + // https://issues.jboss.org/browse/SWITCHYARD-1082 + // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + String source = new StringPuller().pull(DIGEST_TXT, AuthorizationHeaderCredentialExtractorTests.class); + Set creds = new AuthorizationHeaderCredentialExtractor().extract(source); + boolean foundName = false; + for (Credential cred : creds) { + if (cred instanceof NameCredential) { + foundName = true; + String name = ((NameCredential)cred).getName(); + Assert.assertEquals("Mufasa", name); + } + } + if (!foundName) { + Assert.fail("name not found"); + } + // TODO: complete per SWITCHYARD-1082 + } + +} diff --git a/core/security/base/src/test/java/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests.java b/core/security/base/src/test/java/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests.java new file mode 100644 index 000000000..12e528035 --- /dev/null +++ b/core/security/base/src/test/java/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.credential.extractor; + +import java.io.InputStream; +import java.security.cert.Certificate; +import java.util.Set; + +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPConstants; +import javax.xml.soap.SOAPMessage; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.security.credential.AssertionCredential; +import org.switchyard.security.credential.CertificateCredential; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.NameCredential; +import org.switchyard.security.credential.PasswordCredential; +import org.w3c.dom.Element; + +/** + * SOAPMessageCredentialExtractor tests. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class SOAPMessageCredentialExtractorTests { + + private static final String BASE_PATH = "/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-"; + private static final String ASSERTION_XML = BASE_PATH + "Assertion.xml"; + private static final String USERNAME_TOKEN_XML = BASE_PATH + "UsernameToken.xml"; + private static final String BINARY_SECURITY_TOKEN_XML = BASE_PATH + "BinarySecurityToken.xml"; + + @Test + public void testAssertion() throws Exception { + SOAPMessage source = createMessage(ASSERTION_XML); + Set creds = new SOAPMessageCredentialExtractor().extract(source); + boolean foundAssertion = false; + for (Credential cred : creds) { + if (cred instanceof AssertionCredential) { + foundAssertion = true; + Element assertion = ((AssertionCredential)cred).getAssertion(); + Assert.assertEquals("ID_00cdd057-e611-439d-a189-581e1437e560", assertion.getAttribute("ID")); + } + } + if (!foundAssertion) { + Assert.fail("assertion not found"); + } + } + + @Test + public void testUsernameToken() throws Exception { + SOAPMessage source = createMessage(USERNAME_TOKEN_XML); + Set creds = new SOAPMessageCredentialExtractor().extract(source); + boolean foundName = false; + boolean foundPassword = false; + for (Credential cred : creds) { + if (cred instanceof NameCredential) { + foundName = true; + String name = ((NameCredential)cred).getName(); + Assert.assertEquals("Aladdin", name); + } else if (cred instanceof PasswordCredential) { + foundPassword = true; + String password = new String(((PasswordCredential)cred).getPassword()); + Assert.assertEquals("open sesame", password); + } + } + if (!foundName) { + Assert.fail("name not found"); + } + if (!foundPassword) { + Assert.fail("password not found"); + } + } + + @Test + public void testBinarySecurityToken() throws Exception { + CertificateCredential cred = getBinarySecurityTokenCertificateCredential(); + if (cred == null) { + Assert.fail("certificate not found"); + } + Certificate certificate = ((CertificateCredential)cred).getCertificate(); + Assert.assertEquals("X.509", certificate.getType()); + } + + public static CertificateCredential getBinarySecurityTokenCertificateCredential() throws Exception { + SOAPMessage source = createMessage(BINARY_SECURITY_TOKEN_XML); + Set creds = new SOAPMessageCredentialExtractor().extract(source); + for (Credential cred : creds) { + if (cred instanceof CertificateCredential) { + return (CertificateCredential)cred; + } + } + return null; + } + + private static SOAPMessage createMessage(String path) throws Exception { + InputStream is = Classes.getResourceAsStream(path, SOAPMessageCredentialExtractorTests.class); + try { + return MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createMessage(null, is); + } finally { + if (is != null) { + is.close(); + } + } + } + +} diff --git a/core/security/base/src/test/resources/log4j.properties b/core/security/base/src/test/resources/log4j.properties new file mode 100644 index 000000000..02a249c1d --- /dev/null +++ b/core/security/base/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootCategory=INFO, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=DEBUG +log4j.appender.CONSOLE.Target=System.out +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n diff --git a/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests-Basic.txt b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests-Basic.txt new file mode 100644 index 000000000..a15eafddc --- /dev/null +++ b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests-Basic.txt @@ -0,0 +1 @@ +Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== \ No newline at end of file diff --git a/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests-Digest.txt b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests-Digest.txt new file mode 100644 index 000000000..906262f86 --- /dev/null +++ b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/AuthorizationHeaderCredentialExtractorTests-Digest.txt @@ -0,0 +1,9 @@ +Digest username="Mufasa" + realm="testrealm@host.com" + nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093" + uri="/dir/index.html" + qop=auth, + nc=00000001 + cnonce="0a4f113b" + response="6629fae49393a05397450978507c4ef1" + opaque="5ccc069c403ebaf9f0171e9517f40e41" \ No newline at end of file diff --git a/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-Assertion.xml b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-Assertion.xml new file mode 100644 index 000000000..603d1325e --- /dev/null +++ b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-Assertion.xml @@ -0,0 +1,49 @@ + + + + + + PicketLinkSTS + + + + + + + + + + + 0I4VREOz6/E7fEaeAkwnVk2AyZw= + + + eFdKOlRlnTre8cWdyM7NPanKE1n0uRMIMWvr5mWAVSoY7sSAm4I/cBs5gXjGxp45NPo2C2pjjdvc+EoJd2xvxYx6z3qsHMfK3EGDoLXJusjSB+hgXGZ8UgjjktHVkA5NOwwdY2xFmglAINWYMGi+cOezYUNhb4OEJWoPsXMI9qg= + + + + suGIyhVTbFvDwZdx8Av62zmP+aGOlsBN8WUE3eEEcDtOIZgO78SImMQGwB2C0eIVMhiLRzVPqoW1dCPAveTm653zHOmubaps1fY0lLJDSZbTbhjeYhoQmmaBro/tDpVw5lKJns2qVnMuRK19ju2dxpKwlYGGtrP5VQv00dfNPbs= + AQAB + + + + + + admin + + + + + + urn:oasis:names:tc:SAML:2.0:cm:bearer + + + + + + + bar + + diff --git a/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-BinarySecurityToken.xml b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-BinarySecurityToken.xml new file mode 100644 index 000000000..c6911eb3a --- /dev/null +++ b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-BinarySecurityToken.xml @@ -0,0 +1,14 @@ + + + + + MIICIjCCAYsCBEj0TGMwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQkIxDDAKBgNVBAgTA0JhZDEMMAoGA1UEBxMDQmFkMQwwCgYDVQQKEwNCYWQxDDAKBgNVBAsTA0JhZDERMA8GA1UEAxMIQmFkIHVzZXIwHhcNMDgxMDE0MDczODExWhcNMTEwNzEwMDczODExWjBYMQswCQYDVQQGEwJCQjEMMAoGA1UECBMDQmFkMQwwCgYDVQQHEwNCYWQxDDAKBgNVBAoTA0JhZDEMMAoGA1UECxMDQmFkMREwDwYDVQQDEwhCYWQgdXNlcjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAhlb/SagmAPrp5+CqSexB/X/GhdtaYXQHY0rKvyE/E2g5bKsXDcNAUu9ZwHmUHIPoyHTGTdQbYgQVbehOPys2RiyQr7MOP1L7X+H2YC6Fce55eydFliIFDKq9+991fmPSOZ6lz/vYnfN4fEwMuw4CbJ2Zlt+vb44AvVVyZHZpZykCAwEAATANBgkqhkiG9w0BAQQFAAOBgQB5fMiT7ApyoUoP3dq9rmpjrUxKIxBvbkWCWrR9KyN7kPT6/zDcqlmljjhVWZdOEQ6dTOmuA56fvNE8WO1xLq6F+OZZni3IDQ/cPgqEa/REOuv+tFGK08Te0WIe3Ff5vodp0s+H/X75X2Sy3ZbZMXCV115q5rASRbOjsxE5fVaRMw== + + + + bar + + diff --git a/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-UsernameToken.xml b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-UsernameToken.xml new file mode 100644 index 000000000..c9491888f --- /dev/null +++ b/core/security/base/src/test/resources/org/switchyard/security/credential/extractor/SOAPMessageCredentialExtractorTests-UsernameToken.xml @@ -0,0 +1,17 @@ + + + + + + Aladdin + open sesame + + + + + bar + + diff --git a/core/security/jboss/pom.xml b/core/security/jboss/pom.xml new file mode 100644 index 000000000..9a00558d7 --- /dev/null +++ b/core/security/jboss/pom.xml @@ -0,0 +1,84 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-security-jboss + bundle + SwitchYard: Security - JBoss + The JBoss security library. + http://switchyard.org + + + org.switchyard.security.jboss.* + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-security + + + + org.jboss.as + jboss-as-web + provided + + + org.jboss.web + jbossweb + provided + + + org.jboss.com.sun.httpserver + httpserver + provided + + + org.picketbox + picketbox + compile + + + org.picketlink + picketlink-federation + provided + + + org.picketlink.distribution + picketlink-jbas7 + provided + + + org.wildfly + wildfly-picketlink + provided + + + diff --git a/core/security/jboss/src/main/java/org/switchyard/security/jboss/JBossSecurityLogger.java b/core/security/jboss/src/main/java/org/switchyard/security/jboss/JBossSecurityLogger.java new file mode 100644 index 000000000..d59f953d4 --- /dev/null +++ b/core/security/jboss/src/main/java/org/switchyard/security/jboss/JBossSecurityLogger.java @@ -0,0 +1,41 @@ +package org.switchyard.security.jboss; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.WARN; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 14600-14699 for logger messages. + *

+ */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface JBossSecurityLogger { + + /** + * Default root logger. + */ + JBossSecurityLogger ROOT_LOGGER = Logger.getMessageLogger(JBossSecurityLogger.class, JBossSecurityLogger.class.getPackage().getName()); + + /** + * switchyardDomainNotMatchJBossDomain method definition. + * @param switchYardDomain switchYardDomain + * @param jbossDomain jbossDomain + */ + @LogMessage(level = WARN) + @Message(id = 14600, value = "SwitchYard security domain (%s) does not match JBoss security domain (%s).") + void switchyardDomainNotMatchJBossDomain(String switchYardDomain, String jbossDomain); + + /** + * clearSecurityContextAssociation method definition. + * @param throwable throwable + */ + @LogMessage(level = ERROR) + @Message(id = 14601, value = "Problem clearing SecurityContextAssociation : %s") + void clearSecurityContextAssociation(Throwable throwable); + +} diff --git a/core/security/jboss/src/main/java/org/switchyard/security/jboss/JBossSecurityMessages.java b/core/security/jboss/src/main/java/org/switchyard/security/jboss/JBossSecurityMessages.java new file mode 100644 index 000000000..f29e6a230 --- /dev/null +++ b/core/security/jboss/src/main/java/org/switchyard/security/jboss/JBossSecurityMessages.java @@ -0,0 +1,27 @@ +package org.switchyard.security.jboss; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 14700-14799 for logger messages. + *

+ */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface JBossSecurityMessages { + + /** + * Default messages. + */ + JBossSecurityMessages MESSAGES = Messages.getBundle(JBossSecurityMessages.class); + + /** + * credentialsNotSet method definition. + * @return IllegalStateException + */ + @Message(id = 14700, value = "Credentials not set") + IllegalStateException credentialsNotSet(); + +} diff --git a/core/security/jboss/src/main/java/org/switchyard/security/jboss/callback/handler/STSIssueCallbackHandler.java b/core/security/jboss/src/main/java/org/switchyard/security/jboss/callback/handler/STSIssueCallbackHandler.java new file mode 100644 index 000000000..5735a4b75 --- /dev/null +++ b/core/security/jboss/src/main/java/org/switchyard/security/jboss/callback/handler/STSIssueCallbackHandler.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.jboss.callback.handler; + +import java.io.IOException; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.UnsupportedCallbackException; + +import org.switchyard.security.callback.handler.NamePasswordCallbackHandler; +import org.switchyard.security.callback.handler.SwitchYardCallbackHandler; + +/** + * STSIssueCallbackHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class STSIssueCallbackHandler extends SwitchYardCallbackHandler { + + /** + * Constructs a new STSIssueCallbackHandler. + */ + public STSIssueCallbackHandler() {} + + /** + * {@inheritDoc} + */ + @Override + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + handle(callbacks, new NamePasswordCallbackHandler()); + handle(callbacks, new STSTokenCallbackHandler()); + } + + private void handle(Callback[] callbacks, SwitchYardCallbackHandler handler) throws IOException, UnsupportedCallbackException { + handler.setProperties(getProperties()); + handler.setCredentials(getCredentials()); + handler.handle(callbacks); + } + +} diff --git a/core/security/jboss/src/main/java/org/switchyard/security/jboss/callback/handler/STSTokenCallbackHandler.java b/core/security/jboss/src/main/java/org/switchyard/security/jboss/callback/handler/STSTokenCallbackHandler.java new file mode 100644 index 000000000..9c5c46931 --- /dev/null +++ b/core/security/jboss/src/main/java/org/switchyard/security/jboss/callback/handler/STSTokenCallbackHandler.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.jboss.callback.handler; + +import java.io.IOException; +import java.util.Set; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.UnsupportedCallbackException; + +import org.picketlink.identity.federation.core.wstrust.auth.TokenCallback; +import org.switchyard.security.callback.handler.SwitchYardCallbackHandler; +import org.switchyard.security.credential.AssertionCredential; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.jboss.JBossSecurityMessages; + +/** + * STSTokenCallbackHandler. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class STSTokenCallbackHandler extends SwitchYardCallbackHandler { + + /** + * Constructs a new STSTokenCallbackHandler. + */ + public STSTokenCallbackHandler() {} + + /** + * {@inheritDoc} + */ + @Override + public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { + Set credentials = getCredentials(); + if (credentials == null) { + throw JBossSecurityMessages.MESSAGES.credentialsNotSet(); + } + for (Callback cb : callbacks) { + if (cb instanceof TokenCallback) { + for (Credential cred : credentials) { + if (cred instanceof AssertionCredential) { + ((TokenCallback)cb).setToken(((AssertionCredential)cred).getAssertion()); + } + } + } + } + } + +} diff --git a/core/security/jboss/src/main/java/org/switchyard/security/jboss/credential/extractor/HttpExchangeCredentialExtractor.java b/core/security/jboss/src/main/java/org/switchyard/security/jboss/credential/extractor/HttpExchangeCredentialExtractor.java new file mode 100644 index 000000000..9ea1055cb --- /dev/null +++ b/core/security/jboss/src/main/java/org/switchyard/security/jboss/credential/extractor/HttpExchangeCredentialExtractor.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.jboss.credential.extractor; + +import java.security.Principal; +import java.util.HashSet; +import java.util.Set; + +import org.jboss.com.sun.net.httpserver.HttpExchange; +import org.switchyard.common.lang.Strings; +import org.switchyard.security.credential.ConfidentialityCredential; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.PrincipalCredential; +import org.switchyard.security.credential.extractor.AuthorizationHeaderCredentialExtractor; +import org.switchyard.security.credential.extractor.CredentialExtractor; + +/** + * HttpExchangeCredentialExtractor. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class HttpExchangeCredentialExtractor implements CredentialExtractor { + + /** + * Constructs a new HttpExchangeCredentialsExtractor. + */ + public HttpExchangeCredentialExtractor() {} + + /** + * {@inheritDoc} + */ + @Override + public Set extract(HttpExchange source) { + Set credentials = new HashSet(); + if (source != null) { + String protocol = source.getProtocol(); + if (protocol != null) { + credentials.add(new ConfidentialityCredential(protocol.toLowerCase().startsWith("https"))); + } + Principal principal = source.getPrincipal(); + if (principal != null) { + credentials.add(new PrincipalCredential(principal, true)); + } + // TODO: Should we go after this? + /* + String remoteUser = source.getRequestHeaders().getFirst("REMOTE_USER"); + if (remoteUser != null) { + credentials.add(new PrincipalCredential(new User(remoteUser), false)); // true? + } + */ + String charsetName = null; + String contentType = source.getRequestHeaders().getFirst("Content-Type"); + if (contentType != null) { + int pos = contentType.lastIndexOf("charset="); + if (pos > -1) { + charsetName = Strings.trimToNull(contentType.substring(pos+8, contentType.length())); + } + } + AuthorizationHeaderCredentialExtractor ahce; + if (charsetName != null) { + ahce = new AuthorizationHeaderCredentialExtractor(charsetName); + } else { + ahce = new AuthorizationHeaderCredentialExtractor(); + } + credentials.addAll(ahce.extract(source.getRequestHeaders().getFirst("Authorization"))); + } + return credentials; + } + +} diff --git a/core/security/jboss/src/main/java/org/switchyard/security/jboss/credential/extractor/JBossServletRequestCredentialExtractor.java b/core/security/jboss/src/main/java/org/switchyard/security/jboss/credential/extractor/JBossServletRequestCredentialExtractor.java new file mode 100644 index 000000000..9318c7633 --- /dev/null +++ b/core/security/jboss/src/main/java/org/switchyard/security/jboss/credential/extractor/JBossServletRequestCredentialExtractor.java @@ -0,0 +1,80 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.jboss.credential.extractor; + +import java.security.Principal; +import java.util.HashSet; +import java.util.Set; + +import javax.security.auth.Subject; +import javax.servlet.ServletRequest; + +import org.apache.catalina.connector.Request; +import org.apache.catalina.connector.RequestFacade; +import org.jboss.as.web.security.JBossGenericPrincipal; +import org.switchyard.common.type.reflect.Access; +import org.switchyard.common.type.reflect.FieldAccess; +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.SubjectCredential; +import org.switchyard.security.credential.extractor.DefaultServletRequestCredentialExtractor; + +/** + * JBossServletRequestCredentialExtractor. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class JBossServletRequestCredentialExtractor extends DefaultServletRequestCredentialExtractor { + + private static final Access REQUEST_ACCESS; + private static final Access PRINCIPAL_ACCESS; + static { + final Access requestAccess = new FieldAccess(RequestFacade.class, "request"); + REQUEST_ACCESS = requestAccess.isReadable() ? requestAccess : null; + final Access principalAccess = new FieldAccess(Request.class, "userPrincipal"); + PRINCIPAL_ACCESS = principalAccess.isReadable() ? principalAccess : null; + } + + /** + * Constructs a new JBossServletRequestCredentialExtractor. + */ + public JBossServletRequestCredentialExtractor() {} + + /** + * {@inheritDoc} + */ + @Override + public Set extract(ServletRequest source) { + Set credentials = new HashSet(); + if (source != null) { + credentials.addAll(super.extract(source)); + Request request = null; + if (source instanceof Request) { + request = (Request)source; + } else if (source instanceof RequestFacade && REQUEST_ACCESS != null) { + request = REQUEST_ACCESS.read((RequestFacade)source); + } + if (request != null && PRINCIPAL_ACCESS != null) { + Principal principal = PRINCIPAL_ACCESS.read(request); + if (principal instanceof JBossGenericPrincipal) { + Subject subject = ((JBossGenericPrincipal)principal).getSubject(); + if (subject != null) { + credentials.add(new SubjectCredential(subject)); + } + } + } + } + return credentials; + } + +} diff --git a/core/security/jboss/src/main/java/org/switchyard/security/jboss/provider/JBossSecurityProvider.java b/core/security/jboss/src/main/java/org/switchyard/security/jboss/provider/JBossSecurityProvider.java new file mode 100644 index 000000000..35c61d024 --- /dev/null +++ b/core/security/jboss/src/main/java/org/switchyard/security/jboss/provider/JBossSecurityProvider.java @@ -0,0 +1,288 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.jboss.provider; + + +import java.security.AccessController; +import java.security.Principal; +import java.security.PrivilegedAction; +import java.security.acl.Group; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.security.auth.Subject; + + +import org.jboss.security.RunAs; +import org.jboss.security.RunAsIdentity; +import org.jboss.security.SecurityContextAssociation; +import org.jboss.security.SecurityContextFactory; +import org.jboss.security.identity.Identity; +import org.jboss.security.identity.Role; +import org.jboss.security.identity.RoleGroup; +import org.jboss.security.identity.extensions.CredentialIdentityFactory; +import org.jboss.security.identity.plugins.SimpleRoleGroup; +import org.jboss.security.mapping.MappingResult; +import org.picketlink.identity.federation.bindings.jboss.auth.mapping.STSGroupMappingProvider; +import org.picketlink.identity.federation.bindings.jboss.auth.mapping.STSPrincipalMappingProvider; +import org.picketlink.identity.federation.core.wstrust.auth.AbstractSTSLoginModule; +import org.switchyard.ServiceSecurity; +import org.switchyard.security.context.SecurityContext; +import org.switchyard.security.credential.AssertionCredential; +import org.switchyard.security.jboss.JBossSecurityLogger; +import org.switchyard.security.principal.GroupPrincipal; +import org.switchyard.security.principal.RolePrincipal; +import org.switchyard.security.principal.UserPrincipal; +import org.switchyard.security.provider.DefaultSecurityProvider; +import org.w3c.dom.Element; + +/** + * JBossSecurityProvider. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class JBossSecurityProvider extends DefaultSecurityProvider { + + static { + // Here to trigger fallback usage of a different SecurityProvider (or DefaultSecurityProvider), + // if the org.picketbox:picketbox dependency is not available. + SecurityContextAssociation.getSecurityContext(); + } + + /** + * Constructs a new JBossSecurityProvider. + */ + public JBossSecurityProvider() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + String sy_securityDomain = serviceSecurity.getSecurityDomain(); + Subject sy_subject = securityContext.getSubject(sy_securityDomain); + org.jboss.security.SecurityContext jb_securityContext = SecurityContextAssociation.getSecurityContext(); + if (jb_securityContext != null) { + // populate from pre-authenticated container context + String jb_securityDomain = jb_securityContext.getSecurityDomain(); + if (!sy_securityDomain.equals(jb_securityDomain)) { + pushSubjectContext(sy_securityDomain); + } + Subject jb_subject = jb_securityContext.getUtil().getSubject(); + transfer(jb_subject, sy_subject); + } else { + // populate from pre-verified federated assertion + Set assertionCredentials = securityContext.getCredentials(AssertionCredential.class); + for (AssertionCredential assertionCredential : assertionCredentials) { + Element assertionElement = assertionCredential.getAssertion(); + if (assertionElement != null) { + Subject sts_subject = new Subject(); + boolean sts_mapped = false; + Map contextMap = new HashMap(); + contextMap.put(AbstractSTSLoginModule.SHARED_TOKEN, assertionElement); + STSPrincipalMappingProvider principalMapper = new STSPrincipalMappingProvider(); + principalMapper.init(contextMap); + MappingResult principalResult = new MappingResult(); + principalMapper.setMappingResult(principalResult); + principalMapper.performMapping(contextMap, null); + Principal principal = principalResult.getMappedObject(); + if (principal != null) { + sts_subject.getPrincipals().add(new UserPrincipal(principal.getName())); + sts_mapped = true; + } + STSGroupMappingProvider rolesMapper = new STSGroupMappingProvider(); + rolesMapper.init(contextMap); + MappingResult rolesResult = new MappingResult(); + rolesMapper.setMappingResult(rolesResult); + rolesMapper.performMapping(contextMap, null); + RoleGroup roleGroup = rolesResult.getMappedObject(); + if (roleGroup != null) { + GroupPrincipal roles = null; + for (Role role : roleGroup.getRoles()) { + if (roles == null) { + roles = new GroupPrincipal(GroupPrincipal.ROLES); + } + roles.addMember(new RolePrincipal(role.getRoleName())); + } + if (roles != null) { + sts_subject.getPrincipals().add(roles); + sts_mapped = true; + } + } + if (sts_mapped) { + transfer(sts_subject, sy_subject); + } + } + } + } + super.populate(serviceSecurity, securityContext); + } + + /** + * Create new security context for the specified domain, transferring the + * current subject, principal and credentials into the new domain. + * + * @param domain the domain + */ + public void pushSubjectContext(final String domain) { + AccessController.doPrivileged(new PrivilegedAction() { + + public Void run() { + org.jboss.security.SecurityContext oldSecurityContext = SecurityContextAssociation.getSecurityContext(); + org.jboss.security.SecurityContext securityContext = createSecurityContext(domain); + setSecurityContextOnAssociation(securityContext); + securityContext.getUtil().createSubjectInfo(oldSecurityContext.getUtil().getUserPrincipal(), oldSecurityContext.getUtil().getCredential(), oldSecurityContext.getUtil().getSubject()); + return null; + } + }); + } + + /** + * Create a JBoss Security Context with the given security domain name + * + * @param domain the security domain name (such as "other" ) + * @return an instanceof {@code SecurityContext} + */ + private static org.jboss.security.SecurityContext createSecurityContext(final String domain) { + return AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public org.jboss.security.SecurityContext run() { + try { + return SecurityContextFactory.createSecurityContext(domain); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + }); + } + + /** + * Set the {@code SecurityContext} on the {@code SecurityContextAssociation} + * + * @param sc the security context + */ + private static void setSecurityContextOnAssociation(final org.jboss.security.SecurityContext sc) { + AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public Void run() { + SecurityContextAssociation.setSecurityContext(sc); + return null; + } + }); + } + + /** + * {@inheritDoc} + */ + @Override + protected Object setContainerContext(String securityDomain, Subject subject, Principal principal, Group rolesGroup, String runAs) throws Exception { + Set roles = new HashSet(); + if (runAs != null) { + roles.add(runAs); + } + if (rolesGroup != null) { + for (Principal role : Collections.list(rolesGroup.members())) { + if (runAs == null) { + runAs = role.getName(); + } + roles.add(role.getName()); + } + } + RunAs new_jb_runAs = runAs != null ? new RunAsIdentity(runAs, principal != null ? principal.getName() : null, roles) : null; + org.jboss.security.SecurityContext old_jb_securityContext = SecurityContextAssociation.getSecurityContext(); + if (old_jb_securityContext == null) { + Set credentials = subject.getPrivateCredentials(); + Object credential = !credentials.isEmpty() ? credentials.iterator().next() : null; + org.jboss.security.SecurityContext new_jb_securityContext = SecurityContextFactory.createSecurityContext(securityDomain); + SecurityContextAssociation.setSecurityContext(new_jb_securityContext); + if (rolesGroup != null) { + RoleGroup roleGroup = new SimpleRoleGroup(rolesGroup); + Identity identity = CredentialIdentityFactory.createIdentity(principal, credential, roleGroup); + new_jb_securityContext.getUtil().createSubjectInfo(identity, subject); + new_jb_securityContext.getSubjectInfo().setRoles(roleGroup); + } else { + Identity identity = CredentialIdentityFactory.createIdentity(principal, credential); + new_jb_securityContext.getUtil().createSubjectInfo(identity, subject); + } + if (new_jb_runAs != null) { + new_jb_securityContext.setOutgoingRunAs(new_jb_runAs); + } + return new JBossContainerContext(null, null, null); + } else { + RoleGroup old_jb_roleGroup = old_jb_securityContext.getSubjectInfo().getRoles(); + if (rolesGroup != null) { + old_jb_securityContext.getSubjectInfo().setRoles(new SimpleRoleGroup(rolesGroup)); + } + RunAs old_jb_runAs = old_jb_securityContext.getOutgoingRunAs(); + if (new_jb_runAs != null) { + old_jb_securityContext.setOutgoingRunAs(new_jb_runAs); + } + return new JBossContainerContext(old_jb_securityContext, old_jb_roleGroup, old_jb_runAs); + } + } + + /** + * {@inheritDoc} + */ + @Override + protected void resetContainerContext(Object previous) throws Exception { + JBossContainerContext old_jb = (JBossContainerContext)previous; + if (old_jb._securityContext == null) { + SecurityContextAssociation.clearSecurityContext(); + } else { + SecurityContextAssociation.setSecurityContext(old_jb._securityContext); + old_jb._securityContext.getSubjectInfo().setRoles(old_jb._roleGroup); + old_jb._securityContext.setOutgoingRunAs(old_jb._runAs); + } + } + + private static final class JBossContainerContext { + private final org.jboss.security.SecurityContext _securityContext; + private final RoleGroup _roleGroup; + private final RunAs _runAs; + private JBossContainerContext(org.jboss.security.SecurityContext securityContext, RoleGroup roleGroup, RunAs runAs) { + this._securityContext = securityContext; + this._roleGroup = roleGroup; + this._runAs = runAs; + } + } + + /** + * {@inheritDoc} + */ + @Override + public void clear(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + super.clear(serviceSecurity, securityContext); + try { + org.jboss.security.SecurityContext jb_securityContext = SecurityContextAssociation.getSecurityContext(); + if (jb_securityContext != null) { + String sy_securityDomain = serviceSecurity.getSecurityDomain(); + String jb_securityDomain = jb_securityContext.getSecurityDomain(); + if (sy_securityDomain.equals(jb_securityDomain)) { + SecurityContextAssociation.clearSecurityContext(); + } + } + } catch (Throwable t) { + JBossSecurityLogger.ROOT_LOGGER.clearSecurityContextAssociation(t); + } + } + +} diff --git a/core/security/jboss/src/main/resources/META-INF/services/org.switchyard.security.credential.extractor.ServletRequestCredentialExtractor b/core/security/jboss/src/main/resources/META-INF/services/org.switchyard.security.credential.extractor.ServletRequestCredentialExtractor new file mode 100644 index 000000000..f87ebc61c --- /dev/null +++ b/core/security/jboss/src/main/resources/META-INF/services/org.switchyard.security.credential.extractor.ServletRequestCredentialExtractor @@ -0,0 +1,13 @@ +# Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +org.switchyard.security.jboss.credential.extractor.JBossServletRequestCredentialExtractor diff --git a/core/security/jboss/src/main/resources/META-INF/services/org.switchyard.security.provider.SecurityProvider b/core/security/jboss/src/main/resources/META-INF/services/org.switchyard.security.provider.SecurityProvider new file mode 100644 index 000000000..f9adc4d85 --- /dev/null +++ b/core/security/jboss/src/main/resources/META-INF/services/org.switchyard.security.provider.SecurityProvider @@ -0,0 +1,13 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +org.switchyard.security.jboss.provider.JBossSecurityProvider diff --git a/core/security/jboss/src/test/resources/log4j.properties b/core/security/jboss/src/test/resources/log4j.properties new file mode 100644 index 000000000..02a249c1d --- /dev/null +++ b/core/security/jboss/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootCategory=INFO, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=DEBUG +log4j.appender.CONSOLE.Target=System.out +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n diff --git a/core/security/karaf/pom.xml b/core/security/karaf/pom.xml new file mode 100644 index 000000000..713401447 --- /dev/null +++ b/core/security/karaf/pom.xml @@ -0,0 +1,60 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-security-karaf + bundle + SwitchYard: Security - Karaf + The Karaf security library. + http://switchyard.org + + + org.switchyard.security.karaf.* + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-security + + + + org.apache.karaf.jaas + org.apache.karaf.jaas.boot + provided + + + org.apache.karaf.jaas + org.apache.karaf.jaas.modules + provided + + + org.jboss.spec.javax.servlet + jboss-servlet-api_3.0_spec + provided + + + diff --git a/core/security/karaf/src/main/java/org/switchyard/security/karaf/KarafSecurityLogger.java b/core/security/karaf/src/main/java/org/switchyard/security/karaf/KarafSecurityLogger.java new file mode 100644 index 000000000..22a85fbe4 --- /dev/null +++ b/core/security/karaf/src/main/java/org/switchyard/security/karaf/KarafSecurityLogger.java @@ -0,0 +1,32 @@ +package org.switchyard.security.karaf; + +import static org.jboss.logging.Logger.Level.WARN; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 14800-14899 for logger messages. + *

+ */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface KarafSecurityLogger { + + /** + * Default root logger. + */ + KarafSecurityLogger ROOT_LOGGER = Logger.getMessageLogger(KarafSecurityLogger.class, KarafSecurityLogger.class.getPackage().getName()); + + /** + * switchyardDomainNotMatchKarafDomain method definition. + * @param switchYardDomain switchYardDomain + * @param karafDomain karafDomain + */ + @LogMessage(level = WARN) + @Message(id = 14800, value = "SwitchYard security domain (%s) does not match Karaf security domain (%s).") + void switchyardDomainNotMatchKarafDomain(String switchYardDomain, String karafDomain); + +} diff --git a/core/security/karaf/src/main/java/org/switchyard/security/karaf/KarafSecurityMessages.java b/core/security/karaf/src/main/java/org/switchyard/security/karaf/KarafSecurityMessages.java new file mode 100644 index 000000000..fcf448b79 --- /dev/null +++ b/core/security/karaf/src/main/java/org/switchyard/security/karaf/KarafSecurityMessages.java @@ -0,0 +1,27 @@ +package org.switchyard.security.karaf; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 14900-14999 for logger messages. + *

+ */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface KarafSecurityMessages { + + /** + * Default messages. + */ + KarafSecurityMessages MESSAGES = Messages.getBundle(KarafSecurityMessages.class); + + /** + * credentialsNotSet method definition. + * @return IllegalStateException + */ + @Message(id = 14900, value = "Credentials not set") + IllegalStateException credentialsNotSet(); + +} diff --git a/core/security/karaf/src/main/java/org/switchyard/security/karaf/credential/extractor/KarafServletRequestCredentialExtractor.java b/core/security/karaf/src/main/java/org/switchyard/security/karaf/credential/extractor/KarafServletRequestCredentialExtractor.java new file mode 100644 index 000000000..01219502d --- /dev/null +++ b/core/security/karaf/src/main/java/org/switchyard/security/karaf/credential/extractor/KarafServletRequestCredentialExtractor.java @@ -0,0 +1,48 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.karaf.credential.extractor; + +import java.util.HashSet; +import java.util.Set; + +import javax.servlet.ServletRequest; + +import org.switchyard.security.credential.Credential; +import org.switchyard.security.credential.extractor.DefaultServletRequestCredentialExtractor; + +/** + * KarafServletRequestCredentialExtractor. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class KarafServletRequestCredentialExtractor extends DefaultServletRequestCredentialExtractor { + + /** + * Constructs a new KarafServletRequestCredentialExtractor. + */ + public KarafServletRequestCredentialExtractor() {} + + /** + * {@inheritDoc} + */ + @Override + public Set extract(ServletRequest source) { + Set credentials = new HashSet(); + if (source != null) { + credentials.addAll(super.extract(source)); + } + return credentials; + } + +} diff --git a/core/security/karaf/src/main/java/org/switchyard/security/karaf/provider/KarafSecurityProvider.java b/core/security/karaf/src/main/java/org/switchyard/security/karaf/provider/KarafSecurityProvider.java new file mode 100644 index 000000000..8b616e4cd --- /dev/null +++ b/core/security/karaf/src/main/java/org/switchyard/security/karaf/provider/KarafSecurityProvider.java @@ -0,0 +1,118 @@ +/* + * Copyright 2015 JBoss Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.security.karaf.provider; + +import java.security.Principal; +import java.util.Enumeration; +import java.util.Set; + +import javax.security.auth.Subject; + +import org.apache.karaf.jaas.boot.ProxyLoginModule; +import org.apache.karaf.jaas.boot.principal.GroupPrincipal; +import org.switchyard.ServiceSecurity; +import org.switchyard.security.context.SecurityContext; +import org.switchyard.security.provider.DefaultSecurityProvider; + +// TODO: Auto-generated Javadoc +/** + * KarafSecurityProvider. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class KarafSecurityProvider extends DefaultSecurityProvider { + + static { + // Here to trigger fallback usage of a different SecurityProvider (or DefaultSecurityProvider), + // if the org.apache.karaf.jaas:org.apache.karaf.jaas.modules dependency is not available. + new ProxyLoginModule(); + } + + /** + * Constructs a new KarafSecurityProvider. + */ + public KarafSecurityProvider() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public void populate(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + super.populate(serviceSecurity, securityContext); + } + + /** + * {@inheritDoc} + */ + @Override + public void clear(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + super.clear(serviceSecurity, securityContext); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean checkRolesAllowed(ServiceSecurity serviceSecurity, SecurityContext securityContext) { + Set rolesAllowed = serviceSecurity.getRolesAllowed(); + if (rolesAllowed.isEmpty()) { + return true; + } + String securityDomain = serviceSecurity.getSecurityDomain(); + for (String roleName : rolesAllowed) { + boolean isInRole = this.isCallerInRole(securityContext, roleName, securityDomain); + if (isInRole) { + return true; + } + } + return false; + } + + /** + * Checks if is caller in role. + * + * @param securityContext + * the security context + * @param roleName + * the role name + * @param securityDomain + * the security domain + * @return true, if is caller in role + */ + public boolean isCallerInRole(SecurityContext securityContext, String roleName, String securityDomain) { + Subject subject = securityContext.getSubject(securityDomain, false); + if (subject != null) { + for (Principal principal : subject.getPrincipals()) { + if (principal instanceof GroupPrincipal) { + if (principal.getName().equalsIgnoreCase(roleName)) { + return true; + } + } else if (principal instanceof org.switchyard.security.principal.GroupPrincipal) { + Enumeration e = ((org.switchyard.security.principal.GroupPrincipal) principal).members(); + while (e.hasMoreElements()) { + Principal p = e.nextElement(); + if (p.getName().equals(roleName)) { + return true; + } + } + } + } + } + return false; + } +} diff --git a/core/security/karaf/src/main/resources/META-INF/services/org.switchyard.security.credential.extractor.ServletRequestCredentialExtractor b/core/security/karaf/src/main/resources/META-INF/services/org.switchyard.security.credential.extractor.ServletRequestCredentialExtractor new file mode 100644 index 000000000..42e26aad4 --- /dev/null +++ b/core/security/karaf/src/main/resources/META-INF/services/org.switchyard.security.credential.extractor.ServletRequestCredentialExtractor @@ -0,0 +1,13 @@ +# Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +org.switchyard.security.karaf.credential.extractor.KarafServletRequestCredentialExtractor diff --git a/core/security/karaf/src/main/resources/META-INF/services/org.switchyard.security.provider.SecurityProvider b/core/security/karaf/src/main/resources/META-INF/services/org.switchyard.security.provider.SecurityProvider new file mode 100644 index 000000000..6b7faeae4 --- /dev/null +++ b/core/security/karaf/src/main/resources/META-INF/services/org.switchyard.security.provider.SecurityProvider @@ -0,0 +1,13 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +org.switchyard.security.karaf.provider.KarafSecurityProvider diff --git a/core/security/karaf/src/test/resources/log4j.properties b/core/security/karaf/src/test/resources/log4j.properties new file mode 100644 index 000000000..02a249c1d --- /dev/null +++ b/core/security/karaf/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootCategory=INFO, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=DEBUG +log4j.appender.CONSOLE.Target=System.out +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n diff --git a/core/serial/base/pom.xml b/core/serial/base/pom.xml new file mode 100644 index 000000000..fed02d151 --- /dev/null +++ b/core/serial/base/pom.xml @@ -0,0 +1,45 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-serial + bundle + SwitchYard: Serial + The base serialization library. + http://switchyard.org + + + org.switchyard.serial.* + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + + diff --git a/core/serial/base/src/main/java/org/switchyard/serial/BaseSerializer.java b/core/serial/base/src/main/java/org/switchyard/serial/BaseSerializer.java new file mode 100644 index 000000000..a3bcd653d --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/BaseSerializer.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.switchyard.common.io.Buffers; + +/** + * Base serializer implementation. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class BaseSerializer implements Serializer { + + private final FormatType _format; + private final CompressionType _compression; + + private int _bufferSize = Buffers.DEFAULT_SIZE; + private boolean _closeEnabled = false; + private boolean _prettyPrint = false; + + /** + * Constructor with a format. + * @param formatType the format. + */ + public BaseSerializer(FormatType formatType) { + this(formatType, null); + } + + /** + * Constructor with a format and compression. + * @param format the format + * @param compression the compression + */ + public BaseSerializer(FormatType format, CompressionType compression) { + _format = format; + _compression = compression; + } + + /** + * {@inheritDoc} + */ + @Override + public byte[] serialize(T obj, Class type) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(getBufferSize()); + int count = serialize(obj, type, out); + byte[] bytes = out.toByteArray(); + assert count == bytes.length; + return bytes; + } + + /** + * {@inheritDoc} + */ + @Override + public T deserialize(byte[] bytes, Class type) throws IOException { + return deserialize(new ByteArrayInputStream(bytes), type); + } + + /** + * {@inheritDoc} + */ + @Override + public FormatType getFormat() { + return _format; + } + + /** + * {@inheritDoc} + */ + @Override + public CompressionType getCompression() { + return _compression; + } + + /** + * {@inheritDoc} + */ + @Override + public int getBufferSize() { + return _bufferSize; + } + + /** + * {@inheritDoc} + */ + @Override + public Serializer setBufferSize(int bufferSize) { + _bufferSize = bufferSize; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isCloseEnabled() { + return _closeEnabled; + } + + /** + * {@inheritDoc} + */ + @Override + public Serializer setCloseEnabled(boolean closeEnabled) { + _closeEnabled = closeEnabled; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPrettyPrint() { + return _prettyPrint; + } + + /** + * {@inheritDoc} + */ + @Override + public Serializer setPrettyPrint(boolean prettyPrint) { + _prettyPrint = prettyPrint; + return this; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/CompressionType.java b/core/serial/base/src/main/java/org/switchyard/serial/CompressionType.java new file mode 100644 index 000000000..af4fedc8c --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/CompressionType.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial; + +/** + * Serialization compressions. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum CompressionType { + + /** GZIP. */ + GZIP, + /** ZIP. */ + ZIP; + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/FormatType.java b/core/serial/base/src/main/java/org/switchyard/serial/FormatType.java new file mode 100644 index 000000000..23edb6423 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/FormatType.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial; + +/** + * Serialization formats. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum FormatType { + + /** Protostuff graph. */ + GRAPH_PROTOSTUFF, + /** JSON. */ + JSON, + /** Numeric JSON. */ + JSON_NUMERIC, + /** Protostuff native. */ + NATIVE_PROTOSTUFF, + /** Google Protobuf. */ + PROTOBUF, + /** Serialized object. */ + SER_OBJECT, + /** Bean XML. */ + XML_BEAN, + /** Protostuff XML. */ + XML_PROTOSTUFF; + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/SerialLogger.java b/core/serial/base/src/main/java/org/switchyard/serial/SerialLogger.java new file mode 100644 index 000000000..671e667da --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/SerialLogger.java @@ -0,0 +1,33 @@ +package org.switchyard.serial; + +import static org.jboss.logging.Logger.Level.WARN; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 15000-15199 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface SerialLogger { + + /** + * Default root logger. + */ + SerialLogger ROOT_LOGGER = Logger.getMessageLogger(SerialLogger.class, SerialLogger.class.getPackage().getName()); + + /** + * classUnsupportedByFactory method definition. + * @param className className + * @param factoryClassName factoryClassName + */ + @LogMessage(level = WARN) + @Message(id = 15000, value = "Class [%s] unsupported by Factory [%s]; returning null") + void classUnsupportedByFactoryReturningNull(String className, String factoryClassName); + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/SerialMessages.java b/core/serial/base/src/main/java/org/switchyard/serial/SerialMessages.java new file mode 100644 index 000000000..61a035b14 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/SerialMessages.java @@ -0,0 +1,31 @@ +package org.switchyard.serial; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 15200-15399 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface SerialMessages { + + /** + * Default messages. + */ + SerialMessages MESSAGES = Messages.getBundle(SerialMessages.class); + + /** + * couldNotInstantiateThrowable method definition. + * @param className className + * @param cause cause + * @return SwitchYardException + */ + @Message(id=15200, value = "Could not instantiate Throwable class [%s] because [%s]") + SwitchYardException couldNotInstantiateThrowable(String className, String cause); + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/Serializer.java b/core/serial/base/src/main/java/org/switchyard/serial/Serializer.java new file mode 100644 index 000000000..0d4640539 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/Serializer.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * Serializes and deserializes objects. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface Serializer { + + /** + * Serializes an object of a type to a byte array. + * @param the type of object + * @param obj the object + * @param type the type + * @return the byte array + * @throws IOException something wicked this way comes + */ + public byte[] serialize(T obj, Class type) throws IOException; + + /** + * Serializes an object of a type to an output stream. + * @param the type of object + * @param obj the object + * @param type the type + * @param out the output stream + * @return how many bytes were written + * @throws IOException something wicked this way comes + */ + public int serialize(T obj, Class type, OutputStream out) throws IOException; + + /** + * Deserializes a byte array to an object of a type. + * @param the type of object + * @param bytes the byte array + * @param type the type + * @return the object + * @throws IOException something wicked this way comes + */ + public T deserialize(byte[] bytes, Class type) throws IOException; + + /** + * Deserializes an input stream to an object of a type. + * @param the type of object + * @param in the input stream + * @param type the type + * @return the object + * @throws IOException something wicked this way comes + */ + public T deserialize(InputStream in, Class type) throws IOException; + + /** + * Gets the type of format being used. + * @return the format + */ + public FormatType getFormat(); + + /** + * Gets the type of compression being used. + * @return the compression + */ + public CompressionType getCompression(); + + /** + * Gets the buffer size being used. + * @return the buffer size + */ + public int getBufferSize(); + + /** + * Sets the buffer size being used. + * @param bufferSize the buffer size + * @return this instance (useful for chaining) + */ + public Serializer setBufferSize(int bufferSize); + + /** + * Gets if streams will be closed. + * @return if streams will be closed + */ + public boolean isCloseEnabled(); + + /** + * Sets if streams will be closed. + * @param closeEnabled if streams will be closed + * @return this instance (useful for chaining) + */ + public Serializer setCloseEnabled(boolean closeEnabled); + + /** + * Gets if pretty-print should be attempted by supported formats. + * @return if pretty-print should be attempted by supported formats + */ + public boolean isPrettyPrint(); + + /** + * Sets if pretty-print should be attempted by supported formats. + * @param prettyPrint if pretty-print should be attempted by supported formats + * @return this instance (useful for chaining) + */ + public Serializer setPrettyPrint(boolean prettyPrint); + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/SerializerFactory.java b/core/serial/base/src/main/java/org/switchyard/serial/SerializerFactory.java new file mode 100644 index 000000000..2c5301499 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/SerializerFactory.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial; + +import org.switchyard.serial.compress.GZIPSerializer; +import org.switchyard.serial.compress.ZIPSerializer; +import org.switchyard.serial.graph.GraphSerializer; +import org.switchyard.serial.spi.SerializationProvider; + +/** + * Creates serializers. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class SerializerFactory { + + /** + * Creates a serializer of the default format ({@link FormatType.SER_OBJECT}) and no compression. + * @return the serializer + */ + public static final Serializer create() { + return create(FormatType.SER_OBJECT); + } + + /** + * Creates a serializer of the specified format and no compression. + * @param format the specified format + * @return the serializer + */ + public static final Serializer create(FormatType format) { + return create(format, null); + } + + /** + * Creates a serializer of the specified format and compression. + * @param format the format + * @param compression the compression + * @return the serializer + */ + public static final Serializer create(FormatType format, CompressionType compression) { + return create(format, compression, false); + } + + /** + * Creates a serializer of the specified format, compression, and graph enabling. + * @param format the format + * @param compression the compression + * @param graph if graphing should be enabled + * @return the serializer + */ + public static final Serializer create(FormatType format, CompressionType compression, boolean graph) { + Serializer serializer = null; + SerializationProvider provider = SerializationProvider.getPrimaryProvider(format); + if (provider != null) { + serializer = provider.newSerializer(format); + if (graph) { + serializer = new GraphSerializer(serializer); + } + if (compression != null) { + if (CompressionType.GZIP.equals(compression)) { + serializer = new GZIPSerializer(serializer); + } else if (CompressionType.ZIP.equals(compression)) { + serializer = new ZIPSerializer(serializer); + } + } + } + return serializer; + } + + private SerializerFactory() {} + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/WrapperSerializer.java b/core/serial/base/src/main/java/org/switchyard/serial/WrapperSerializer.java new file mode 100644 index 000000000..a33176a57 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/WrapperSerializer.java @@ -0,0 +1,106 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * A serializer that wraps another serializer. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class WrapperSerializer extends BaseSerializer { + + private final Serializer _wrapped; + + /** + * Constructor with a serializer to wrap. + * @param serializer the serializer to wrap + */ + public WrapperSerializer(Serializer serializer) { + super(serializer.getFormat(), serializer.getCompression()); + _wrapped = serializer; + } + + /** + * Constructor with a serializer and compression. + * @param serializer the serializer + * @param compression the compression + */ + public WrapperSerializer(Serializer serializer, CompressionType compression) { + super(serializer.getFormat(), compression); + _wrapped = serializer; + } + + /** + * Gets the wrapped serializer. + * @return the wrapped serializer + */ + public Serializer getWrapped() { + return _wrapped; + } + + /** + * {@inheritDoc} + */ + @Override + public int serialize(T obj, Class type, OutputStream out) throws IOException { + return getWrapped().serialize(obj, type, out); + } + + /** + * {@inheritDoc} + */ + @Override + public T deserialize(InputStream in, Class type) throws IOException { + return getWrapped().deserialize(in, type); + } + + /** + * {@inheritDoc} + */ + @Override + public int getBufferSize() { + return getWrapped().getBufferSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public Serializer setBufferSize(int bufferSize) { + getWrapped().setBufferSize(bufferSize); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPrettyPrint() { + return getWrapped().isPrettyPrint(); + } + + /** + * {@inheritDoc} + */ + @Override + public Serializer setPrettyPrint(boolean prettyPrint) { + getWrapped().setPrettyPrint(prettyPrint); + return this; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/compress/GZIPSerializer.java b/core/serial/base/src/main/java/org/switchyard/serial/compress/GZIPSerializer.java new file mode 100644 index 000000000..247e20f40 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/compress/GZIPSerializer.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.compress; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +import org.switchyard.common.io.CountingOutputStream; +import org.switchyard.serial.CompressionType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.WrapperSerializer; + +/** + * A wrapper serializer that performs GZIP compression/decompression. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class GZIPSerializer extends WrapperSerializer { + + /** + * Constructor with a serializer to wrap. + * @param serializer the serializer to wrap + */ + public GZIPSerializer(Serializer serializer) { + super(serializer, CompressionType.GZIP); + } + + /** + * {@inheritDoc} + */ + @Override + public int serialize(T obj, Class type, OutputStream out) throws IOException { + out = new CountingOutputStream(out); + GZIPOutputStream gzip = new GZIPOutputStream(out, getBufferSize()); + try { + getWrapped().serialize(obj, type, gzip); + gzip.finish(); + gzip.flush(); + } finally { + if (isCloseEnabled()) { + gzip.close(); + } + } + return ((CountingOutputStream)out).getCount(); + } + + /** + * {@inheritDoc} + */ + @Override + public T deserialize(InputStream in, Class type) throws IOException { + in = new GZIPInputStream(in, getBufferSize()); + try { + return getWrapped().deserialize(in, type); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/compress/ZIPSerializer.java b/core/serial/base/src/main/java/org/switchyard/serial/compress/ZIPSerializer.java new file mode 100644 index 000000000..9c268c979 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/compress/ZIPSerializer.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.compress; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +import org.switchyard.common.io.CountingOutputStream; +import org.switchyard.serial.CompressionType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.WrapperSerializer; + +/** + * A wrapper serializer that performs ZIP compression/decompression. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class ZIPSerializer extends WrapperSerializer { + + /** + * Constructor with a serializer to wrap. + * @param serializer the serializer to wrap + */ + public ZIPSerializer(Serializer serializer) { + super(serializer, CompressionType.ZIP); + } + + /** + * {@inheritDoc} + */ + @Override + public int serialize(T obj, Class type, OutputStream out) throws IOException { + out = new CountingOutputStream(out); + ZipOutputStream zip = new ZipOutputStream(out); + try { + zip.putNextEntry(new ZipEntry("z")); + getWrapped().serialize(obj, type, zip); + zip.closeEntry(); + zip.finish(); + zip.flush(); + } finally { + if (isCloseEnabled()) { + zip.close(); + } + } + return ((CountingOutputStream)out).getCount(); + } + + /** + * {@inheritDoc} + */ + @Override + public T deserialize(InputStream in, Class type) throws IOException { + ZipInputStream zip = new ZipInputStream(in); + try { + zip.getNextEntry(); + return getWrapped().deserialize(zip, type); + } finally { + if (isCloseEnabled()) { + zip.close(); + } + } + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/format/SERObjectSerializer.java b/core/serial/base/src/main/java/org/switchyard/serial/format/SERObjectSerializer.java new file mode 100644 index 000000000..48bfbd206 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/format/SERObjectSerializer.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.format; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; + +import org.switchyard.common.io.CountingOutputStream; +import org.switchyard.serial.BaseSerializer; +import org.switchyard.serial.FormatType; + +/** + * A JDK serializer that performs {@link FormatType.SER_OBJECT} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class SERObjectSerializer extends BaseSerializer { + + /** + * Default constructor. + */ + public SERObjectSerializer() { + super(FormatType.SER_OBJECT); + } + + /** + * {@inheritDoc} + */ + @Override + public int serialize(T obj, Class type, OutputStream out) throws IOException { + out = new CountingOutputStream(new BufferedOutputStream(out, getBufferSize())); + try { + @SuppressWarnings("resource") + ObjectOutputStream oos = new ObjectOutputStream(out); + oos.writeObject(obj); + oos.flush(); + } finally { + if (isCloseEnabled()) { + out.close(); + } + } + return ((CountingOutputStream)out).getCount(); + } + + /** + * {@inheritDoc} + */ + @Override + public T deserialize(InputStream in, Class type) throws IOException { + in = new BufferedInputStream(in, getBufferSize()); + try { + ObjectInputStream ois = new ObjectInputStream(in); + Object obj = ois.readObject(); + return type.cast(obj); + } catch (ClassNotFoundException cnfe) { + throw new IOException(cnfe); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/format/XMLBeanSerializer.java b/core/serial/base/src/main/java/org/switchyard/serial/format/XMLBeanSerializer.java new file mode 100644 index 000000000..f4b56dde4 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/format/XMLBeanSerializer.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.format; + +import java.beans.ExceptionListener; +import java.beans.XMLDecoder; +import java.beans.XMLEncoder; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.switchyard.common.io.CountingOutputStream; +import org.switchyard.common.type.Classes; +import org.switchyard.serial.BaseSerializer; +import org.switchyard.serial.FormatType; + +/** + * A JDK serializer that performs {@link FormatType.XML_BEAN} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class XMLBeanSerializer extends BaseSerializer { + + /** + * Default constructor. + */ + public XMLBeanSerializer() { + super(FormatType.XML_BEAN); + } + + /** + * {@inheritDoc} + */ + @Override + public int serialize(T obj, Class type, OutputStream out) throws IOException { + out = new CountingOutputStream(new BufferedOutputStream(out, getBufferSize())); + EL el = new EL(); + XMLEncoder enc = new XMLEncoder(out); + try { + enc.setExceptionListener(el); + enc.writeObject(obj); + enc.flush(); + } finally { + if (isCloseEnabled()) { + enc.close(); + } + } + IOException ioe = el.getIOException(); + if (ioe != null) { + throw ioe; + } + return ((CountingOutputStream)out).getCount(); + } + + /** + * {@inheritDoc} + */ + @Override + public T deserialize(InputStream in, Class type) throws IOException { + in = new BufferedInputStream(in, getBufferSize()); + EL el = new EL(); + XMLDecoder dec = new XMLDecoder(in, null, el, Classes.getTCCL()); + Object obj; + try { + obj = dec.readObject(); + } finally { + if (isCloseEnabled()) { + dec.close(); + } + } + IOException ioe = el.getIOException(); + if (ioe != null) { + throw ioe; + } + return type.cast(obj); + } + + private static final class EL implements ExceptionListener { + + private Exception _e; + + /** + * {@inheritDoc} + */ + @Override + public void exceptionThrown(Exception e) { + if (_e != null) { + _e = e; + } + } + + /** + * Gets any problem that occurred as an IOException. + * @return the problem + */ + public IOException getIOException() { + if (_e != null) { + if (_e instanceof IOException) { + return (IOException)_e; + } + return new IOException(_e); + } + return null; + } + + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/AccessType.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/AccessType.java new file mode 100644 index 000000000..aa8fcee7e --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/AccessType.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +/** + * The type of access the AccessNode will use. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum AccessType { + + /** Access using bean properties. */ + BEAN, + /** Access using field members. */ + FIELD; + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/BaseFactory.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/BaseFactory.java new file mode 100644 index 000000000..691686e18 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/BaseFactory.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +/** + * A base Factory implementation. + * + * @param the factory type + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public abstract class BaseFactory extends Factory { + + /** + * {@inheritDoc} + */ + @Override + public boolean supports(Class type) { + return type != null; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/CoverageType.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/CoverageType.java new file mode 100644 index 000000000..5523f5b8a --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/CoverageType.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +/** + * The type of coverage the AccessNode will use. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public enum CoverageType { + + /** Include all fields or properties. */ + INCLUSIVE, + /** Exclude all fields or properties. */ + EXCLUSIVE; + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/DefaultFactory.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/DefaultFactory.java new file mode 100644 index 000000000..8508ab52a --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/DefaultFactory.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.serial.graph.node.Node; + +/** + * The default factory the AccessNode will use. + * + * @param the factory type + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class DefaultFactory extends BaseFactory { + + /** + * {@inheritDoc} + */ + @Override + public boolean supports(Class type) { + if (type != null) { + try { + if (type.getDeclaredConstructor() != null) { + return true; + } + } catch (NoSuchMethodException nsme) { + // keep checkstyle happy (at least one statement) + nsme.getMessage(); + } + try { + if (type.getConstructor() != null) { + return true; + } + } catch (NoSuchMethodException nsme) { + // keep checkstyle happy (at least one statement) + nsme.getMessage(); + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public T create(Class type, Node node) { + if (type != null) { + return Construction.construct(type); + } + return null; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/Exclude.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/Exclude.java new file mode 100644 index 000000000..088b09c23 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/Exclude.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Used to override individual field or property coverage when the type is inclusive. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target({FIELD,METHOD}) +@Retention(RUNTIME) +@Documented +public @interface Exclude {} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/Factory.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/Factory.java new file mode 100644 index 000000000..4683ae917 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/Factory.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.serial.graph.node.Node; + +/** + * The factory the AccessNode will use. + * + * @param the factory type + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class Factory { + + /** + * Whether this factory supports the specified type. + * @param type the type + * @return if the type is supported + */ + public abstract boolean supports(Class type); + + /** + * Creates a new object of the specified type. + * @param type the type + * @param node the graph node for implementations that need extra information + * @return the object + */ + public abstract T create(Class type, Node node); + + /** + * Gets the factory for the specified type. + * @param the factory type + * @param type the type + * @return the factory + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static final Factory getFactory(Class type) { + Strategy strategy = type.getAnnotation(Strategy.class); + if (strategy != null) { + Class factoryClass = strategy.factory(); + if (!UndefinedFactory.class.equals(factoryClass)) { + return Construction.construct(factoryClass); + } + } + if (Throwable.class.isAssignableFrom(type)) { + return new ThrowableFactory(); + } + return new DefaultFactory(); + } + + /** + * Used as the default value for the {@link Strategy#factory()} annotation attribute. + * @param the factory type + */ + static final class UndefinedFactory extends Factory { + /** + * {@inheritDoc} + */ + @Override + public boolean supports(Class type) { + return false; + } + /** + * {@inheritDoc} + */ + @Override + public T create(Class type, Node node) { + return null; + } + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/Graph.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/Graph.java new file mode 100644 index 000000000..e9eb98e3e --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/Graph.java @@ -0,0 +1,204 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +import java.io.Serializable; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import org.switchyard.serial.graph.node.Node; +import org.switchyard.serial.graph.node.NodeBuilder; + +/** + * A graph holds references to all nodes. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class Graph implements Serializable { + + private static final long serialVersionUID = 1L; + + private Integer _root; + private Map _references = new LinkedHashMap(); + private transient Map _ids; + private transient AtomicInteger _sequence; + private transient Queue _resolutions; + + /** + * Default constructor. + */ + public Graph() {} + + /** + * Constructor which composes the specified root object. + * @param obj the specified root object + */ + public Graph(Object obj) { + composeRoot(obj); + } + + /** + * Gets the root node id. + * @return the root node id + */ + public Integer getRoot() { + return _root; + } + + /** + * Sets the root node id. + * @param root the root node id + */ + public void setRoot(Integer root) { + _root = root; + } + + /** + * Gets the node references. + * @return the node references + */ + public Map getReferences() { + return _references; + } + + /** + * Sets the node references. + * @param references the node references + */ + public void setReferences(Map references) { + _references = references; + } + + /** + * Gets a reference with the specified id. + * @param id the specified id + * @return the reference + */ + public Object getReference(Integer id) { + return _references.get(id); + } + + /** + * Gets a reference id with the specified object. + * @param obj the specified object + * @return the reference id + */ + public Integer getReferenceId(Object obj) { + if (obj != null) { + for (Map.Entry entry : _references.entrySet()) { + if (entry.getValue() == obj) { + return entry.getKey(); + } + } + } + return null; + } + + /** + * Puts a reference with the specified id. + * @param id the specified id + * @param obj the reference + */ + public void putReference(Integer id, Object obj) { + _references.put(id, obj); + } + + private Queue getResolutions() { + if (_resolutions == null) { + _resolutions = new ConcurrentLinkedQueue(); + } + return _resolutions; + } + + /** + * Adds a runnable reference resolution. + * @param res the runnable reference resolution + */ + public void addResolution(Runnable res) { + getResolutions().offer(res); + } + + /** + * Composes the root object. + * @param obj the root object + */ + public void composeRoot(Object obj) { + setRoot(NodeBuilder.build(obj, this)); + } + + /** + * Decomposes the root object. + * @return the root object + */ + public Object decomposeRoot() { + Object obj = decomposeReference(getRoot()); + Runnable res = getResolutions().poll(); + while (res != null) { + res.run(); + res = getResolutions().poll(); + } + return obj; + } + + /** + * Decomposes a reference with the specified id. + * @param id the specified id + * @return the decomposed reference + */ + public Object decomposeReference(Integer id) { + Object obj = getReference(id); + if (obj instanceof Node) { + obj = ((Node)obj).decompose(this); + putReference(id, obj); + } + return obj; + } + + private Map getIds() { + if (_ids == null) { + _ids = new IdentityHashMap(); + } + return _ids; + } + + private Integer nextId() { + if (_sequence == null) { + _sequence = new AtomicInteger(0); + } + return _sequence.incrementAndGet(); + } + + /** + * Creates an id for the specified object. + * @param obj the specified object + * @return the id, or 0 if obj is null + */ + public Integer id(Object obj) { + if (obj == null) { + return 0; + } + Map ids = getIds(); + Integer id = ids.get(obj); + if (id == null) { + id = nextId(); + ids.put(obj, id); + } + return id; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/GraphSerializer.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/GraphSerializer.java new file mode 100644 index 000000000..ebbb4c313 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/GraphSerializer.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.switchyard.serial.Serializer; +import org.switchyard.serial.WrapperSerializer; + +/** + * A wrapper serializer that walks/handles object graphs before/after serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class GraphSerializer extends WrapperSerializer { + + /** + * Constructor with a serializer to wrap. + * @param serializer the serializer to wrap + */ + public GraphSerializer(Serializer serializer) { + super(serializer); + } + + /** + * {@inheritDoc} + */ + @Override + public int serialize(T obj, Class type, OutputStream out) throws IOException { + Graph graph = new Graph(obj); + try { + return getWrapped().serialize(graph, Graph.class, out); + } finally { + if (isCloseEnabled()) { + out.close(); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("unchecked") + public T deserialize(InputStream in, Class type) throws IOException { + try { + Graph graph = getWrapped().deserialize(in, Graph.class); + return (T)graph.decomposeRoot(); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/Include.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/Include.java new file mode 100644 index 000000000..40fa6369f --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/Include.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * Used to override individual field or property coverage when the type is exclusive. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target({FIELD,METHOD}) +@Retention(RUNTIME) +@Documented +public @interface Include {} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/Strategy.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/Strategy.java new file mode 100644 index 000000000..4edc2788c --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/Strategy.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +/** + * The strategy the AccessNode will use. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Target(TYPE) +@Retention(RUNTIME) +@Documented +public @interface Strategy { + + /** The type of access. */ + AccessType access() default AccessType.BEAN; + + /** The type of coverage. */ + CoverageType coverage() default CoverageType.INCLUSIVE; + + /** The factory to create new objects. */ + @SuppressWarnings("rawtypes") + Class factory() default Factory.UndefinedFactory.class; + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/ThrowableFactory.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/ThrowableFactory.java new file mode 100644 index 000000000..f2a74a30d --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/ThrowableFactory.java @@ -0,0 +1,91 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph; + +import java.lang.reflect.Constructor; +import java.lang.reflect.UndeclaredThrowableException; + +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.serial.SerialMessages; +import org.switchyard.serial.graph.node.Node; +import org.switchyard.serial.graph.node.ThrowableAccessNode; + +/** + * The default factory the AccessNode will use. + * + * @param the factory type + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class ThrowableFactory extends BaseFactory { + + private static final Class[][] PARAMETER_TYPES = new Class[][]{ + new Class[]{String.class}, + new Class[0] + }; + + /** + * {@inheritDoc} + */ + @Override + public boolean supports(Class type) { + if (type != null) { + return UndeclaredThrowableException.class.equals(type) || getConstructor(type) != null; + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public T create(Class type, Node node) { + T obj = null; + if (type != null) { + final String message = (node instanceof ThrowableAccessNode) ? ((ThrowableAccessNode)node).getMessage() : null; + if (UndeclaredThrowableException.class.equals(type)) { + return type.cast(new UndeclaredThrowableException(null, message)); + } + Constructor constructor = getConstructor(type); + Class[] parameterTypes = constructor != null ? constructor.getParameterTypes() : new Class[0]; + try { + if (parameterTypes.length == 0) { + obj = Construction.construct(type); + } else if (parameterTypes.length == 1) { + obj = Construction.construct(type, parameterTypes, new Object[]{message}); + } + } catch (Throwable t) { + throw SerialMessages.MESSAGES.couldNotInstantiateThrowable(type.getName(), t.getMessage()); + } + } + return obj; + } + + private Constructor getConstructor(Class type) { + Constructor constructor = null; + for (Class[] parameterTypes : PARAMETER_TYPES) { + try { + constructor = type.getConstructor(parameterTypes); + if (constructor != null) { + break; + } + } catch (Throwable t) { + // keep checkstyle happy ("at least one statement") + t.getMessage(); + } + } + return constructor; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/AccessNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/AccessNode.java new file mode 100644 index 000000000..e1134996f --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/AccessNode.java @@ -0,0 +1,255 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.switchyard.common.type.reflect.Access; +import org.switchyard.common.type.reflect.BeanAccess; +import org.switchyard.common.type.reflect.FieldAccess; +import org.switchyard.common.type.reflect.MethodAccess; +import org.switchyard.serial.SerialLogger; +import org.switchyard.serial.graph.AccessType; +import org.switchyard.serial.graph.CoverageType; +import org.switchyard.serial.graph.Exclude; +import org.switchyard.serial.graph.Factory; +import org.switchyard.serial.graph.Graph; +import org.switchyard.serial.graph.Include; +import org.switchyard.serial.graph.Strategy; + +/** + * Reflection-based node for arbitrary objects. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +@SuppressWarnings("serial") +public abstract class AccessNode implements Node { + + static final Set IGNORED_ACCESS_NAMES; + static { + Set ignoredAccessNames = new HashSet(); + ignoredAccessNames.add("class"); + ignoredAccessNames.add("ignoredAccessNames"); + IGNORED_ACCESS_NAMES = Collections.unmodifiableSet(ignoredAccessNames); + } + + /** + * Gets the set of ignored access names. + * @return the set of ignored access names. + */ + Set getIgnoredAccessNames() { + return IGNORED_ACCESS_NAMES; + } + + /** + * Gets the class. + * @return the class. + */ + public abstract Integer getClazz(); + + /** + * Sets the class. + * @param clazz the class + */ + public abstract void setClazz(Integer clazz); + + /** + * Gets the ids. + * @return the ids + */ + public abstract Map getIds(); + + /** + * Sets the ids. + * @param ids the ids + */ + public abstract void setIds(Map ids); + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + if (obj != null) { + Class clazz = obj.getClass(); + setClazz(NodeBuilder.build(clazz, graph)); + for (Access access : getAccessList(clazz)) { + if (!(access instanceof FieldAccess) && !access.isWriteable()) { + continue; + } + Object value = access.read(obj); + if (value != null) { + Map ids = getIds(); + if (ids == null) { + ids = new LinkedHashMap(); + setIds(ids); + } + Integer id = NodeBuilder.build(value, graph); + if (id != null) { + ids.put(access.getName(), id); + } + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Object decompose(final Graph graph) { + if (getClazz() == null) { + return null; + } + final Class clazz = (Class)graph.decomposeReference(getClazz()); + final Factory factory = Factory.getFactory(clazz); + final Object obj; + if (factory.supports(clazz)) { + obj = factory.create(clazz, this); + } else { + final String className = clazz != null ? clazz.getName() : "null"; + SerialLogger.ROOT_LOGGER.classUnsupportedByFactoryReturningNull(className, factory.getClass().getName()); + obj = null; + } + Map ids = getIds(); + if (obj != null && ids != null) { + for (final Access access : getAccessList(clazz)) { + final Integer id = ids.get(access.getName()); + if (id != null) { + graph.addResolution(new Runnable() { + public void run() { + Object value = graph.decomposeReference(id); + if (value != null) { + boolean skip = !access.isWriteable(); + Class accessType = access.getType(); + if (access instanceof FieldAccess) { + if (NodeBuilder.isCollection(accessType) && value instanceof Collection) { + ((Collection)access.read(obj)).addAll((Collection)value); + skip = true; + } else if (NodeBuilder.isMap(accessType) && value instanceof Map) { + ((Map)access.read(obj)).putAll((Map)value); + skip = true; + } + } + if (!skip) { + if (NodeBuilder.isArray(accessType) && value.getClass().isArray()) { + Object[] old_array = (Object[])value; + Object[] new_array = (Object[])Array.newInstance(accessType.getComponentType(), old_array.length); + System.arraycopy(old_array, 0, new_array, 0, old_array.length); + value = new_array; + } + access.write(obj, value); + } + } + } + }); + } + } + } + return obj; + } + + @SuppressWarnings("rawtypes") + private List getAccessList(Class clazz) { + List accessList = new ArrayList(); + if (clazz.getAnnotation(Deprecated.class) != null) { + return accessList; + } + Strategy strategy = clazz.getAnnotation(Strategy.class); + AccessType accessType = strategy != null ? strategy.access() : AccessType.BEAN; + CoverageType coverageType = strategy != null ? strategy.coverage() : CoverageType.INCLUSIVE; + switch (accessType) { + case BEAN: + BeanInfo info; + try { + info = Introspector.getBeanInfo(clazz); + } catch (IntrospectionException ie) { + throw new RuntimeException(ie); + } + for (PropertyDescriptor desc : info.getPropertyDescriptors()) { + Method readMethod = desc.getReadMethod(); + if (((CoverageType.INCLUSIVE.equals(coverageType) + && readMethod.getAnnotation(Exclude.class) == null) + || (CoverageType.EXCLUSIVE.equals(coverageType) + && readMethod.getAnnotation(Include.class) != null)) + && readMethod.getAnnotation(Deprecated.class) == null) { + Access access = null; + Method writeMethod = desc.getWriteMethod(); + if (writeMethod == null) { + String readName = readMethod.getName(); + if (readName.startsWith("get") || readName.startsWith("is")) { + String writeName = "set" + (readName.startsWith("get") ? readName.substring(3) : readName.substring(2)); + Class declaringClass = readMethod.getDeclaringClass(); + try { + writeMethod = declaringClass.getDeclaredMethod(writeName, desc.getPropertyType()); + } catch (NoSuchMethodException nsme1) { + try { + writeMethod = declaringClass.getMethod(writeName, desc.getPropertyType()); + } catch (NoSuchMethodException nsme2) { + writeMethod = null; + } + } + if (writeMethod != null) { + Class returnClass = writeMethod.getReturnType(); + if (returnClass == null || returnClass.isAssignableFrom(declaringClass)) { + access = new MethodAccess(readMethod, writeMethod); + } + } + } + } + if (access == null) { + access = new BeanAccess(desc); + } + if (access.isReadable() && !getIgnoredAccessNames().contains(access.getName())) { + accessList.add(access); + } + } + } + break; + case FIELD: + for (Field field : clazz.getDeclaredFields()) { + if (((CoverageType.INCLUSIVE.equals(coverageType) + && field.getAnnotation(Exclude.class) == null) + || (CoverageType.EXCLUSIVE.equals(coverageType) + && field.getAnnotation(Include.class) != null)) + && field.getAnnotation(Deprecated.class) == null + && !Modifier.isTransient(field.getModifiers())) { + Access access = new FieldAccess(field); + if (access.isReadable()) { + accessList.add(access); + } + } + } + break; + } + return accessList; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ArrayNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ArrayNode.java new file mode 100644 index 000000000..d88c828e4 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ArrayNode.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.util.ArrayList; +import java.util.List; + +import org.switchyard.serial.graph.Graph; + +/** + * A node representing an array. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public class ArrayNode implements Node { + + private Integer[] _ids; + + /** + * Default constructor. + */ + public ArrayNode() {} + + /** + * Gets the ids. + * @return the ids + */ + public Integer[] getIds() { + return _ids; + } + + /** + * Sets the ids. + * @param ids the ids + */ + public void setIds(Integer[] ids) { + _ids = ids; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + Object[] array = (Object[])obj; + List ids = new ArrayList(); + for (int i=0; i < array.length; i++) { + Integer id = NodeBuilder.build(array[i], graph); + if (!(graph.getReference(id) instanceof NoopNode)) { + ids.add(id); + } + } + _ids = ids.toArray(new Integer[ids.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + Object[] array = new Object[_ids.length]; + for (int i=0; i < _ids.length; i++) { + array[i] = graph.decomposeReference(_ids[i]); + } + return array; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ClassNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ClassNode.java new file mode 100644 index 000000000..be46de01a --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ClassNode.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import org.switchyard.common.type.Classes; +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a Class. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class ClassNode implements Node { + + private String _name; + + /** + * Default constructor. + */ + public ClassNode() {} + + /** + * Gets the name. + * @return the name + */ + public String getName() { + return _name; + } + + /** + * Sets the name. + * @param name the name + */ + public void setName(String name) { + _name = name; + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("rawtypes") + public void compose(Object obj, Graph graph) { + Class clazz = (Class)obj; + setName(clazz.getName()); + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + return Classes.forName(getName(), getClass()); + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/CollectionNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/CollectionNode.java new file mode 100644 index 000000000..f680155d0 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/CollectionNode.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.util.Collection; +import java.util.LinkedList; + +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a Collection. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class CollectionNode implements Node { + + private LinkedList _ids; + + /** + * Default constructor. + */ + public CollectionNode() {} + + /** + * Gets the ids. + * @return the ids + */ + public LinkedList getIds() { + return _ids; + } + + /** + * Sets the ids. + * @param ids the ids + */ + public void setIds(LinkedList ids) { + _ids = ids; + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("rawtypes") + public void compose(Object obj, Graph graph) { + _ids = new LinkedList(); + Collection coll = (Collection)obj; + for (Object o : coll) { + Integer id = NodeBuilder.build(o, graph); + if (!(graph.getReference(id) instanceof NoopNode)) { + _ids.add(NodeBuilder.build(o, graph)); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Object decompose(Graph graph) { + if (_ids != null) { + Collection coll = new LinkedList(); + for (Integer id : _ids) { + coll.add(graph.decomposeReference(id)); + } + return coll; + } + return null; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DOMNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DOMNode.java new file mode 100644 index 000000000..89ffef2e6 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DOMNode.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.io.IOException; +import java.io.StringReader; + +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a DOM. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class DOMNode implements Node { + + private String _xml; + + /** + * Default constructor. + */ + public DOMNode() {} + + /** + * Gets the xml. + * @return the xml + */ + public String getXml() { + return _xml; + } + + /** + * Sets the xml. + * @param xml the xml + */ + public void setXml(String xml) { + _xml = xml; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + org.w3c.dom.Node node = (org.w3c.dom.Node)obj; + setXml(XMLHelper.toString(node)); + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + try { + return new ElementPuller(false).pull(new StringReader(_xml)); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DataSourceNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DataSourceNode.java new file mode 100644 index 000000000..ea206910c --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DataSourceNode.java @@ -0,0 +1,143 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.activation.DataSource; + +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a DataSource. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class DataSourceNode implements Node { + + private String _name; + private String _contentType; + private Integer _inputStreamId; + + /** + * Default constructor. + */ + public DataSourceNode() {} + + /** + * Gets the name. + * @return the name + */ + public String getName() { + return _name; + } + + /** + * Sets the name. + * @param name the name + */ + public void setName(String name) { + _name = name; + } + + /** + * Gets the content type. + * @return the content type + */ + public String getContentType() { + return _contentType; + } + + /** + * Sets the content type. + * @param contentType the content type + */ + public void setContentType(String contentType) { + _contentType = contentType; + } + + /** + * Gets the input stream node id. + * @return the input stream node id + */ + public Integer getInputStreamId() { + return _inputStreamId; + } + + /** + * Sets the input stream node id. + * @param inputStreamId the input stream node id + */ + public void setInputStreamId(Integer inputStreamId) { + _inputStreamId = inputStreamId; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + DataSource ds = (DataSource)obj; + setName(ds.getName()); + setContentType(ds.getContentType()); + try { + setInputStreamId(NodeBuilder.build(ds.getInputStream(), graph)); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + InputStream is = (InputStream)graph.decomposeReference(getInputStreamId()); + return new NodeDataSource(getName(), getContentType(), is); + } + + private static final class NodeDataSource implements DataSource { + + private String _name; + private String _contentType; + private InputStream _inputStream; + + public NodeDataSource(String name, String contentType, InputStream inputStream) { + _name = name; + _contentType = contentType; + _inputStream = inputStream; + } + + public String getName() { + return _name; + } + + public String getContentType() { + return _contentType; + } + + public InputStream getInputStream() throws IOException { + return _inputStream; + } + + public OutputStream getOutputStream() throws IOException { + throw new UnsupportedOperationException(); + } + + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DefaultAccessNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DefaultAccessNode.java new file mode 100644 index 000000000..89ba5b481 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/DefaultAccessNode.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.util.Map; + +/** + * Reflection-based node for arbitrary objects. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class DefaultAccessNode extends AccessNode { + + private Integer _clazz; + private Map _ids; + + /** + * Default constructor. + */ + public DefaultAccessNode() {} + + /** + * {@inheritDoc} + */ + @Override + public Integer getClazz() { + return _clazz; + } + + /** + * {@inheritDoc} + */ + @Override + public void setClazz(Integer clazz) { + _clazz = clazz; + } + + /** + * {@inheritDoc} + */ + @Override + public Map getIds() { + return _ids; + } + + /** + * {@inheritDoc} + */ + @Override + public void setIds(Map ids) { + _ids = ids; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/InputStreamNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/InputStreamNode.java new file mode 100644 index 000000000..805724d44 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/InputStreamNode.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.switchyard.common.codec.Base64; +import org.switchyard.common.io.Buffers; +import org.switchyard.serial.graph.Graph; + +/** + * A node representing an InputStream. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class InputStreamNode implements Node { + + private String _base64; + + /** + * Default constructor. + */ + public InputStreamNode() {} + + /** + * Gets the Base64 representation. + * @return the Base64 representation + */ + public String getBase64() { + return _base64; + } + + /** + * Sets the Base64 representation. + * @param base64 the Base64 representation + */ + public void setBase64(String base64) { + _base64 = base64; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + int bs = Buffers.DEFAULT_SIZE; + BufferedInputStream bis = new BufferedInputStream((InputStream)obj, bs); + ByteArrayOutputStream baos = new ByteArrayOutputStream(bs); + BufferedOutputStream bos = new BufferedOutputStream(baos, bs); + byte[] buff = new byte[bs]; + int read = 0; + try { + while ((read = bis.read(buff)) != -1) { + bos.write(buff, 0, read); + } + bos.flush(); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } finally { + try { + bis.close(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + setBase64(Base64.encode(baos.toByteArray())); + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + return new ByteArrayInputStream(Base64.decode(getBase64())); + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/MapNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/MapNode.java new file mode 100644 index 000000000..62fdc4d6a --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/MapNode.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a Map. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class MapNode implements Node { + + private LinkedHashMap _ids; + + /** + * Default constructor. + */ + public MapNode() {} + + /** + * Gets the ids. + * @return the ids + */ + public LinkedHashMap getIds() { + return _ids; + } + + /** + * Sets the ids. + * @param ids the ids + */ + public void setIds(LinkedHashMap ids) { + _ids = ids; + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings("rawtypes") + public void compose(Object obj, Graph graph) { + _ids = new LinkedHashMap(); + Map map = (Map)obj; + + Iterator it = map.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry pairs = (Map.Entry)it.next(); + Object key = pairs.getKey(); + Integer key_id = NodeBuilder.build(key, graph); + if (!(graph.getReference(key_id) instanceof NoopNode)) { + Object val = pairs.getValue(); + Integer val_id = NodeBuilder.build(val, graph); + if (!(graph.getReference(val_id) instanceof NoopNode)) { + _ids.put(key_id, val_id); + } + } + } + } + + /** + * {@inheritDoc} + */ + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Object decompose(Graph graph) { + Map map = new LinkedHashMap(); + for (Integer key : _ids.keySet()) { + Integer val = _ids.get(key); + map.put(graph.decomposeReference(key), graph.decomposeReference(val)); + } + return map; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/Node.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/Node.java new file mode 100644 index 000000000..1d5136a59 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/Node.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.io.Serializable; + +import org.switchyard.serial.graph.Graph; + +/** + * Represents a node in a graph. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public interface Node extends Serializable { + + /** + * Composes the specified object into the graph. + * @param obj the specified object + * @param graph the graph + */ + public void compose(Object obj, Graph graph); + + /** + * Decomposes the object from the graph. + * @param graph the graph + * @return the object + */ + public Object decompose(Graph graph); + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/NodeBuilder.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/NodeBuilder.java new file mode 100644 index 000000000..9c23e9e5e --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/NodeBuilder.java @@ -0,0 +1,180 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.io.InputStream; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.UUID; + +import javax.activation.DataSource; +import javax.xml.namespace.QName; + +import org.switchyard.serial.graph.Factory; +import org.switchyard.serial.graph.Graph; + +/** + * Builds nodes for a graph. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class NodeBuilder { + + private static final Class[] SIMPLE_TYPES = new Class[] { + Boolean.class, + Calendar.class, + Character.class, + CharSequence.class, + Date.class, + Number.class + }; + + /** + * Builds a node representing the specified object and adds it to the graph. + * @param obj the specified object + * @param graph the graph + * @return the node id + */ + public static Integer build(Object obj, Graph graph) { + Integer id = graph.id(obj); + if (id == 0 || graph.getReference(id) != null) { + return id; + } + Class clazz = obj.getClass(); + if (isSimple(clazz)) { + graph.putReference(id, obj); + } else if (isArray(clazz)) { + if (isSimple(clazz.getComponentType())) { + graph.putReference(id, obj); + } else { + Node node = new ArrayNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } + } else if (isClass(clazz)) { + Node node = new ClassNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isCollection(clazz)) { + Node node = new CollectionNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isMap(clazz)) { + Node node = new MapNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isDOM(clazz)) { + Node node = new DOMNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isQName(clazz)) { + Node node = new QNameNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isDataSource(clazz)) { + Node node = new DataSourceNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isInputStream(clazz)) { + Node node = new InputStreamNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isUUID(clazz)) { + Node node = new UUIDNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isStackTraceElement(clazz)) { + Node node = new StackTraceElementNode(); + graph.putReference(id, node); + node.compose(obj, graph); + } else if (isAccessible(clazz)) { + Node node; + if (isThrowable(clazz)) { + node = new ThrowableAccessNode(); + } else { + node = new DefaultAccessNode(); + } + graph.putReference(id, node); + node.compose(obj, graph); + } else { + graph.putReference(id, NoopNode.INSTANCE); + } + return id; + } + + static boolean isArray(Class clazz) { + return clazz.isArray(); + } + + static boolean isClass(Class clazz) { + return Class.class.isAssignableFrom(clazz); + } + + static boolean isCollection(Class clazz) { + return Collection.class.isAssignableFrom(clazz); + } + + static boolean isDataSource(Class clazz) { + return DataSource.class.isAssignableFrom(clazz); + } + + static boolean isDOM(Class clazz) { + return org.w3c.dom.Node.class.isAssignableFrom(clazz); + } + + static boolean isInputStream(Class clazz) { + return InputStream.class.isAssignableFrom(clazz); + } + + static boolean isMap(Class clazz) { + return Map.class.isAssignableFrom(clazz); + } + + static boolean isQName(Class clazz) { + return QName.class.isAssignableFrom(clazz); + } + + static boolean isSimple(Class clazz) { + if (clazz.isPrimitive() || clazz.isEnum()) { + return true; + } + for (Class st : SIMPLE_TYPES) { + if (st.isAssignableFrom(clazz)) { + return true; + } + } + return false; + } + + static boolean isStackTraceElement(Class clazz) { + return StackTraceElement.class.isAssignableFrom(clazz); + } + + static boolean isThrowable(Class clazz) { + return Throwable.class.isAssignableFrom(clazz); + } + + static boolean isUUID(Class clazz) { + return UUID.class.isAssignableFrom(clazz); + } + + static boolean isAccessible(Class clazz) { + return Factory.getFactory(clazz).supports(clazz); + } + + private NodeBuilder() {} + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/NoopNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/NoopNode.java new file mode 100644 index 000000000..d8c0cad9c --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/NoopNode.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a noop. + * + * Note that there is a noop property, however it isn't used. It only exists so serializer implementations (like Jackson or Protostuff) don't complain about "no properties". + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@SuppressWarnings("serial") +public class NoopNode implements Node { + + /** + * A single instance of NoopNode. + */ + public static final NoopNode INSTANCE = new NoopNode(); + + private String _noop; + + /** + * Gets the noop. + * @return the noop + */ + public String getNoop() { + return _noop; + } + + /** + * Sets the noop. + * @param noop the noop + */ + public void setNoop(String noop) { + _noop = noop; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + // noop + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + // noop + return null; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/QNameNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/QNameNode.java new file mode 100644 index 000000000..a26e7dee5 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/QNameNode.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import javax.xml.namespace.QName; + +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a QName. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class QNameNode implements Node { + + private String _namespaceURI; + private String _localPart; + private String _prefix; + + /** + * Default constructor. + */ + public QNameNode() {} + + /** + * Gets the namespace uri. + * @return the namespace uri + */ + public String getNamespaceURI() { + return _namespaceURI; + } + + /** + * Sets the namespace uri. + * @param namespaceURI the namespace uri + */ + public void setNamespaceURI(String namespaceURI) { + _namespaceURI = namespaceURI; + } + + /** + * Gets the local part. + * @return the local part + */ + public String getLocalPart() { + return _localPart; + } + + /** + * Sets the local part. + * @param localPart the local part + */ + public void setLocalPart(String localPart) { + _localPart = localPart; + } + + /** + * Gets the prefix. + * @return the prefix + */ + public String getPrefix() { + return _prefix; + } + + /** + * Sets the prefix. + * @param prefix the prefix + */ + public void setPrefix(String prefix) { + _prefix = prefix; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + QName qname = (QName)obj; + setNamespaceURI(qname.getNamespaceURI()); + setLocalPart(qname.getLocalPart()); + setPrefix(qname.getPrefix()); + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + return new QName(getNamespaceURI(), getLocalPart(), getPrefix()); + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/StackTraceElementNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/StackTraceElementNode.java new file mode 100644 index 000000000..1862f1a8f --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/StackTraceElementNode.java @@ -0,0 +1,120 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a StackTraceElement. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class StackTraceElementNode implements Node { + + private String _className; + private String _methodName; + private String _fileName; + private int _lineNumber; + + /** + * Default constructor. + */ + public StackTraceElementNode() {} + + /** + * Gets the class name. + * @return the class name + */ + public String getClassName() { + return _className; + } + + /** + * Sets the class name. + * @param className the class name + */ + public void setClassName(String className) { + _className = className; + } + + /** + * Gets the method name. + * @return the method name + */ + public String getMethodName() { + return _methodName; + } + + /** + * Sets the method name. + * @param methodName the method name + */ + public void setMethodName(String methodName) { + _methodName = methodName; + } + + /** + * Gets the file name. + * @return the file name + */ + public String getFileName() { + return _fileName; + } + + /** + * Sets the file name. + * @param fileName the file name + */ + public void setFileName(String fileName) { + _fileName = fileName; + } + + /** + * Gets the line number. + * @return the line number + */ + public int getLineNumber() { + return _lineNumber; + } + + /** + * Sets the line number. + * @param lineNumber the line number + */ + public void setLineNumber(int lineNumber) { + _lineNumber = lineNumber; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + StackTraceElement ste = (StackTraceElement)obj; + setClassName(ste.getClassName()); + setMethodName(ste.getMethodName()); + setFileName(ste.getFileName()); + setLineNumber(ste.getLineNumber()); + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + return new StackTraceElement(getClassName(), getMethodName(), getFileName(), getLineNumber()); + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ThrowableAccessNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ThrowableAccessNode.java new file mode 100644 index 000000000..88238ed24 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/ThrowableAccessNode.java @@ -0,0 +1,207 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.lang.reflect.UndeclaredThrowableException; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.switchyard.HandlerException; +import org.switchyard.common.type.reflect.FieldAccess; +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a Throwable. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class ThrowableAccessNode extends AccessNode { + + static final Set THROWABLE_IGNORED_ACCESS_NAMES; + static { + Set throwableIgnoredAccessNames = new HashSet(); + throwableIgnoredAccessNames.addAll(AccessNode.IGNORED_ACCESS_NAMES); + throwableIgnoredAccessNames.add("message"); + throwableIgnoredAccessNames.add("cause"); + throwableIgnoredAccessNames.add("stackTrace"); + THROWABLE_IGNORED_ACCESS_NAMES = Collections.unmodifiableSet(throwableIgnoredAccessNames); + } + + private Integer _clazz; + private Map _ids; + private String _message; + private Integer _cause; + private Integer _stackTrace; + private Boolean _wrapper; + + /** + * Default constructor. + */ + public ThrowableAccessNode() {} + + /** + * {@inheritDoc} + */ + @Override + Set getIgnoredAccessNames() { + return THROWABLE_IGNORED_ACCESS_NAMES; + } + + /** + * {@inheritDoc} + */ + @Override + public Integer getClazz() { + return _clazz; + } + + /** + * {@inheritDoc} + */ + @Override + public void setClazz(Integer clazz) { + _clazz = clazz; + } + + /** + * {@inheritDoc} + */ + @Override + public Map getIds() { + return _ids; + } + + /** + * {@inheritDoc} + */ + @Override + public void setIds(Map ids) { + _ids = ids; + } + + /** + * Gets the message. + * @return the message + */ + public String getMessage() { + return _message; + } + + /** + * Sets the message. + * @param message the message + */ + public void setMessage(String message) { + _message = message; + } + + /** + * Gets the cause. + * @return the cause + */ + public Integer getCause() { + return _cause; + } + + /** + * Sets the cause. + * @param cause the cause + */ + public void setCause(Integer cause) { + _cause = cause; + } + + /** + * Gets the stack trace. + * @return the stack trace + */ + public Integer getStackTrace() { + return _stackTrace; + } + + /** + * Sets the stack trace. + * @param stackTrace the stack trace + */ + public void setStackTrace(Integer stackTrace) { + _stackTrace = stackTrace; + } + + /** + * Gets the wrapper. + * @return the wrapper + */ + public Boolean getWrapper() { + return _wrapper; + } + + /** + * Sets the wrapper. + * @param wrapper the wrapper + */ + public void setWrapper(Boolean wrapper) { + _wrapper = wrapper; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + super.compose(obj, graph); + Throwable throwable = (Throwable)obj; + setMessage(throwable.getMessage()); + setCause(NodeBuilder.build(throwable.getCause(), graph)); + setStackTrace(NodeBuilder.build(throwable.getStackTrace(), graph)); + if (throwable instanceof HandlerException) { + setWrapper(((HandlerException)throwable).isWrapper()); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + Throwable throwable = (Throwable)super.decompose(graph); + Throwable cause = (Throwable)graph.decomposeReference(getCause()); + if (cause != null) { + if (UndeclaredThrowableException.class.equals(throwable.getClass())) { + Integer referenceId = graph.getReferenceId(throwable); + throwable = new UndeclaredThrowableException(cause, throwable.getMessage()); + if (referenceId != null) { + graph.putReference(referenceId, throwable); + } + } else { + throwable.initCause(cause); + } + } + Object[] array = (Object[])graph.decomposeReference(getStackTrace()); + if (array != null) { + StackTraceElement[] stackTrace = new StackTraceElement[array.length]; + for (int i=0; i < array.length; i++) { + stackTrace[i] = (StackTraceElement)array[i]; + } + throwable.setStackTrace(stackTrace); + } + if (throwable instanceof HandlerException && getWrapper() != null) { + new FieldAccess(HandlerException.class, "_wrapper").write(throwable, getWrapper()); + } + return throwable; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/graph/node/UUIDNode.java b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/UUIDNode.java new file mode 100644 index 000000000..604ccb72c --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/graph/node/UUIDNode.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.graph.node; + +import java.util.UUID; + +import org.switchyard.serial.graph.Graph; + +/** + * A node representing a UUID. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class UUIDNode implements Node { + + private String _uuid; + + /** + * Default constructor. + */ + public UUIDNode() {} + + /** + * Gets the uuid. + * @return the uuid + */ + public String getUuid() { + return _uuid; + } + + /** + * Sets the uuid. + * @param uuid the uuid + */ + public void setUuid(String uuid) { + _uuid = uuid; + } + + /** + * {@inheritDoc} + */ + @Override + public void compose(Object obj, Graph graph) { + UUID uuid = (UUID)obj; + setUuid(uuid.toString()); + } + + /** + * {@inheritDoc} + */ + @Override + public Object decompose(Graph graph) { + return UUID.fromString(getUuid()); + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/pull/DeserializingPuller.java b/core/serial/base/src/main/java/org/switchyard/serial/pull/DeserializingPuller.java new file mode 100644 index 000000000..489afc866 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/pull/DeserializingPuller.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.pull; + +import java.io.IOException; +import java.io.InputStream; + +import org.switchyard.common.io.pull.Puller; +import org.switchyard.serial.Serializer; + +/** + * Utility class to safely deserialize ("pull") Objects from various sources. + * + * @param the type of object + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class DeserializingPuller extends Puller { + + private final Serializer _serializer; + private final Class _type; + + /** + * Constructor with a serializer and type. + * @param serializer the serializer + * @param type the type + */ + public DeserializingPuller(Serializer serializer, Class type) { + _serializer = serializer; + _type = type; + } + + /** + * {@inheritDoc} + */ + @Override + public T pull(InputStream stream) throws IOException { + return _serializer.deserialize(stream, _type); + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/spi/JDKSerializationProvider.java b/core/serial/base/src/main/java/org/switchyard/serial/spi/JDKSerializationProvider.java new file mode 100644 index 000000000..26710eebf --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/spi/JDKSerializationProvider.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.spi; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.format.SERObjectSerializer; +import org.switchyard.serial.format.XMLBeanSerializer; + +/** + * JDK built-in serialization provider. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class JDKSerializationProvider extends SerializationProvider { + + private static final Map> MAP; + static { + Map> map = new LinkedHashMap>(); + map.put(FormatType.SER_OBJECT, SERObjectSerializer.class); + map.put(FormatType.XML_BEAN, XMLBeanSerializer.class); + MAP = Collections.unmodifiableMap(map); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getSupportedFormats() { + return MAP.keySet(); + } + + /** + * {@inheritDoc} + */ + @Override + public Serializer newSerializer(FormatType format) { + Class c = MAP.get(format); + return c != null ? Construction.construct(c) : null; + } + +} diff --git a/core/serial/base/src/main/java/org/switchyard/serial/spi/SerializationProvider.java b/core/serial/base/src/main/java/org/switchyard/serial/spi/SerializationProvider.java new file mode 100644 index 000000000..c81339346 --- /dev/null +++ b/core/serial/base/src/main/java/org/switchyard/serial/spi/SerializationProvider.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.spi; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.switchyard.common.type.Classes; +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; + +/** + * Provides serializers for supported formats. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class SerializationProvider { + + private static final Map> MAP; + static { + Map> map = new LinkedHashMap>(); + Iterable providers = ProviderRegistry.getProviders(SerializationProvider.class, Classes.getClassLoader(SerializationProvider.class)); + for (SerializationProvider provider : providers) { + for (FormatType format : provider.getSupportedFormats()) { + List list = map.get(format); + if (list == null) { + list = new ArrayList(); + map.put(format, list); + } + list.add(provider); + } + } + for (FormatType format : new LinkedHashSet(map.keySet())) { + map.put(format, Collections.unmodifiableList(map.remove(format))); + } + MAP = Collections.unmodifiableMap(map); + } + + /** + * Gets the supported formats. + * @return the supported formats + */ + public abstract Set getSupportedFormats(); + + /** + * Creates a new serializer for a format. + * @param format the format + * @return the serializer + */ + public abstract Serializer newSerializer(FormatType format); + + /** + * Gets all providers that support a format. + * @param format the format + * @return the providers + */ + public static final List getProviders(FormatType format) { + return MAP.containsKey(format) ? MAP.get(format) : Collections.emptyList(); + } + + /** + * Gets the primary provider that supports a format. + * @param format the format + * @return the primary provider + */ + public static final SerializationProvider getPrimaryProvider(FormatType format) { + Iterator providers = getProviders(format).iterator(); + return providers.hasNext() ? providers.next() : null; + } + +} diff --git a/core/serial/base/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider b/core/serial/base/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider new file mode 100644 index 000000000..d447aafaa --- /dev/null +++ b/core/serial/base/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider @@ -0,0 +1 @@ +org.switchyard.serial.spi.JDKSerializationProvider diff --git a/core/serial/base/src/test/resources/log4j.properties b/core/serial/base/src/test/resources/log4j.properties new file mode 100644 index 000000000..02a249c1d --- /dev/null +++ b/core/serial/base/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootCategory=INFO, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=DEBUG +log4j.appender.CONSOLE.Target=System.out +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n diff --git a/core/serial/jackson/pom.xml b/core/serial/jackson/pom.xml new file mode 100644 index 000000000..d1151dee6 --- /dev/null +++ b/core/serial/jackson/pom.xml @@ -0,0 +1,53 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-serial-jackson + bundle + SwitchYard: Serial - Jackson + The Jackson serialization library. + http://switchyard.org + + + org.switchyard.serial.jackson.* + + + + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-serial + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-mapper-asl + + + diff --git a/core/serial/jackson/src/main/java/org/switchyard/serial/jackson/format/JSONJacksonSerializer.java b/core/serial/jackson/src/main/java/org/switchyard/serial/jackson/format/JSONJacksonSerializer.java new file mode 100644 index 000000000..05f0fe000 --- /dev/null +++ b/core/serial/jackson/src/main/java/org/switchyard/serial/jackson/format/JSONJacksonSerializer.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.jackson.format; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.codehaus.jackson.JsonFactory; +import org.codehaus.jackson.JsonGenerator; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.ObjectWriter; +import org.codehaus.jackson.map.SerializationConfig; +import org.switchyard.common.io.CountingOutputStream; +import org.switchyard.serial.BaseSerializer; +import org.switchyard.serial.FormatType; + +/** + * A Jackson serializer that performs {@link FormatType.JSON} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class JSONJacksonSerializer extends BaseSerializer { + + private final ObjectMapper _objectMapper; + + /** + * Default constructor. + */ + public JSONJacksonSerializer() { + super(FormatType.JSON); + JsonFactory jsonFactory = new JsonFactory(); + jsonFactory.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE); + jsonFactory.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); + _objectMapper = new ObjectMapper(jsonFactory); + _objectMapper.enableDefaultTyping(); + _objectMapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS); + } + + /** + * {@inheritDoc} + */ + @Override + public int serialize(T obj, Class type, OutputStream out) throws IOException { + out = new CountingOutputStream(new BufferedOutputStream(out, getBufferSize())); + try { + ObjectWriter writer = _objectMapper.writerWithType(type); + if (isPrettyPrint()) { + writer = writer.withDefaultPrettyPrinter(); + } + writer.writeValue(out, obj); + } finally { + if (isCloseEnabled()) { + out.close(); + } + } + return ((CountingOutputStream)out).getCount(); + } + + /** + * {@inheritDoc} + */ + @Override + public T deserialize(InputStream in, Class type) throws IOException { + T obj; + try { + obj = _objectMapper.readValue(in, type); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + return obj; + } + +} diff --git a/core/serial/jackson/src/main/java/org/switchyard/serial/jackson/spi/JacksonSerializationProvider.java b/core/serial/jackson/src/main/java/org/switchyard/serial/jackson/spi/JacksonSerializationProvider.java new file mode 100644 index 000000000..6c9d3387e --- /dev/null +++ b/core/serial/jackson/src/main/java/org/switchyard/serial/jackson/spi/JacksonSerializationProvider.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.jackson.spi; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.jackson.format.JSONJacksonSerializer; +import org.switchyard.serial.spi.SerializationProvider; + +/** + * Jackson serialization provider. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class JacksonSerializationProvider extends SerializationProvider { + + private static final Map> MAP; + static { + Map> map = new LinkedHashMap>(); + map.put(FormatType.JSON, JSONJacksonSerializer.class); + //map.put(FormatType.JSON_NUMERIC, NumericJSONJacksonSerializer.class); + MAP = Collections.unmodifiableMap(map); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getSupportedFormats() { + return MAP.keySet(); + } + + /** + * {@inheritDoc} + */ + @Override + public Serializer newSerializer(FormatType format) { + Class c = MAP.get(format); + return c != null ? Construction.construct(c) : null; + } + +} diff --git a/core/serial/jackson/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider b/core/serial/jackson/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider new file mode 100644 index 000000000..b4557b851 --- /dev/null +++ b/core/serial/jackson/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider @@ -0,0 +1 @@ +org.switchyard.serial.jackson.spi.JacksonSerializationProvider diff --git a/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonComparisonSerializationTest.java b/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonComparisonSerializationTest.java new file mode 100644 index 000000000..ddc2c4bbf --- /dev/null +++ b/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonComparisonSerializationTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.jackson; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.serial.CompressionType; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; +import org.switchyard.serial.jackson.JacksonSerializationData.Car; +import org.switchyard.serial.jackson.JacksonSerializationData.Person; + +/** + * Tests various serializers, using both a passed in object, and a mapped object, uncompressed and compressed. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class JacksonComparisonSerializationTest { + + @Test + public void testSerialization() throws Exception { + for (FormatType format : new FormatType[]{FormatType.JSON, FormatType.SER_OBJECT, FormatType.XML_BEAN}) { + doTest(format); + } + } + + private void doTest(FormatType format) throws Exception { + doRun(SerializerFactory.create(format, null, false), 0, false); + doRun(SerializerFactory.create(format, CompressionType.ZIP, false), 4, false); + doRun(SerializerFactory.create(format, CompressionType.GZIP, false), 4, false); + doRun(SerializerFactory.create(format, null, true), 4, false); + doRun(SerializerFactory.create(format, CompressionType.ZIP, true), 8, false); + doRun(SerializerFactory.create(format, CompressionType.GZIP, true), 8, true); + } + + private void doRun(Serializer serializer, int spaces, boolean newline) throws Exception { + //serializer.setPrettyPrint(true); + Car car = new Car(new Person("Dave")); + long start = System.currentTimeMillis(); + byte[] bytes = serializer.serialize(car, Car.class); + //System.out.println(new String(bytes)); + car = serializer.deserialize(bytes, Car.class); + long stop = System.currentTimeMillis(); + boolean debug = false; // toggle this is you're interested in performance + if (debug) { + StringBuilder sb = new StringBuilder(); + for (int i=0; i < spaces; i++) { + sb.append(' '); + } + sb.append(serializer.getClass().getSimpleName()); + sb.append(": "); + sb.append(bytes.length); + sb.append(" bytes serialized and deserialized in "); + sb.append(stop - start); + sb.append(" milliseconds"); + if (newline) { + sb.append("\n"); + } + System.out.println(sb); + } + Assert.assertEquals("Dave", car.getDriver().getNickName()); + } + +} diff --git a/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonComplexSerializationTest.java b/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonComplexSerializationTest.java new file mode 100644 index 000000000..aa483d596 --- /dev/null +++ b/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonComplexSerializationTest.java @@ -0,0 +1,293 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.jackson; + +import java.io.StringReader; +import java.lang.reflect.UndeclaredThrowableException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.HandlerException; +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; +import org.switchyard.serial.jackson.JacksonSerializationData.Antennae; +import org.switchyard.serial.jackson.JacksonSerializationData.Car; +import org.switchyard.serial.jackson.JacksonSerializationData.CustomPart; +import org.switchyard.serial.jackson.JacksonSerializationData.ExpiredPart; +import org.switchyard.serial.jackson.JacksonSerializationData.FlatTireException; +import org.switchyard.serial.jackson.JacksonSerializationData.FluentTitle; +import org.switchyard.serial.jackson.JacksonSerializationData.Name; +import org.switchyard.serial.jackson.JacksonSerializationData.OutOfGasException; +import org.switchyard.serial.jackson.JacksonSerializationData.Part; +import org.switchyard.serial.jackson.JacksonSerializationData.Person; +import org.switchyard.serial.jackson.JacksonSerializationData.StrictTitle; +import org.switchyard.serial.jackson.JacksonSerializationData.Title; +import org.switchyard.serial.jackson.JacksonSerializationData.Wheel; +import org.w3c.dom.Element; + +/** + * Tests more complex de/serialization scenarios. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class JacksonComplexSerializationTest { + + private T serDeser(T object, Class clazz) throws Exception { + Serializer ser = SerializerFactory.create(FormatType.JSON, null, true); + //ser.setPrettyPrint(true); + byte[] bytes = ser.serialize(object, clazz); + //System.out.println(new String(bytes)); + return ser.deserialize(bytes, clazz); + } + + @Test + public void testSpecificArray() throws Exception { + Car car = new Car(); + car.setPassengers(new Person[] {new Person("passengerA"), new Person("passengerB")}); + car = serDeser(car, Car.class); + Assert.assertEquals(2, car.getPassengers().length); + Assert.assertEquals("passengerB", car.getPassengers()[1].getNickName()); + } + + @Test + public void testPolymorphicArray() throws Exception { + Car car = new Car(); + car.setCheapParts(new Part[] {new Wheel(), new CustomPart(true)}); + car = serDeser(car, Car.class); + Assert.assertEquals(2, car.getCheapParts().length); + Assert.assertEquals(true, car.getCheapParts()[1].isReplaceable()); + } + + @Test + public void testPolymorphicCollection() throws Exception { + Car car = new Car(); + Collection ep = new ArrayList(); + for (int i=0; i < 4; i++) { + ep.add(new Wheel()); + } + ep.add(new CustomPart(false)); + car.setExpensiveParts(ep); + car = serDeser(car, Car.class); + Assert.assertEquals(5, car.getExpensiveParts().size()); + List list = new ArrayList(car.getExpensiveParts()); + Assert.assertEquals(true, list.get(3).isReplaceable()); + Assert.assertEquals(false, list.get(4).isReplaceable()); + } + + @Test + public void testSpecificUnsupportedType() throws Exception { + ExpiredPart part = new ExpiredPart(new Date()); + part = serDeser(part, ExpiredPart.class); + Assert.assertNull(part); + } + + @Test + public void testUnsupportedTypeArray() throws Exception { + Car car = new Car(); + car.setCheapParts(new Part[] {new Wheel(), new ExpiredPart(new Date())}); + car = serDeser(car, Car.class); + Assert.assertEquals(1, car.getCheapParts().length); + } + + @Test + public void testUnsupportedTypeCollection() throws Exception { + Car car = new Car(); + Collection ep = new ArrayList(); + for (int i=0; i < 4; i++) { + ep.add(new Wheel()); + } + ep.add(new ExpiredPart(new Date())); + car.setExpensiveParts(ep); + car = serDeser(car, Car.class); + Assert.assertEquals(4, car.getExpensiveParts().size()); + } + + @Test + @SuppressWarnings("unchecked") + public void testUnsupportedTypeMap() throws Exception { + Map map = new HashMap(); + map.put("wheel", new Wheel()); + map.put("crank", new ExpiredPart(new Date())); + map = serDeser(map, Map.class); + Assert.assertEquals(1, map.size()); + } + + @Test + public void testCircularReferences() throws Exception { + Name bob = new Name("Bob", "Bobby", "Bobson"); + Person me = new Person("me", bob); + Person bff = new Person("bff", bob); + me.setBestFriend(bff); + bff.setBestFriend(me); + Person mom = new Person("mom"); + Person dad = new Person("dad"); + mom.setBestFriend(dad); + dad.setBestFriend(mom); + me.getRelatives().add(mom); + me.getRelatives().add(dad); + mom.getRelatives().add(me); + dad.getRelatives().add(me); + me = serDeser(me, Person.class); + bff = me.getBestFriend(); + Iterator parents = me.getRelatives().iterator(); + mom = parents.next(); + dad = parents.next(); + Assert.assertEquals("me", me.getNickName()); + Assert.assertEquals("Bob", me.getFullName().getFirst()); + Assert.assertEquals("bff", bff.getNickName()); + Assert.assertSame(me.getFullName(), bff.getFullName()); + Assert.assertEquals("mom", mom.getNickName()); + Assert.assertEquals("dad", dad.getNickName()); + Assert.assertSame(me, me.getBestFriend().getBestFriend()); + Assert.assertSame(bff, bff.getBestFriend().getBestFriend()); + Assert.assertSame(me.getFullName(), me.getBestFriend().getBestFriend().getFullName()); + Assert.assertSame(mom, mom.getBestFriend().getBestFriend()); + Assert.assertSame(dad, dad.getBestFriend().getBestFriend()); + Assert.assertSame(me, mom.getRelatives().iterator().next()); + Assert.assertSame(me, dad.getRelatives().iterator().next()); + } + + @Test + public void testDOM() throws Exception { + final String expectedXML = "NY"; + final Element expectedDOM = new ElementPuller().pull(new StringReader(expectedXML)); + Car car = new Car(); + car.setInspection(expectedDOM); + car = serDeser(car, Car.class); + final Element actualDOM = car.getInspection(); + final String actualXML = XMLHelper.toString(actualDOM); + Assert.assertEquals(expectedXML, actualXML); + } + + @Test + public void testBasicExceptions() throws Exception { + final IllegalStateException expectedIllegalStateException = new IllegalStateException("expectedIllegalStateException"); + expectedIllegalStateException.fillInStackTrace(); + final HandlerException expectedHandlerException = new HandlerException(expectedIllegalStateException); + expectedHandlerException.fillInStackTrace(); + final Exception expectedException = new Exception("expectedException", expectedHandlerException); + expectedException.fillInStackTrace(); + final Exception actualException = serDeser(expectedException, Exception.class); + final HandlerException actualHandlerException = (HandlerException)actualException.getCause(); + final IllegalStateException actualIllegalStateException = (IllegalStateException)actualHandlerException.getCause(); + Assert.assertEquals(expectedException.getMessage(), actualException.getMessage()); + Assert.assertEquals(expectedHandlerException.getMessage(), actualHandlerException.getMessage()); + Assert.assertEquals(expectedIllegalStateException.getMessage(), actualIllegalStateException.getMessage()); + Assert.assertEquals(expectedException.getStackTrace().length, actualException.getStackTrace().length); + Assert.assertEquals(expectedHandlerException.getStackTrace().length, actualHandlerException.getStackTrace().length); + Assert.assertEquals(expectedIllegalStateException.getStackTrace().length, actualIllegalStateException.getStackTrace().length); + Assert.assertEquals(expectedHandlerException.isWrapper(), actualHandlerException.isWrapper()); + } + + @Test + public void testCustomExceptions() throws Exception { + final OutOfGasException expectedOutOfGasException = new OutOfGasException("Dagnabit!"); + final FlatTireException expectedFlatTireException = new FlatTireException(new Wheel(Wheel.Location.BACK_RIGHT)); + Car car = new Car(); + car.setProblems(Arrays.asList(new Exception[]{expectedOutOfGasException, expectedFlatTireException})); + car = serDeser(car, Car.class); + final List actualExceptions = car.getProblems(); + final OutOfGasException actualOutOfGasException = (OutOfGasException)actualExceptions.get(0); + final FlatTireException actualFlatTireException = (FlatTireException)actualExceptions.get(1); + Assert.assertEquals(expectedOutOfGasException.getExplicitive(), actualOutOfGasException.getExplicitive()); + Assert.assertSame(expectedFlatTireException.getWheel().getLocation(), actualFlatTireException.getWheel().getLocation()); + Assert.assertEquals("Really?", actualFlatTireException.getMessage()); + } + + @Test + public void testUndeclaredThrowableException() throws Exception { + final UndeclaredThrowableException expectedUndeclaredThrowableException = new UndeclaredThrowableException(new Throwable("undeclared"), "message"); + Car car = new Car(); + car.setProblems(Arrays.asList(new Exception[]{expectedUndeclaredThrowableException, expectedUndeclaredThrowableException})); + car = serDeser(car, Car.class); + final List actualExceptions = car.getProblems(); + final UndeclaredThrowableException actualUndeclaredThrowableException = (UndeclaredThrowableException)actualExceptions.get(0); + final UndeclaredThrowableException sameUndeclaredThrowableException = (UndeclaredThrowableException)actualExceptions.get(1); + Assert.assertSame(actualUndeclaredThrowableException, sameUndeclaredThrowableException); + Assert.assertEquals("message", actualUndeclaredThrowableException.getMessage()); + Assert.assertEquals(expectedUndeclaredThrowableException.getMessage(), actualUndeclaredThrowableException.getMessage()); + Assert.assertEquals(expectedUndeclaredThrowableException.getStackTrace().length, actualUndeclaredThrowableException.getStackTrace().length); + Assert.assertEquals("undeclared", actualUndeclaredThrowableException.getUndeclaredThrowable().getMessage()); + Assert.assertSame(actualUndeclaredThrowableException.getUndeclaredThrowable(), actualUndeclaredThrowableException.getCause()); + } + + @Test + public void testStrictBean() throws Exception { + final UUID id = UUID.randomUUID(); + Car car = new Car(); + StrictTitle title = new StrictTitle(); + title.setId(id); + title.setState("NY"); + title.setLiened(true); + car.setTitle(title); + car = serDeser(car, Car.class); + Assert.assertEquals(id, car.getTitle().getId()); + Assert.assertEquals("NY", car.getTitle().getState()); + Assert.assertTrue(car.getTitle().isLiened()); + } + + @Test + public void testFluentBean() throws Exception { + final UUID id = UUID.randomUUID(); + Car car = new Car(); + Title title = new FluentTitle().setId(id).setState("NY").setLiened(true); + car.setTitle(title); + car = serDeser(car, Car.class); + Assert.assertEquals(id, car.getTitle().getId()); + Assert.assertEquals("NY", car.getTitle().getState()); + Assert.assertTrue(car.getTitle().isLiened()); + } + + @Test + public void testEmptyBean() throws Exception { + Car car = new Car(); + Antennae antennae = new Antennae(); + car.setAntennae(antennae); + car = serDeser(car, Car.class); + antennae = car.getAntennae(); + Assert.assertNotNull(antennae); + } + + @Test + public void testDuplicateValues() throws Exception { + Name name = new Name("me", "me", "me"); + name = serDeser(name, Name.class); + Assert.assertEquals("me", name.getFirst()); + Assert.assertEquals("me", name.getMiddle()); + Assert.assertEquals("me", name.getLast()); + name = new Name("you", null, "you"); + name = serDeser(name, Name.class); + Assert.assertEquals("you", name.getFirst()); + Assert.assertNull(name.getMiddle()); + Assert.assertEquals("you", name.getLast()); + name = new Name("him", "her", null); + name = serDeser(name, Name.class); + Assert.assertEquals("him", name.getFirst()); + Assert.assertEquals("her", name.getMiddle()); + Assert.assertNull(name.getLast()); + } + +} diff --git a/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonSerializationData.java b/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonSerializationData.java new file mode 100644 index 000000000..f0b9a4489 --- /dev/null +++ b/core/serial/jackson/src/test/java/org/switchyard/serial/jackson/JacksonSerializationData.java @@ -0,0 +1,349 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.jackson; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.switchyard.serial.graph.AccessType; +import org.switchyard.serial.graph.Strategy; +import org.w3c.dom.Element; + +/** + * Data for tests. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class JacksonSerializationData { + + public static final class Name implements Serializable { + private String _first; + private String _middle; + private String _last; + public Name() {} + public Name(String first, String middle, String last) { + setFirst(first).setMiddle(middle).setLast(last); + } + public String getFirst() { + return _first; + } + public Name setFirst(String first) { + _first = first; + return this; + } + public String getMiddle() { + return _middle; + } + public Name setMiddle(String middle) { + _middle = middle; + return this; + } + public String getLast() { + return _last; + } + public Name setLast(String last) { + _last = last; + return this; + } + public String toString() { + return "Name@" + System.identityHashCode(this) + "(first=" + getFirst() + ", middle=" + getMiddle() + ", last=" + getLast() + ")"; + } + } + + public static final class Person implements Serializable { + private String _nickName; + private Name _fullName; + private Person _bestFriend; + private Collection _relatives = new ArrayList(); + public Person() {} + public Person(String nickName) { + setNickName(nickName); + } + public Person(Name fullName) { + setFullName(fullName); + } + public Person(String nickName, Name fullName) { + setNickName(nickName); + setFullName(fullName); + } + public String getNickName() { + return _nickName; + } + public void setNickName(String nickName) { + _nickName = nickName; + } + public Name getFullName() { + return _fullName; + } + public void setFullName(Name fullName) { + _fullName = fullName; + } + public Person getBestFriend() { + return _bestFriend; + } + public void setBestFriend(Person bestFriend) { + _bestFriend = bestFriend; + } + public Collection getRelatives() { + return _relatives; + } + public void setRelatives(Collection relatives) { + _relatives = relatives; + } + public String toString() { + return "Person@" + System.identityHashCode(this) + "(nickName=" + getNickName() + ", fullName=" + getFullName() + ", bestFriend=" + (_bestFriend != null ? _bestFriend.getNickName() : "") + ", relatives=" + getRelatives().size() + ")"; + } + } + + public static final class Car implements Serializable { + private Person _driver; + private Person[] _passengers; + private Title _title; + private Part[] _cheapParts; + private Collection _expensiveParts; + private Element _inspection; + private List _problems; + private Antennae _antennae; + public Car() {} + public Car(Person driver) { + setDriver(driver); + } + public Person getDriver() { + return _driver; + } + public void setDriver(Person driver) { + _driver = driver; + } + public Person[] getPassengers() { + return _passengers; + } + public void setPassengers(Person[] passengers) { + _passengers = passengers; + } + public Title getTitle() { + return _title; + } + public void setTitle(Title title) { + _title = title; + } + public Part[] getCheapParts() { + return _cheapParts; + } + public void setCheapParts(Part[] cheapParts) { + _cheapParts = cheapParts; + } + public Collection getExpensiveParts() { + return _expensiveParts; + } + public void setExpensiveParts(Collection expensiveParts) { + _expensiveParts = expensiveParts; + } + public Element getInspection() { + return _inspection; + } + public void setInspection(Element inspection) { + _inspection = inspection; + } + public List getProblems() { + return _problems; + } + public void setProblems(List problems) { + _problems = problems; + } + public Antennae getAntennae() { + return _antennae; + } + public void setAntennae(Antennae antennae) { + _antennae = antennae; + } + public String toString() { + return "Car@" + System.identityHashCode(this) + "(driver=" + getDriver() + ", passengers=" + Arrays.toString(getPassengers()) + ", cheapParts=" + Arrays.toString(getCheapParts()) + ", expensiveParts=" + getExpensiveParts() + ", inspection=" + getInspection() + ", problems=" + getProblems() + ")"; + } + } + + public static interface Title { + public UUID getId(); + public String getState(); + public boolean isLiened(); + } + + public static final class StrictTitle implements Title { + private UUID _id; + private String _state; + private boolean _liened; + public StrictTitle() {} + public UUID getId() { + return _id; + } + public void setId(UUID id) { + _id = id; + } + public String getState() { + return _state; + } + public void setState(String state) { + _state = state; + } + public boolean isLiened() { + return _liened; + } + public void setLiened(boolean liened) { + _liened = liened; + } + public String toString() { + return "StrictTitle@" + System.identityHashCode(this) + "(id=" + getId() + ", state=" + getState() + ", liened" + isLiened() + ")"; + } + } + + public static final class FluentTitle implements Title { + private UUID _id; + private String _state; + private boolean _liened; + public FluentTitle() {} + public UUID getId() { + return _id; + } + // purposely returns the implementation type, for the sake of the test + public FluentTitle setId(UUID id) { + _id = id; + return this; + } + public String getState() { + return _state; + } + // purposely returns the implementation type, for the sake of the test + public FluentTitle setState(String state) { + _state = state; + return this; + } + public boolean isLiened() { + return _liened; + } + // purposely returns the interface type, for the sake of the test + public Title setLiened(boolean liened) { + _liened = liened; + return this; + } + public String toString() { + return "FluentTitle@" + System.identityHashCode(this) + "(id=" + getId() + ", state=" + getState() + ", liened" + isLiened() + ")"; + } + } + + public static interface Part { + public boolean isReplaceable(); + } + + @Strategy(access=AccessType.FIELD) + public static final class Wheel implements Part { + private Location _location; + public Wheel() { + this(Location.UNSPECIFIED); + } + public Wheel(Location location) { + _location = location; + } + public boolean isReplaceable() { + return true; + } + public Location getLocation() { + return _location; + } + public String toString() { + return "Wheel(replaceable=" + isReplaceable() + ", location=" + getLocation() + ")"; + } + public static enum Location { + UNSPECIFIED, FRONT_LEFT, FRONT_RIGHT, BACK_LEFT, BACK_RIGHT; + } + } + + public static final class CustomPart implements Part { + private boolean _replaceable; + public CustomPart() {} + public CustomPart(boolean replaceable) { + setReplaceable(replaceable); + } + public boolean isReplaceable() { + return _replaceable; + } + public void setReplaceable(boolean replaceable) { + _replaceable = replaceable; + } + public String toString() { + return "CustomPart@" + System.identityHashCode(this) + "(replaceable=" + isReplaceable() + ")"; + } + } + + public static final class ExpiredPart implements Part { + private Date _expiredDate; + public ExpiredPart(Date expiredDate) { + _expiredDate = expiredDate; + } + public boolean isReplaceable() { + return false; + } + public Date getExpiredDate() { + return _expiredDate; + } + public String toString() { + return "BadPart@" + System.identityHashCode(this) + "(replaceable=" + isReplaceable() + ", expiredDate=" + getExpiredDate() + ")"; + } + } + + public static final class Antennae implements Serializable { + public String toString() { + return "Antennae@" + System.identityHashCode(this); + } + } + + public static final class OutOfGasException extends Exception { + private String _explicitive; + public OutOfGasException() { + super(); + } + public OutOfGasException(String explicitive) { + super(); + setExplicitive(explicitive); + } + public String getExplicitive() { + return _explicitive; + } + public void setExplicitive(String explicitive) { + _explicitive = explicitive; + } + } + + @Strategy(access=AccessType.FIELD) + public static final class FlatTireException extends Exception { + private Wheel _wheel; + public FlatTireException() { + super("Really?"); + } + public FlatTireException(Wheel wheel) { + super(); + _wheel = wheel; + } + public Wheel getWheel() { + return _wheel; + } + } + + private JacksonSerializationData() {} + +} diff --git a/core/serial/jackson/src/test/resources/log4j.properties b/core/serial/jackson/src/test/resources/log4j.properties new file mode 100644 index 000000000..02a249c1d --- /dev/null +++ b/core/serial/jackson/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootCategory=INFO, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=DEBUG +log4j.appender.CONSOLE.Target=System.out +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n diff --git a/core/serial/protostuff/pom.xml b/core/serial/protostuff/pom.xml new file mode 100644 index 000000000..1008bbaf8 --- /dev/null +++ b/core/serial/protostuff/pom.xml @@ -0,0 +1,95 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-serial-protostuff + bundle + SwitchYard: Serial - Protostuff + The Protostuff serialization library. + http://switchyard.org + + 1.0.8 + + org.switchyard.serial.protostuff.* + + + + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-serial + + + + com.dyuproject.protostuff + protostuff-api + + + com.dyuproject.protostuff + protostuff-core + + + com.dyuproject.protostuff + protostuff-json + + + com.dyuproject.protostuff + protostuff-runtime + + + com.dyuproject.protostuff + protostuff-xml + + + + + + com.dyuproject.protostuff + protostuff-api + ${version.com.dyuproject.protostuff} + + + com.dyuproject.protostuff + protostuff-core + ${version.com.dyuproject.protostuff} + + + com.dyuproject.protostuff + protostuff-json + ${version.com.dyuproject.protostuff} + + + com.dyuproject.protostuff + protostuff-runtime + ${version.com.dyuproject.protostuff} + + + com.dyuproject.protostuff + protostuff-xml + ${version.com.dyuproject.protostuff} + + + + diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/BaseJSONProtostuffSerializer.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/BaseJSONProtostuffSerializer.java new file mode 100644 index 000000000..49f98e452 --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/BaseJSONProtostuffSerializer.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.format; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.switchyard.serial.FormatType; + +import com.dyuproject.protostuff.JsonIOUtil; +import com.dyuproject.protostuff.LinkedBuffer; +import com.dyuproject.protostuff.Schema; + +/** + * Base JSON Protostuff serializer. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class BaseJSONProtostuffSerializer extends BaseProtostuffSerializer { + + private final boolean _numeric; + + /** + * Constructor with a numeric flag. + * @param numeric the numeric flag + */ + public BaseJSONProtostuffSerializer(boolean numeric) { + super(numeric ? FormatType.JSON_NUMERIC : FormatType.JSON); + _numeric = numeric; + } + + /** + * {@inheritDoc} + */ + @Override + public void writeTo(OutputStream out, T obj, Schema schema) throws IOException { + try { + JsonIOUtil.writeTo(out, obj, schema, _numeric, LinkedBuffer.allocate(getBufferSize())); + out.flush(); + } finally { + if (isCloseEnabled()) { + out.close(); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mergeFrom(InputStream in, T obj, Schema schema) throws IOException { + try { + JsonIOUtil.mergeFrom(in, obj, schema, _numeric, LinkedBuffer.allocate(getBufferSize())); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + } + +} diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/BaseProtostuffSerializer.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/BaseProtostuffSerializer.java new file mode 100644 index 000000000..02b01f108 --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/BaseProtostuffSerializer.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.format; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.switchyard.common.io.CountingOutputStream; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.serial.BaseSerializer; +import org.switchyard.serial.FormatType; + +import com.dyuproject.protostuff.Schema; +import com.dyuproject.protostuff.runtime.RuntimeSchema; + +/** + * Base Protostuff serializer. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public abstract class BaseProtostuffSerializer extends BaseSerializer { + + /** + * Constructor with a format. + * @param format the format + */ + protected BaseProtostuffSerializer(FormatType format) { + super(format); + } + + /** + * {@inheritDoc} + */ + @Override + public int serialize(T obj, Class type, OutputStream out) throws IOException { + out = new CountingOutputStream(new BufferedOutputStream(out, getBufferSize())); + Schema schema = RuntimeSchema.getSchema(type); + writeTo(out, obj, schema); + return ((CountingOutputStream)out).getCount(); + } + + /** + * Protostuff serialization mechanism. + * @param the type of object + * @param out the output stream + * @param obj the object + * @param schema the schema + * @throws IOException something wicked this way comes + */ + public abstract void writeTo(OutputStream out, T obj, Schema schema) throws IOException; + + /** + * {@inheritDoc} + */ + @Override + public T deserialize(InputStream in, Class type) throws IOException { + in = new BufferedInputStream(in, getBufferSize()); + T obj = Construction.construct(type); + Schema schema = RuntimeSchema.getSchema(type); + mergeFrom(in, obj, schema); + return obj; + } + + /** + * Protostuff deserialization mechanism. + * @param the type of object + * @param in the input stream + * @param obj the object + * @param schema the schema + * @throws IOException something wicked this way comes + */ + public abstract void mergeFrom(InputStream in, T obj, Schema schema) throws IOException; + +} diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/GraphProtostuffSerializer.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/GraphProtostuffSerializer.java new file mode 100644 index 000000000..4b902e2bc --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/GraphProtostuffSerializer.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.format; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.switchyard.serial.FormatType; + +import com.dyuproject.protostuff.GraphIOUtil; +import com.dyuproject.protostuff.LinkedBuffer; +import com.dyuproject.protostuff.Schema; + +/** + * A Protostuff serializer that performs {@link FormatType.GRAPH_PROTOSTUFF} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class GraphProtostuffSerializer extends BaseProtostuffSerializer { + + /** + * Default constructor. + */ + public GraphProtostuffSerializer() { + super(FormatType.GRAPH_PROTOSTUFF); + } + + /** + * {@inheritDoc} + */ + @Override + public void writeTo(OutputStream out, T obj, Schema schema) throws IOException { + try { + GraphIOUtil.writeTo(out, obj, schema, LinkedBuffer.allocate(getBufferSize())); + out.flush(); + } finally { + if (isCloseEnabled()) { + out.close(); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mergeFrom(InputStream in, T obj, Schema schema) throws IOException { + try { + GraphIOUtil.mergeFrom(in, obj, schema, LinkedBuffer.allocate(getBufferSize())); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + } + +} diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/JSONProtostuffSerializer.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/JSONProtostuffSerializer.java new file mode 100644 index 000000000..93652dc0d --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/JSONProtostuffSerializer.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.format; + +/** + * A Protostuff serializer that performs {@link org.switchyard.serial.FormatType.JSON} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class JSONProtostuffSerializer extends BaseJSONProtostuffSerializer { + + /** + * Default constructor. + */ + public JSONProtostuffSerializer() { + super(false); + } + +} diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/NativeProtostuffSerializer.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/NativeProtostuffSerializer.java new file mode 100644 index 000000000..3949996e5 --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/NativeProtostuffSerializer.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.format; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.switchyard.serial.FormatType; + +import com.dyuproject.protostuff.LinkedBuffer; +import com.dyuproject.protostuff.ProtostuffIOUtil; +import com.dyuproject.protostuff.Schema; + +/** + * A Protostuff serializer that performs {@link FormatType.NATIVE_PROTOSTUFF} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class NativeProtostuffSerializer extends BaseProtostuffSerializer { + + /** + * Default constructor. + */ + public NativeProtostuffSerializer() { + super(FormatType.NATIVE_PROTOSTUFF); + } + + /** + * {@inheritDoc} + */ + @Override + public void writeTo(OutputStream out, T obj, Schema schema) throws IOException { + try { + ProtostuffIOUtil.writeTo(out, obj, schema, LinkedBuffer.allocate(getBufferSize())); + out.flush(); + } finally { + if (isCloseEnabled()) { + out.close(); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mergeFrom(InputStream in, T obj, Schema schema) throws IOException { + try { + ProtostuffIOUtil.mergeFrom(in, obj, schema, LinkedBuffer.allocate(getBufferSize())); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + } + +} diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/NumericJSONProtostuffSerializer.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/NumericJSONProtostuffSerializer.java new file mode 100644 index 000000000..b1c034859 --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/NumericJSONProtostuffSerializer.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.format; + +/** + * A Protostuff serializer that performs {@link org.switchyard.serial.FormatType.JSON_NUMERIC} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class NumericJSONProtostuffSerializer extends BaseJSONProtostuffSerializer { + + /** + * Default constructor. + */ + public NumericJSONProtostuffSerializer() { + super(true); + } + +} diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/ProtobufProtostuffSerializer.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/ProtobufProtostuffSerializer.java new file mode 100644 index 000000000..e1f963527 --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/ProtobufProtostuffSerializer.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.format; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.switchyard.serial.FormatType; + +import com.dyuproject.protostuff.LinkedBuffer; +import com.dyuproject.protostuff.ProtobufIOUtil; +import com.dyuproject.protostuff.Schema; + +/** + * A Protostuff serializer that performs {@link FormatType.PROTOBUF} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class ProtobufProtostuffSerializer extends BaseProtostuffSerializer { + + /** + * Default constructor. + */ + public ProtobufProtostuffSerializer() { + super(FormatType.PROTOBUF); + } + + /** + * {@inheritDoc} + */ + @Override + public void writeTo(OutputStream out, T obj, Schema schema) throws IOException { + try { + ProtobufIOUtil.writeTo(out, obj, schema, LinkedBuffer.allocate(getBufferSize())); + out.flush(); + } finally { + if (isCloseEnabled()) { + out.close(); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mergeFrom(InputStream in, T obj, Schema schema) throws IOException { + try { + ProtobufIOUtil.mergeFrom(in, obj, schema, LinkedBuffer.allocate(getBufferSize())); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + } + +} diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/XMLProtostuffSerializer.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/XMLProtostuffSerializer.java new file mode 100644 index 000000000..5900d53b1 --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/format/XMLProtostuffSerializer.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.format; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.switchyard.serial.FormatType; + +import com.dyuproject.protostuff.Schema; +import com.dyuproject.protostuff.XmlIOUtil; + +/** + * A Protostuff serializer that performs {@link FormatType.XML_PROTOSTUFF} serialization/deserialization. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class XMLProtostuffSerializer extends BaseProtostuffSerializer { + + /** + * Default constructor. + */ + public XMLProtostuffSerializer() { + super(FormatType.XML_PROTOSTUFF); + } + + /** + * {@inheritDoc} + */ + @Override + public void writeTo(OutputStream out, T obj, Schema schema) throws IOException { + try { + XmlIOUtil.writeTo(out, obj, schema); + out.flush(); + } finally { + if (isCloseEnabled()) { + out.close(); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void mergeFrom(InputStream in, T obj, Schema schema) throws IOException { + try { + XmlIOUtil.mergeFrom(in, obj, schema); + } finally { + if (isCloseEnabled()) { + in.close(); + } + } + } + +} diff --git a/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/spi/ProtostuffSerializationProvider.java b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/spi/ProtostuffSerializationProvider.java new file mode 100644 index 000000000..d173937ea --- /dev/null +++ b/core/serial/protostuff/src/main/java/org/switchyard/serial/protostuff/spi/ProtostuffSerializationProvider.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff.spi; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.protostuff.format.GraphProtostuffSerializer; +import org.switchyard.serial.protostuff.format.JSONProtostuffSerializer; +import org.switchyard.serial.protostuff.format.NativeProtostuffSerializer; +import org.switchyard.serial.protostuff.format.NumericJSONProtostuffSerializer; +import org.switchyard.serial.protostuff.format.ProtobufProtostuffSerializer; +import org.switchyard.serial.protostuff.format.XMLProtostuffSerializer; +import org.switchyard.serial.spi.SerializationProvider; + +/** + * Protostuff serialization provider. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class ProtostuffSerializationProvider extends SerializationProvider { + + private static final Map> MAP; + static { + Map> map = new LinkedHashMap>(); + map.put(FormatType.GRAPH_PROTOSTUFF, GraphProtostuffSerializer.class); + map.put(FormatType.JSON, JSONProtostuffSerializer.class); + map.put(FormatType.JSON_NUMERIC, NumericJSONProtostuffSerializer.class); + map.put(FormatType.NATIVE_PROTOSTUFF, NativeProtostuffSerializer.class); + map.put(FormatType.PROTOBUF, ProtobufProtostuffSerializer.class); + map.put(FormatType.XML_PROTOSTUFF, XMLProtostuffSerializer.class); + MAP = Collections.unmodifiableMap(map); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getSupportedFormats() { + return MAP.keySet(); + } + + /** + * {@inheritDoc} + */ + @Override + public Serializer newSerializer(FormatType format) { + Class c = MAP.get(format); + return c != null ? Construction.construct(c) : null; + } + +} diff --git a/core/serial/protostuff/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider b/core/serial/protostuff/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider new file mode 100644 index 000000000..feba36277 --- /dev/null +++ b/core/serial/protostuff/src/main/resources/META-INF/services/org.switchyard.serial.spi.SerializationProvider @@ -0,0 +1 @@ +org.switchyard.serial.protostuff.spi.ProtostuffSerializationProvider diff --git a/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffComparisonSerializationTest.java b/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffComparisonSerializationTest.java new file mode 100644 index 000000000..437221603 --- /dev/null +++ b/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffComparisonSerializationTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.serial.CompressionType; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Car; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Person; + +/** + * Tests various serializers, using both a passed in object, and a mapped object, uncompressed and compressed. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public final class ProtostuffComparisonSerializationTest { + + @Test + public void testSerialization() throws Exception { + for (FormatType format : FormatType.values()) { + doTest(format); + } + } + + private void doTest(FormatType format) throws Exception { + doRun(SerializerFactory.create(format, null, false), 0, false); + doRun(SerializerFactory.create(format, CompressionType.ZIP, false), 4, false); + doRun(SerializerFactory.create(format, CompressionType.GZIP, false), 4, false); + doRun(SerializerFactory.create(format, null, true), 4, false); + doRun(SerializerFactory.create(format, CompressionType.ZIP, true), 8, false); + doRun(SerializerFactory.create(format, CompressionType.GZIP, true), 8, true); + } + + private void doRun(Serializer serializer, int spaces, boolean newline) throws Exception { + //serializer.setPrettyPrint(true); + Car car = new Car(new Person("Dave")); + long start = System.currentTimeMillis(); + byte[] bytes = serializer.serialize(car, Car.class); + //System.out.println(new String(bytes)); + car = serializer.deserialize(bytes, Car.class); + long stop = System.currentTimeMillis(); + boolean debug = false; // toggle this is you're interested in performance + if (debug) { + StringBuilder sb = new StringBuilder(); + for (int i=0; i < spaces; i++) { + sb.append(' '); + } + sb.append(serializer.getClass().getSimpleName()); + sb.append(": "); + sb.append(bytes.length); + sb.append(" bytes serialized and deserialized in "); + sb.append(stop - start); + sb.append(" milliseconds"); + if (newline) { + sb.append("\n"); + } + System.out.println(sb); + } + Assert.assertEquals("Dave", car.getDriver().getNickName()); + } + +} diff --git a/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffComplexSerializationTest.java b/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffComplexSerializationTest.java new file mode 100644 index 000000000..da38b0d88 --- /dev/null +++ b/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffComplexSerializationTest.java @@ -0,0 +1,293 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff; + +import java.io.StringReader; +import java.lang.reflect.UndeclaredThrowableException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.HandlerException; +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.serial.FormatType; +import org.switchyard.serial.Serializer; +import org.switchyard.serial.SerializerFactory; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Antennae; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Car; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.CustomPart; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.ExpiredPart; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.FlatTireException; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.FluentTitle; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Name; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.OutOfGasException; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Part; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Person; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.StrictTitle; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Title; +import org.switchyard.serial.protostuff.ProtostuffSerializationData.Wheel; +import org.w3c.dom.Element; + +/** + * Tests more complex de/serialization scenarios. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class ProtostuffComplexSerializationTest { + + private T serDeser(T object, Class clazz) throws Exception { + Serializer ser = SerializerFactory.create(FormatType.JSON, null, true); + //ser.setPrettyPrint(true); + byte[] bytes = ser.serialize(object, clazz); + //System.out.println(new String(bytes)); + return ser.deserialize(bytes, clazz); + } + + @Test + public void testSpecificArray() throws Exception { + Car car = new Car(); + car.setPassengers(new Person[] {new Person("passengerA"), new Person("passengerB")}); + car = serDeser(car, Car.class); + Assert.assertEquals(2, car.getPassengers().length); + Assert.assertEquals("passengerB", car.getPassengers()[1].getNickName()); + } + + @Test + public void testPolymorphicArray() throws Exception { + Car car = new Car(); + car.setCheapParts(new Part[] {new Wheel(), new CustomPart(true)}); + car = serDeser(car, Car.class); + Assert.assertEquals(2, car.getCheapParts().length); + Assert.assertEquals(true, car.getCheapParts()[1].isReplaceable()); + } + + @Test + public void testPolymorphicCollection() throws Exception { + Car car = new Car(); + Collection ep = new ArrayList(); + for (int i=0; i < 4; i++) { + ep.add(new Wheel()); + } + ep.add(new CustomPart(false)); + car.setExpensiveParts(ep); + car = serDeser(car, Car.class); + Assert.assertEquals(5, car.getExpensiveParts().size()); + List list = new ArrayList(car.getExpensiveParts()); + Assert.assertEquals(true, list.get(3).isReplaceable()); + Assert.assertEquals(false, list.get(4).isReplaceable()); + } + + @Test + public void testSpecificUnsupportedType() throws Exception { + ExpiredPart part = new ExpiredPart(new Date()); + part = serDeser(part, ExpiredPart.class); + Assert.assertNull(part); + } + + @Test + public void testUnsupportedTypeArray() throws Exception { + Car car = new Car(); + car.setCheapParts(new Part[] {new Wheel(), new ExpiredPart(new Date())}); + car = serDeser(car, Car.class); + Assert.assertEquals(1, car.getCheapParts().length); + } + + @Test + public void testUnsupportedTypeCollection() throws Exception { + Car car = new Car(); + Collection ep = new ArrayList(); + for (int i=0; i < 4; i++) { + ep.add(new Wheel()); + } + ep.add(new ExpiredPart(new Date())); + car.setExpensiveParts(ep); + car = serDeser(car, Car.class); + Assert.assertEquals(4, car.getExpensiveParts().size()); + } + + @Test + @SuppressWarnings("unchecked") + public void testUnsupportedTypeMap() throws Exception { + Map map = new HashMap(); + map.put("wheel", new Wheel()); + map.put("crank", new ExpiredPart(new Date())); + map = serDeser(map, Map.class); + Assert.assertEquals(1, map.size()); + } + + @Test + public void testCircularReferences() throws Exception { + Name bob = new Name("Bob", "Bobby", "Bobson"); + Person me = new Person("me", bob); + Person bff = new Person("bff", bob); + me.setBestFriend(bff); + bff.setBestFriend(me); + Person mom = new Person("mom"); + Person dad = new Person("dad"); + mom.setBestFriend(dad); + dad.setBestFriend(mom); + me.getRelatives().add(mom); + me.getRelatives().add(dad); + mom.getRelatives().add(me); + dad.getRelatives().add(me); + me = serDeser(me, Person.class); + bff = me.getBestFriend(); + Iterator parents = me.getRelatives().iterator(); + mom = parents.next(); + dad = parents.next(); + Assert.assertEquals("me", me.getNickName()); + Assert.assertEquals("Bob", me.getFullName().getFirst()); + Assert.assertEquals("bff", bff.getNickName()); + Assert.assertSame(me.getFullName(), bff.getFullName()); + Assert.assertEquals("mom", mom.getNickName()); + Assert.assertEquals("dad", dad.getNickName()); + Assert.assertSame(me, me.getBestFriend().getBestFriend()); + Assert.assertSame(bff, bff.getBestFriend().getBestFriend()); + Assert.assertSame(me.getFullName(), me.getBestFriend().getBestFriend().getFullName()); + Assert.assertSame(mom, mom.getBestFriend().getBestFriend()); + Assert.assertSame(dad, dad.getBestFriend().getBestFriend()); + Assert.assertSame(me, mom.getRelatives().iterator().next()); + Assert.assertSame(me, dad.getRelatives().iterator().next()); + } + + @Test + public void testDOM() throws Exception { + final String expectedXML = "NY"; + final Element expectedDOM = new ElementPuller().pull(new StringReader(expectedXML)); + Car car = new Car(); + car.setInspection(expectedDOM); + car = serDeser(car, Car.class); + final Element actualDOM = car.getInspection(); + final String actualXML = XMLHelper.toString(actualDOM); + Assert.assertEquals(expectedXML, actualXML); + } + + @Test + public void testBasicExceptions() throws Exception { + final IllegalStateException expectedIllegalStateException = new IllegalStateException("expectedIllegalStateException"); + expectedIllegalStateException.fillInStackTrace(); + final HandlerException expectedHandlerException = new HandlerException(expectedIllegalStateException); + expectedHandlerException.fillInStackTrace(); + final Exception expectedException = new Exception("expectedException", expectedHandlerException); + expectedException.fillInStackTrace(); + final Exception actualException = serDeser(expectedException, Exception.class); + final HandlerException actualHandlerException = (HandlerException)actualException.getCause(); + final IllegalStateException actualIllegalStateException = (IllegalStateException)actualHandlerException.getCause(); + Assert.assertEquals(expectedException.getMessage(), actualException.getMessage()); + Assert.assertEquals(expectedHandlerException.getMessage(), actualHandlerException.getMessage()); + Assert.assertEquals(expectedIllegalStateException.getMessage(), actualIllegalStateException.getMessage()); + Assert.assertEquals(expectedException.getStackTrace().length, actualException.getStackTrace().length); + Assert.assertEquals(expectedHandlerException.getStackTrace().length, actualHandlerException.getStackTrace().length); + Assert.assertEquals(expectedIllegalStateException.getStackTrace().length, actualIllegalStateException.getStackTrace().length); + Assert.assertEquals(expectedHandlerException.isWrapper(), actualHandlerException.isWrapper()); + } + + @Test + public void testCustomExceptions() throws Exception { + final OutOfGasException expectedOutOfGasException = new OutOfGasException("Dagnabit!"); + final FlatTireException expectedFlatTireException = new FlatTireException(new Wheel(Wheel.Location.BACK_RIGHT)); + Car car = new Car(); + car.setProblems(Arrays.asList(new Exception[]{expectedOutOfGasException, expectedFlatTireException})); + car = serDeser(car, Car.class); + final List actualExceptions = car.getProblems(); + final OutOfGasException actualOutOfGasException = (OutOfGasException)actualExceptions.get(0); + final FlatTireException actualFlatTireException = (FlatTireException)actualExceptions.get(1); + Assert.assertEquals(expectedOutOfGasException.getExplicitive(), actualOutOfGasException.getExplicitive()); + Assert.assertSame(expectedFlatTireException.getWheel().getLocation(), actualFlatTireException.getWheel().getLocation()); + Assert.assertEquals("Really?", actualFlatTireException.getMessage()); + } + + @Test + public void testUndeclaredThrowableException() throws Exception { + final UndeclaredThrowableException expectedUndeclaredThrowableException = new UndeclaredThrowableException(new Throwable("undeclared"), "message"); + Car car = new Car(); + car.setProblems(Arrays.asList(new Exception[]{expectedUndeclaredThrowableException, expectedUndeclaredThrowableException})); + car = serDeser(car, Car.class); + final List actualExceptions = car.getProblems(); + final UndeclaredThrowableException actualUndeclaredThrowableException = (UndeclaredThrowableException)actualExceptions.get(0); + final UndeclaredThrowableException sameUndeclaredThrowableException = (UndeclaredThrowableException)actualExceptions.get(1); + Assert.assertSame(actualUndeclaredThrowableException, sameUndeclaredThrowableException); + Assert.assertEquals("message", actualUndeclaredThrowableException.getMessage()); + Assert.assertEquals(expectedUndeclaredThrowableException.getMessage(), actualUndeclaredThrowableException.getMessage()); + Assert.assertEquals(expectedUndeclaredThrowableException.getStackTrace().length, actualUndeclaredThrowableException.getStackTrace().length); + Assert.assertEquals("undeclared", actualUndeclaredThrowableException.getUndeclaredThrowable().getMessage()); + Assert.assertSame(actualUndeclaredThrowableException.getUndeclaredThrowable(), actualUndeclaredThrowableException.getCause()); + } + + @Test + public void testStrictBean() throws Exception { + final UUID id = UUID.randomUUID(); + Car car = new Car(); + StrictTitle title = new StrictTitle(); + title.setId(id); + title.setState("NY"); + title.setLiened(true); + car.setTitle(title); + car = serDeser(car, Car.class); + Assert.assertEquals(id, car.getTitle().getId()); + Assert.assertEquals("NY", car.getTitle().getState()); + Assert.assertTrue(car.getTitle().isLiened()); + } + + @Test + public void testFluentBean() throws Exception { + final UUID id = UUID.randomUUID(); + Car car = new Car(); + Title title = new FluentTitle().setId(id).setState("NY").setLiened(true); + car.setTitle(title); + car = serDeser(car, Car.class); + Assert.assertEquals(id, car.getTitle().getId()); + Assert.assertEquals("NY", car.getTitle().getState()); + Assert.assertTrue(car.getTitle().isLiened()); + } + + @Test + public void testEmptyBean() throws Exception { + Car car = new Car(); + Antennae antennae = new Antennae(); + car.setAntennae(antennae); + car = serDeser(car, Car.class); + antennae = car.getAntennae(); + Assert.assertNotNull(antennae); + } + + @Test + public void testDuplicateValues() throws Exception { + Name name = new Name("me", "me", "me"); + name = serDeser(name, Name.class); + Assert.assertEquals("me", name.getFirst()); + Assert.assertEquals("me", name.getMiddle()); + Assert.assertEquals("me", name.getLast()); + name = new Name("you", null, "you"); + name = serDeser(name, Name.class); + Assert.assertEquals("you", name.getFirst()); + Assert.assertNull(name.getMiddle()); + Assert.assertEquals("you", name.getLast()); + name = new Name("him", "her", null); + name = serDeser(name, Name.class); + Assert.assertEquals("him", name.getFirst()); + Assert.assertEquals("her", name.getMiddle()); + Assert.assertNull(name.getLast()); + } + +} diff --git a/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffSerializationData.java b/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffSerializationData.java new file mode 100644 index 000000000..f6fe62474 --- /dev/null +++ b/core/serial/protostuff/src/test/java/org/switchyard/serial/protostuff/ProtostuffSerializationData.java @@ -0,0 +1,349 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.serial.protostuff; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.switchyard.serial.graph.AccessType; +import org.switchyard.serial.graph.Strategy; +import org.w3c.dom.Element; + +/** + * Data for tests. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@SuppressWarnings("serial") +public final class ProtostuffSerializationData { + + public static final class Name implements Serializable { + private String _first; + private String _middle; + private String _last; + public Name() {} + public Name(String first, String middle, String last) { + setFirst(first).setMiddle(middle).setLast(last); + } + public String getFirst() { + return _first; + } + public Name setFirst(String first) { + _first = first; + return this; + } + public String getMiddle() { + return _middle; + } + public Name setMiddle(String middle) { + _middle = middle; + return this; + } + public String getLast() { + return _last; + } + public Name setLast(String last) { + _last = last; + return this; + } + public String toString() { + return "Name@" + System.identityHashCode(this) + "(first=" + getFirst() + ", middle=" + getMiddle() + ", last=" + getLast() + ")"; + } + } + + public static final class Person implements Serializable { + private String _nickName; + private Name _fullName; + private Person _bestFriend; + private Collection _relatives = new ArrayList(); + public Person() {} + public Person(String nickName) { + setNickName(nickName); + } + public Person(Name fullName) { + setFullName(fullName); + } + public Person(String nickName, Name fullName) { + setNickName(nickName); + setFullName(fullName); + } + public String getNickName() { + return _nickName; + } + public void setNickName(String nickName) { + _nickName = nickName; + } + public Name getFullName() { + return _fullName; + } + public void setFullName(Name fullName) { + _fullName = fullName; + } + public Person getBestFriend() { + return _bestFriend; + } + public void setBestFriend(Person bestFriend) { + _bestFriend = bestFriend; + } + public Collection getRelatives() { + return _relatives; + } + public void setRelatives(Collection relatives) { + _relatives = relatives; + } + public String toString() { + return "Person@" + System.identityHashCode(this) + "(nickName=" + getNickName() + ", fullName=" + getFullName() + ", bestFriend=" + (_bestFriend != null ? _bestFriend.getNickName() : "") + ", relatives=" + getRelatives().size() + ")"; + } + } + + public static final class Car implements Serializable { + private Person _driver; + private Person[] _passengers; + private Title _title; + private Part[] _cheapParts; + private Collection _expensiveParts; + private Element _inspection; + private List _problems; + private Antennae _antennae; + public Car() {} + public Car(Person driver) { + setDriver(driver); + } + public Person getDriver() { + return _driver; + } + public void setDriver(Person driver) { + _driver = driver; + } + public Person[] getPassengers() { + return _passengers; + } + public void setPassengers(Person[] passengers) { + _passengers = passengers; + } + public Title getTitle() { + return _title; + } + public void setTitle(Title title) { + _title = title; + } + public Part[] getCheapParts() { + return _cheapParts; + } + public void setCheapParts(Part[] cheapParts) { + _cheapParts = cheapParts; + } + public Collection getExpensiveParts() { + return _expensiveParts; + } + public void setExpensiveParts(Collection expensiveParts) { + _expensiveParts = expensiveParts; + } + public Element getInspection() { + return _inspection; + } + public void setInspection(Element inspection) { + _inspection = inspection; + } + public List getProblems() { + return _problems; + } + public void setProblems(List problems) { + _problems = problems; + } + public Antennae getAntennae() { + return _antennae; + } + public void setAntennae(Antennae antennae) { + _antennae = antennae; + } + public String toString() { + return "Car@" + System.identityHashCode(this) + "(driver=" + getDriver() + ", passengers=" + Arrays.toString(getPassengers()) + ", cheapParts=" + Arrays.toString(getCheapParts()) + ", expensiveParts=" + getExpensiveParts() + ", inspection=" + getInspection() + ", problems=" + getProblems() + ")"; + } + } + + public static interface Title { + public UUID getId(); + public String getState(); + public boolean isLiened(); + } + + public static final class StrictTitle implements Title { + private UUID _id; + private String _state; + private boolean _liened; + public StrictTitle() {} + public UUID getId() { + return _id; + } + public void setId(UUID id) { + _id = id; + } + public String getState() { + return _state; + } + public void setState(String state) { + _state = state; + } + public boolean isLiened() { + return _liened; + } + public void setLiened(boolean liened) { + _liened = liened; + } + public String toString() { + return "StrictTitle@" + System.identityHashCode(this) + "(id=" + getId() + ", state=" + getState() + ", liened" + isLiened() + ")"; + } + } + + public static final class FluentTitle implements Title { + private UUID _id; + private String _state; + private boolean _liened; + public FluentTitle() {} + public UUID getId() { + return _id; + } + // purposely returns the implementation type, for the sake of the test + public FluentTitle setId(UUID id) { + _id = id; + return this; + } + public String getState() { + return _state; + } + // purposely returns the implementation type, for the sake of the test + public FluentTitle setState(String state) { + _state = state; + return this; + } + public boolean isLiened() { + return _liened; + } + // purposely returns the interface type, for the sake of the test + public Title setLiened(boolean liened) { + _liened = liened; + return this; + } + public String toString() { + return "FluentTitle@" + System.identityHashCode(this) + "(id=" + getId() + ", state=" + getState() + ", liened" + isLiened() + ")"; + } + } + + public static interface Part { + public boolean isReplaceable(); + } + + @Strategy(access=AccessType.FIELD) + public static final class Wheel implements Part { + private Location _location; + public Wheel() { + this(Location.UNSPECIFIED); + } + public Wheel(Location location) { + _location = location; + } + public boolean isReplaceable() { + return true; + } + public Location getLocation() { + return _location; + } + public String toString() { + return "Wheel(replaceable=" + isReplaceable() + ", location=" + getLocation() + ")"; + } + public static enum Location { + UNSPECIFIED, FRONT_LEFT, FRONT_RIGHT, BACK_LEFT, BACK_RIGHT; + } + } + + public static final class CustomPart implements Part { + private boolean _replaceable; + public CustomPart() {} + public CustomPart(boolean replaceable) { + setReplaceable(replaceable); + } + public boolean isReplaceable() { + return _replaceable; + } + public void setReplaceable(boolean replaceable) { + _replaceable = replaceable; + } + public String toString() { + return "CustomPart@" + System.identityHashCode(this) + "(replaceable=" + isReplaceable() + ")"; + } + } + + public static final class ExpiredPart implements Part { + private Date _expiredDate; + public ExpiredPart(Date expiredDate) { + _expiredDate = expiredDate; + } + public boolean isReplaceable() { + return false; + } + public Date getExpiredDate() { + return _expiredDate; + } + public String toString() { + return "BadPart@" + System.identityHashCode(this) + "(replaceable=" + isReplaceable() + ", expiredDate=" + getExpiredDate() + ")"; + } + } + + public static final class Antennae implements Serializable { + public String toString() { + return "Antennae@" + System.identityHashCode(this); + } + } + + public static final class OutOfGasException extends Exception { + private String _explicitive; + public OutOfGasException() { + super(); + } + public OutOfGasException(String explicitive) { + super(); + setExplicitive(explicitive); + } + public String getExplicitive() { + return _explicitive; + } + public void setExplicitive(String explicitive) { + _explicitive = explicitive; + } + } + + @Strategy(access=AccessType.FIELD) + public static final class FlatTireException extends Exception { + private Wheel _wheel; + public FlatTireException() { + super("Really?"); + } + public FlatTireException(Wheel wheel) { + super(); + _wheel = wheel; + } + public Wheel getWheel() { + return _wheel; + } + } + + private ProtostuffSerializationData() {} + +} diff --git a/core/serial/protostuff/src/test/resources/log4j.properties b/core/serial/protostuff/src/test/resources/log4j.properties new file mode 100644 index 000000000..02a249c1d --- /dev/null +++ b/core/serial/protostuff/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootCategory=INFO, CONSOLE + +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=DEBUG +log4j.appender.CONSOLE.Target=System.out +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p [%c{1}] %m%n diff --git a/core/test/Readme.md b/core/test/Readme.md new file mode 100644 index 000000000..8a92c0090 --- /dev/null +++ b/core/test/Readme.md @@ -0,0 +1,4 @@ +# SwitchYard Test Utilities +This module contains a test utilities for SwitchYard. Things like MockHandlers, TestRunners and TestMixins are +all contained in this module. + diff --git a/core/test/pom.xml b/core/test/pom.xml new file mode 100644 index 000000000..c24053f8b --- /dev/null +++ b/core/test/pom.xml @@ -0,0 +1,81 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-test + jar + SwitchYard: Test Utilities + Test Utility classes. + http://switchyard.org + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-transform + + + + junit + junit + compile + + + xmlunit + xmlunit + + + org.jboss.weld.se + weld-se-core + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + org.slf4j + slf4j-ext + + + diff --git a/core/test/src/main/java/org/switchyard/test/BeforeDeploy.java b/core/test/src/main/java/org/switchyard/test/BeforeDeploy.java new file mode 100644 index 000000000..0d44daeda --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/BeforeDeploy.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Indicate the method to be invoked before deploy SwitchYard application. + * + * @author Tomohisa Igarashi + */ +@Target({METHOD}) +@Retention(RUNTIME) +@Documented +public @interface BeforeDeploy { +} diff --git a/core/test/src/main/java/org/switchyard/test/InvocationFaultException.java b/core/test/src/main/java/org/switchyard/test/InvocationFaultException.java new file mode 100644 index 000000000..02517e371 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/InvocationFaultException.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import org.switchyard.Message; + +/** + * Represents an exchange fault in the form of an exception. Invoker will + * throw an InvocationFaultException when a message exchange results in a + * fault message.

+ * NOTE : InvocationFaultException is an unchecked Exception so that test methods + * that don't care about handling it explicitly (e.g. exception = automatic failure) + * are not required to code try/catch or declare a throws. + */ +public class InvocationFaultException extends RuntimeException { + + private static final long serialVersionUID = 4261226339096599247L; + + private Message _faultMessage; + + /** + * Create a new InvocationFaultException based on the specified fault message. + * @param faultMessage fault message + */ + public InvocationFaultException(Message faultMessage) { + super(); + _faultMessage = faultMessage; + } + + /** + * Return the underlying fault message. + * @return fault message + */ + public Message getFaultMessage() { + return _faultMessage; + } + + /** + * Determines if the content of the underlying fault message matches the + * specified type. If the content is an exception, we traverse the parent + * graph to see if any of the exceptions match the specified type. + * @param type expected type + * @return true if the fault content is of the specified type, false otherwise + */ + public boolean isType(Class type) { + if (Throwable.class.isAssignableFrom(_faultMessage.getContent().getClass())) { + Throwable t = _faultMessage.getContent(Throwable.class); + for (; t != null; t = t.getCause()) { + if (t.getClass().isAssignableFrom(type)) { + return true; + } + } + } + // not a nested throwable, so see if it matches directly + return _faultMessage.getContent().getClass().isAssignableFrom(type); + } + + @Override + public Throwable getCause() { + if (Throwable.class.isAssignableFrom(_faultMessage.getContent().getClass())) { + return _faultMessage.getContent(Throwable.class); + } else { + return super.getCause(); + } + } +} diff --git a/core/test/src/main/java/org/switchyard/test/Invoker.java b/core/test/src/main/java/org/switchyard/test/Invoker.java new file mode 100644 index 000000000..89527f6ac --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/Invoker.java @@ -0,0 +1,433 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +import javax.activation.DataSource; +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.ExchangeHandler; +import org.switchyard.ExchangePattern; +import org.switchyard.ExchangeState; +import org.switchyard.HandlerException; +import org.switchyard.Message; +import org.switchyard.Scope; +import org.switchyard.ServiceDomain; +import org.switchyard.ServiceReference; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.metadata.BaseService; +import org.switchyard.metadata.InOnlyOperation; +import org.switchyard.metadata.InOutOperation; +import org.switchyard.metadata.ServiceOperation; + +/** + * Unit Test Invoker. + * + * @author tom.fennelly@gmail.com + */ +public class Invoker { + + private ServiceDomain _domain; + private QName _serviceName; + private String _operationName; + private ServiceOperation _serviceOperation; + private ExchangeHandlerProxy _exchangeHandlerProxy; + private long _timeoutMillis = 10000; + private QName _inputType; + private QName _expectedOutputType; + private QName _expectedFaultType; + private Map> _properties = new HashMap>(); + private Map _attachments = new HashMap(); + + /** + * Protected invoker. + * @param domain The ServiceDomain. + * @param serviceName The Service name. + */ + protected Invoker(ServiceDomain domain, String serviceName) { + this(domain, XMLHelper.createQName(domain.getName().getNamespaceURI(), serviceName)); + } + + /** + * Protected invoker. + * @param domain The ServiceDomain. + * @param serviceName The Service name. + */ + public Invoker(ServiceDomain domain, QName serviceName) { + _domain = domain; + + String[] serviceNameTokens = serviceName.getLocalPart().split("\\."); + + if (serviceNameTokens.length == 1) { + _serviceName = serviceName; + } else if (serviceNameTokens.length == 2) { + _serviceName = XMLHelper.createQName(serviceName.getNamespaceURI(), serviceNameTokens[0]); + _operationName = serviceNameTokens[1]; + } else if (serviceNameTokens.length >= 3) { + // in case the service name contains dot + String serviceOpName = serviceName.getLocalPart(); + int operDotIndex = serviceOpName.lastIndexOf('.'); + _serviceName = XMLHelper.createQName(serviceName.getNamespaceURI(), serviceOpName.substring(0, operDotIndex)); + _operationName = serviceOpName.substring(operDotIndex+1); + } + } + + /** + * Get the target Service Name. + * @return The target Service Name. + */ + public QName getServiceName() { + return _serviceName; + } + + /** + * Get the target Operation Name. + * @return The target Operation Name. + */ + public String getOperationName() { + return _operationName; + } + + /** + * Set the target operation name. + * @param operationName The operation name. + * @return This invoker instance. + */ + public Invoker operation(String operationName) { + _operationName = operationName; + return this; + } + + /** + * Set the target operation. + * @param serviceOperation The target operation. + * @return This invoker instance. + */ + public Invoker operation(ServiceOperation serviceOperation) { + _serviceOperation = serviceOperation; + return this; + } + + /** + * Set the response handler. + * @param handler The response handler. + * @return This invoker instance. + */ + public Invoker responseHandler(ExchangeHandler handler) { + if (handler != null) { + _exchangeHandlerProxy = createHandlerProxy(handler); + } + return this; + } + + /** + * Set the timeout for in-out invocations. + *

+ * Default is 10000ms (10s). + * + * @param timeoutMillis The timeout time in milliseconds. + * @return This invoker instance. + */ + public Invoker timeout(long timeoutMillis) { + _timeoutMillis = timeoutMillis; + return this; + } + + /** + * Set the input type for the exchange contract. + *

+ * Not relevant if an {@link #contract ExchangeContract is set} on this Invoker instance. + * + * @param inputType The input type for the exchange contract. + * @return This invoker instance. + */ + public Invoker inputType(QName inputType) { + _inputType = inputType; + return this; + } + + /** + * Set the output type for the exchange contract. + *

+ * Not relevant if an {@link #contract ExchangeContract is set} on this Invoker instance. + * + * @param expectedOutputType The output type for the exchange contract. + * @return This invoker instance. + */ + public Invoker expectedOutputType(QName expectedOutputType) { + _expectedOutputType = expectedOutputType; + return this; + } + + /** + * Set the expected fault type for the exchange contract. + *

+ * Not relevant if an {@link #contract ExchangeContract is set} on this Invoker instance. + * + * @param expectedFaultType The expected fault type for the exchange contract. + * @return This invoker instance. + */ + public Invoker expectedFaultType(QName expectedFaultType) { + _expectedFaultType = expectedFaultType; + return this; + } + + /** + * Sets a property at {@link Scope.MESSAGE}. + * @param name the name + * @param value the value + * @return This invoker instance. + */ + public Invoker property(String name, Object value) { + return property(name, value, null); + } + + /** + * Sets a property at the specified scope. + * @param name the name + * @param value the value + * @param scope the scope + * @return This invoker instance. + */ + public Invoker property(String name, Object value, Scope scope) { + if (name != null) { + if (scope == null) { + scope = Scope.MESSAGE; + } + Map map = _properties.get(scope); + if (map == null) { + map = new HashMap(); + _properties.put(scope, map); + } + if (value != null) { + map.put(name, value); + } else { + map.remove(name); + } + } + return this; + } + + private void setProperties(Exchange exchange, Message message) { + Context exchangeContext = exchange.getContext(); + Map exchangeProperties = _properties.get(Scope.EXCHANGE); + if (exchangeProperties != null) { + for (Map.Entry exchangeProperty : exchangeProperties.entrySet()) { + exchangeContext.setProperty(exchangeProperty.getKey(), exchangeProperty.getValue(), Scope.EXCHANGE); + } + } + Context messageContext = exchange.getContext(message); + Map messageProperties = _properties.get(Scope.MESSAGE); + if (messageProperties != null) { + for (Map.Entry messageProperty : messageProperties.entrySet()) { + messageContext.setProperty(messageProperty.getKey(), messageProperty.getValue(), Scope.MESSAGE); + } + } + } + + /** + * Adds an attachment for created Messages. + * @param name the name of the attachment + * @param attachment the attachment + * @return This invoker instance. + */ + public Invoker attachment(String name, DataSource attachment) { + if (name == null) { + name = attachment.getName(); + } + if (name != null) { + if (attachment != null) { + _attachments.put(name, attachment); + } else { + _attachments.remove(name); + } + } + return this; + } + + private void addAttachments(Message message) { + for (Map.Entry entry : _attachments.entrySet()) { + message.addAttachment(entry.getKey(), entry.getValue()); + } + } + + /** + * Send an IN_ONLY message to the target Service. + * @param messagePayload The message payload. + * @throws InvocationFaultException if the message exchange produces a fault + */ + public void sendInOnly(Object messagePayload) throws InvocationFaultException { + ExchangeHandlerProxy exchangeHandlerProxy = _exchangeHandlerProxy; + ResponseCatcher responseCatcher = null; + + if (exchangeHandlerProxy == null) { + responseCatcher = new ResponseCatcher(); + exchangeHandlerProxy = createHandlerProxy(responseCatcher); + } + + Exchange exchange = createExchange(ExchangePattern.IN_ONLY, exchangeHandlerProxy._exchangeHandlerProxy); + + Message message = exchange.createMessage().setContent(messagePayload); + setProperties(exchange, message); + addAttachments(message); + exchange.send(message); + + if (exchange.getState().equals(ExchangeState.FAULT)) { + throw new InvocationFaultException(exchange.getMessage()); + } + } + + /** + * Send an IN_OUT message to the target Service. + * @param messagePayload The message payload. + * @return The response message. + * @throws InvocationFaultException if the message exchange produces a fault + */ + public Message sendInOut(Object messagePayload) throws InvocationFaultException { + ExchangeHandlerProxy exchangeHandlerProxy = _exchangeHandlerProxy; + ResponseCatcher responseCatcher = null; + + if (exchangeHandlerProxy == null) { + responseCatcher = new ResponseCatcher(); + exchangeHandlerProxy = createHandlerProxy(responseCatcher); + } + + Exchange exchange = createExchange(ExchangePattern.IN_OUT, exchangeHandlerProxy._exchangeHandlerProxy); + + Message message = exchange.createMessage().setContent(messagePayload); + setProperties(exchange, message); + addAttachments(message); + exchange.send(message); + exchangeHandlerProxy._proxyInvocationHandler.waitForResponse(_timeoutMillis); + + if (responseCatcher != null) { + if (responseCatcher._isFault) { + throw new InvocationFaultException(responseCatcher._response); + } else { + return responseCatcher._response; + } + } + + return null; + } + + /** + * Create an {@link Exchange} instance for the target service operation. + * @param handler The ExchangeHandler to be used on the Exchange. + * @return The Exchange instance. + */ + public Exchange createExchange(ExchangeHandler handler) { + return createExchange(null, handler); + } + + private Exchange createExchange(ExchangePattern pattern, ExchangeHandler handler) { + + ServiceOperation operation = _serviceOperation; + ServiceReference reference; + + if (operation == null) { + if (ExchangePattern.IN_ONLY.equals(pattern)) { + operation = new InOnlyOperation(_operationName, _inputType); + } else { + operation = new InOutOperation(_operationName, _inputType, _expectedOutputType, _expectedFaultType); + } + } + + reference = _domain.registerServiceReference(_serviceName, new BaseService(operation), handler); + return _operationName == null ? reference.createExchange() : reference.createExchange(_operationName); + } + + private ExchangeHandlerProxy createHandlerProxy(ExchangeHandler handler) { + ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler(handler); + ExchangeHandler exchangeHandlerProxy = (ExchangeHandler) Proxy.newProxyInstance(ExchangeHandler.class.getClassLoader(), + new Class[]{ExchangeHandler.class}, + proxyInvocationHandler); + + return new ExchangeHandlerProxy(proxyInvocationHandler, exchangeHandlerProxy); + } + + private static final class ExchangeHandlerProxy { + private ProxyInvocationHandler _proxyInvocationHandler; + private ExchangeHandler _exchangeHandlerProxy; + + private ExchangeHandlerProxy(ProxyInvocationHandler proxyInvocationHandler, ExchangeHandler exchangeHandlerProxy) { + _proxyInvocationHandler = proxyInvocationHandler; + _exchangeHandlerProxy = exchangeHandlerProxy; + } + } + + private static final class ProxyInvocationHandler implements InvocationHandler { + + private ExchangeHandler _handler; + private boolean _responseReceived; + + public ProxyInvocationHandler(ExchangeHandler handler) { + _handler = handler; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + try { + return method.invoke(_handler, args); + } finally { + if (method.getName().equals("handleMessage") || method.getName().equals("handleFault")) { + _responseReceived = true; + } + } + } + + private void waitForResponse(long timeout) { + long startTime = System.currentTimeMillis(); + while (!_responseReceived) { + if (System.currentTimeMillis() > startTime + timeout) { + // timed out... + Assert.fail("Timed out waiting on response."); + break; + } else { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Assert.fail("Unexpected InterruptedException: " + e.getMessage()); + } + } + } + } + } + + private static final class ResponseCatcher implements ExchangeHandler { + + private Message _response; + private boolean _isFault; + + @Override + public void handleMessage(Exchange exchange) throws HandlerException { + _response = exchange.getMessage(); + } + + @Override + public void handleFault(Exchange exchange) { + _isFault = true; + _response = exchange.getMessage(); + } + } +} diff --git a/core/test/src/main/java/org/switchyard/test/MixInDependencies.java b/core/test/src/main/java/org/switchyard/test/MixInDependencies.java new file mode 100644 index 000000000..1a577a15f --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/MixInDependencies.java @@ -0,0 +1,38 @@ +package org.switchyard.test; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * An annotation to indicate MixIn dependencies. + * + * @author Tomohisa Igarashi + * + */ +@Target({TYPE}) +@Retention(RUNTIME) +@Documented +public @interface MixInDependencies { + + /** + * A list of mixins which must be initialized before the annotated mixin does. + * These mixins will be instantiated by SwitchYardTestKit even if they are not on the + * mixins list of {@link SwitchYardTestCaseConfig} annotation. + */ + Class[] required() default SwitchYardTestKit.NullMixIns.class; + + /** + * A list of mixins which should be initialized before the annotated mixin does + * if they will be used. These mixins will not be instantiated unless they are on the + * mixins list of {@link SwitchYardTestCaseConfig} annotation. + * This option can be used to handle the case like that - the MixInA doesn't always need + * MixInB, but when we use MixInA and MixInB together, MixInB should be initialized first. + * In this case the MixInA should have a optional dependency on MixInB. + */ + Class[] optional() default SwitchYardTestKit.NullMixIns.class; +} diff --git a/core/test/src/main/java/org/switchyard/test/MockHandler.java b/core/test/src/main/java/org/switchyard/test/MockHandler.java new file mode 100644 index 000000000..1fb5abfef --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/MockHandler.java @@ -0,0 +1,228 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import java.util.concurrent.LinkedBlockingQueue; + +import junit.framework.TestCase; + +import org.switchyard.BaseHandler; +import org.switchyard.Exchange; +import org.switchyard.ExchangePattern; +import org.switchyard.HandlerException; + +/** + * Mock Handler. + * + * @author tom.fennelly@gmail.com + */ +public class MockHandler extends BaseHandler { + + private enum Behavior { + FORWARD_IN_TO_OUT, // send the in message as a reply + FORWARD_IN_TO_FAULT, // send the in message as a fault + REPLY_WITH_OUT, // reply with a specific message as out + REPLY_WITH_FAULT}; // reply with a specific message as fault + + /** + * Messages. + */ + private final LinkedBlockingQueue _messages = + new LinkedBlockingQueue(); + + /** + * Faults. + */ + private final LinkedBlockingQueue _faults = + new LinkedBlockingQueue(); + + /** + * Default sleep. + */ + private static final int DEFAULT_SLEEP_MS = 100; + /** + * Default wait timeout. + */ + private static final int DEFAULT_WAIT_TIMEOUT = 5000; + + /** + * Wait timeout value. + */ + private long _waitTimeout = DEFAULT_WAIT_TIMEOUT; // default of 5 seconds + + /** + * Specific content for reply messages/faults. + */ + private Object _replyContent; + + /** + * Handler behavior for replies. + */ + private Behavior _behavior; + + /** + * Constructor. + */ + public MockHandler() { + } + + /** + * @return wait timeout + */ + public long getWaitTimeout() { + return _waitTimeout; + } + + /** + * @param waitTimeout wait timeout + */ + public void setWaitTimeout(long waitTimeout) { + _waitTimeout = waitTimeout; + } + + /** + * Message getter. + * @return messages messages + */ + public LinkedBlockingQueue getMessages() { + return _messages; + } + + /** + * Fault getter. + * @return faults faults + */ + public LinkedBlockingQueue getFaults() { + return _faults; + } + + /** + * Forward input to output. + * @return MockHandler mockhandler + */ + public MockHandler forwardInToOut() { + _behavior = Behavior.FORWARD_IN_TO_OUT; + return this; + } + + /** + * Forward input to fault. + * @return MockHandler mockhandler + */ + public MockHandler forwardInToFault() { + _behavior = Behavior.FORWARD_IN_TO_FAULT; + return this; + } + + /** + * Reply with an out message using the specified content. + * @param content content to reply with + * @return this handler + */ + public MockHandler replyWithOut(Object content) { + _behavior = Behavior.REPLY_WITH_OUT; + _replyContent = content; + return this; + } + + /** + * Reply with a fault message using the specified content. + * @param content content to reply with + * @return this handler + */ + public MockHandler replyWithFault(Object content) { + _behavior = Behavior.REPLY_WITH_FAULT; + _replyContent = content; + return this; + } + + @Override + public void handleMessage(final Exchange exchange) throws HandlerException { + _messages.offer(exchange); + + if (_behavior == null || exchange.getContract().getProviderOperation().getExchangePattern().equals(ExchangePattern.IN_ONLY)) { + return; + } + + switch (_behavior) { + case FORWARD_IN_TO_OUT : + exchange.send(exchange.getMessage().copy()); + break; + case FORWARD_IN_TO_FAULT : + exchange.sendFault(exchange.getMessage().copy()); + break; + case REPLY_WITH_OUT : + exchange.send(exchange.createMessage().setContent(_replyContent)); + break; + case REPLY_WITH_FAULT : + exchange.sendFault(exchange.createMessage().setContent(_replyContent)); + break; + } + } + + @Override + public void handleFault(final Exchange exchange) { + _faults.offer(exchange); + } + + /** + * Wait for a message. + * @return MockHandler mockhandler + */ + public MockHandler waitForOKMessage() { + waitFor(_messages, 1); + return this; + } + + /** + * Wait for a number of messages. + * @return MockHandler mockhandler + */ + public MockHandler waitForFaultMessage() { + waitFor(_faults, 1); + return this; + } + + /** + * Wait for a number of messages. + * @param eventQueue event queue + * @param numMessages number of messages + */ + private void waitFor(final LinkedBlockingQueue eventQueue, + final int numMessages) { + long start = System.currentTimeMillis(); + + while (System.currentTimeMillis() < start + _waitTimeout) { + if (eventQueue.size() >= numMessages) { + return; + } + sleep(); + } + + TestCase.fail("Timed out waiting on event queue length to be " + + numMessages + " or greater."); + } + + /** + * Sleep. + */ + private void sleep() { + try { + Thread.sleep(DEFAULT_SLEEP_MS); + } catch (InterruptedException e) { + TestCase.fail("Failed to sleep: " + e.getMessage()); + } + } +} diff --git a/core/test/src/main/java/org/switchyard/test/ServiceOperation.java b/core/test/src/main/java/org/switchyard/test/ServiceOperation.java new file mode 100644 index 000000000..1f6f5c040 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/ServiceOperation.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Service Operation name. + *

+ * Dot delimited Service operation name ("[service-name].[operation-name]") e.g. "OrderService.createOrder". + * + * @author tom.fennelly@gmail.com + */ +@Target({FIELD}) +@Retention(RUNTIME) +@Documented +public @interface ServiceOperation { + + /** + * Dot delimited Service operation name ("[service-name].[operation-name]"). + */ + String value(); +} diff --git a/core/test/src/main/java/org/switchyard/test/SimpleTestDeployment.java b/core/test/src/main/java/org/switchyard/test/SimpleTestDeployment.java new file mode 100644 index 000000000..45964e64d --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/SimpleTestDeployment.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.Lifecycle; +import org.switchyard.deploy.internal.AbstractDeployment; + +/** + * Simple Test Deployment. + *

+ * Does nothing extra. + * + * @author tom.fennelly@gmail.com + */ +public class SimpleTestDeployment extends AbstractDeployment { + + /** + * Constructor. + * + */ + protected SimpleTestDeployment() { + super(null); + } + + @Override + /* + * Init method. + * + * @param serviceDomain The ServiceDomain that the deployment is a member of. + */ + protected void doInit(List activators) { + } + + @Override + public void start() { + } + + @Override + public void stop() { + } + + @Override + public void destroy() { + if (getDomain() != null) { + getDomain().destroy(); + } + } + + @Override + public Lifecycle getGatwayLifecycle(QName serviceName, String bindingName) { + return null; + } +} diff --git a/core/test/src/main/java/org/switchyard/test/SwitchYardRunner.java b/core/test/src/main/java/org/switchyard/test/SwitchYardRunner.java new file mode 100644 index 000000000..7270e491e --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/SwitchYardRunner.java @@ -0,0 +1,176 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import java.lang.reflect.Field; + +import org.jboss.logging.Logger; +import org.junit.Assert; +import org.junit.runner.Description; +import org.junit.runner.notification.RunListener; +import org.junit.runner.notification.RunNotifier; +import org.junit.runners.BlockJUnit4ClassRunner; +import org.junit.runners.model.InitializationError; +import org.switchyard.common.camel.SwitchYardCamelContext; + +/** + * SwitchYard test runner. + * + * @author tom.fennelly@gmail.com + */ +public class SwitchYardRunner extends BlockJUnit4ClassRunner { + + private static Logger LOG = Logger.getLogger(SwitchYardRunner.class); + private SwitchYardTestKit _testKit; + private Object _testInstance; + + /** + * Creates a SwitchYardRunner to run {@code klass}. + * + * @param clazz Test Class. + * @throws org.junit.runners.model.InitializationError + * if the test class is malformed. + */ + public SwitchYardRunner(Class clazz) throws InitializationError { + super(clazz); + } + + @Override + protected Object createTest() throws Exception { + _testInstance = super.createTest(); + _testKit = new SwitchYardTestKit(_testInstance); + + for (TestMixIn mixIn : _testKit.getMixIns()) { + set(mixIn, PropertyMatchResolution.EQUALS); + } + + try { + _testKit.start(); + } catch (Throwable t) { + LOG.error("Error while test kit startup", t); + _testKit.cleanup(); + throw new Exception(t); + } + + set(_testKit, PropertyMatchResolution.EQUALS); + set(_testKit.getDeployment(), PropertyMatchResolution.ASSIGNABLE); + set(_testKit.getConfigModel(), PropertyMatchResolution.ASSIGNABLE); + set(_testKit.getServiceDomain(), PropertyMatchResolution.ASSIGNABLE); + set(_testKit.getServiceDomain().getTransformerRegistry(), PropertyMatchResolution.ASSIGNABLE); + set(_testKit.getServiceDomain().getProperty(SwitchYardCamelContext.CAMEL_CONTEXT_PROPERTY), PropertyMatchResolution.ASSIGNABLE); + + setInvokers(); + + return _testInstance; + } + + @Override + public void run(RunNotifier notifier) { + TestLifecycleListener listener = new TestLifecycleListener(); + + notifier.addListener(listener); + try { + super.run(notifier); + } finally { + notifier.removeListener(listener); + } + } + + private class TestLifecycleListener extends RunListener { + + @Override + public void testFinished(Description description) throws Exception { + _testKit.cleanup(); + } + } + + private enum PropertyMatchResolution { + ASSIGNABLE { + @Override + public boolean matches(Field field, Object propertyValue) { + return field.getType().isInstance(propertyValue); + } + }, + EQUALS { + @Override + public boolean matches(Field field, Object propertyValue) { + return field.getType() == propertyValue.getClass(); + } + }; + public boolean matches(Field field, Object propertyValue) { + throw new AbstractMethodError(); + } + } + + private void set(Object propertyValue, PropertyMatchResolution matchRes) throws IllegalAccessException { + // check whole class hierarchy recursive + set(_testInstance.getClass(), propertyValue, matchRes); + } + + private void set(Class clazz, Object propertyValue, PropertyMatchResolution matchRes) throws IllegalAccessException { + if (Object.class.equals(clazz) || clazz == null) { + return; + } + + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + if (matchRes.matches(field, propertyValue)) { + setValue(field, propertyValue); + } + } + // check parent class fields + set(clazz.getSuperclass(), propertyValue, matchRes); + } + + private void setValue(Field field, Object propertyValue) throws IllegalAccessException { + boolean accessible = field.isAccessible(); + field.setAccessible(true); + try { + field.set(_testInstance, propertyValue); + } finally { + field.setAccessible(accessible); + } + } + + private void setInvokers() throws IllegalAccessException { + setInvokers(_testInstance.getClass()); + } + + private void setInvokers(Class clazz) throws IllegalAccessException { + if (Object.class.equals(clazz) || clazz == null) { + return; + } + + Field[] fields = clazz.getDeclaredFields(); + for (Field field : fields) { + if (field.getType() == Invoker.class) { + ServiceOperation serviceOp = field.getAnnotation(ServiceOperation.class); + + if (serviceOp == null) { + Assert.fail("Invoker property '" + field.getName() + "' on test class '" + _testInstance.getClass().getName() + "' needs to be annotated with a @ServiceOperation."); + } + + Invoker invoker = _testKit.newInvoker(serviceOp.value()); + + if (invoker == null) { + Assert.fail("Invoker property '" + field.getName() + "' on test class '" + _testInstance.getClass().getName() + "' contains an a @ServiceOperation defining an unknown Service Operation value '" + serviceOp.value() + "'."); + } + + setValue(field, invoker); + } + } + setInvokers(clazz.getSuperclass()); + } +} diff --git a/core/test/src/main/java/org/switchyard/test/SwitchYardTestCaseConfig.java b/core/test/src/main/java/org/switchyard/test/SwitchYardTestCaseConfig.java new file mode 100644 index 000000000..8390c8c5f --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/SwitchYardTestCaseConfig.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import org.switchyard.config.model.Scanner; +import org.switchyard.deploy.internal.AbstractDeployment; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * SwitchYard test deployment configuration annotation. + * + * @author tom.fennelly@gmail.com + */ +@Target({TYPE}) +@Retention(RUNTIME) +@Documented +public @interface SwitchYardTestCaseConfig { + + /** + * Default classpath location for the switchyard configuration. + */ + String SWITCHYARD_XML = AbstractDeployment.SWITCHYARD_XML; + /** + * Constant for the {@link SwitchYardTestCaseConfig#config()} default. + */ + String NULL_CONFIG = "$$NULL_SW_CONFIG$$"; + + /** + * Classpath path to a switchyard.xml configuration. + */ + String config() default NULL_CONFIG; + + /** + * Whether validating SwitchYard configuration model or not. + */ + boolean validate() default true; + + /** + * {@link Scanner Scanners} to be used in the test. + *

+ * These are the same application scanners used by the SwitchYard maven plugin. The + * augment the configuration model pointed to by the {@link #config()} value. The scanners + * are only applied if a {@link #config()} is specified. + */ + Class[] scanners() default SwitchYardTestKit.NullScanners.class; + + /** + * The Mix in types. + */ + Class[] mixins() default SwitchYardTestKit.NullMixIns.class; + + /** + * Component types to include. + */ + String[] include() default {}; + + /** + * Component types to exclude. + */ + String[] exclude() default {}; +} diff --git a/core/test/src/main/java/org/switchyard/test/SwitchYardTestKit.java b/core/test/src/main/java/org/switchyard/test/SwitchYardTestKit.java new file mode 100644 index 000000000..92dd25eb6 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/SwitchYardTestKit.java @@ -0,0 +1,1082 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.jboss.logging.Logger; +import org.junit.Assert; +import org.switchyard.ExchangeHandler; +import org.switchyard.Service; +import org.switchyard.ServiceDomain; +import org.switchyard.SwitchYardException; +import org.switchyard.common.type.Classes; +import org.switchyard.common.type.classpath.ClasspathScanner; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.model.MergeScanner; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.Models; +import org.switchyard.config.model.Scannable; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.ActivatorLoader; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.internal.AbstractDeployment; +import org.switchyard.deploy.internal.Deployment; +import org.switchyard.handlers.MessageTraceHandler; +import org.switchyard.metadata.InOnlyService; +import org.switchyard.metadata.InOutService; +import org.switchyard.metadata.ServiceInterface; +import org.switchyard.test.mixins.AbstractTestMixIn; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.Transformer; +import org.w3c.dom.Document; + +/** + * @author tom.fennelly@gmail.com + */ +public class SwitchYardTestKit { + + /** + * Logger. + */ + private static Logger _logger = Logger.getLogger(SwitchYardTestKit.class); + /** + * Constant for the {@link org.switchyard.test.SwitchYardTestCaseConfig#config()} default. + */ + protected static final String NULL_CONFIG = "$$NULL_SW_CONFIG$$"; + + /** + * Class test instance. + */ + private Object _testInstance; + /** + * Test configuration model. + */ + private SwitchYardModel _configModel; + /** + * The deployment. + */ + private AbstractDeployment _deployment; + /** + * Test Mix-Ins. + */ + private Map, MixInEntry> _testMixInInstances = + new LinkedHashMap, MixInEntry>(); + + private List _activators; + + /** + * Public default constructor. + * @param testInstance The test instance. + * @exception Exception Error initializing test kit. + */ + public SwitchYardTestKit(Object testInstance) throws Exception { + this._testInstance = testInstance; + + SwitchYardTestCaseConfig testCaseConfig = testInstance.getClass().getAnnotation(SwitchYardTestCaseConfig.class); + + if (testCaseConfig != null) { + String config = testCaseConfig.config(); + if (config != null && !config.equals(NULL_CONFIG)) { + InputStream is = getResourceAsStream(config); + + if (is == null) { + // Try the file system... + File file = new File(config); + if (file.isFile()) { + is = new FileInputStream(file); + } + } + + if (is == null) { + Assert.fail("Failed to locate test configuration '" + config + "' on the classpath or project sub-directory. See the @" + SwitchYardTestCaseConfig.class.getSimpleName() + " annotation on test class '" + _testInstance.getClass().getName() + "'."); + } + + try { + _configModel = createSwitchYardModel(is, createScanners(testCaseConfig), testCaseConfig.validate()); + } finally { + try { + is.close(); + } catch (Throwable t) { + // just to keep checkstyle happy + t.getMessage(); + } + } + } + Class[] testMixIns = testCaseConfig.mixins(); + if (testMixIns == null) { + // No MixIns... + _logger.debug("No TestMixIns for test."); + } else if (testMixIns.length == 1 && testMixIns[0] == NullMixIns.class) { + // No MixIns... + _logger.debug("No TestMixIns for test."); + } else { + for (Class mixIn : testMixIns) { + _testMixInInstances.put(mixIn, null); + } + } + } + createMixInInstances(); + initializeMixIns(); + } + + /** + * invoke the methods annotated with {@link BeforeDeploy} on test class and deploy SwitchYard application. + * + * @throws Exception failed to deploy + */ + public void start() throws Exception { + beforeDeploy(); + deploy(); + } + + + /** + * Cleanup. + */ + public void cleanup() { + undeploy(); + cleanupMixIns(); + } + + /** + * Get the test class instance. + * @return The test class instance. + */ + public Object getTestInstance() { + return _testInstance; + } + + /** + * Get the configuration model driving this test instance, if one exists. + *

+ * An abstract deployment is created if no configuration model is supplied on construction. + * + * @return The config model, or null if no config model was used to construct the TestCase instance. + */ + public SwitchYardModel getConfigModel() { + return _configModel; + } + + /** + * Get the list of activators for the test. + * @return Activator list. + */ + public List getActivators() { + return _activators; + } + + /** + * Get the deployment instance associated with the test case. + * @return The deployment instance associated with the test case. + */ + public AbstractDeployment getDeployment() { + return _deployment; + } + + /** + * Get the ServiceDomain. + * @return The service domain. + */ + public ServiceDomain getServiceDomain() { + assertDeployed(); + return _deployment.getDomain(); + } + + /** + * Creates a QName given this test kit's config model's targetNamespace + the specified localPart. + * @param localPart the specified localPart + * @return the QName + */ + public QName createQName(String localPart) { + final String tns; + if (_configModel != null) { + CompositeModel composite = _configModel.getComposite(); + tns = composite != null ? composite.getTargetNamespace() : _configModel.getTargetNamespace(); + } else { + tns = null; + } + return XMLHelper.createQName(tns, localPart); + } + + /** + * Register an IN_OUT Service. + *

+ * Registers a {@link MockHandler} as the service handler. + * + * @param serviceName The Service name. + * @return The {@link MockHandler} service handler. + */ + public MockHandler registerInOutService(String serviceName) { + MockHandler handler = new MockHandler(); + getServiceDomain().registerService(createQName(serviceName), new InOutService(), handler); + return handler; + } + + /** + * Register an IN_OUT Service. + * + * @param serviceName The Service name. + * @param serviceHandler The service handler. + */ + public void registerInOutService(String serviceName, ExchangeHandler serviceHandler) { + getServiceDomain().registerService(createQName(serviceName), new InOutService(), serviceHandler); + } + + /** + * Register an IN_OUT Service. + * + * @param serviceName The Service name. + * @param serviceHandler The service handler. + * @param metadata Service interface. + */ + public void registerInOutService(String serviceName, ExchangeHandler serviceHandler, ServiceInterface metadata) { + getServiceDomain().registerService(createQName(serviceName), metadata, serviceHandler); + } + + /** + * Register an IN_ONLY Service. + *

+ * Registers a {@link MockHandler} as the fault service handler. + * + * @param serviceName The Service name. + * @return The {@link MockHandler} service fault handler. + */ + public MockHandler registerInOnlyService(String serviceName) { + MockHandler handler = new MockHandler(); + getServiceDomain().registerService(createQName(serviceName), new InOnlyService(), handler); + return handler; + } + + /** + * Register an IN_ONLY Service. + * + * @param serviceName The Service name. + * @param serviceHandler The service handler. + */ + public void registerInOnlyService(String serviceName, ExchangeHandler serviceHandler) { + getServiceDomain().registerService(createQName(serviceName), new InOnlyService(), serviceHandler); + } + + /** + * Replaces an existing service registration (e.g. reference binding) with a test handler using + * the same contract as the existing service provider. If multiple services are registered with + * the specified name, the first one found is used. Generally speaking, it's not a good idea + * to use this method if you have multiple services registered with the same name. In that + * situation, use the removeService() and registerService() methods instead. + * @param name name of the service to replace + * @return mock service handler representing the service provider + * @throws SwitchYardException if a service with the specified name does not exist + */ + public MockHandler replaceService(String name) throws SwitchYardException { + return replaceService(createQName(name)); + } + + /** + * Replaces an existing service registration (e.g. reference binding) with a test handler using + * the same contract as the existing service provider. If multiple services are registered with + * the specified name, the first one found is used. Generally speaking, it's not a good idea + * to use this method if you have multiple services registered with the same name. In that + * situation, use the removeService() and registerService() methods instead. + * @param name name of the service to replace + * @param handler implementation to use as the service provider + * @throws SwitchYardException if a service with the specified name does not exist + */ + public void replaceService(String name, ExchangeHandler handler) throws SwitchYardException { + replaceService(createQName(name), handler); + } + + /** + * Replaces an existing service registration (e.g. reference binding) with a test handler using + * the same contract as the existing service provider. If multiple services are registered with + * the specified name, the first one found is used. Generally speaking, it's not a good idea + * to use this method if you have multiple services registered with the same name. In that + * situation, use the removeService() and registerService() methods instead. + * @param name name of the service to replace + * @return mock service handler representing the service provider + * @throws SwitchYardException if a service with the specified name does not exist + */ + public MockHandler replaceService(QName name) throws SwitchYardException { + MockHandler handler = new MockHandler(); + replaceService(name, handler); + return handler; + } + + /** + * Replaces an existing service registration (e.g. reference binding) with a test handler using + * the same contract as the existing service provider. If multiple services are registered with + * the specified name, the first one found is used. Generally speaking, it's not a good idea + * to use this method if you have multiple services registered with the same name. In that + * situation, use the removeService() and registerService() methods instead. + * @param name name of the service to replace + * @param handler implementation to use as the service provider + * @throws SwitchYardException if a service with the specified name does not exist + */ + public void replaceService(QName name, ExchangeHandler handler) throws SwitchYardException { + List services = getServiceDomain().getServices(name); + if (services.isEmpty()) { + throw new SwitchYardException("Failed to replace service: " + name + + ". No service is registered with that name."); + } + + // select the service to replace + Service replacedService = services.get(0); + replacedService.unregister(); + + // add the replacement service + getServiceDomain().registerService(name, replacedService.getInterface(), handler, + replacedService.getServiceMetadata()); + } + + /** + * Removes all service providers from the domain with the specified name. + * @param serviceName local part of a service QName + */ + public void removeService(String serviceName) { + removeService(createQName(serviceName)); + } + + /** + * Removes all service providers from the domain with the specified name. + * @param serviceName qualified name of the service + */ + public void removeService(QName serviceName) { + for (Service service : getServiceDomain().getServices(serviceName)) { + service.unregister(); + } + } + + /** + * Add a Transformer instance. + * @param transformer The transformer instance. + */ + public void addTransformer(Transformer transformer) { + getServiceDomain().getTransformerRegistry().addTransformer(transformer); + } + + /** + * Create a new {@link Invoker} instance for invoking a Service in the test ServiceDomain. + * @param serviceName The target Service name. + * @return The invoker instance. + */ + public Invoker newInvoker(QName serviceName) { + return new Invoker(getServiceDomain(), serviceName); + } + + /** + * Create a new {@link Invoker} instance for invoking a Service in the test ServiceDomain. + * @param serviceName The target Service name. Can be a serialized {@link QName}. Can also + * include the operation name e.g. "OrderManagementService.createOrder". + * @return The invoker instance. + */ + public Invoker newInvoker(String serviceName) { + return newInvoker(createQName(serviceName)); + } + + /** + * Create a new {@link Transformer} instance from the specified {@link org.switchyard.config.model.transform.TransformModel}. + * @param transformModel The TransformModel. + * @return The Transformer instance. + */ + public Transformer newTransformer(TransformModel transformModel) { + return _deployment.getTransformerRegistryLoader().newTransformer(transformModel); + } + + /** + * Create a new {@link Transformer} instance from the specified {@link TransformModel} and + * register it with the test ServiceDomain. + * @param transformModel The TransformModel. + * @return The Transformer instance. + */ + public Transformer registerTransformer(TransformModel transformModel) { + if (transformModel.getFrom() == null || transformModel.getTo() == null) { + Assert.fail("Invalid TransformModel instance. Must specify 'from' and 'to' data types."); + } + + Transformer transformer = _deployment.getTransformerRegistryLoader().newTransformer(transformModel); + if (transformer.getFrom() == null) { + transformer = new TransformerWrapper(transformer, transformModel); + } + _deployment.getDomain().getTransformerRegistry().addTransformer(transformer); + + return transformer; + } + + /** + * Get the {@link TestMixIn} instances associated with this test instance. + * @return The {@link TestMixIn} instances associated with this test instance. + */ + public List getMixIns() { + List mixins = new ArrayList(); + for (MixInEntry entry : _testMixInInstances.values()) { + mixins.add(entry.getMixIn()); + } + return Collections.unmodifiableList(mixins); + } + + /** + * Get the "active" {@link TestMixIn} instance of the specified type. + *

+ * This method can only be called from inside a test method. + * + * @param type The {@link TestMixIn} type, as specified in the {@link SwitchYardTestCaseConfig} annotation. + * @param type {@link TestMixIn} type. + * @return The {@link TestMixIn} instance. + */ + public T getMixIn(Class type) { + if (_testMixInInstances == null || _testMixInInstances.isEmpty()) { + Assert.fail("No TestMixIns specified on Test class instance. Use the @TestMixIns annotation."); + } + if (_testMixInInstances.size() != getMixIns().size()) { + Assert.fail("TestMixIn instances only available during test method execution."); + } + + MixInEntry mixIn = _testMixInInstances.get(type); + if (mixIn == null) { + Assert.fail("Required TestMixIn '" + type.getName() + "' is not specified on TestCase '" + _testInstance.getClass().getName() + "'."); + } + + return type.cast(mixIn.getMixIn()); + } + + /** + * Returns required mixin dependencies. + * + * @param mixIn Mix in asking about dependencies. + * @return Dependencies which are mandatory for mixin + */ + public Set getRequiredDependencies(TestMixIn mixIn) { + return Collections.unmodifiableSet(_testMixInInstances.get(mixIn.getClass()).getRequiredDeps()); + } + + /** + * Returns optional mixin dependencies. + * + * @param mixIn Mix in asking about dependencies. + * @return Dependencies which are not mandatory for mixin + */ + public Set getOptionalDependencies(TestMixIn mixIn) { + return Collections.unmodifiableSet(_testMixInInstances.get(mixIn.getClass()).getOptionalDeps()); + } + + /** + * Finds a resource with a given name. + *

+ * Searches relative to the implementing class definition. + * + * @param name Name of the desired resource + * @return A {@link java.io.InputStream} object or null if no resource with this name is found. + * + * @see org.switchyard.common.type.Classes#getResourceAsStream(String,Class) + */ + public InputStream getResourceAsStream(String name) { + try { + return Classes.getResourceAsStream(name, _testInstance.getClass()); + } catch (IOException ioe) { + return null; + } + } + + /** + * Read a classpath resource and return as a byte array. + * @param path The path to the classpath resource. The specified path can be + * relative to the test class' location on the classpath. + * @return The resource as an array of bytes. + */ + public byte[] readResourceBytes(String path) { + if (path == null) { + Assert.fail("Resource 'path' not specified."); + } + + InputStream resourceStream = getResourceAsStream(path); + if (resourceStream == null) { + Assert.fail("Resource '" + path + "' not found on classpath relative to test class '" + _testInstance.getClass().getName() + "'. May need to fix the relative path, or make the path absolute."); + } + + ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream(); + try { + byte[] readBuffer = new byte[128]; + int readCount = 0; + + while ((readCount = resourceStream.read(readBuffer)) != -1) { + byteOutStream.write(readBuffer, 0, readCount); + } + } catch (IOException e) { + Assert.fail("Unexpected read error reading classpath resource '" + path + "'" + e.getMessage()); + } finally { + try { + resourceStream.close(); + } catch (IOException e) { + Assert.fail("Unexpected exception closing classpath resource '" + path + "'" + e.getMessage()); + } + } + + return byteOutStream.toByteArray(); + } + + /** + * Read a classpath resource and return as a String. + * @param path The path to the classpath resource. The specified path can be + * relative to the test class' location on the classpath. + * @return The resource as a String. + */ + public String readResourceString(String path) { + try { + return new String(readResourceBytes(path), "UTF-8"); + } catch (UnsupportedEncodingException e) { + Assert.fail("Unexpected exception reading classpath resource '" + path + "' as a String. Perhaps this resource is a binary resource that cannot be encoded as a String." + e.getMessage()); + return null; // Keep the compiler happy. + } + } + + /** + * Read a classpath resource and return as an XML DOM Document. + * + * @param path The path to the classpath resource. The specified path can be + * relative to the test class' location on the classpath. + * @return The resource as a Document. + */ + public Document readResourceDocument(String path) { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + return db.parse(getResourceAsStream(path)); + } catch (Exception e) { + Assert.fail("Unexpected exception reading classpath resource '" + path + "' as a DOM Document." + e.getMessage()); + return null; // Keep the compiler happy. + } + } + + /** + * Load the SwitchYard configuration model specified by the configModel stream. + * @param configModel The config model stream. + * @return The SwitchYard config model. + */ + public SwitchYardModel loadSwitchYardModel(InputStream configModel) { + return loadSwitchYardModel(configModel, true); + } + + /** + * Load the SwitchYard configuration model specified by the configModel stream. + * @param configModel The config model stream. + * @param validate Validate the model? + * @return The SwitchYard config model. + */ + public SwitchYardModel loadSwitchYardModel(InputStream configModel, boolean validate) { + return loadConfigModel(configModel, SwitchYardModel.class, validate); + } + + /** + * Load the configuration model specified by the configModel stream. + * @param Model type. + * @param configModel The config model stream. + * @param modelType Model type. + * @return The config model. + */ + public M loadConfigModel(InputStream configModel, Class modelType) { + return loadConfigModel(configModel, modelType, true); + } + + /** + * Load the SwitchYard configuration model specified by the configModel stream. + * @param Model type. + * @param configModel The config model stream. + * @param modelType Model type. + * @param validate Validate the model? + * @return The SwitchYard config model. + */ + public M loadConfigModel(InputStream configModel, Class modelType, boolean validate) { + if (configModel == null) { + throw new IllegalArgumentException("null 'configModel' arg."); + } + try { + M pulledModel = new ModelPuller().pull(configModel); + if (validate) { + pulledModel.assertModelValid(); + } + return pulledModel; + } catch (IOException e) { + Assert.fail("Unexpected error building " + modelType.getSimpleName() + ": " + e.getMessage()); + } finally { + try { + configModel.close(); + } catch (IOException e) { + Assert.fail("Unexpected error closing " + modelType.getSimpleName() + " stream: " + e.getMessage()); + } + } + return null; + } + + /** + * Compare an XML string (e.g. a result) against a classpath resource. + * @param xml The XML (as a String) to be compared against the XML in the specified + * classpath resource. + * @param resourcePath The path to the classpath resource against which the XML is to be + * compared. The specified path can be relative to the test class' location on the classpath. + */ + public void compareXMLToResource(String xml, String resourcePath) { + XMLUnit.setIgnoreWhitespace(true); + try { + XMLAssert.assertXMLEqual(readResourceString(resourcePath), xml); + } catch (Exception e) { + Assert.fail("Unexpected error performing XML comparison: " + e.getMessage()); + } + } + + /** + * Compare an XML String (e.g. a result) against another String. + * @param xml The XML (as a String) to be compared against the XML in the specified + * classpath resource. + * @param string The String against which the XML is to be + * compared. + */ + public static void compareXMLToString(String xml, String string) { + XMLUnit.setIgnoreWhitespace(true); + try { + XMLAssert.assertXMLEqual(string, xml); + } catch (Exception e) { + Assert.fail("Unexpected error performing XML comparison."); + } + } + + /** + * Enables message tracing for the application under test. + * @param doTrace true to enable message tracing, false to disable + */ + public void traceMessages(boolean doTrace) { + getServiceDomain().setProperty(MessageTraceHandler.TRACE_ENABLED, true); + } + + /** + * invoke the methods annotated with {@link BeforeDeploy} on test class. + */ + private void beforeDeploy() throws Exception { + Method[] publicMethods = _testInstance.getClass().getMethods(); + for (Method method : publicMethods) { + BeforeDeploy beforeAnno = method.getAnnotation(BeforeDeploy.class); + if (beforeAnno != null) { + method.invoke(_testInstance); + } + } + } + + /** + * Create and initialise the deployment. + * @throws Exception creating the deployment. + */ + private final void deploy() throws Exception { + _deployment = createDeployment(); + ServiceDomain domain = new ServiceDomainManager().createDomain( + ServiceDomainManager.ROOT_DOMAIN, _deployment.getConfig()); + + _activators = ActivatorLoader.createActivators(domain); + SwitchYardTestCaseConfig testCaseConfig = _testInstance.getClass().getAnnotation(SwitchYardTestCaseConfig.class); + + if (testCaseConfig != null) { + // Process includes... + Collection includes = new HashSet(Arrays.asList(testCaseConfig.include())); + if (!includes.isEmpty()) { + Iterator activatorsIt = _activators.iterator(); + while (activatorsIt.hasNext()) { + Activator activator = activatorsIt.next(); + + // If the activator does not specify one of the include types, then remove it... + if (!intersection(includes, activator.getActivationTypes())) { + activatorsIt.remove(); + } + } + } + + // Process excludes... + Collection excludes = new HashSet(Arrays.asList(testCaseConfig.exclude())); + if (!excludes.isEmpty()) { + Iterator activatorsIt = _activators.iterator(); + while (activatorsIt.hasNext()) { + Activator activator = activatorsIt.next(); + + // If the activator specifies one of the exclude types, then remove it... + if (intersection(excludes, activator.getActivationTypes())) { + activatorsIt.remove(); + } + } + } + } + + _deployment.init(domain, _activators); + mixInBefore(); + + _deployment.setFailOnMissingActivator(false); // It's OK to have a "missing" activator for a test, so we don't want to fail. + _deployment.start(); + } + + /** + * Undeploy the deployment. + */ + private final void undeploy() { + assertDeployed(); + _deployment.stop(); + mixInAfter(); + _deployment.destroy(); + } + + /** + * Create the deployment instance. + * @return The deployment instance. + * @throws Exception creating the deployment. + */ + private AbstractDeployment createDeployment() throws Exception { + if (_configModel != null) { + return new Deployment(_configModel); + } else { + return new SimpleTestDeployment(); + } + } + + + private void initializeMixIns() { + for (TestMixIn mixIn : getMixIns()) { + mixIn.initialize(); + } + } + + private void mixInBefore() { + for (TestMixIn mixIn : getMixIns()) { + mixIn.before(_deployment); + } + } + + private void mixInAfter() { + // Apply after MixIns in reverse order... + List mixins = new ArrayList(getMixIns()); + Collections.reverse(mixins); + for (TestMixIn mixIn : mixins) { + mixIn.after(_deployment); + } + } + + private void cleanupMixIns() { + // Destroy MixIns in reverse order... + List mixins = new ArrayList(getMixIns()); + Collections.reverse(mixins); + for (TestMixIn mixIn : mixins) { + mixIn.uninitialize(); + } + } + + private void createMixInInstances() { + if (_testMixInInstances == null || _testMixInInstances.isEmpty()) { + // No Mix-Ins... + return; + } + + Set> mixinClasses = new LinkedHashSet>( + _testMixInInstances.keySet()); + for (Class mixInType : mixinClasses) { + createMixInRecursively(mixInType); + } + } + + private MixInEntry createMixInRecursively(Class mixInType) { + if (_testMixInInstances.containsKey(mixInType) && _testMixInInstances.get(mixInType) != null) { + return _testMixInInstances.get(mixInType); + } + + Set requiredDeps = new LinkedHashSet(); + Set optionalDeps = new LinkedHashSet(); + + // create dependencies first + MixInDependencies dependencies = mixInType.getAnnotation(MixInDependencies.class); + if (dependencies != null) { + Class[] activeDependencies = dependencies.required(); + if (activeDependencies != null && activeDependencies[0] != NullMixIns.class) { + for (Class mixin : activeDependencies) { + MixInEntry dependency = createMixInRecursively(mixin); + requiredDeps.add(dependency.getMixIn()); + _testMixInInstances.put(mixin, dependency); + } + } + Class[] passiveDependencies = dependencies.optional(); + if (passiveDependencies != null && passiveDependencies[0] != NullMixIns.class) { + for (Class mixin : passiveDependencies) { + if (_testMixInInstances.containsKey(mixin)) { + MixInEntry dependency = createMixInRecursively(mixin); + optionalDeps.add(dependency.getMixIn()); + _testMixInInstances.put(mixin, dependency); + } + } + } + } + + TestMixIn testMixIn = newMixInInstance(mixInType, _testInstance); + testMixIn.setTestKit(this); + MixInEntry entry = new MixInEntry(testMixIn, requiredDeps, optionalDeps); + // here is where whole trick is done - we must move created mixin after + // it's dependencies, so we remove entry and add same instance once again + _testMixInInstances.remove(mixInType); + _testMixInInstances.put(mixInType, entry); + return entry; + } + + protected static T newMixInInstance(Class mixInType, Object testInstance) { + Class testClass = testInstance.getClass(); + Method[] methods = testClass.getDeclaredMethods(); + + // Check for a factory method for the MixIn type... + for (Method method : methods) { + int modifiers = method.getModifiers(); + + if (Modifier.isPublic(modifiers)) { + if (method.getReturnType() == mixInType && method.getParameterTypes().length == 0) { + try { + if (Modifier.isStatic(modifiers)) { + return mixInType.cast(method.invoke(null)); + } else { + return mixInType.cast(method.invoke(testInstance)); + } + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Failed to create instance of TestMixIn type " + mixInType.getName() + ". Error invoking the MixIn factory method '" + method.getName() + "': " + e.getMessage()); + return null; + } + } + } + } + + try { + return mixInType.newInstance(); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail("Failed to create instance of TestMixIn type " + mixInType.getName() + " via public default constructor: " + e.getMessage()); + return null; + } + } + + private SwitchYardModel createSwitchYardModel(InputStream configModel, List> scanners, boolean validate) { + Assert.assertNotNull("Test 'configModel' is null.", configModel); + + final SwitchYardModel returnModel; + try { + SwitchYardModel model = loadSwitchYardModel(configModel, false); + ClassLoader classLoader = _testInstance.getClass().getClassLoader(); + + if (scanners != null && !scanners.isEmpty() && classLoader instanceof URLClassLoader) { + String uri = model.getModelRootNamespace(); + SwitchYardNamespace ns = SwitchYardNamespace.fromUri(uri); + MergeScanner merge_scanner = new MergeScanner(true, scanners); + List scanURLs = getScanURLs((URLClassLoader)classLoader); + + ScannerInput scanner_input = new ScannerInput() + .setSwitchyardNamespace(ns).setCompositeName(model.getName()).setURLs(scanURLs); + V1SwitchYardModel scannedModel = merge_scanner.scan(scanner_input).getModel(); + + returnModel = Models.merge(scannedModel, model, false); + } else { + returnModel = model; + } + if (validate) { + returnModel.assertModelValid(); + } + return returnModel; + } catch (java.io.IOException ioEx) { + throw new SwitchYardException("Failed to read switchyard config.", ioEx); + } + } + + private void assertDeployed() { + if (_deployment == null) { + Assert.fail("TestCase deployment not yet deployed. You may need to make an explicit call to the deploy() method."); + } + } + + private List> createScanners(SwitchYardTestCaseConfig testCaseConfig) { + List> scanners = new ArrayList>(); + + if (testCaseConfig != null) { + Class[] scannerClasses = testCaseConfig.scanners(); + + if (scannerClasses == null) { + // No Scanners + _logger.debug("No Scanners for test."); + } else if (scannerClasses.length == 1 && scannerClasses[0] == NullScanners.class) { + // No Scanners + _logger.debug("No Scanners for test."); + } else { + for (Class scannerClass : scannerClasses) { + try { + scanners.add(scannerClass.newInstance()); + } catch (Exception e) { + Assert.fail("Exception creating instance of Scanner class '" + scannerClass.getName() + "': " + e.getMessage()); + } + } + } + } + + return scanners; + } + + private List getScanURLs(URLClassLoader classLoader) { + URL[] classPathURLs = classLoader.getURLs(); + List scanURLs = new ArrayList(); + + // Only scan directories. Above all, we want to make sure we don't + // start scanning JDK jars etc... + for (URL classpathURL : classPathURLs) { + try { + File file = ClasspathScanner.toClassPathFile(classpathURL); + if (file.isDirectory()) { + scanURLs.add(classpathURL); + } + } catch (IOException e) { + Assert.fail("Failed to convert classpath URL '" + classpathURL + "' to a File instance."); + } + } + + // Temp hack to work around SWITCHYARD-343 (https://issues.jboss.org/browse/SWITCHYARD-343)... + if (scanURLs.isEmpty()) { + try { + scanURLs.add(new File("target/test-classes").toURI().toURL()); + scanURLs.add(new File("target/classes").toURI().toURL()); + } catch (MalformedURLException e) { + Assert.fail("Unexpected exception adding target test classes folders to test scan URLs: " + e.getMessage()); + } + } + + return scanURLs; + } + + private boolean intersection(Collection set1, Collection set2) { + if (set1.isEmpty() || set2.isEmpty()) { + return false; + } + + Collection set1Copy = new HashSet(set1); + + set1Copy.removeAll(set2); + + // If entries were removed from the set then we have an intersect, otherwise we don't... + return (set1Copy.size() < set1.size()); + } + + @Scannable(false) + private static final class TransformerWrapper extends BaseTransformer { + + private Transformer _transformer; + private TransformModel _transformModel; + + private TransformerWrapper(Transformer transformer, TransformModel transformModel) { + this._transformer = transformer; + this._transformModel = transformModel; + } + + @Override + public Object transform(Object from) { + return _transformer.transform(from); + } + + @Override + public QName getFrom() { + return _transformModel.getFrom(); + } + + @Override + public QName getTo() { + return _transformModel.getTo(); + } + } + + /** + * Hidden marker type to provide a valid NULL + * Scanners configuration for {@link SwitchYardTestCaseConfig}. + */ + protected static final class NullScanners implements Scanner { + @Override + public ScannerOutput scan(ScannerInput scannerInput) throws IOException { + return null; + } + } + + /** + * Hidden marker type to provide a valid NULL + * TestMixIns configuration for {@link SwitchYardTestCaseConfig}. + */ + protected static final class NullMixIns extends AbstractTestMixIn { + } + + /** + * Helper class to keep mixin and it's dependencies. + * + */ + protected static class MixInEntry { + + private final TestMixIn _mixin; + private Set _requiredDeps; + private Set _optionalDeps; + + public MixInEntry(TestMixIn mixin, Set requiredDeps, Set optionalDeps) { + this._mixin = mixin; + this._requiredDeps = requiredDeps; + this._optionalDeps = optionalDeps; + } + + public TestMixIn getMixIn() { + return _mixin; + } + + public Set getRequiredDeps() { + return _requiredDeps; + } + + public Set getOptionalDeps() { + return _optionalDeps; + } + + } +} diff --git a/core/test/src/main/java/org/switchyard/test/TestDataSource.java b/core/test/src/main/java/org/switchyard/test/TestDataSource.java new file mode 100644 index 000000000..a2a1835f0 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/TestDataSource.java @@ -0,0 +1,202 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Serializable; +import java.nio.charset.Charset; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import javax.activation.DataSource; + +/** + * An thread-safe, in-memory DataSource for testing purposes. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@SuppressWarnings("serial") +public class TestDataSource implements DataSource, Serializable { + + private static final Charset UTF8 = Charset.forName("UTF-8"); + + private String _name; + private String _contentType; + private byte[] _data; + private final ReadWriteLock _dataLock = new ReentrantReadWriteLock(); + + /** + * Constructs a new TestDataSource. + */ + public TestDataSource() {} + + /** + * Constructs a new TestDataSource. + * @param name the name + */ + public TestDataSource(String name) { + setName(name); + } + + /** + * Constructs a new TestDataSource. + * @param name the name + * @param contentType the contentType + */ + public TestDataSource(String name, String contentType) { + setName(name).setContentType(contentType); + } + + /** + * Constructs a new TestDataSource. + * @param name the name + * @param contentType the contentType + * @param data the data + */ + public TestDataSource(String name, String contentType, byte[] data) { + setName(name).setContentType(contentType).setData(data); + } + + /** + * Constructs a new TestDataSource. + * @param name the name + * @param contentType the contentType + * @param data the data as a String + */ + public TestDataSource(String name, String contentType, String data) { + setName(name).setContentType(contentType).setDataString(data); + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return _name; + } + + /** + * Sets the name. + * @param name the name + * @return this TestDataSource (useful for chaining) + */ + public TestDataSource setName(String name) { + _name = name; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getContentType() { + return _contentType; + } + + /** + * Sets the contentType. + * @param contentType the contentType + * @return this TestDataSource (useful for chaining) + */ + public TestDataSource setContentType(String contentType) { + _contentType = contentType; + return this; + } + + /** + * Gets the data. + * @return the data + */ + public byte[] getData() { + byte[] copy; + _dataLock.readLock().lock(); + try { + copy = new byte[_data.length]; + System.arraycopy(_data, 0, copy, 0, _data.length); + } finally { + _dataLock.readLock().unlock(); + } + return copy; + } + + /** + * Sets the data. + * @param data the data + * @return this TestDataSource (useful for chaining) + */ + public TestDataSource setData(byte[] data) { + if (data == null) { + data = new byte[0]; + } + byte[] copy = new byte[data.length]; + System.arraycopy(data, 0, copy, 0, data.length); + _dataLock.writeLock().lock(); + try { + _data = copy; + } finally { + _dataLock.writeLock().unlock(); + } + return this; + } + + /** + * Gets the data as a String. + * @return the data as a String + */ + public String getDataString() { + return new String(getData(), UTF8); + } + + /** + * Sets the data as a String. + * @param data the data as a String + * @return this TestDataSource (useful for chaining) + */ + public TestDataSource setDataString(String data) { + setData(data != null ? data.getBytes(UTF8) : null); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(getData()); + } + + /** + * {@inheritDoc} + */ + @Override + public OutputStream getOutputStream() throws IOException { + return new ByteArrayOutputStream() { + @Override + public void flush() throws IOException { + super.flush(); + setData(toByteArray()); + } + @Override + public void close() throws IOException { + super.close(); + setData(toByteArray()); + } + }; + } + +} diff --git a/core/test/src/main/java/org/switchyard/test/TestLogger.java b/core/test/src/main/java/org/switchyard/test/TestLogger.java new file mode 100644 index 000000000..ffc8d7850 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/TestLogger.java @@ -0,0 +1,18 @@ +package org.switchyard.test; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 15400-15599 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface TestLogger { + /** + * Default root logger. + */ + TestLogger ROOT_LOGGER = Logger.getMessageLogger(TestLogger.class, TestLogger.class.getPackage().getName()); +} diff --git a/core/test/src/main/java/org/switchyard/test/TestMessages.java b/core/test/src/main/java/org/switchyard/test/TestMessages.java new file mode 100644 index 000000000..50f0d6874 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/TestMessages.java @@ -0,0 +1,18 @@ +package org.switchyard.test; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 15600-15799 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface TestMessages { + /** + * Default messages. + */ + TestMessages MESSAGES = Messages.getBundle(TestMessages.class); +} diff --git a/core/test/src/main/java/org/switchyard/test/TestMixIn.java b/core/test/src/main/java/org/switchyard/test/TestMixIn.java new file mode 100644 index 000000000..9ccf48122 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/TestMixIn.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import org.switchyard.deploy.internal.AbstractDeployment; + +/** + * Test Mix-In. + *

+ * Test Mix-Ins are used to extend the behavior of {@link SwitchYardTestKit}. + * See the {@link org.switchyard.test.mixins} package for a list of the {@link TestMixIn TestMixIns} + * available out of the box. + *

+ * Test Mix-Ins have a lifecycle associated with your TestCase. They are created + * and destroyed with the TestCase instance and the {@link #before(org.switchyard.deploy.internal.AbstractDeployment)} + * and {@link #after(org.switchyard.deploy.internal.AbstractDeployment)} methods are called @Before and @After) + * each test method. See the javadoc on each of the methods of this class. + * + * @author tom.fennelly@gmail.com + */ +public interface TestMixIn { + + /** + * Set the test kit instance on the MixIn. + * @param kit The kit instance. + */ + void setTestKit(SwitchYardTestKit kit); + + /** + * MixIn initialization. + *

+ * Performed on test construction. + */ + void initialize(); + + /** + * Before test method execution (init). + * @param deployment The deployment. + */ + void before(AbstractDeployment deployment); + + /** + * After test method execution (cleanup). + *

+ * Performed before the deployment is destroyed. + * + * @param deployment The deployment. + */ + void after(AbstractDeployment deployment); + + /** + * MixIn uninitialize. + *

+ * Performed after TesCase TestRunner has finished running all the TestCase test methods. + */ + void uninitialize(); + +} diff --git a/core/test/src/main/java/org/switchyard/test/mixins/AbstractTestMixIn.java b/core/test/src/main/java/org/switchyard/test/mixins/AbstractTestMixIn.java new file mode 100644 index 000000000..a928c25e8 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/mixins/AbstractTestMixIn.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test.mixins; + +import org.switchyard.deploy.internal.AbstractDeployment; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.test.TestMixIn; + +/** + * Abstract {@link TestMixIn}. + * + * @author tom.fennelly@gmail.com + */ +public abstract class AbstractTestMixIn implements TestMixIn { + + private SwitchYardTestKit _kit; + + @Override + public void setTestKit(SwitchYardTestKit kit) { + this._kit = kit; + } + + /** + * Get the test kit instance associated with the test mixin. + * @return The test kit instance instance. + */ + public SwitchYardTestKit getTestKit() { + return _kit; + } + + @Override + public void initialize() { + } + + @Override + public void before(AbstractDeployment deployment) { + } + + @Override + public void after(AbstractDeployment deployment) { + } + + @Override + public void uninitialize() { + } +} diff --git a/core/test/src/main/java/org/switchyard/test/mixins/PropertyMixIn.java b/core/test/src/main/java/org/switchyard/test/mixins/PropertyMixIn.java new file mode 100644 index 000000000..d8979ac86 --- /dev/null +++ b/core/test/src/main/java/org/switchyard/test/mixins/PropertyMixIn.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.mixins; + +import java.util.Map; + +import org.switchyard.common.property.TestPropertyResolver; + +/** + * Property Test Mix-In for setting test properties that will be respected in configurations. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +public class PropertyMixIn extends AbstractTestMixIn { + + /** + * {@inheritDoc} + */ + @Override + public void initialize() { + clear(); + } + + /** + * Gets the test Map. + * @return the test Map + */ + public Map getMap() { + return TestPropertyResolver.INSTANCE.getMap(); + } + + /** + * Gets a test property. + * @param key the property key + * @return the property value + */ + public Object get(String key) { + return getMap().get(key); + } + + /** + * Sets a test property. + * @param key the property key + * @param value the property value + */ + public void set(String key, Object value) { + getMap().put(key, value); + } + + /** + * Clears all test properties. + */ + public void clear() { + getMap().clear(); + } + + /** + * {@inheritDoc} + */ + @Override + public void uninitialize() { + clear(); + } + +} diff --git a/core/test/src/test/java/org/switchyard/test/CamelContextInjectionTest.java b/core/test/src/test/java/org/switchyard/test/CamelContextInjectionTest.java new file mode 100644 index 000000000..c2375465b --- /dev/null +++ b/core/test/src/test/java/org/switchyard/test/CamelContextInjectionTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test; + +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertTrue; + +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.Test; +import org.junit.runner.RunWith; + +/** + * Test if camel context injection works well. + */ +@RunWith(SwitchYardRunner.class) +public class CamelContextInjectionTest { + + private DefaultCamelContext _context; + + @Test + public void testContextPresent() { + assertNotNull(_context); + assertTrue(_context.isStarted()); + } + +} diff --git a/core/test/src/test/java/org/switchyard/test/InvocationFaultExceptionTest.java b/core/test/src/test/java/org/switchyard/test/InvocationFaultExceptionTest.java new file mode 100644 index 000000000..c9eef087b --- /dev/null +++ b/core/test/src/test/java/org/switchyard/test/InvocationFaultExceptionTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.internal.DefaultMessage; + +public class InvocationFaultExceptionTest { + + @Test + public void testTypeMatchesException() { + InvocationFaultException infEx = new InvocationFaultException( + new DefaultMessage().setContent(new DummyException())); + Assert.assertTrue(infEx.isType(DummyException.class)); + } + + @Test + public void testTypeMatchesObject() { + InvocationFaultException infEx = new InvocationFaultException( + new DefaultMessage().setContent(new DummyObject())); + Assert.assertTrue(infEx.isType(DummyObject.class)); + } + + @Test + public void testGetCauseMatchesFault() { + DummyException testEx = new DummyException(); + InvocationFaultException infEx = new InvocationFaultException(new DefaultMessage().setContent(testEx)); + Assert.assertEquals(testEx, infEx.getCause()); + } +} + +class DummyException extends Exception { + +} + +class DummyObject { + +} diff --git a/core/test/src/test/java/org/switchyard/test/SwitchYardTestKitTest.java b/core/test/src/test/java/org/switchyard/test/SwitchYardTestKitTest.java new file mode 100644 index 000000000..e4796a492 --- /dev/null +++ b/core/test/src/test/java/org/switchyard/test/SwitchYardTestKitTest.java @@ -0,0 +1,171 @@ +package org.switchyard.test; + +import java.io.StringReader; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.config.Configuration; +import org.switchyard.config.ConfigurationPuller; +import org.switchyard.test.mixins.AbstractTestMixIn; +import org.switchyard.test.mixins.PropertyMixIn; + +/** + * @author tom.fennelly@gmail.com + */ +public class SwitchYardTestKitTest { + + @Test + public void test_property_mixin() throws Exception { + PropertyMixIn pmi = SwitchYardTestKit.newMixInInstance(PropertyMixIn.class, this); + Assert.assertNotNull(pmi); + pmi.set("test.name", "ThyName"); + pmi.set("test.value", Integer.valueOf(100)); + String xml = "${test.value}"; + Configuration config = new ConfigurationPuller().pull(new StringReader(xml)); + Assert.assertEquals("ThyName", config.getAttribute("name")); + Assert.assertEquals("100", config.getValue()); + } + + @Test + public void test_factory_mixin_creation_static_method() { + MixIn1 mixIn = SwitchYardTestKit.newMixInInstance(MixIn1.class, this); + Assert.assertNotNull(mixIn); + Assert.assertEquals(MixIn1.class.getName(), mixIn.getaVar()); + } + + @Test + public void test_factory_mixin_creation_nonstatic_method() { + MixIn2 mixIn = SwitchYardTestKit.newMixInInstance(MixIn2.class, this); + Assert.assertNotNull(mixIn); + Assert.assertEquals(MixIn2.class.getName(), mixIn.getaVar()); + } + + @Test + public void test_mixin_dependency_required() throws Exception { + SwitchYardTestKit testkit = new SwitchYardTestKit(new MixInDependencyRequiredTest()); + testkit.start(); + List mixins = testkit.getMixIns(); + Assert.assertEquals(2, mixins.size()); + MixIn3 mixin5 = MixIn3.class.cast(mixins.get(0)); + MixIn3 mixin4 = MixIn3.class.cast(mixins.get(1)); + Assert.assertEquals(MixIn5.class, mixin5.getClass()); + Assert.assertTrue(mixin5.initialized()); + Assert.assertEquals(MixIn4.class, mixin4.getClass()); + Assert.assertTrue(mixin4.initialized()); + + testkit.cleanup(); + Assert.assertFalse(mixin4.initialized()); + Assert.assertFalse(mixin5.initialized()); + } + + @Test + public void test_mixin_dependency_optional() throws Exception { + SwitchYardTestKit testkit = new SwitchYardTestKit(new MixInDependencyOptionalTest()); + testkit.start(); + List mixins = testkit.getMixIns(); + Assert.assertEquals(3, mixins.size()); + MixIn3 mixin5 = MixIn3.class.cast(mixins.get(0)); + MixIn3 mixin6 = MixIn3.class.cast(mixins.get(1)); + MixIn3 mixin4 = MixIn3.class.cast(mixins.get(2)); + Assert.assertEquals(MixIn5.class, mixin5.getClass()); + Assert.assertTrue(mixin5.initialized()); + Assert.assertEquals(MixIn6.class, mixin6.getClass()); + Assert.assertTrue(mixin6.initialized()); + Assert.assertEquals(MixIn4.class, mixin4.getClass()); + Assert.assertTrue(mixin4.initialized()); + + testkit.cleanup(); + Assert.assertFalse(mixin4.initialized()); + Assert.assertFalse(mixin5.initialized()); + Assert.assertFalse(mixin6.initialized()); + } + + public static MixIn1 createMixIn1() { + MixIn1 mixIn1 = new MixIn1(); + mixIn1.setaVar(MixIn1.class.getName()); + return mixIn1; + } + + public MixIn2 createMixIn2() { + MixIn2 mixIn2 = new MixIn2(); + mixIn2.setaVar(MixIn2.class.getName()); + return mixIn2; + } + + public static class MixIn1 extends AbstractTestMixIn { + private String aVar; + + public String getaVar() { + return aVar; + } + + public void setaVar(String aVar) { + this.aVar = aVar; + } + } + + public static class MixIn2 extends AbstractTestMixIn { + private String aVar; + + public String getaVar() { + return aVar; + } + + public void setaVar(String aVar) { + this.aVar = aVar; + } + } + + public static class MixIn3 extends AbstractTestMixIn { + boolean initialized = false; + + @Override + public void initialize() { + synchronized(this) { + if (initialized) { + Assert.fail(this.getClass().getName() + ": initialized twice"); + } else { + initialized = true; + } + } + } + + @Override + public void uninitialize() { + synchronized(this) { + if (!initialized) { + Assert.fail(this.getClass().getName() + ": uninitialize() is called before initialized"); + } else { + initialized = false; + } + } + } + + public boolean initialized() { + return initialized; + } + } + + @MixInDependencies(required=MixIn5.class, optional=MixIn6.class) + public static class MixIn4 extends MixIn3 { + } + + public static class MixIn5 extends MixIn3 { + } + + public static class MixIn6 extends MixIn3 { + } + + @SwitchYardTestCaseConfig(mixins=MixIn4.class) + public class MixInDependencyRequiredTest { + @Test + public void dummy() {} + } + + @SwitchYardTestCaseConfig(mixins={MixIn4.class, MixIn6.class}) + public class MixInDependencyOptionalTest { + @Test + public void dummy() {} + } +} diff --git a/core/test/src/test/java/org/switchyard/test/TestDataSourceTest.java b/core/test/src/test/java/org/switchyard/test/TestDataSourceTest.java new file mode 100644 index 000000000..ff0924935 --- /dev/null +++ b/core/test/src/test/java/org/switchyard/test/TestDataSourceTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test; + +import java.io.OutputStream; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; + +/** + * Tests the {@link TestDataSource}. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class TestDataSourceTest { + + @Test + public void testDataSource() throws Exception { + TestDataSource ds = new TestDataSource("name", "text/plain", "data"); + Assert.assertEquals("name", ds.getName()); + Assert.assertEquals("text/plain", ds.getContentType()); + Assert.assertEquals("data", new StringPuller().pull(ds.getInputStream())); + Assert.assertEquals("data", ds.getDataString()); + ds.setDataString("delta"); + Assert.assertEquals("delta", ds.getDataString()); + OutputStream os = ds.getOutputStream(); + os.write("written".getBytes("UTF-8")); + os.flush(); + Assert.assertEquals("written", ds.getDataString()); + } + +} diff --git a/core/test/src/test/resources/META-INF/beans.xml b/core/test/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/core/test/src/test/resources/log4j.xml b/core/test/src/test/resources/log4j.xml new file mode 100644 index 000000000..0b2a242af --- /dev/null +++ b/core/test/src/test/resources/log4j.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/tools/maven/archetypes/application/pom.xml b/core/tools/maven/archetypes/application/pom.xml new file mode 100644 index 000000000..2a945de17 --- /dev/null +++ b/core/tools/maven/archetypes/application/pom.xml @@ -0,0 +1,44 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../../../pom.xml + + org.switchyard.archetypes + switchyard-application + maven-archetype + SwitchYard: Application Archetype + + 2.1.0-SNAPSHOT + + + + + org.apache.maven.archetype + archetype-packaging + + + + + org.apache.maven.plugins + maven-archetype-plugin + + + + diff --git a/core/tools/maven/archetypes/application/src/main/resources/META-INF/maven/archetype-metadata.xml b/core/tools/maven/archetypes/application/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100644 index 000000000..3eaedb0c9 --- /dev/null +++ b/core/tools/maven/archetypes/application/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,22 @@ + + + + src/main/resources + + + src/test/resources + + + src/main/java + + **/*.java + + + + src/test/java + + **/*.java + + + + diff --git a/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/pom.xml b/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/pom.xml new file mode 100644 index 000000000..903f39b90 --- /dev/null +++ b/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/pom.xml @@ -0,0 +1,80 @@ + + 4.0.0 + + ${groupId} + ${artifactId} + ${version} + jar + + SwitchYard project + + + org.switchyard + switchyard-api + ${version} + + + org.switchyard + switchyard-plugin + ${version} + + + org.switchyard.components + switchyard-component-bean + ${version} + + + org.switchyard.components + switchyard-component-soap + ${version} + + + org.switchyard + switchyard-test + ${version} + + + junit + junit + 4.8.1 + test + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + true + true + true + + + + org.switchyard + switchyard-plugin + ${version} + + + org.switchyard.component.bean.config.model.BeanSwitchYardScanner + org.switchyard.component.camel.model.RouteScanner + org.switchyard.transform.config.model.TransformSwitchYardScanner + org.switchyard.validate.config.model.ValidateSwitchYardScanner + + + + + + configure + + + + + + + diff --git a/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml b/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/src/main/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/src/main/resources/META-INF/switchyard.xml b/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/src/main/resources/META-INF/switchyard.xml new file mode 100644 index 000000000..7887326cb --- /dev/null +++ b/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/src/main/resources/META-INF/switchyard.xml @@ -0,0 +1,11 @@ + + + diff --git a/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml b/core/tools/maven/archetypes/application/src/main/resources/archetype-resources/src/test/resources/META-INF/beans.xml new file mode 100644 index 000000000..e69de29bb diff --git a/core/tools/maven/plugins/switchyard/pom.xml b/core/tools/maven/plugins/switchyard/pom.xml new file mode 100644 index 000000000..12f9f5267 --- /dev/null +++ b/core/tools/maven/plugins/switchyard/pom.xml @@ -0,0 +1,92 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../../../../pom.xml + + switchyard-plugin + maven-plugin + SwitchYard: "switchyard" Plugin + The SwitchYard Plugin. + http://switchyard.org + + + + org.apache.maven.plugins + maven-plugin-plugin + + switchyard + true + + + + + descriptor + + + + + + + + + + junit + junit + + + xmlunit + xmlunit + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-config + + + org.apache.maven.plugins + maven-plugin-plugin + + + org.codehaus.plexus + plexus-utils + + + org.apache.maven.plugin-tools + maven-plugin-annotations + + + org.apache.maven + maven-model + + + org.apache.maven + maven-plugin-api + + + org.sonatype.sisu + sisu-guava + + + + + diff --git a/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/ConfigureMojo.java b/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/ConfigureMojo.java new file mode 100644 index 000000000..03f3f5931 --- /dev/null +++ b/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/ConfigureMojo.java @@ -0,0 +1,263 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.tools.maven.plugins.switchyard; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Resource; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.StringUtils; +import org.switchyard.common.type.Classes; +import org.switchyard.config.OutputKey; +import org.switchyard.config.model.MergeScanner; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.ModelPullerScanner; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; + +/** + * Maven mojo for configuring SwitchYard. + * + * @param the Model type being configured + * + * @author David Ward <dward@jboss.org> © 2011 Red Hat Inc. + */ +@Mojo(name="configure", defaultPhase=LifecyclePhase.PROCESS_CLASSES, requiresDependencyResolution=ResolutionScope.COMPILE) +public class ConfigureMojo extends AbstractMojo { + + private static final String SWITCHARD_XML_FILE_NAME = "switchyard.xml"; + private static final String SWITCHYARD_XML_DEFAULT_FOLDER = "META-INF"; + private static final String DEFAULT_SWITCHYARD_XML_FILE_PATH = SWITCHYARD_XML_DEFAULT_FOLDER + File.separator + SWITCHARD_XML_FILE_NAME; + + @Parameter(property="project.artifactId") + private String _project_artifactId; + + @Parameter(property="project.build.outputDirectory", alias="outputDirectory") + private File _project_build_outputDirectory; + + @Parameter(property="project.compileClasspathElements") + private List _project_compileClasspathElements; + + @Parameter(property="project.resources") + private List _project_resources; + + @Parameter(property="validate", alias="validate") + private boolean _validate = true; + + @Parameter(alias="outputFile") + private File _outputFile; + + @Parameter(alias="scanDirectories") + private File[] _scanDirectories = new File[] {}; + + @Parameter(alias="scannerClassNames") + private String[] _scannerClassNames = new String[] {}; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + final List mojoURLs = new ArrayList(); + try { + for (String compileClasspaths : _project_compileClasspathElements) { + mojoURLs.add(new File(compileClasspaths).toURI().toURL()); + } + for (Resource resource : _project_resources) { + String path = resource.getTargetPath(); + if (path != null) { + File file = new File(path); + if (file.exists()) { + mojoURLs.add(file.toURI().toURL()); + } + } + } + if (_project_build_outputDirectory.getAbsoluteFile().exists()) { + mojoURLs.add(_project_build_outputDirectory.getAbsoluteFile().toURI().toURL()); + } + for (File scanDir : _scanDirectories) { + if (scanDir != null) { + scanDir = scanDir.getAbsoluteFile(); + if (scanDir.exists()) { + mojoURLs.add(scanDir.toURI().toURL()); + } + } + } + } catch (MalformedURLException mue) { + throw new MojoExecutionException(mue.getMessage(), mue); + } + ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction() { + public URLClassLoader run() { + return new URLClassLoader(mojoURLs.toArray(new URL[mojoURLs.size()]), ConfigureMojo.class.getClassLoader()); + } + }); + ClassLoader previous = Classes.setTCCL(loader); + Writer writer = null; + try { + List> scanners = new ArrayList>(); + addModelPullerScanners(scanners); + for (String scannerClassName : _scannerClassNames) { + @SuppressWarnings("unchecked") + Class> scannerClass = (Class>)Classes.forName(scannerClassName, loader); + if (scannerClass != null) { + Scanner scanner = scannerClass.newInstance(); + scanners.add(scanner); + } + } + //getLog().info("SwitchYard configure plugin using scanners: " + scanners); + MergeScanner merge_scanner = new MergeScanner(true, scanners); + List scannerURLs = new ArrayList(); + if (_scanDirectories.length == 0) { + scannerURLs.add(_project_build_outputDirectory.toURI().toURL()); + } else { + for (File scanDir : _scanDirectories) { + if (scanDir != null) { + scannerURLs.add(scanDir.toURI().toURL()); + } + } + } + getLog().info("SwitchYard configure plugin scanner URLs: " + scannerURLs); + ScannerInput scanner_input = new ScannerInput().setCompositeName(_project_artifactId).setURLs(scannerURLs); + M model = merge_scanner.scan(scanner_input).getModel(); + if (_outputFile == null) { + File od = new File(_project_build_outputDirectory, SWITCHYARD_XML_DEFAULT_FOLDER); + if (!od.exists()) { + if (!od.mkdirs()) { + throw new Exception("mkdirs() on " + od + " failed."); + } + } + _outputFile = new File(od, SWITCHARD_XML_FILE_NAME); + } else { + // make sure output directory exists + File od = _outputFile.getParentFile(); + if (!od.exists()) { + if (!od.mkdirs()) { + throw new Exception("mkdirs() on " + od + " failed."); + } + } + } + getLog().info("Outputting SwitchYard configuration model to " + _outputFile.getAbsolutePath()); + writer = new BufferedWriter(new FileWriter(_outputFile)); + model.write(writer, OutputKey.PRETTY_PRINT); + writer.flush(); + // we write the output before we assert validity so that the user can compare the written XML to the validation error + if (_validate) { + getLog().info("Validating SwitchYard configuration model..."); + model.assertModelValid(); + } else { + getLog().warn("Skipping validation of SwitchYard configuration model. (Enable with true.)"); + } + } catch (Throwable t) { + throw new MojoExecutionException(t.getMessage(), t); + } finally { + Classes.setTCCL(previous); + if (writer != null) { + try { + writer.close(); + } catch (IOException ioe) { + throw new MojoExecutionException(ioe.getMessage(), ioe); + } + } + } + } + + /** + * Add a ModelPullerScanner for each instance of META-INF/switchyard.xml + * that is found in a resource or scan folder. Any includes or excludes + * specified for the resource folder are respected (i.e. if a switchyard.xml + * file is in the resource folder, but excluded, a scanner will not be added + * for that file). No filtering is applied to scan folders. + * + * @param scanners the scanners list + * @throws IOException if an error occurs scanning the resource folder(s) for files. + */ + private void addModelPullerScanners(final List> scanners) throws IOException { + for (Resource resource : _project_resources) { + addModelPullerScanner(new File(resource.getDirectory()).getCanonicalFile(), + convertInExcludes(resource.getIncludes()), convertInExcludes(resource.getExcludes()), scanners); + } + for (File file : _scanDirectories) { + addModelPullerScanner(file.getCanonicalFile(), null, null, scanners); + } + } + + /** + * Adds a scanner if a "META-INF/switchyard.xml" file is found in the folder specified by baseDir. + * + * @param baseDir the directory to search. + * @param includes file includes. + * @param excludes file excludes. + * @param scanners the scanners list + * @throws IOException if an error occurs. + */ + private void addModelPullerScanner(final File baseDir, final String includes, final String excludes, final List> scanners) throws IOException { + final File switchYardFile = new File(baseDir, DEFAULT_SWITCHYARD_XML_FILE_PATH).getCanonicalFile(); + for (File file : (List)FileUtils.getFiles(baseDir, includes, excludes)) { + file = file.getCanonicalFile(); + if (switchYardFile.equals(file)) { + // found a match, add a scanner + scanners.add(new ModelPullerScanner(file) { + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + ScannerOutput output = super.scan(input); + M model = output.getModel(); + if (model != null) { + Model root = model.getModelRoot(); + if (root instanceof SwitchYardModel) { + if (!input.isSwitchyardNamespaceSet()) { + String uri = root.getModelRootNamespace(); + SwitchYardNamespace ns = SwitchYardNamespace.fromUri(uri); + input.setSwitchyardNamespace(ns); + } + } + } + return output; + } + }); + // one file per folder + return; + } + } + } + + private String convertInExcludes(List cludes) { + if (cludes == null) { + return null; + } + final String converted = StringUtils.join(cludes.iterator(), ","); + if (converted.length() == 0) { + return null; + } + return converted; + } + +} diff --git a/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/MavenLogger.java b/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/MavenLogger.java new file mode 100644 index 000000000..ab565d940 --- /dev/null +++ b/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/MavenLogger.java @@ -0,0 +1,18 @@ +package org.switchyard.tools.maven.plugins.switchyard; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 16200-16399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface MavenLogger { + /** + * Default root logger. + */ + MavenLogger ROOT_LOGGER = Logger.getMessageLogger(MavenLogger.class, MavenLogger.class.getPackage().getName()); +} diff --git a/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/MavenMessages.java b/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/MavenMessages.java new file mode 100644 index 000000000..7830b4822 --- /dev/null +++ b/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/MavenMessages.java @@ -0,0 +1,18 @@ +package org.switchyard.tools.maven.plugins.switchyard; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.MessageBundle; + +/** + *

+ * This file is using the subset 16400-16599 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface MavenMessages { + /** + * Default messages. + */ + MavenMessages MESSAGES = Messages.getBundle(MavenMessages.class); +} diff --git a/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/SetVersionMojo.java b/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/SetVersionMojo.java new file mode 100644 index 000000000..7affab7fb --- /dev/null +++ b/core/tools/maven/plugins/switchyard/src/main/java/org/switchyard/tools/maven/plugins/switchyard/SetVersionMojo.java @@ -0,0 +1,249 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.tools.maven.plugins.switchyard; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.lang.Strings; +import org.switchyard.config.Configuration; +import org.switchyard.config.ConfigurationPuller; +import org.switchyard.config.OutputKey; + +/** + * Maven mojo for setting the SwitchYard version. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@Mojo(name="setVersion", defaultPhase=LifecyclePhase.VALIDATE, requiresDirectInvocation=true) +public class SetVersionMojo extends AbstractMojo { + + private static final String XML_DECLARATION = "\n"; + + private static final String XML_COPYRIGHT = + "\n"; + + @Parameter(property="project.file", required=true) + private File _project_file; + + @Parameter(property="oldVersion", required=true) + private String _oldVersion; + + @Parameter(property="newVersion", required=true) + private String _newVersion; + + @Parameter(property="prettyPrint", alias="prettyPrint") + private boolean _prettyPrint = true; + + private String _oldVersion_pom; + private String _oldVersion_download; + private String _oldVersion_distro; + + private String _newVersion_pom; + private String _newVersion_download; + private String _newVersion_distro; + + /** + * {@inheritDoc} + */ + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + parseVersion(_oldVersion, true); + parseVersion(_newVersion, false); + AtomicBoolean projectModified = new AtomicBoolean(false); + try { + Configuration project = new ConfigurationPuller(false).pull(_project_file); + if (project != null) { + setVersion(project.getFirstChild("version"), _newVersion_pom, projectModified); + Configuration project_parent = project.getFirstChild("parent"); + if (project_parent != null) { + Configuration project_parent_groupId = project_parent.getFirstChild("groupId"); + if (project_parent_groupId != null) { + String ppgid = Strings.trimToNull(project_parent_groupId.getValue()); + if (ppgid != null && ppgid.startsWith("org.switchyard")) { + setVersion(project_parent.getFirstChild("version"), _newVersion_pom, projectModified); + } + } + } + Configuration project_properties = project.getFirstChild("properties"); + if (project_properties != null) { + setVersion(project_properties.getFirstChild("switchyard.version"), _newVersion_pom, projectModified); + setVersion(project_properties.getFirstChild("version.switchyard.runtime"), _newVersion_pom, projectModified); + setVersion(project_properties.getFirstChild("version.distro"), _newVersion_distro, projectModified); + } + if (projectModified.get()) { + getLog().info(_project_file.getAbsolutePath() + " modified. Writing..."); + write(project, _project_file); + } else { + getLog().info(_project_file.getAbsolutePath() + " not modified. Skipping..."); + } + File installerFile = new File(new File(_project_file.getParentFile(), "scripts"), "installer.properties"); + if (installerFile.exists()) { + final String installerOld = new StringPuller().pull(installerFile); + String installerNew = installerOld; + String[][] replacements = new String[][] { + new String[] {_oldVersion_pom, _newVersion_pom}, + new String[] {_oldVersion_download, _newVersion_download}, + new String[] {_oldVersion_distro, _newVersion_distro} + }; + for (String[] replacement : replacements) { + replacement[0] = replacement[0].replaceAll("\\.", "\\\\."); + installerNew = installerNew.replaceAll(replacement[0], replacement[1]); + } + if (!installerNew.equals(installerOld)) { + getLog().info(installerFile.getAbsolutePath() + " modified. Writing..."); + write(installerNew, installerFile); + } else { + getLog().info(installerFile.getAbsolutePath() + " not modified. Skipping..."); + } + } + } + } catch (IOException ioe) { + throw new MojoExecutionException(ioe.getMessage(), ioe); + } + } + + private void parseVersion(String version, boolean old) throws MojoExecutionException { + // 0.6.0.Beta1, 0.6, v0.6.Beta1 (formats: pom, distro, download) + version = Strings.trimToNull(version); + if (version == null) { + throw new MojoExecutionException((old ? "old" : "new") + "Version unspecified"); + } + String[] dotSplit = version.split("\\.", 4); + String major = dotSplit.length > 0 ? dotSplit[0] : null; + String minor = dotSplit.length > 1 ? dotSplit[1] : null; + String incremental = dotSplit.length > 2 ? dotSplit[2] : null; + String qualifier = dotSplit.length > 3 ? dotSplit[3] : null; + boolean dash = false; + if (incremental != null && qualifier == null) { + String[] dashSplit = incremental.split("-", 2); + if (dashSplit.length > 1) { + incremental = dashSplit[0]; + qualifier = dashSplit[1]; + dash = true; + } + } + boolean numbers = false; + try { + Integer.parseInt(major); + Integer.parseInt(minor); + Integer.parseInt(incremental); + numbers = true; + } catch (NumberFormatException nfe) { + getLog().error(NumberFormatException.class.getSimpleName() + ": " + nfe.getMessage()); + } + if (!numbers || qualifier == null) { + String emsg = String.format("Could not parse %s version [%s]: major=%s, minor=%s, incremental=%s, dash=%b, qualifier=%s", + (old ? "old" : "new"), version, major, minor, incremental, dash, qualifier); + throw new MojoExecutionException(emsg); + } + String pom = major + '.' + minor + '.' + incremental + (dash ? '-' : '.') + qualifier; + String download = 'v' + major + '.' + minor + '.' + qualifier; + String distro = major + '.' + minor; + if (old) { + _oldVersion_pom = pom; + _oldVersion_download = download; + _oldVersion_distro = distro; + } else { + _newVersion_pom = pom; + _newVersion_download = download; + _newVersion_distro = distro; + } + } + + private void setVersion(Configuration config, String newVersion, AtomicBoolean modified) { + if (config != null) { + String oldVersion = config.getValue(); + if (newVersion.equals(oldVersion)) { + getLog().info(String.format("old version already matches new version: %s - skipping...", newVersion)); + return; + } + config.setValue(newVersion); + modified.set(true); + } + } + + private void write(Configuration config, File file) throws IOException { + Writer writer = new BufferedWriter(new FileWriter(file)); + try { + writer.write(XML_DECLARATION); + writer.write(XML_COPYRIGHT.replaceFirst("YEAR", new SimpleDateFormat("yyyy").format(new Date()))); + if (_prettyPrint) { + config.write(writer, OutputKey.OMIT_XML_DECLARATION, OutputKey.PRETTY_PRINT); + } else { + config.write(writer, OutputKey.OMIT_XML_DECLARATION); + writer.write("\n"); + } + writer.flush(); + } finally { + writer.close(); + } + } + + private void write(String content, File file) throws IOException { + Writer writer = new BufferedWriter(new FileWriter(file)); + try { + writer.write(content); + writer.flush(); + } finally { + writer.close(); + } + } + + /** + * Parse test. + * @param args unused + * @throws Exception if something blows up + */ + public static void main(String... args) throws Exception { + String[] oldVersions = new String[]{"0.6.0-SNAPSHOT", "0.6.0.Beta1", "0.6.0.Final"}; + String[] newVersions = new String[]{"0.6.0.Final", "0.6.0-SNAPSHOT", "0.7.0-SNAPSHOT"}; + for (int i=0; i < oldVersions.length; i++) { + SetVersionMojo m = new SetVersionMojo(); + m._oldVersion = oldVersions[i]; + m._newVersion = newVersions[i]; + m.parseVersion(m._oldVersion, true); + m.parseVersion(m._newVersion, false); + System.out.println(String.format( + "_oldVersion_pom[%s], _oldVersion_download[%s], _oldVersion_distro[%s], _newVersion_pom[%s], _newVersion_download[%s], _newVersion_distro[%s]", + m._oldVersion_pom, m._oldVersion_download, m._oldVersion_distro, m._newVersion_pom, m._newVersion_download, m._newVersion_distro)); + } + } + +} diff --git a/core/transform/pom.xml b/core/transform/pom.xml new file mode 100644 index 000000000..8bdd9cf1c --- /dev/null +++ b/core/transform/pom.xml @@ -0,0 +1,143 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-transform + bundle + SwitchYard: Transform + The SwitchYard Transform library. + http://switchyard.org + + + org.switchyard.transform.config.*; + org.switchyard.transform.dozer.*; + org.switchyard.transform.internal.*; + org.switchyard.transform.jaxb.*; + org.switchyard.transform.json.*; + org.switchyard.transform.ootb.*; + org.switchyard.transform.smooks.*; + org.switchyard.transform.xslt.*; + org.switchyard.transform.osgi.internal.*; + + + org.dozer.*;resolution:=optional, + org.milyn.*;resolution:=optional, + org.mvel2.*;resolution:=optional, + javax.enterprise.inject.spi;resolution:=optional, + org.switchyard.common.cdi;resolution:=optional;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-cdi + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-extensions-java + + + + org.milyn + milyn-smooks-all + + + xml-apis + xml-apis + + + xerces + xercesImpl + + + xerces + xmlParserAPIs + + + org.mvel + mvel2 + + + + + + net.sf.dozer + dozer + + + org.switchyard + switchyard-runtime + test + + + junit + junit + test + + + xmlunit + xmlunit + test + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + org.codehaus.jackson + jackson-mapper-asl + + + org.codehaus.jackson + jackson-core-asl + + + org.mvel + mvel2 + + + org.osgi + org.osgi.core + provided + + + diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/DozerFileEntryModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/DozerFileEntryModel.java new file mode 100644 index 000000000..a9610aa4f --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/DozerFileEntryModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.Model; + +/** + * A "entry" configuration model. + */ +public interface DozerFileEntryModel extends Model { + + /** entry. */ + public static final String ENTRY = "entry"; + + /** file. */ + public static final String FILE = "file"; + + /** + * Get file. + * @return file + */ + String getFile(); + + /** + * Set file. + * @param file file + * @return model representation + */ + DozerFileEntryModel setFile(String file); + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/DozerMappingFilesModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/DozerMappingFilesModel.java new file mode 100644 index 000000000..899f0a693 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/DozerMappingFilesModel.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A "mappingFiles" configuration model for dozer transformer. + */ +public interface DozerMappingFilesModel extends Model { + + /** mapping files. */ + public static final String MAPPING_FILES = "mappingFiles"; + + /** + * Get file entries. + * @return file entries + */ + List getEntries(); + + /** + * Set a file entry. + * @param entry file entry + * @return model representation + */ + DozerMappingFilesModel addEntry(DozerFileEntryModel entry); + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/DozerTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/DozerTransformModel.java new file mode 100644 index 000000000..b81bc96f0 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/DozerTransformModel.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.transform.TransformModel; + +/** + * A "transform.dozer" configuration model. + */ +public interface DozerTransformModel extends TransformModel { + + /** The "dozer" name. */ + String DOZER = "dozer"; + + /** + * @return get a DozerMappingFiles model. + */ + DozerMappingFilesModel getDozerMappingFiles(); + + /** Set a DozerMappingFiles model. + * @param model MappingFiles Model + * @return model representation + */ + DozerTransformModel setDozerMappingFiles(DozerMappingFilesModel model); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/JAXBTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/JAXBTransformModel.java new file mode 100644 index 000000000..efae49e04 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/JAXBTransformModel.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.transform.TransformModel; + +/** + * A "transform.jaxb" configuration model. + * + * @author tom.fennelly@gmail.com + */ +public interface JAXBTransformModel extends TransformModel { + + /** The "jaxb" name. */ + public static final String JAXB = "jaxb"; + + /** The "contextPath" name. */ + public static final String CONTEXT_PATH = "contextPath"; + + /** + * Gets the contextPath attribute. + * @return the contextPath attribute + */ + public String getContextPath(); + + /** + * Sets the contextPath attribute. + * @param contextPath the contextPath attribute + * @return this JAXBTransformModel (useful for chaining) + */ + public JAXBTransformModel setContextPath(String contextPath); + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/JSONTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/JSONTransformModel.java new file mode 100644 index 000000000..eec0963e0 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/JSONTransformModel.java @@ -0,0 +1,30 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.transform.TransformModel; + +/** + * A "transform.json" configuration model. + * + * @author Alejandro Montenegro <aamonten@gmail.com> + */ +public interface JSONTransformModel extends TransformModel{ + + /** + * json transform model namespace. + */ + public static final String JSON = "json"; +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/Java2XmlTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/Java2XmlTransformModel.java new file mode 100644 index 000000000..63f4540e8 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/Java2XmlTransformModel.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.transform.TransformModel; + +/** + * A "transform.java2xml" configuration model. + * + * @author tom.fennelly@gmail.com + */ +public interface Java2XmlTransformModel extends TransformModel { + + /** The "java2xml" name. */ + public static final String JAVA2XML = "java2xml"; + + /** The "config" name. */ + public static final String CONFIG = "config"; + + /** + * Gets the config attribute. + * @return the config attribute + */ + public String getConfig(); + + /** + * Sets the config attribute. + * @param config the config attribute + * @return this Java2XmlTransformModel (useful for chaining) + */ + public Java2XmlTransformModel setConfig(String config); + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/JavaTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/JavaTransformModel.java new file mode 100644 index 000000000..27703f9cf --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/JavaTransformModel.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.transform.TransformModel; + +/** + * A "transform.java" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface JavaTransformModel extends TransformModel { + + /** The "java" name. */ + public static final String JAVA = "java"; + + /** The "class" name. */ + public static final String CLASS = "class"; + + /** The "bean" name. */ + public static final String BEAN = "bean"; + + /** + * Gets the class attribute. + * @return the class attribute + */ + public String getClazz(); + + /** + * Sets the class attribute. + * @param clazz the class attribute + * @return this JavaTransformModel (useful for chaining) + */ + public JavaTransformModel setClazz(String clazz); + + /** + * Gets the bean attribute. + * @return the bean attribute + */ + public String getBean(); + + /** + * Sets the bean attribute. + * @param bean the bean attribute + * @return this JavaTransformModel (useful for chaining) + */ + public JavaTransformModel setBean(String bean); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/JavaTransformType.java b/core/transform/src/main/java/org/switchyard/transform/config/model/JavaTransformType.java new file mode 100644 index 000000000..11baa7b89 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/JavaTransformType.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +/** + * Java transformation type. + * + * @author tom.fennelly@gmail.com + */ +public enum JavaTransformType { + /** + * XML to Java Transformation. + */ + XML2JAVA, + /** + * Java to XML Transformation. + */ + JAVA2XML +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/SmooksTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/SmooksTransformModel.java new file mode 100644 index 000000000..fc40ded91 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/SmooksTransformModel.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.transform.TransformModel; + +/** + * A "transform.smooks" configuration model. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public interface SmooksTransformModel extends TransformModel { + + /** The "smooks" name. */ + public static final String SMOOKS = "smooks"; + + /** The "config" name. */ + public static final String CONFIG = "config"; + + /** The "type" name. */ + public static final String TYPE = "type"; + + /** The "reportPath" name. */ + public static final String REPORT_PATH = "reportPath"; + + /** + * Gets the type attribute. + * @return the type attribute + */ + public String getTransformType(); + + /** + * Sets the type attribute. + * @param type the type attribute + * @return this SmooksTransformModel (useful for chaining) + */ + public SmooksTransformModel setTransformType(String type); + + /** + * Gets the config attribute. + * @return the config attribute + */ + public String getConfig(); + + + /** + * Sets the config attribute. + * @param config the config attribute + * @return this SmooksTransformModel (useful for chaining) + */ + public SmooksTransformModel setConfig(String config); + + /** + * Gets the reportPath attribute. + * @return the reportPath attribute + */ + public String getReportPath(); + + /** + * Sets the reportPath attribute. + * @param reportPath the reportPath attribute + * @return this SmooksTransformModel (useful for chaining) + */ + public SmooksTransformModel setReportPath(String reportPath); + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/SmooksTransformType.java b/core/transform/src/main/java/org/switchyard/transform/config/model/SmooksTransformType.java new file mode 100644 index 000000000..038ec3ae6 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/SmooksTransformType.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +/** + * Smooks transformation type. + * + * @author tom.fennelly@gmail.com + */ +public enum SmooksTransformType { + /** + * Basic Smooks Transformation. + *

+ * The result type is defined through the <core:exports> + * section of the configuration. + *

+ * See the Smooks User Guide. + */ + SMOOKS, + /** + * XML to Java Transformation via Smooks Java Binding configurations. + *

+ * See the Smooks User Guide. + */ + XML2JAVA, + /** + * Java to XML Transformation via Smooks Java Binding configurations. + *

+ * See the Smooks User Guide. + */ + JAVA2XML +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/TransformNamespace.java b/core/transform/src/main/java/org/switchyard/transform/config/model/TransformNamespace.java new file mode 100644 index 000000000..37549940d --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/TransformNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Transform config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum TransformNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new TransformNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + TransformNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the TransformNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the TransformNamespace + */ + public static TransformNamespace fromUri(String uri) { + return Util.fromUri(TransformNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(TransformNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-config:transform", version); + } + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/TransformSwitchYardScanner.java b/core/transform/src/main/java/org/switchyard/transform/config/model/TransformSwitchYardScanner.java new file mode 100644 index 000000000..d9a096de4 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/TransformSwitchYardScanner.java @@ -0,0 +1,110 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import java.io.IOException; +import java.net.URL; +import java.util.List; + +import org.switchyard.common.cdi.CDIUtil; +import org.switchyard.common.type.classpath.AbstractTypeFilter; +import org.switchyard.common.type.classpath.ClasspathScanner; +import org.switchyard.config.model.Scannable; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.model.transform.v1.V1TransformsModel; +import org.switchyard.transform.config.model.v1.V1JavaTransformModel; +import org.switchyard.transform.internal.TransformerTypes; +import org.switchyard.transform.internal.TransformerUtil; + +/** + * Scanner for {@link org.switchyard.transform.Transformer} implementations. + * + * @author tom.fennelly@gmail.com + */ +public class TransformSwitchYardScanner implements Scanner { + + /** + * {@inheritDoc} + */ + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + SwitchYardNamespace switchyardNamespace = input.getSwitchyardNamespace(); + SwitchYardModel switchyardModel = new V1SwitchYardModel(switchyardNamespace.uri()); + TransformsModel transformsModel = null; + + TransformNamespace transformNamespace = TransformNamespace.DEFAULT; + for (TransformNamespace value : TransformNamespace.values()) { + if (value.versionMatches(switchyardNamespace)) { + transformNamespace = value; + break; + } + } + + List> transformerClasses = scanForTransformers(input.getURLs()); + for (Class transformer : transformerClasses) { + List supportedTransforms = TransformerUtil.listTransformations(transformer); + + for (TransformerTypes supportedTransform : supportedTransforms) { + JavaTransformModel transformModel = new V1JavaTransformModel(transformNamespace.uri()); + + String bean = CDIUtil.getNamedAnnotationValue(transformer); + if (bean != null) { + transformModel.setBean(bean); + } else { + transformModel.setClazz(transformer.getName()); + } + transformModel.setFrom(supportedTransform.getFrom()); + transformModel.setTo(supportedTransform.getTo()); + + if (transformsModel == null) { + transformsModel = new V1TransformsModel(switchyardNamespace.uri()); + switchyardModel.setTransforms(transformsModel); + } + transformsModel.addTransform(transformModel); + } + } + + return new ScannerOutput().setModel(switchyardModel); + } + + private List> scanForTransformers(List urls) throws IOException { + AbstractTypeFilter filter = new TransformerInstanceOfFilter(); + ClasspathScanner scanner = new ClasspathScanner(filter); + + for (URL url : urls) { + scanner.scan(url); + } + + return filter.getMatchedTypes(); + } + + private class TransformerInstanceOfFilter extends AbstractTypeFilter { + @Override + public boolean matches(Class clazz) { + Scannable scannable = clazz.getAnnotation(Scannable.class); + if (scannable != null && !scannable.value()) { + // Marked as being non-scannable... + return false; + } + return TransformerUtil.isTransformer(clazz); + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/Xml2JavaTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/Xml2JavaTransformModel.java new file mode 100644 index 000000000..33a6d99be --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/Xml2JavaTransformModel.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.transform.TransformModel; + +/** + * A "transform.xml2java" configuration model. + * + * @author tom.fennelly@gmail.com + */ +public interface Xml2JavaTransformModel extends TransformModel { + + /** The "xml2java" name. */ + public static final String XML2JAVA = "xml2java"; + + /** The "config" name. */ + public static final String CONFIG = "config"; + + /** + * Gets the config attribute. + * @return the config attribute + */ + public String getConfig(); + + /** + * Sets the config attribute. + * @param config the config attribute + * @return this Xml2JavaTransformModel (useful for chaining) + */ + public Xml2JavaTransformModel setConfig(String config); + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/XsltTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/XsltTransformModel.java new file mode 100644 index 000000000..00cb5b6d6 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/XsltTransformModel.java @@ -0,0 +1,58 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import org.switchyard.config.model.transform.TransformModel; + +/** + * @author Alejandro Montenegro + */ +public interface XsltTransformModel extends TransformModel { + + /** The "xslt" name. */ + String XSLT = "xslt"; + + /** The "xslt file" location. */ + String XSLT_FILE_URI = "xsltFile"; + + /** whether a warning should be reported as an Exception. */ + String FAIL_ON_WARNING = "failOnWarning"; + + /** + * @return xslt identifier + */ + String getXsltFile(); + + /** Set xslt identifier. + * @param xsltFile URI of xslt file + * @return model representation + */ + XsltTransformModel setXsltFile(String xsltFile); + + /** Return whether a warning should be reported as an SwitchYardException. + * If failOnWarning attribute is "true", then a warning should be reported + * as an SwitchYardException, otherwise just log. + * @return whether a warning should be reported as an SwitchYardException + */ + boolean failOnWarning(); + + /** Set whether a warning should be reported as an SwitchYardException. + * If failOnWarning attribute is "true", then a warning should be reported + * as an SwitchYardException, otherwise just log. + * @param failOnWarning whether a warning should be reported as an SwitchYardException + * @return model representation + */ + XsltTransformModel setFailOnWarning(boolean failOnWarning); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JAXBTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JAXBTransformModel.java new file mode 100644 index 000000000..70bbb28fa --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JAXBTransformModel.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; +import org.switchyard.transform.config.model.JAXBTransformModel; +import org.switchyard.transform.internal.TransformerFactoryClass; +import org.switchyard.transform.jaxb.internal.JAXBTransformerFactory; + +/** + * A version 1 JAXBTransformModel. + * + * @author tom.fennelly@gmail.com + */ +@TransformerFactoryClass(JAXBTransformerFactory.class) +public class V1JAXBTransformModel extends V1BaseTransformModel implements JAXBTransformModel { + + /** + * Constructs a new V1JAXBTransformModel. + * @param namespace namespace + */ + public V1JAXBTransformModel(String namespace) { + super(new QName(namespace, TransformModel.TRANSFORM + '.' + JAXB)); + } + + /** + * Constructs a new V1SmooksTransformModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1JAXBTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getContextPath() { + return getModelAttribute(CONTEXT_PATH); + } + + /** + * {@inheritDoc} + */ + @Override + public JAXBTransformModel setContextPath(String contextPath) { + setModelAttribute(CONTEXT_PATH, contextPath); + return this; + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JSONTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JSONTransformModel.java new file mode 100644 index 000000000..8f5e7ba6a --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JSONTransformModel.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; +import org.switchyard.transform.config.model.JSONTransformModel; +import org.switchyard.transform.internal.TransformerFactoryClass; +import org.switchyard.transform.json.internal.JSONTransformFactory; + +/** + * Version 1 JSON Transform Model. + * + * @author Alejandro Montenegro <aamonten@gmail.com> + */ +@TransformerFactoryClass(JSONTransformFactory.class) +public class V1JSONTransformModel extends V1BaseTransformModel implements JSONTransformModel { + + /** + * Constructor. + * @param namespace namespace + */ + public V1JSONTransformModel(String namespace) { + super(new QName(namespace, TransformModel.TRANSFORM + '.' + JSON)); + } + + /** + * Constructor. + * @param config configuration. + * @param desc descriptor. + */ + public V1JSONTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1Java2XmlTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1Java2XmlTransformModel.java new file mode 100644 index 000000000..96b5a154e --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1Java2XmlTransformModel.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; +import org.switchyard.transform.config.model.Java2XmlTransformModel; + +/** + * A version 1 Java2XmlTransformModel. + * + * @author tom.fennelly@gmail.com + */ +public class V1Java2XmlTransformModel extends V1BaseTransformModel implements Java2XmlTransformModel { + + /** + * Constructs a new V1Java2XmlTransformModel. + * @param namespace namespace + */ + public V1Java2XmlTransformModel(String namespace) { + super(new QName(namespace, TransformModel.TRANSFORM + '.' + JAVA2XML)); + } + + /** + * Constructs a new V1Java2XmlTransformModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1Java2XmlTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getConfig() { + return getModelAttribute(CONFIG); + } + + /** + * {@inheritDoc} + */ + @Override + public V1Java2XmlTransformModel setConfig(String config) { + setModelAttribute(CONFIG, config); + return this; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JavaTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JavaTransformModel.java new file mode 100644 index 000000000..5b1185c1b --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1JavaTransformModel.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; +import org.switchyard.transform.config.model.JavaTransformModel; + +/** + * A version 1 JavaTransformModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1JavaTransformModel extends V1BaseTransformModel implements JavaTransformModel { + + /** + * Constructs a new V1JavaTransformModel. + * @param namespace namespace + */ + public V1JavaTransformModel(String namespace) { + super(new QName(namespace, TransformModel.TRANSFORM + '.' + JAVA)); + } + + /** + * Constructs a new V1JavaTransformModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1JavaTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getClazz() { + return getModelAttribute(CLASS); + } + + /** + * {@inheritDoc} + */ + @Override + public JavaTransformModel setClazz(String clazz) { + setModelAttribute(CLASS, clazz); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getBean() { + return getModelAttribute(BEAN); + } + + /** + * {@inheritDoc} + */ + @Override + public JavaTransformModel setBean(String bean) { + setModelAttribute(BEAN, bean); + return this; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1SmooksTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1SmooksTransformModel.java new file mode 100644 index 000000000..4609c600f --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1SmooksTransformModel.java @@ -0,0 +1,114 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; +import org.switchyard.transform.config.model.SmooksTransformModel; +import org.switchyard.transform.config.model.SmooksTransformType; +import org.switchyard.transform.internal.TransformerFactoryClass; +import org.switchyard.transform.smooks.internal.SmooksTransformFactory; + +/** + * A version 1 SmooksTransformModel. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +@TransformerFactoryClass(SmooksTransformFactory.class) +public class V1SmooksTransformModel extends V1BaseTransformModel implements SmooksTransformModel { + + /** + * Constructs a new V1SmooksTransformModel. + * @param namespace namespace + */ + public V1SmooksTransformModel(String namespace) { + super(new QName(namespace, TransformModel.TRANSFORM + '.' + SMOOKS)); + } + + /** + * Constructs a new V1SmooksTransformModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1SmooksTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getTransformType() { + return getModelAttribute(TYPE); + } + + /** + * {@inheritDoc} + */ + @Override + public V1SmooksTransformModel setTransformType(String type) { + setModelAttribute(TYPE, type); + return this; + } + + /** + * Set the Smooks Transformation type. + * @param type The transformation type. + * @return this TransformModel instance. + */ + public V1SmooksTransformModel setTransformType(SmooksTransformType type) { + setModelAttribute(TYPE, type.toString()); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getConfig() { + return getModelAttribute(CONFIG); + } + + /** + * {@inheritDoc} + */ + @Override + public V1SmooksTransformModel setConfig(String config) { + setModelAttribute(CONFIG, config); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getReportPath() { + return getModelAttribute(REPORT_PATH); + } + + /** + * {@inheritDoc} + */ + @Override + public V1SmooksTransformModel setReportPath(String reportPath) { + setModelAttribute(REPORT_PATH, reportPath); + return this; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1TransformMarshaller.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1TransformMarshaller.java new file mode 100644 index 000000000..cdcfd7844 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1TransformMarshaller.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.transform.config.model.JAXBTransformModel; +import org.switchyard.transform.config.model.JSONTransformModel; +import org.switchyard.transform.config.model.JavaTransformModel; +import org.switchyard.transform.config.model.SmooksTransformModel; +import org.switchyard.transform.config.model.XsltTransformModel; + +/** + * Marshalls transform Models. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class V1TransformMarshaller extends BaseMarshaller { + + private static final String TRANSFORM_JAVA = TransformModel.TRANSFORM + "." + JavaTransformModel.JAVA; + private static final String TRANSFORM_SMOOKS = TransformModel.TRANSFORM + "." + SmooksTransformModel.SMOOKS; + private static final String TRANSFORM_JSON = TransformModel.TRANSFORM + "." + JSONTransformModel.JSON; + private static final String TRANSFORM_XSLT = TransformModel.TRANSFORM + "." + XsltTransformModel.XSLT; + private static final String TRANSFORM_JAXB = TransformModel.TRANSFORM + "." + JAXBTransformModel.JAXB; + + /** + * Constructs a new V1TransformMarshaller with the specified Descriptor. + * @param desc the Descriptor + */ + public V1TransformMarshaller(Descriptor desc) { + super(desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + + if (name.equals(TRANSFORM_JAVA)) { + return new V1JavaTransformModel(config, desc); + } else if (name.equals(TRANSFORM_SMOOKS)) { + return new V1SmooksTransformModel(config, desc); + } else if (name.equals(TRANSFORM_JSON)) { + return new V1JSONTransformModel(config, desc); + } else if (name.equals(TRANSFORM_XSLT)) { + return new V1XsltTransformModel(config, desc); + } else if (name.equals(TRANSFORM_JAXB)) { + return new V1JAXBTransformModel(config, desc); + } + + return null; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1Xml2JavaTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1Xml2JavaTransformModel.java new file mode 100644 index 000000000..c5e0c5d88 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1Xml2JavaTransformModel.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; +import org.switchyard.transform.config.model.Xml2JavaTransformModel; + +/** + * A version 1 Xml2JavaTransformModel. + * + * @author tom.fennelly@gmail.com + */ +public class V1Xml2JavaTransformModel extends V1BaseTransformModel implements Xml2JavaTransformModel { + + /** + * Constructs a new V1Xml2JavaTransformModel. + * @param namespace namespace + */ + public V1Xml2JavaTransformModel(String namespace) { + super(new QName(namespace, TransformModel.TRANSFORM + '.' + XML2JAVA)); + } + + /** + * Constructs a new V1Xml2JavaTransformModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1Xml2JavaTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getConfig() { + return getModelAttribute(CONFIG); + } + + /** + * {@inheritDoc} + */ + @Override + public V1Xml2JavaTransformModel setConfig(String config) { + setModelAttribute(CONFIG, config); + return this; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1XsltTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1XsltTransformModel.java new file mode 100644 index 000000000..b07d1029c --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v1/V1XsltTransformModel.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; +import org.switchyard.transform.config.model.XsltTransformModel; +import org.switchyard.transform.internal.TransformerFactoryClass; +import org.switchyard.transform.xslt.internal.XsltTransformFactory; + +/** + * @author Alejandro Montenegro aamonten@gmail.com + */ +@TransformerFactoryClass(XsltTransformFactory.class) +public class V1XsltTransformModel extends V1BaseTransformModel implements XsltTransformModel { + + /** + * Constructs a new V1XsltTransformModel. + * @param namespace namespace + */ + public V1XsltTransformModel(String namespace) { + super(new QName(namespace, TransformModel.TRANSFORM + '.' + XSLT)); + } + + /** + * Constructs a new V1XsltTransformModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + protected V1XsltTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getXsltFile() { + return getModelAttribute(XSLT_FILE_URI); + } + + /** + * {@inheritDoc} + */ + @Override + public V1XsltTransformModel setXsltFile(String xsltFile) { + setModelAttribute(XSLT_FILE_URI, xsltFile); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean failOnWarning() { + String failOnWarn = getModelAttribute(FAIL_ON_WARNING); + return Boolean.parseBoolean(failOnWarn); + } + + /** + * {@inheritDoc} + */ + @Override + public XsltTransformModel setFailOnWarning(boolean failOnWarning) { + setModelAttribute(FAIL_ON_WARNING, Boolean.toString(failOnWarning)); + return this; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerFileEntryModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerFileEntryModel.java new file mode 100644 index 000000000..e24927475 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerFileEntryModel.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v2; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.transform.config.model.DozerFileEntryModel; + +/** + * A version 1 DozerFileEntryModel. + */ +public class V2DozerFileEntryModel extends BaseModel implements DozerFileEntryModel { + + /** + * Constructs a new V1DozerFileEntryModel. + * @param namespace namespace + */ + public V2DozerFileEntryModel(String namespace) { + super(new QName(namespace, DozerFileEntryModel.ENTRY)); + } + + /** + * Constructs a new V1DozerFileEntryModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V2DozerFileEntryModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getFile() { + return getModelAttribute(DozerFileEntryModel.FILE); + } + + @Override + public DozerFileEntryModel setFile(String file) { + setModelAttribute(DozerFileEntryModel.FILE, file); + return this; + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerMappingFilesModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerMappingFilesModel.java new file mode 100644 index 000000000..aabb32c6a --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerMappingFilesModel.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v2; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.transform.config.model.DozerFileEntryModel; +import org.switchyard.transform.config.model.DozerMappingFilesModel; + +/** + * A version 1 DozerMappingFilesModel. + */ +public class V2DozerMappingFilesModel extends BaseModel implements DozerMappingFilesModel { + + private List _entries = new ArrayList(); + + /** + * Constructs a new V1DozerMappingFilesModel. + * @param namespace namespace + */ + public V2DozerMappingFilesModel(String namespace) { + super(new QName(namespace, DozerMappingFilesModel.MAPPING_FILES)); + } + + /** + * Constructs a new V1DozerMappingFilesModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V2DozerMappingFilesModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration entryConfig : config.getChildrenStartsWith(DozerFileEntryModel.ENTRY)) { + DozerFileEntryModel entry = (DozerFileEntryModel)readModel(entryConfig); + if (entry != null) { + _entries.add(entry); + } + } + setModelChildrenOrder(DozerFileEntryModel.ENTRY); + } + + /** + * {@inheritDoc} + */ + @Override + public List getEntries() { + return _entries; + } + + /** + * {@inheritDoc} + */ + @Override + public DozerMappingFilesModel addEntry(DozerFileEntryModel entry) { + addChildModel(entry); + _entries.add(entry); + return this; + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerTransformModel.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerTransformModel.java new file mode 100644 index 000000000..771f73c3f --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2DozerTransformModel.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v2; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.v1.V1BaseTransformModel; +import org.switchyard.transform.config.model.DozerMappingFilesModel; +import org.switchyard.transform.config.model.DozerTransformModel; +import org.switchyard.transform.internal.TransformerFactoryClass; +import org.switchyard.transform.dozer.internal.DozerTransformFactory; + +/** + * A version 1 DozerTransformModel. + */ +@TransformerFactoryClass(DozerTransformFactory.class) +public class V2DozerTransformModel extends V1BaseTransformModel implements DozerTransformModel { + + private DozerMappingFilesModel _mappingFilesModel; + + /** + * Constructs a new V1DozerTransformModel. + * @param namespace namespace + */ + public V2DozerTransformModel(String namespace) { + super(new QName(namespace, TransformModel.TRANSFORM + '.' + DOZER)); + } + + /** + * Constructs a new V1DozerTransformModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V2DozerTransformModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public DozerMappingFilesModel getDozerMappingFiles() { + if (_mappingFilesModel == null) { + _mappingFilesModel = (DozerMappingFilesModel)getFirstChildModelStartsWith(DozerMappingFilesModel.MAPPING_FILES); + } + return _mappingFilesModel; + } + + /** + * {@inheritDoc} + */ + @Override + public V2DozerTransformModel setDozerMappingFiles(DozerMappingFilesModel model) { + setChildModel(model); + _mappingFilesModel = model; + return this; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2TransformMarshaller.java b/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2TransformMarshaller.java new file mode 100644 index 000000000..7956c7702 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/config/model/v2/V2TransformMarshaller.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.v2; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.transform.config.model.DozerFileEntryModel; +import org.switchyard.transform.config.model.DozerMappingFilesModel; +import org.switchyard.transform.config.model.DozerTransformModel; +import org.switchyard.transform.config.model.v1.V1TransformMarshaller; + +/** + * Marshalls transform Models. + * + * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc. + */ +public class V2TransformMarshaller extends V1TransformMarshaller { + + private static final String TRANSFORM_DOZER = TransformModel.TRANSFORM + "." + DozerTransformModel.DOZER; + + /** + * Constructs a new V2TransformMarshaller with the specified Descriptor. + * @param desc the Descriptor + */ + public V2TransformMarshaller(Descriptor desc) { + super(desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Model read(Configuration config) { + Model model = super.read(config); + if (model != null) { + return model; + } + + String name = config.getName(); + Descriptor desc = getDescriptor(); + if (name.equals(TRANSFORM_DOZER)) { + return new V2DozerTransformModel(config, desc); + } else if (name.equals(DozerMappingFilesModel.MAPPING_FILES)) { + return new V2DozerMappingFilesModel(config, desc); + } else if (name.equals(DozerFileEntryModel.ENTRY)) { + return new V2DozerFileEntryModel(config, desc); + } + + return null; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/dozer/internal/DozerTransformFactory.java b/core/transform/src/main/java/org/switchyard/transform/dozer/internal/DozerTransformFactory.java new file mode 100644 index 000000000..993f14ca6 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/dozer/internal/DozerTransformFactory.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.dozer.internal; + +import java.util.ArrayList; +import java.util.List; + +import org.switchyard.ServiceDomain; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.DozerFileEntryModel; +import org.switchyard.transform.config.model.DozerMappingFilesModel; +import org.switchyard.transform.config.model.DozerTransformModel; +import org.switchyard.transform.internal.TransformMessages; +import org.switchyard.transform.internal.TransformerFactory; + +import javax.xml.namespace.QName; + +/** + * Dozer Transformer factory. + */ +public class DozerTransformFactory implements TransformerFactory { + + /** + * Create a {@link Transformer} instance from the supplied {@link DozerTransformModel}. + * @param domain ServiceDomain instance. + * @param model The model. + * @return The Transformer instance. + */ + public Transformer newTransformer(ServiceDomain domain, DozerTransformModel model) { + QName from = model.getFrom(); + QName to = model.getTo(); + if (from == null || !QNameUtil.isJavaMessageType(from)) { + throw TransformMessages.MESSAGES.invalidFromTypeForDozerTransformer(from); + } + if (to == null || !QNameUtil.isJavaMessageType(to)) { + throw TransformMessages.MESSAGES.invalidToTypeForDozerTransformer(to); + } + + List mappingFiles = new ArrayList(); + DozerMappingFilesModel files = model.getDozerMappingFiles(); + if (files != null) { + for (DozerFileEntryModel entry : files.getEntries()) { + String filename = entry.getFile(); + if (filename != null && !filename.isEmpty()) { + mappingFiles.add(filename); + } + } + } + + return new DozerTransformer(from, to, mappingFiles); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/dozer/internal/DozerTransformer.java b/core/transform/src/main/java/org/switchyard/transform/dozer/internal/DozerTransformer.java new file mode 100644 index 000000000..87385c144 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/dozer/internal/DozerTransformer.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.dozer.internal; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.dozer.DozerBeanMapper; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; + +/** + * Dozer {@link org.switchyard.transform.Transformer}. + */ +@Scannable(false) +public class DozerTransformer extends BaseTransformer { + + private DozerBeanMapper _dozerBeanMapper; + + /** + * Constructor. + * @param from From type. + * @param to To type. + * @param config config. + */ + protected DozerTransformer(final QName from, final QName to, List configs) { + super(from, to); + _dozerBeanMapper = new DozerBeanMapper(); + if (configs != null && !configs.isEmpty()) { + _dozerBeanMapper.setMappingFiles(configs); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Object transform(Object message) { + return _dozerBeanMapper.map(message, QNameUtil.toJavaMessageType(getTo())); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/internal/DuplicateTransformerException.java b/core/transform/src/main/java/org/switchyard/transform/internal/DuplicateTransformerException.java new file mode 100644 index 000000000..12a2d6369 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/internal/DuplicateTransformerException.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal; + +import org.switchyard.SwitchYardException; + +/** + * A DuplicateTransformerException is thrown by SwitchYard when a duplicate transformer + * is trying to be registered for a 'from' and 'to' type for which there already exists + * a transformer in the transformer registry. + * + * @author Daniel Bevenius + */ +public class DuplicateTransformerException extends SwitchYardException { + + /** + * Serial version unique id. + */ + private static final long serialVersionUID = -8937972965502786027L; + + /** + * Public constructor. + * @param message Exception message. + */ + public DuplicateTransformerException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Throwable cause. + */ + public DuplicateTransformerException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/internal/TransformLogger.java b/core/transform/src/main/java/org/switchyard/transform/internal/TransformLogger.java new file mode 100644 index 000000000..1a0857861 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/internal/TransformLogger.java @@ -0,0 +1,50 @@ +package org.switchyard.transform.internal; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.WARN; + +import javax.xml.transform.TransformerException; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 16600-16799 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface TransformLogger { + /** + * Default root logger. + */ + TransformLogger ROOT_LOGGER = Logger.getMessageLogger(TransformLogger.class, TransformLogger.class.getPackage().getName()); + + /** + * warningDuringTransformation method definition. + * @param te te + */ + @LogMessage(level = WARN) + @Message(id = 16600, value = "Warning during xslt transformation") + void warningDuringTransformation(@Cause TransformerException te); + + /** + * warningDuringCompilation method definition. + * @param te te + */ + @LogMessage(level = WARN) + @Message(id = 16601, value = "Warning during xslt compilation") + void warningDuringCompilation(@Cause TransformerException te); + + /** + * exceptionClosingDOMInputSource method definition. + * @param message message + */ + @LogMessage(level = ERROR) + @Message(id = 16602, value = "Exception while closing DOM InputSource: %s") + void exceptionClosingDOMInputSource(String message); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/internal/TransformMessages.java b/core/transform/src/main/java/org/switchyard/transform/internal/TransformMessages.java new file mode 100644 index 000000000..7ffd5b7de --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/internal/TransformMessages.java @@ -0,0 +1,562 @@ +package org.switchyard.transform.internal; + +import java.beans.IntrospectionException; +import java.io.IOException; + +import javax.xml.bind.JAXBException; +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerConfigurationException; + +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.JsonProcessingException; +import org.codehaus.jackson.map.JsonMappingException; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; +import org.xml.sax.SAXException; + + +/** + *

+ * This file is using the subset 16800-16999 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface TransformMessages { + /** + * Default messages. + */ + TransformMessages MESSAGES = Messages.getBundle(TransformMessages.class); + + /** + * errorDuringXsltTransformation method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16800, value = "Error during xslt transformation") + SwitchYardException errorDuringXsltTransformation(@Cause Exception e); + + /** + * noXSLFileDefined method definition. + * @return SwitchYardException + */ + @Message(id=16801, value = "No xsl file has been defined. Check your transformer configuration.") + SwitchYardException noXSLFileDefined(); + + /** + * unexpectedErrorOcurred method definition. + * @param tce tce + * @return SwitchYardException + */ + @Message(id=16802, value = "An unexpected error ocurred while creating the xslt transformer") + SwitchYardException unexpectedErrorOcurred(@Cause TransformerConfigurationException tce); + + /** + * unableToLocateXSLTFile method definition. + * @param fileName fileName + * @param ioe ioe + * @return SwitchYardException + */ + @Message(id=16803, value = "Unable to locate the xslt file %s") + SwitchYardException unableToLocateXSLTFile(String fileName, @Cause IOException ioe); + + /** + * failedToLoadXSLFile method definition. + * @param xsltFileUri xsltFileUri + * @return SwitchYardException + */ + @Message(id=16804, value = "Failed to load xsl file '%s' from classpath.") + SwitchYardException failedToLoadXSLFile(String xsltFileUri); + + /** + * exceptionTransformingFromXML method definition. + * @param beanClassName beanClassName + * @param ioe ioe + * @return SwitchYardException + */ + @Message(id=16805, value = "Exception while transforming from XML to '%s'.") + SwitchYardException exceptionTransformingFromXML(String beanClassName, @Cause IOException ioe); + + /** + * cannotTransformToXML method definition. + * @param inputType inputType + * @param expectedType expectedType + * @return SwitchYardException + */ + @Message(id=16806, value = "Cannot transform to XML. Input type is '%s' but should be '%s'.") + SwitchYardException cannotTransformToXML(String inputType, String expectedType); + + /** + * invalidSmooksConfigurationModelNullType method definition. + * @return SwitchYardException + */ + @Message(id=16807, value = "Invalid Smooks configuration model. null or empty 'type' specification.") + SwitchYardException invalidSmooksConfigurationModelNullType(); + + /** + * invalidSmooksConfigurationModelNullConfig method definition. + * @return SwitchYardException + */ + @Message(id=16808, value = "Invalid Smooks configuration model. null or empty 'config' specification.") + SwitchYardException invalidSmooksConfigurationModelNullConfig(); + + /** + * invalidSmooksConfigurationModelNullFrom method definition. + * @return SwitchYardException + */ + @Message(id=16809, value = "Invalid Smooks configuration model. null or 'from' specification.") + SwitchYardException invalidSmooksConfigurationModelNullFrom(); + + /** + * invalidSmooksConfigurationModelNullTo method definition. + * @return SwitchYardException + */ + @Message(id=16810, value = "Invalid Smooks configuration model. null or 'to' specification.") + SwitchYardException invalidSmooksConfigurationModelNullTo(); + + /** + * failedToCreateSmooksInstance method definition. + * @param config config + * @param e e + * @return SwitchYardException + */ + @Message(id=16811, value = "Failed to create Smooks instance for config '%s'.") + SwitchYardException failedToCreateSmooksInstance(String config, @Cause Exception e); + + /** + * invalidBindingConfiguration method definition. + * @param direction direction + * @return SwitchYardException + */ + @Message(id=16812, value = "Invalid %s binding configuration. No configurations found.") + SwitchYardException invalidBindingConfiguration(String direction); + + /** + * unhandledSmooksTransformationType method definition. + * @param type type + * @return SwitchYardException + */ + @Message(id=16813, value = "Unhandled Smooks transformation type '%s'.") + SwitchYardException unhandledSmooksTransformationType(String type); + + /** + * smooksConfigurationNoExports method definition. + * @return SwitchYardException + */ + @Message(id=16814, value = "Invalid Smooks configuration file. Must define an section with " + + "a single . See Smooks User Guide.") + SwitchYardException smooksConfigurationNoExports(); + + /** + * unsupportedSmooksExport method definition. + * @param type type + * @return SwitchYardException + */ + @Message(id=16815, value = "Unsupported Smooks type '%s'. Only supports StringResult or " + + "JavaResult.") + SwitchYardException unsupportedSmooksExport(String type); + + /** + * unsupportedExceptionCreatingResult method definition. + * @param type type + * @param e e + * @return SwitchYardException + */ + @Message(id=16816, value = "Unexpected exception while creating an instance of Result type '%s'.") + SwitchYardException unsupportedExceptionCreatingResult(String type, @Cause Exception e); + + /** + * unexpectedDOMParserConfigException method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16817, value = "Unexpected DOM parser configuration exception.") + SwitchYardException unexpectedDOMParserConfigException(@Cause ParserConfigurationException e); + + /** + * errorSerializingDOMNode method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16818, value = "Error serializing DOM node.") + SwitchYardException errorSerializingDOMNode(@Cause TransformerException e); + + /** + * unexpectedExceptionCreatingJDKTransformer method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16819, value = "Unexpected exception creating JDK Transformer instance.") + SwitchYardException unexpectedExceptionCreatingJDKTransformer(@Cause TransformerConfigurationException e); + + /** + * errorReadingDOMSourceSAX method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16820, value = "Error reading DOM source.") + SwitchYardException errorReadingDOMSourceSAX(@Cause SAXException e); + + /** + * errorReadingDOMSourceIO method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16821, value = "Error reading DOM source.") + SwitchYardException errorReadingDOMSourceIO(@Cause IOException e); + + /** + * invalidToTypeNotJavaObject method definition. + * @param type type + * @return SwitchYardException + */ + @Message(id=16822, value = "Invalid 'to' type '%s'. Must be a Java Object type.") + SwitchYardException invalidToTypeNotJavaObject(String type); + + /** + * invalidToTypeClassNotFound method definition. + * @param type type + * @return SwitchYardException + */ + @Message(id=16823, value = "Invalid 'to' type '%s'. Class Not Found.") + SwitchYardException invalidToTypeClassNotFound(String type); + + /** + * failedToExtractBeanInfo method definition. + * @param type type + * @param ioe ioe + * @return SwitchYardException + */ + @Message(id=16824, value = "Failed to extract bean information from bean type '%s'.") + SwitchYardException failedToExtractBeanInfo(String type, @Cause IntrospectionException ioe); + + /** + * noSetterMethodForProperty method definition. + * @param property property + * @param className className + * @return SwitchYardException + */ + @Message(id=16825, value = "No setter method for property '%s' on class '%s'.") + SwitchYardException noSetterMethodForProperty(String property, String className); + + /** + * unableToCreateInstance method definition. + * @param type type + * @param e e + * @return SwitchYardException + */ + @Message(id=16826, value = "Unable to create instance of type '%s'.") + SwitchYardException unableToCreateInstance(String type, @Cause Exception e); + + /** + * errorInvokingSetter method definition. + * @param methodName methodName + * @param typeName typeName + * @param e e + * @return SwitchYardException + */ + @Message(id=16827, value = "Error invoking setter method '%s' on type '%s'.") + SwitchYardException errorInvokingSetter(String methodName, String typeName, @Cause Exception e); + + /** + * objectToTransformWrongType method definition. + * @param type type + * @return SwitchYardException + */ + @Message(id=16828, value = "The object to transform is of wrong instance type %s") + SwitchYardException objectToTransformWrongType(String type); + + /** + * unexpectedJSONProcessingException method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16829, value = "Unexpected JSON processing exception, check your transformer configuration") + SwitchYardException unexpectedJSONProcessingException(@Cause JsonProcessingException e); + + /** + * unexpectedIOException method definition. + * @param ioe ioe + * @return SwitchYardException + */ + @Message(id=16830, value = "Unexpected I/O exception, check your transformer configuration") + SwitchYardException unexpectedIOException(@Cause IOException ioe); + + /** + * transformationResultWrongType method definition. + * @param typeName typeName + * @return SwitchYardException + */ + @Message(id=16831, value = "Result of transformation has wrong instance type %s") + SwitchYardException transformationResultWrongType(String typeName); + + /** + * unexpectedJSONParseException method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16832, value = "Unexpected JSON parse exception, check your transformer configuration") + SwitchYardException unexpectedJSONParseException(@Cause JsonParseException e); + + /** + * unexpectedJSONMappingException method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16833, value = "Unexpected JSON mapping exception, check your transformer configuration") + SwitchYardException unexpectedJSONMappingException(@Cause JsonMappingException e); + + /** + * unexpectedIOExceptionCheckTransformer method definition. + * @param e e + * @return SwitchYardException + */ + @Message(id=16834, value = "Unexpected I/O exception, check your transformer configuration") + SwitchYardException unexpectedIOExceptionCheckTransformer(@Cause IOException e); + + /** + * notAbleToFindClassDefinition method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id=16835, value = "Not able to find class definition %s") + SwitchYardException notAbleToFindClassDefinition(String className); + + /** + * onlyOneJavaType method definition. + * @return SwitchYardException + */ + @Message(id=16836, value = "Invalid JSON Transformer configuration. One (and only one) of the " + + "specified 'to' and 'from' transform types must be a Java type.") + SwitchYardException onlyOneJavaType(); + + /** + * failedToCreateJAXBContext method definition. + * @param from from + * @param e e + * @return SwitchYardException + */ + @Message(id=16837, value = "Failed to create JAXBContext for '%s'.") + SwitchYardException failedToCreateJAXBContext(String from, @Cause JAXBException e); + + /** + * failedToCreateMarshaller method definition. + * @param type type + * @param e e + * @return SwitchYardException + */ + @Message(id=16838, value = "Failed to create Marshaller for type '%s'.") + SwitchYardException failedToCreateMarshaller(String type, @Cause JAXBException e); + + /** + * failedToUnmarshallForType method definition. + * @param type type + * @param e e + * @return SwitchYardException + * @see #failedToMarshallForType(String, JAXBException) + */ + @Message(id=16839, value = "Failed to unmarshall for type '%s'.") + SwitchYardException failedToUnmarshallForType(String type, @Cause JAXBException e); + + /** + * noJAXBElementFactoryDefined method definition. + * @param typeName typeName + * @param factoryName factoryName + * @return String + */ + @Message(id=16840, value = "JAXB Type '%s' does not have a JAXBElement factory method defined in %s" + + ". The supported JAXBElement factory methods are for types:") + String noJAXBElementFactoryDefined(String typeName, String factoryName); + + /** + * bothJavaTypes method definition. + * @return SwitchYardException + */ + @Message(id=16841, value = "Invalid JAXB Transformer configuration. The 'from' and 'to' " + + "transformation types are both Java types. Exactly one must be a Java type.") + SwitchYardException bothJavaTypes(); + + /** + * neitherJavaType method definition. + * @return SwitchYardException + */ + @Message(id=16842, value = "Invalid JAXB Transformer configuration. Neither 'from' or 'to' " + + "transformation types is a Java type. Exactly one must be a Java type.") + SwitchYardException neitherJavaType(); + + /** + * nullTransformerRegistryArgument method definition. + * @return IllegalArgumentException + */ + @Message(id=16843, value = "null 'transformerRegistry' argument.") + IllegalArgumentException nullTransformerRegistryArgument(); + + /** + * errorReadingTransformerConfig method definition. + * @param xml xml + * @param ioe ioe + * @return SwitchYardException + */ + @Message(id=16844, value = "Error reading out-of-the-box Transformer configurations from classpath (%s).") + SwitchYardException errorReadingTransformerConfig(String xml, @Cause IOException ioe); + + /** + * cdiBeanManagerNotFound method definition. + * @return SwitchYardException + */ + @Message(id=16845, value = "CDI BeanManager couldn't be found. A Java transformer class name must be specified if CDI is not enabled.") + SwitchYardException cdiBeanManagerNotFound(); + + /** + * beanNotFoundInCDIRegistry method definition. + * @param bean bean + * @return SwitchYardException + */ + @Message(id=16846, value = "The Java transformer bean '%s' couldn't be found in CDI registry.") + SwitchYardException beanNotFoundInCDIRegistry(String bean); + + + /** + * beanNotFoundInCDIRegistry method definition. + * @return SwitchYardException + */ + @Message(id=16847, value = "'bean' or 'class' must be specified for Java transformer definition") + SwitchYardException beanOrClassMustBeSpecified(); + + /** + * unableToLoadTransformerClass method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id=16848, value = "Unable to load transformer class %s") + SwitchYardException unableToLoadTransformerClass(String className); + + + /** + * unknownTransformModel method definition. + * @param transformModel transformModel + * @return SwitchYardException + */ + @Message(id=16849, value = "Unknown TransformModel type '%s'.") + SwitchYardException unknownTransformModel(String transformModel); + + /** + * transformModelNotAnnotated method definition. + * @param transformModel transformModel + * @return SwitchYardException + */ + @Message(id=16850, value = "TransformModel type '%s' is not annotated with an @TransformerFactoryClass annotation.") + SwitchYardException transformModelNotAnnotated(String transformModel); + + + + + /** + * invalidTransformerFactory method definition. + * @param transformerFactoryClassName transformerFactoryClassName + * @return SwitchYardException + */ + @Message(id=16851, value = "Invalid TransformerFactory implementation. Must implement '%s'.") + SwitchYardException invalidTransformerFactory(String transformerFactoryClassName); + + /** + * failedCreateInstanceofTransformerFactory method definition. + * @param transformModel transformModel + * @return SwitchYardException + */ + @Message(id=16852, value = "Failed to create an instance of TransformerFactory '%s'. Class must have a public default constructor and not be abstract.") + SwitchYardException failedCreateInstanceofTransformerFactory(String transformModel); + + /** + * invalidTransformerClass method definition. + * @param transformClass transformClass + * @return SwitchYardException + */ + @Message(id=16853, value = "Invalid Transformer class '%s'. Must implement the Transformer interface, or have methods annotated with the @Transformer annotation.") + SwitchYardException invalidTransformerClass(String transformClass); + + /** + * errorConstructingTransformer method definition. + * @param transformClass transformClass + * @param e e + * @return SwitchYardException + */ + @Message(id=16854, value = "Error constructing Transformer instance for class '%s'. Class must have a public default constructor.") + SwitchYardException errorConstructingTransformer(String transformClass, @Cause Exception e); + + /** + * classDoesNotSupportTransformation method definition. + * @param transformClass transformClass + * @param fromType fromType + * @param toType toType + * @return SwitchYardException + */ + @Message(id=16855, value = "Error constructing Transformer instance for class '%s'. Class does not support a transformation from type '%s' to type '%s'.") + SwitchYardException classDoesNotSupportTransformation(String transformClass, String fromType, String toType); + + /** + * errorExecutingTransformerMethod method definition. + * @param methodName methodName + * @param className className + * @param e e + * @return SwitchYardException + */ + @Message(id=16856, value = "Error executing @Transformer method '%s' on class '%s'.") + SwitchYardException errorExecutingTransformerMethod(String methodName, String className, @Cause Throwable e); + + /** + * invalidTransformerMethodParameter method definition. + * @param methodName methodName + * @param className className + * @return SwitchYardException + */ + @Message(id=16857, value = "Invalid @Transformer method '%s' on class '%s'. Must have exactly 1 parameter.") + SwitchYardException invalidTransformerMethodParameter(String methodName, String className); + + /** + * invalidTransformerMethodResult method definition. + * @param methodName methodName + * @param className className + * @return SwitchYardException + */ + @Message(id=16858, value = "Invalid @Transformer method '%s' on class '%s'. Must return a result.") + SwitchYardException invalidTransformerMethodResult(String methodName, String className); + + /** + * invalidFromTypeForDozerTransformer method definition. + * @param from 'from' QName + * @return SwitchYardException + */ + @Message(id=16859, value = "Invalid 'from' type '%s' for Dozer transformer") + SwitchYardException invalidFromTypeForDozerTransformer(QName from); + + /** + * invalidToTypeForDozerTransformer method definition. + * @param to 'to' QName + * @return SwitchYardException + */ + @Message(id=16860, value = "Invalid 'to' type '%s' for Dozer transformer") + SwitchYardException invalidToTypeForDozerTransformer(QName to); + + /** + * failedToMarshallForType method definition. + * @param type type + * @param e e + * @return SwitchYardException + * @see #failedToUnmarshallForType(String, JAXBException) + */ + @Message(id=16861, value = "Failed to marshall for type '%s'.") + SwitchYardException failedToMarshallForType(String type, @Cause JAXBException e); + + /** + * nullServiceDomainArgument method definition. + * @return IllegalArgumentException + */ + @Message(id=16862, value = "null 'domain' argument") + IllegalArgumentException nullServiceDomainArgument(); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/internal/TransformerFactory.java b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerFactory.java new file mode 100644 index 000000000..cfa65fcbf --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal; + +import org.switchyard.ServiceDomain; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.transform.Transformer; + +/** + * Transformer Factory. + * + * @author tom.fennelly@gmail.com + * + * @param TransformerModel type. + */ +public interface TransformerFactory { + + /** + * Create a new {@link Transformer} instance. + * @param domain ServiceDomain instance. + * @param model The Transformer config model. + * @return The Transformer instance. + */ + Transformer newTransformer(ServiceDomain domain, T model); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/internal/TransformerFactoryClass.java b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerFactoryClass.java new file mode 100644 index 000000000..8dd08368d --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerFactoryClass.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Transformer factory class annotation. + * + * @author tom.fennelly@gmail.com + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +public @interface TransformerFactoryClass { + + /** + * The component factory class. + */ + Class value(); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/internal/TransformerRegistryLoader.java b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerRegistryLoader.java new file mode 100644 index 000000000..de94ed517 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerRegistryLoader.java @@ -0,0 +1,298 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.common.cdi.CDIUtil; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.transform.config.model.JavaTransformModel; + +/** + * {@link TransformerRegistry} loader class. + * + * @author tom.fennelly@gmail.com + */ +public class TransformerRegistryLoader { + + /** + * Logger. + */ + private static Logger _log = Logger.getLogger(TransformerRegistryLoader.class); + /** + * Classpath location for out-of-the-box transformation configurations. + */ + public static final String TRANSFORMS_XML = "META-INF/switchyard/transforms.xml"; + + /** + * Transformers. + */ + private List> _transformers = new LinkedList>(); + /** + * The registry instance into which the transforms were loaded. + */ + private TransformerRegistry _transformerRegistry; + + private Map, TransformerFactory> _transformerFactories = + new HashMap, TransformerFactory>(); + + private ServiceDomain _serviceDomain; + + /** + * Public constructor. + * @param domain ServiceDomain instance. + */ + public TransformerRegistryLoader(ServiceDomain domain) { + if (domain == null) { + throw TransformMessages.MESSAGES.nullServiceDomainArgument(); + } + this._serviceDomain = domain; + if (_serviceDomain.getTransformerRegistry() == null) { + throw TransformMessages.MESSAGES.nullTransformerRegistryArgument(); + } + this._transformerRegistry = _serviceDomain.getTransformerRegistry(); + } + + /** + * Public constructor. + * @param transformerRegistry The registry instance. + */ + public TransformerRegistryLoader(TransformerRegistry transformerRegistry) { + if (transformerRegistry == null) { + throw TransformMessages.MESSAGES.nullTransformerRegistryArgument(); + } + this._transformerRegistry = transformerRegistry; + this._serviceDomain = null; + } + + /** + * Register a set of transformers in the transform registry associated with this deployment. + * @param transforms The transforms model. + * @throws DuplicateTransformerException an existing transformer has already been registered for the from and to types + */ + public void registerTransformers(TransformsModel transforms) throws DuplicateTransformerException { + registerTransformers(transforms, true); + } + + /** + * Register a set of transformers in the transform registry associated with this deployment. + * @param transforms The transforms model. + * @param failOnError false to eat duplicate exceptions + * @throws DuplicateTransformerException an existing transformer has already been registered for the from and to types + */ + public void registerTransformers(TransformsModel transforms, boolean failOnError) throws DuplicateTransformerException { + if (transforms == null) { + return; + } + + try { + for (TransformModel transformModel : transforms.getTransforms()) { + Collection> transformers = newTransformers(transformModel); + transformerLoop : for (Transformer transformer : transformers) { + if (_transformerRegistry.hasTransformer(transformer.getFrom(), transformer.getTo())) { + Transformer registeredTransformer = _transformerRegistry.getTransformer(transformer.getFrom(), transformer.getTo()); + boolean test = false; + testLoop : for (StackTraceElement ste : Thread.currentThread().getStackTrace()) { + if (ste.getClassName().startsWith("org.switchyard.test.")) { + test = true; + break testLoop; + } + } + String msg = "Failed to register Transformer '" + toDescription(transformer) + + "'. A Transformer for these types is already registered: '" + + toDescription(registeredTransformer) + "'."; + if (test) { + _log.trace(msg); + } else if (failOnError) { + throw new DuplicateTransformerException(msg); + } else { + _log.debug(msg); + } + continue transformerLoop; + } + _log.debug("Adding transformer =>" + + " From: " + transformer.getFrom() + + ", To:" + transformer.getTo()); + _transformerRegistry.addTransformer(transformer); + _transformers.add(transformer); + } + } + } catch (DuplicateTransformerException e) { + throw e; + } catch (RuntimeException e) { + // If there was an exception for any reason... remove all Transformer instance that have + // already been registered with the domain... + unregisterTransformers(); + throw e; + } + } + + /** + * Unregister all transformers. + */ + public void unregisterTransformers() { + for (Transformer transformer : _transformers) { + _transformerRegistry.removeTransformer(transformer); + } + } + + /** + * Load the out of the box transformers. + *

+ * Scans the classpath for {@link #TRANSFORMS_XML} runtime configuration resources. + */ + public void loadOOTBTransforms() { + try { + List resources = getResources(TRANSFORMS_XML); + + for (URL resource : resources) { + InputStream configStream = resource.openStream(); + + try { + TransformsModel transformsModel = new ModelPuller().pull(configStream); + registerTransformers(transformsModel, false); + } catch (final DuplicateTransformerException e) { + _log.debug(e.getMessage()); + } finally { + configStream.close(); + } + } + } catch (IOException e) { + throw TransformMessages.MESSAGES.errorReadingTransformerConfig(TRANSFORMS_XML, e); + } + } + + /** + * Create a new {@link org.switchyard.transform.Transformer} instance from the supplied {@link TransformModel} instance. + * @param transformModel The TransformModel instance. + * @return The Transformer instance. + */ + public Transformer newTransformer(TransformModel transformModel) { + return newTransformers(transformModel).iterator().next(); + } + + /** + * Create a Collection of {@link Transformer} instances from the supplied {@link TransformModel} instance. + * @param transformModel The TransformModel instance. + * @return The Transformer instance. + */ + public Collection> newTransformers(TransformModel transformModel) { + + Collection> transformers = null; + + if (transformModel instanceof JavaTransformModel) { + JavaTransformModel javaTransformModel = JavaTransformModel.class.cast(transformModel); + String bean = javaTransformModel.getBean(); + if (bean != null) { + if (CDIUtil.lookupBeanManager() == null) { + throw TransformMessages.MESSAGES.cdiBeanManagerNotFound(); + } + Object transformer = CDIUtil.lookupBean(bean); + if (transformer == null) { + throw TransformMessages.MESSAGES.beanNotFoundInCDIRegistry(bean); + } + transformers = TransformerUtil.newTransformers(transformer, transformModel.getFrom(), transformModel.getTo()); + } else { + String className = ((JavaTransformModel) transformModel).getClazz(); + if (className == null) { + throw TransformMessages.MESSAGES.beanOrClassMustBeSpecified(); + } + Class transformClass = getClass(className); + if (transformClass == null) { + throw TransformMessages.MESSAGES.unableToLoadTransformerClass(className); + } + transformers = TransformerUtil.newTransformers(transformClass, transformModel.getFrom(), transformModel.getTo()); + } + } else { + TransformerFactory factory = getTransformerFactory(transformModel); + + transformers = new ArrayList>(); + transformers.add(factory.newTransformer(_serviceDomain, transformModel)); + } + + if (transformers == null || transformers.isEmpty()) { + throw TransformMessages.MESSAGES.unknownTransformModel(transformModel.getClass().getName()); + } + + return transformers; + } + + /** + * Overridable method for resolving a class path resource which allows environments + * like OSGi to customize resolution. + */ + protected List getResources(String path) throws java.io.IOException { + return Classes.getResources(path, getClass()); + } + + /** + * Overridable method for resolving a class which allows environments like OSGi + * to customize resolution. + */ + protected Class getClass(String className) { + return Classes.forName(className, TransformerUtil.class); + } + + private String toDescription(Transformer transformer) { + return transformer.getClass().getName() + "(" + transformer.getFrom() + ", " + transformer.getTo() + ")"; + } + + private TransformerFactory getTransformerFactory(TransformModel transformModel) { + TransformerFactoryClass transformerFactoryClass = transformModel.getClass().getAnnotation(TransformerFactoryClass.class); + + if (transformerFactoryClass == null) { + TransformMessages.MESSAGES.transformModelNotAnnotated(transformModel.getClass().getName()); + } + + Class factoryClass = transformerFactoryClass.value(); + if (!TransformerFactory.class.isAssignableFrom(factoryClass)) { + TransformMessages.MESSAGES.invalidTransformerFactory(org.switchyard.transform.internal.TransformerFactory.class.getName()); + } + + try { + if (!_transformerFactories.containsKey(factoryClass)) { + TransformerFactory factory = (TransformerFactory) factoryClass.newInstance(); + _transformerFactories.put(factoryClass, factory); + } + + return _transformerFactories.get(factoryClass); + } catch (ClassCastException e) { + throw TransformMessages.MESSAGES.failedCreateInstanceofTransformerFactory(factoryClass.getName()); + } catch (IllegalArgumentException iae) { + throw TransformMessages.MESSAGES.failedCreateInstanceofTransformerFactory(factoryClass.getName()); + } catch (NullPointerException npe) { + throw TransformMessages.MESSAGES.failedCreateInstanceofTransformerFactory(factoryClass.getName()); + } catch (InstantiationException ie) { + throw TransformMessages.MESSAGES.failedCreateInstanceofTransformerFactory(factoryClass.getName()); + } catch (IllegalAccessException iae) { + throw TransformMessages.MESSAGES.failedCreateInstanceofTransformerFactory(factoryClass.getName()); + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/internal/TransformerTypes.java b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerTypes.java new file mode 100644 index 000000000..0cfc314a0 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerTypes.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.internal; + +import javax.xml.namespace.QName; + +/** + * Transformer data types. + * + * @author tom.fennelly@gmail.com + */ +public class TransformerTypes { + + private QName _from; + private QName _to; + + /** + * Public constructor. + * + * @param from From type. + * @param to To type. + */ + TransformerTypes(QName from, QName to) { + this._from = from; + this._to = to; + } + + /** + * Get from. + * + * @return from. + */ + public QName getFrom() { + return _from; + } + + /** + * Get to. + * + * @return to. + */ + public QName getTo() { + return _to; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("%s [from=%s, to=%s]", getClass().getSimpleName(), getFrom(), getTo()); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/internal/TransformerUtil.java b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerUtil.java new file mode 100644 index 000000000..daf22038c --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/internal/TransformerUtil.java @@ -0,0 +1,357 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal; + +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.Transformer; + +/** + * Transformer Utility methods. + * + * @author tom.fennelly@gmail.com + */ +public final class TransformerUtil { + + private static final Logger LOGGER = Logger.getLogger(TransformerUtil.class); + + private static final QName OBJECT_TYPE = JavaTypes.toMessageType(Object.class); + + private TransformerUtil() {} + + /** + * Create a new {@link org.switchyard.transform.Transformer} instance from the supplied + * Class and supporting the specified from and to. + * @param clazz The Class representing the Transformer. + * @param from The from type. + * @param to The to type. + * @return The collection of Transformer instances. + * @see #isTransformer(Class) + */ + public static Transformer newTransformer(Class clazz, QName from, QName to) { + return newTransformers(clazz, from, to).iterator().next(); + } + + /** + * Create a Collection of {@link Transformer} instances from the supplied + * Class and supporting the specified from and to. + * @param clazz The Class representing the Transformer. + * @param from The from type. + * @param to The to type. + * @return The collection of Transformer instances. + * @see #isTransformer(Class) + */ + public static Collection> newTransformers(Class clazz, QName from, QName to) { + if (!isTransformer(clazz)) { + throw TransformMessages.MESSAGES.invalidTransformerClass(clazz.getName()); + } + + final Object transformerObject; + try { + transformerObject = clazz.newInstance(); + } catch (Exception e) { + throw TransformMessages.MESSAGES.errorConstructingTransformer(clazz.getName(), e); + } + + return TransformerUtil.newTransformers(transformerObject, from, to); + } + + /** + * Create a Collection of {@link Transformer} instances from the supplied + * object and supporting the specified from and to. + * @param transformerObject The Transformer instance + * @param from The from type. + * @param to The to type. + * @return The collection of Transformer instances. + * @see #isTransformer(Class) + */ + public static Collection> newTransformers(Object transformerObject, QName from, QName to) { + boolean fromIsWild = isWildcardType(from); + boolean toIsWild = isWildcardType(to); + Collection> transformers = new ArrayList>(); + + Method[] publicMethods = transformerObject.getClass().getMethods(); + for (Method publicMethod : publicMethods) { + org.switchyard.annotations.Transformer transformerAnno = publicMethod.getAnnotation(org.switchyard.annotations.Transformer.class); + if (transformerAnno != null) { + TransformerMethod transformerMethod = toTransformerMethod(publicMethod, transformerAnno); + + if ((fromIsWild || transformerMethod.getFrom().equals(from)) && (toIsWild || transformerMethod.getTo().equals(to))) { + transformers.add(newTransformer(transformerObject, transformerMethod.getMethod(), transformerMethod.getFrom(), transformerMethod.getTo())); + } + } + } + + if (transformerObject instanceof Transformer) { + Transformer transformer = (Transformer) transformerObject; + QName transFrom = transformer.getFrom(); + QName transTo = transformer.getTo(); + + if (transFrom.equals(OBJECT_TYPE) && transTo.equals(OBJECT_TYPE)) { + // Type info not specified on transformer, so assuming it's a generic/multi-type transformer... + transformers.add(transformer); + } else if ((fromIsWild || transFrom.equals(from)) && (toIsWild || transTo.equals(to))) { + // Matching (specific) or wildcard type info specified... + transformers.add(transformer); + } else if (isAssignableFrom(transFrom, from) && isAssignableFrom(transTo, to)) { + // Compatible Java types... + transformers.add(transformer); + } + + if (!fromIsWild) { + transformer.setFrom(from); + } + if (!toIsWild) { + transformer.setTo(to); + } + } + + if (transformers.isEmpty()) { + throw TransformMessages.MESSAGES.classDoesNotSupportTransformation(transformerObject.getClass().getName(), from.toString(), to.toString()); + } + + return transformers; + } + + /** + * Create a list of all the possible transformations that the supplied Class offers. + * @param clazz The Class to be analyzed. + * @return A Map containing the transformation types, with the key/value representing the to/from. + */ + public static List listTransformations(Class clazz) { + Object transformerObject; + List transformations = new ArrayList(); + + try { + transformerObject = clazz.newInstance(); + } catch (Exception e) { + throw TransformMessages.MESSAGES.errorConstructingTransformer(clazz.getName(), e); + } + + // If the class itself implements the Transformer interface.... + if (transformerObject instanceof org.switchyard.transform.Transformer) { + QName from = ((Transformer) transformerObject).getFrom(); + QName to = ((Transformer) transformerObject).getTo(); + if (from != null && to != null) { + TransformerTypes transformerTypes = new TransformerTypes(from, to); + transformations.add(transformerTypes); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("added: " + transformerTypes); + } + } + } + + // If some of the class methods are annotated with the @Transformer annotation... + Method[] publicMethods = clazz.getMethods(); + for (Method publicMethod : publicMethods) { + org.switchyard.annotations.Transformer transformerAnno = publicMethod.getAnnotation(org.switchyard.annotations.Transformer.class); + if (transformerAnno != null) { + TransformerMethod transformerMethod = toTransformerMethod(publicMethod, transformerAnno); + TransformerTypes transformerTypes = new TransformerTypes(transformerMethod.getFrom(), transformerMethod.getTo()); + transformations.add(transformerTypes); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("added: " + transformerTypes); + } + } + } + + Collections.sort(transformations, new TransformerTypesComparator()); + if (LOGGER.isDebugEnabled()) { + for (TransformerTypes transformerTypes : transformations) { + LOGGER.debug("sorted: " + transformerTypes); + } + } + + return transformations; + } + + /** + * Is the supplied Class a SwitchYard Transformer class. + *

+ * A SwitchYard Transformer class is any class that either implements the {@link org.switchyard.transform.Transformer} + * interface, or has one or more methods annotated with the {@link org.switchyard.annotations.Transformer @Transformer} annotation. + * + * @param clazz The Class instance. + * @return True if the class can be used as a SwitchYard Transformer, otherwise false. + */ + public static boolean isTransformer(Class clazz) { + if (clazz.isInterface()) { + return false; + } + if (clazz.isAnnotation()) { + return false; + } + if (Modifier.isAbstract(clazz.getModifiers())) { + return false; + } + try { + // Must have a default constructor... + clazz.getConstructor(); + } catch (NoSuchMethodException e) { + return false; + } + if (org.switchyard.transform.Transformer.class.isAssignableFrom(clazz)) { + return true; + } + + Method[] publicMethods = clazz.getMethods(); + for (Method publicMethod : publicMethods) { + if (publicMethod.isAnnotationPresent(org.switchyard.annotations.Transformer.class)) { + return true; + } + } + + return false; + } + + private static Transformer newTransformer(final Object transformerObject, final Method publicMethod, QName from, QName to) { + Transformer transformer = new BaseTransformer(from, to) { + @Override + public Object transform(Object from) { + try { + return publicMethod.invoke(transformerObject, from); + } catch (InvocationTargetException e) { + throw TransformMessages.MESSAGES.errorExecutingTransformerMethod(publicMethod.getName(), publicMethod.getDeclaringClass().getName(), e.getCause()); + } catch (Exception e) { + throw TransformMessages.MESSAGES.errorExecutingTransformerMethod(publicMethod.getName(), publicMethod.getDeclaringClass().getName(), e); + } + } + + @Override + public Class getFromType() { + return publicMethod.getParameterTypes()[0]; + } + + @Override + public Class getToType() { + return publicMethod.getReturnType(); + } + }; + + return transformer; + } + + private static boolean isAssignableFrom(QName a, QName b) { + if (QNameUtil.isJavaMessageType(a) && QNameUtil.isJavaMessageType(b)) { + Class aType = QNameUtil.toJavaMessageType(a); + Class bType = QNameUtil.toJavaMessageType(b); + + if (aType == null || bType == null) { + return false; + } + + return aType.isAssignableFrom(bType); + } + + return false; + } + + private static boolean isWildcardType(QName type) { + return type.toString().equals("*"); + } + + private static TransformerMethod toTransformerMethod(Method publicMethod, org.switchyard.annotations.Transformer transformerAnno) { + + QName from; + QName to; + Class fromType; + Class toType; + + Class[] params = publicMethod.getParameterTypes(); + if (params.length != 1) { + throw TransformMessages.MESSAGES.invalidTransformerMethodParameter(publicMethod.getName(), publicMethod.getDeclaringClass().getName()); + } + fromType = params[0]; + toType = publicMethod.getReturnType(); + if (toType == null) { + throw TransformMessages.MESSAGES.invalidTransformerMethodResult(publicMethod.getName(), publicMethod.getDeclaringClass().getName()); + } + + if (!transformerAnno.from().trim().equals("")) { + from = QName.valueOf(transformerAnno.from().trim()); + } else { + from = JavaTypes.toMessageType(fromType); + } + if (!transformerAnno.to().trim().equals("")) { + to = QName.valueOf(transformerAnno.to().trim()); + } else { + to = JavaTypes.toMessageType(toType); + } + + return new TransformerMethod(from, to, publicMethod); + } + + private static class TransformerMethod extends TransformerTypes { + + private Method _method; + + /** + * Public constructor. + * + * @param from From type. + * @param to To type. + * @param publicMethod + */ + TransformerMethod(QName from, QName to, Method publicMethod) { + super(from, to); + this._method = publicMethod; + } + + private Method getMethod() { + return _method; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("%s [from=%s, to=%s, method=%s]", getClass().getSimpleName(), getFrom(), getTo(), getMethod()); + } + } + + private static final class TransformerTypesComparator implements Comparator, Serializable { + /** + * {@inheritDoc} + */ + @Override + public int compare(TransformerTypes tt1, TransformerTypes tt2) { + int c = String.valueOf(tt1.getFrom()).compareTo(String.valueOf(tt2.getFrom())); + if (c == 0) { + c = String.valueOf(tt1.getTo()).compareTo(String.valueOf(tt2.getTo())); + if (c == 0 && tt1 instanceof TransformerMethod && tt2 instanceof TransformerMethod) { + TransformerMethod tm1 = (TransformerMethod)tt1; + TransformerMethod tm2 = (TransformerMethod)tt2; + c = String.valueOf(tm1.getMethod()).compareTo(String.valueOf(tm2.getMethod())); + } + } + return c; + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBMarshalTransformer.java b/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBMarshalTransformer.java new file mode 100644 index 000000000..8700978a3 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBMarshalTransformer.java @@ -0,0 +1,89 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.jaxb.internal; + +import java.io.StringWriter; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.namespace.QName; + +import org.switchyard.Message; +import org.switchyard.SwitchYardException; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.internal.TransformMessages; + +/** + * JAXB Marshalling transformer. + * + * @author tom.fennelly@gmail.com + * + * @param From Type + * @param To Type. + */ +@Scannable(false) +public class JAXBMarshalTransformer extends BaseTransformer { + + private JAXBContext _jaxbContext; + + /** + * Public constructor. + * @param from From type. + * @param to To type. + * @param contextPath JAXB context path (Java package). + * @throws SwitchYardException Failed to create JAXBContext. + */ + public JAXBMarshalTransformer(QName from, QName to, String contextPath) throws SwitchYardException { + super(from, to); + try { + if (contextPath != null) { + _jaxbContext = JAXBContext.newInstance(contextPath); + } else { + _jaxbContext = JAXBContext.newInstance(QNameUtil.toJavaMessageType(from)); + } + } catch (JAXBException e) { + throw TransformMessages.MESSAGES.failedToCreateJAXBContext(from.toString(), e); + } + } + + @Override + public Message transform(Message message) { + Marshaller marshaller; + + try { + marshaller = _jaxbContext.createMarshaller(); + } catch (JAXBException e) { + throw TransformMessages.MESSAGES.failedToCreateMarshaller(getFrom().toString(), e); + } + + try { + StringWriter resultWriter = new StringWriter(); + Object javaObject = message.getContent(); + //JAXBElement jaxbElement = new JAXBElement(getTo(), QNameUtil.toJavaMessageType(getFrom()), javaObject); + + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + marshaller.marshal(javaObject, resultWriter); + + message.setContent(resultWriter.toString()); + } catch (JAXBException e) { + throw TransformMessages.MESSAGES.failedToMarshallForType(getFrom().toString(), e); + } + + return message; + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBTransformerFactory.java b/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBTransformerFactory.java new file mode 100644 index 000000000..3fbeb4719 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBTransformerFactory.java @@ -0,0 +1,207 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.jaxb.internal; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.bind.annotation.XmlElementDecl; +import javax.xml.bind.annotation.XmlType; +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.SwitchYardException; +import org.switchyard.common.type.Classes; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.JAXBTransformModel; +import org.switchyard.transform.config.model.JavaTransformType; +import org.switchyard.transform.internal.TransformMessages; +import org.switchyard.transform.internal.TransformerFactory; + +/** + * JAXB Transformer factory. + * + * @author tom.fennelly@gmail.com + */ +public class JAXBTransformerFactory implements TransformerFactory { + + /** + * Logger. + */ + private static Logger _log = Logger.getLogger(JAXBTransformerFactory.class); + + @Override + public Transformer newTransformer(ServiceDomain domain, JAXBTransformModel model) { + QName fromType = model.getFrom(); + QName toType = model.getTo(); + + if (toJavaTransformType(fromType, toType) == JavaTransformType.JAVA2XML) { + return new JAXBMarshalTransformer(fromType, toType, model.getContextPath()); + } else { + return new JAXBUnmarshalTransformer(fromType, toType, model.getContextPath()); + } + } + + /** + * Factory method for auto-adding JAXB Transformers for a Service interface. + * @param serviceClass The Service class. + * @return The list of JAX Transformers to be added for the supplied service class. + * @throws SwitchYardException Unsupported JAXB type defined on interface. + */ + public static List> newTransformers(Class serviceClass) throws SwitchYardException { + List> transformers = new ArrayList>(); + Set> inputTypeSet = new HashSet>(); + Set> outputTypeSet = new HashSet>(); + + if (serviceClass.isInterface()) { + Method[] serviceOperations = serviceClass.getMethods(); + + for (Method serviceOperation : serviceOperations) { + Class[] inTypes = serviceOperation.getParameterTypes(); + Class outType = serviceOperation.getReturnType(); + + if (inTypes.length == 1) { + inputTypeSet.add(inTypes[0]); + } + if (outType != null && !Void.TYPE.isAssignableFrom(outType)) { + outputTypeSet.add(outType); + } + } + } + + // Add input and output transformers... + for (Class inputType : inputTypeSet) { + addJAXBUnmarshalTransformer(inputType, transformers); + } + for (Class outputType : outputTypeSet) { + addJAXBMarshalTransformer(outputType, transformers); + } + + return transformers; + } + + private static void addJAXBUnmarshalTransformer(Class inType, List> transformers) throws SwitchYardException { + Class objectFactory = getObjectFactory(inType); + + if (objectFactory != null) { + QName fromType = getTypeXMLQName(inType, objectFactory); + + if (fromType != null) { + QName toType = JavaTypes.toMessageType(inType); + transformers.add(new JAXBUnmarshalTransformer(fromType, toType, inType.getPackage().getName())); + } else if (_log.isDebugEnabled()) { + _log.debug(createMissingFactoryMethodMessage(inType, objectFactory)); + } + } + } + + private static void addJAXBMarshalTransformer(Class outType, List> transformers) throws SwitchYardException { + Class objectFactory = getObjectFactory(outType); + + if (objectFactory != null) { + QName toType = getTypeXMLQName(outType, objectFactory); + + if (toType != null) { + QName fromType = JavaTypes.toMessageType(outType); + transformers.add(new JAXBMarshalTransformer(fromType, toType, outType.getPackage().getName())); + } else if (_log.isDebugEnabled()) { + _log.debug(createMissingFactoryMethodMessage(outType, objectFactory)); + } + } + } + + private static QName getTypeXMLQName(Class type, Class objectFactory) throws SwitchYardException { + Method[] factoryMethods = objectFactory.getDeclaredMethods(); + + for (Method factoryMethod : factoryMethods) { + XmlElementDecl xmlElementDecl = factoryMethod.getAnnotation(XmlElementDecl.class); + if (xmlElementDecl != null) { + Class[] factoryParams = factoryMethod.getParameterTypes(); + + if (factoryParams.length == 1) { + QName qName = new QName(xmlElementDecl.namespace(), xmlElementDecl.name()); + Class factoryParam = factoryParams[0]; + + if (factoryParam == type) { + // This is the factory method for the specified type... + return qName; + } + } + } + } + + return null; + } + + private static Class getObjectFactory(Class type) { + if (type.getAnnotation(XmlType.class) != null) { + // Get the ObjectFactory, if it exists... + String objectFactoryName = type.getPackage().getName() + "." + "ObjectFactory"; + + return Classes.forName(objectFactoryName, JAXBTransformerFactory.class); + } + + return null; + } + + protected static String createMissingFactoryMethodMessage(Class type, Class objectFactory) { + StringBuilder messageBuilder = new StringBuilder(); + Method[] factoryMethods = objectFactory.getDeclaredMethods(); + + messageBuilder.append(TransformMessages.MESSAGES.noJAXBElementFactoryDefined(type.getName(), objectFactory.getName())); + + for (Method factoryMethod : factoryMethods) { + XmlElementDecl xmlElementDecl = factoryMethod.getAnnotation(XmlElementDecl.class); + if (xmlElementDecl != null) { + Class[] factoryParams = factoryMethod.getParameterTypes(); + + if (factoryParams.length == 1) { + QName qName = new QName(xmlElementDecl.namespace(), xmlElementDecl.name()); + Class factoryParam = factoryParams[0]; + + messageBuilder.append("\n\t\t- Message QName: '" + qName.toString() + "'. Java Type: " + factoryParam.getName()); + } + } + } + + return messageBuilder.toString(); + } + + private static JavaTransformType toJavaTransformType(QName fromType, QName toType) { + if (QNameUtil.isJavaMessageType(fromType)) { + if (QNameUtil.isJavaMessageType(toType)) { + throw TransformMessages.MESSAGES.bothJavaTypes(); + } + return JavaTransformType.JAVA2XML; + } else if (QNameUtil.isJavaMessageType(toType)) { + if (QNameUtil.isJavaMessageType(fromType)) { + throw TransformMessages.MESSAGES.bothJavaTypes(); + } + return JavaTransformType.XML2JAVA; + } else { + throw TransformMessages.MESSAGES.neitherJavaType(); + } + } + + private static String getJavaPackage(QName type) { + return QNameUtil.toJavaMessageType(type).getPackage().getName(); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBUnmarshalTransformer.java b/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBUnmarshalTransformer.java new file mode 100644 index 000000000..5101a56e1 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/jaxb/internal/JAXBUnmarshalTransformer.java @@ -0,0 +1,115 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.jaxb.internal; + +import java.io.InputStream; +import java.io.Reader; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.namespace.QName; +import javax.xml.transform.Source; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.sax.SAXSource; +import javax.xml.transform.stax.StAXSource; + +import org.jboss.logging.Logger; +import org.switchyard.Message; +import org.switchyard.SwitchYardException; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.internal.TransformMessages; + +/** + * JAXB Unmarshalling transformer. + * + * @author tom.fennelly@gmail.com + * + * @param From Type + * @param To Type. + */ +@Scannable(false) +public class JAXBUnmarshalTransformer extends BaseTransformer { + + private static Logger _logger = Logger.getLogger(JAXBUnmarshalTransformer.class); + + private JAXBContext _jaxbContext; + + /** + * Public constructor. + * @param from From type. + * @param to To type. + * @param contextPath JAXB context path (Java package). + * @throws SwitchYardException Failed to create JAXBContext. + */ + public JAXBUnmarshalTransformer(QName from, QName to, String contextPath) throws SwitchYardException { + super(from, to); + try { + if (contextPath != null) { + _jaxbContext = JAXBContext.newInstance(contextPath); + } else { + _jaxbContext = JAXBContext.newInstance(QNameUtil.toJavaMessageType(to)); + } + } catch (JAXBException e) { + throw TransformMessages.MESSAGES.failedToCreateJAXBContext(to.toString(), e); + } + } + + @Override + public Message transform(Message message) { + Unmarshaller unmarshaller; + + try { + unmarshaller = _jaxbContext.createUnmarshaller(); + } catch (JAXBException e) { + throw TransformMessages.MESSAGES.failedToCreateMarshaller(getTo().toString(), e); + } + + try { + byte[] bytes = null; + if (InputStream.class.isAssignableFrom(message.getContent().getClass()) + || Reader.class.isAssignableFrom(message.getContent().getClass())) { + // Convert the stream/reader content to byte array first so it won't exhausted + bytes = message.getContent(byte[].class); + message.setContent(bytes); + } + Source source = message.getContent(Source.class); + if (source instanceof StAXSource || source instanceof SAXSource) { + // SWITCHYARD-2511 - Avoid StAXSource and SAXSource as those have issues on JAXB unmarshal + if (bytes != null) { + message.setContent(bytes); + } + source = message.getContent(DOMSource.class); + } + if (_logger.isDebugEnabled()) { + _logger.debug("Unmarshalling from " + source.getClass() + ", systemId=" + source.getSystemId()); + } + Object unmarshalledObject = unmarshaller.unmarshal(source); + + if (unmarshalledObject instanceof JAXBElement) { + message.setContent(((JAXBElement)unmarshalledObject).getValue()); + } else { + message.setContent(unmarshalledObject); + } + } catch (JAXBException e) { + throw TransformMessages.MESSAGES.failedToUnmarshallForType(getTo().toString(), e); + } + + return message; + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/json/internal/JSON2JavaTransformer.java b/core/transform/src/main/java/org/switchyard/transform/json/internal/JSON2JavaTransformer.java new file mode 100644 index 000000000..496f29801 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/json/internal/JSON2JavaTransformer.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.json.internal; + +import java.io.IOException; +import java.io.Reader; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.switchyard.Message; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.internal.TransformMessages; + +/** + * JSON to Java Transformer. + * + * @author Alejandro Montenegro <aamonten@gmail.com> + * + * @param From Type + * @param To Type. + */ +public class JSON2JavaTransformer extends BaseTransformer { + + private ObjectMapper _mapper; + private Class _clazz; + + /** + * Public constructor. + * + * @param from From type. + * @param to To type. + * @param mapper JSON Object Mapper instance. + * @param clazz The Java type being mapped. + */ + public JSON2JavaTransformer(QName from, QName to, ObjectMapper mapper, Class clazz) { + super(from, to); + this._mapper = mapper; + this._clazz = clazz; + } + + @Override + public Message transform(Message message) { + + try { + Object result = _mapper.readValue(message.getContent(Reader.class), _clazz); + + if (_clazz.isInstance(result)) { + message.setContent(result); + return message; + } else { + throw TransformMessages.MESSAGES.transformationResultWrongType(result.getClass().toString()); + } + } catch (JsonParseException e) { + throw TransformMessages.MESSAGES.unexpectedJSONParseException(e); + } catch (JsonMappingException e) { + throw TransformMessages.MESSAGES.unexpectedJSONMappingException(e); + } catch (IOException e) { + throw TransformMessages.MESSAGES.unexpectedIOExceptionCheckTransformer(e); + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/json/internal/JSONTransformFactory.java b/core/transform/src/main/java/org/switchyard/transform/json/internal/JSONTransformFactory.java new file mode 100644 index 000000000..bb932c7c9 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/json/internal/JSONTransformFactory.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.json.internal; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.map.ObjectMapper; +import org.switchyard.ServiceDomain; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.JSONTransformModel; +import org.switchyard.transform.internal.TransformMessages; +import org.switchyard.transform.internal.TransformerFactory; + +/** + * JSON Transformer factory. + * + * @author Alejandro Montenegro <aamonten@gmail.com> + */ +public final class JSONTransformFactory implements TransformerFactory { + + /** + * Create a {@link Transformer} instance from the supplied {@link JSONTransformModel}. + * @param domain ServiceDomain instance. + * @param model the JSON transformer model. + * @return the Transformer instance. + */ + public Transformer newTransformer(ServiceDomain domain, JSONTransformModel model) { + + QName from = model.getFrom(); + QName to = model.getTo(); + + assertValidJSONTransformSpec(from, to); + + if (QNameUtil.isJavaMessageType(from)) { + // Java to JSON.... + Class clazz = toJavaMessageType(from); + return new Java2JSONTransformer(from, to, new ObjectMapper(), clazz); + } else { + // JSON to Java.... + Class clazz = toJavaMessageType(to); + return new JSON2JavaTransformer(from, to, new ObjectMapper(), clazz); + } + } + + private static Class toJavaMessageType(QName name) { + Class clazz = QNameUtil.toJavaMessageType(name); + if (clazz == null) { + throw TransformMessages.MESSAGES.notAbleToFindClassDefinition(name.toString()); + } + return clazz; + } + + private static void assertValidJSONTransformSpec(QName from, QName to) { + if (QNameUtil.isJavaMessageType(from)) { + if (QNameUtil.isJavaMessageType(to)) { + // Both of them is a Java type spec... + throwInvalidToFromSpecException(); + } + } else if (QNameUtil.isJavaMessageType(to)) { + if (QNameUtil.isJavaMessageType(from)) { + // Both of them is a Java type spec... + throwInvalidToFromSpecException(); + } + } else { + // Neither of them is a Java type spec... + throwInvalidToFromSpecException(); + } + } + + private static void throwInvalidToFromSpecException() { + throw TransformMessages.MESSAGES.onlyOneJavaType(); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/json/internal/Java2JSONTransformer.java b/core/transform/src/main/java/org/switchyard/transform/json/internal/Java2JSONTransformer.java new file mode 100644 index 000000000..e341a5bab --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/json/internal/Java2JSONTransformer.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.json.internal; + +import java.io.IOException; +import java.io.StringWriter; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.JsonProcessingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.internal.TransformMessages; + +/** + * Java to JSON Transformer. + * + * @author Alejandro Montenegro <aamonten@gmail.com> + * + * @param From Type + * @param To Type. + */ +public class Java2JSONTransformer extends BaseTransformer { + + private ObjectMapper _mapper; + private Class _clazz; + + /** + * Public constructor. + * + * @param from From type. + * @param to To type. + * @param mapper JSON Object Mapper instance. + * @param clazz The Java type being mapped. + */ + public Java2JSONTransformer(QName from, QName to, ObjectMapper mapper, Class clazz) { + super(from, to); + this._mapper = mapper; + this._clazz = clazz; + } + + @Override + public String transform(Object from) { + + try { + StringWriter writer = new StringWriter(); + + if (_clazz.isInstance(from)) { + _mapper.writeValue(writer, from); + return writer.toString(); + } else { + throw TransformMessages.MESSAGES.objectToTransformWrongType(from.getClass().toString()); + } + } catch (JsonProcessingException e) { + throw TransformMessages.MESSAGES.unexpectedJSONProcessingException(e); + } catch (IOException e) { + throw TransformMessages.MESSAGES.unexpectedIOException(e); + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/io/InputSourceTransforms.java b/core/transform/src/main/java/org/switchyard/transform/ootb/io/InputSourceTransforms.java new file mode 100644 index 000000000..c5c60be7b --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/io/InputSourceTransforms.java @@ -0,0 +1,183 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.io; + +import org.switchyard.annotations.Transformer; +import org.xml.sax.InputSource; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; + +/** + * {@link InputSource} Transforms. + *

+ * All transforms close the supplied {@link InputSource} stream/reader before returning. + * + * @author tom.fennelly@gmail.com + */ +public class InputSourceTransforms { + + /** + * Singleton Instance. + */ + public static final InputSourceTransforms TRANSFORMER = new InputSourceTransforms(); + + /** + * Transform to String. + * @param inSource Input Source. + * @return String. + */ + @Transformer + public String toString(InputSource inSource) { + Reader reader = inSource.getCharacterStream(); + + if (reader != null) { + return ReaderTransforms.TRANSFORMER.toString(reader); + } + + InputStream stream = inSource.getByteStream(); + if (stream != null) { + return InputStreamTransforms.TRANSFORMER.toString(stream); + } + + return null; + } + + /** + * Transform to Reader. + * @param inSource Input Source. + * @return Reader. + */ + @Transformer + public Reader toReader(InputSource inSource) { + Reader reader = inSource.getCharacterStream(); + + if (reader != null) { + return new StringReader(ReaderTransforms.TRANSFORMER.toString(reader)); + } + + return null; + } + + /** + * Transform to InputStream. + * @param inSource Input Source. + * @return InputStream. + */ + @Transformer + public InputStream toInputStream(InputSource inSource) { + InputStream stream = inSource.getByteStream(); + + if (stream != null) { + return new ByteArrayInputStream(InputStreamTransforms.TRANSFORMER.toBytes(stream)); + } + + return null; + } + + /** + * Transform to Integer. + * @param inSource Input Source. + * @return Integer. + */ + @Transformer + public Integer toInteger(InputSource inSource) { + return Integer.parseInt(toString(inSource)); + } + + /** + * Transform to Long. + * @param inSource Input Source. + * @return Long. + */ + @Transformer + public Long toLong(InputSource inSource) { + return Long.parseLong(toString(inSource)); + } + + /** + * Transform to Short. + * @param inSource Input Source. + * @return Short. + */ + @Transformer + public Short toShort(InputSource inSource) { + return Short.parseShort(toString(inSource)); + } + + /** + * Transform to char[]. + * @param inSource Input Source. + * @return char[]. + */ + @Transformer + public char[] toChars(InputSource inSource) { + return toString(inSource).toCharArray(); + } + + /** + * Transform to Character. + * @param inSource Input Source. + * @return Character. + */ + @Transformer + public Character toCharacter(InputSource inSource) { + return toString(inSource).charAt(0); + } + + /** + * Transform to byte[]. + * @param inSource Input Source. + * @return byte[]. + */ + @Transformer + public byte[] toBytes(InputSource inSource) { + InputStream stream = inSource.getByteStream(); + + if (stream != null) { + return InputStreamTransforms.TRANSFORMER.toBytes(stream); + } + + Reader reader = inSource.getCharacterStream(); + + if (reader != null) { + return ReaderTransforms.TRANSFORMER.toBytes(reader); + } + + return null; + } + + /** + * Transform to Float. + * @param inSource Input Source. + * @return Float. + */ + @Transformer + public Double toDouble(InputSource inSource) { + return Double.parseDouble(toString(inSource)); + } + + /** + * Transform to Float. + * @param inSource Input Source. + * @return Float. + */ + @Transformer + public Float toFloat(InputSource inSource) { + return Float.parseFloat(toString(inSource)); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/io/InputStreamTransforms.java b/core/transform/src/main/java/org/switchyard/transform/ootb/io/InputStreamTransforms.java new file mode 100644 index 000000000..bc167c16c --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/io/InputStreamTransforms.java @@ -0,0 +1,180 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.ootb.io; + +import org.jboss.logging.Logger; +import org.switchyard.annotations.Transformer; +import org.xml.sax.InputSource; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; + +/** + * {@link java.io.InputStream} Transforms. + *

+ * All transforms close the supplied {@link java.io.InputStream} before returning. + * + * @author tom.fennelly@gmail.com + */ +public class InputStreamTransforms { + + /** + * Singleton Instance. + */ + public static final InputStreamTransforms TRANSFORMER = new InputStreamTransforms(); + /** + * Logger. + */ + private static final Logger LOGGER = Logger.getLogger(ReaderTransforms.class); + + /** + * Transform to String. + * @param inStream Input Stream. + * @return String. + */ + @Transformer + public String toString(InputStream inStream) { + return ReaderTransforms.TRANSFORMER.toString(new InputStreamReader(inStream)); + } + + /** + * Transform to Reader. + * @param inStream Input Stream. + * @return Reader. + */ + @Transformer + public Reader toReader(InputStream inStream) { + return new StringReader(toString(inStream)); + } + + /** + * Transform to InputSource. + * @param inStream Input Stream. + * @return InputSource. + */ + @Transformer + public InputSource toInputSource(InputStream inStream) { + byte[] bytes = toBytes(inStream); + InputSource inputSource = new InputSource(); + + inputSource.setByteStream(new ByteArrayInputStream(bytes)); + // Purposely not setting the character stream because we cannot guarantee decoding of the bytes. + + return inputSource; + } + + /** + * Transform to Integer. + * @param inStream Input Stream. + * @return Integer. + */ + @Transformer + public Integer toInteger(InputStream inStream) { + return Integer.parseInt(toString(inStream)); + } + + /** + * Transform to Long. + * @param inStream Input Stream. + * @return Long. + */ + @Transformer + public Long toLong(InputStream inStream) { + return Long.parseLong(toString(inStream)); + } + + /** + * Transform to Short. + * @param inStream Input Stream. + * @return Short. + */ + @Transformer + public Short toShort(InputStream inStream) { + return Short.parseShort(toString(inStream)); + } + + /** + * Transform to char[]. + * @param inStream Input Stream. + * @return char[]. + */ + @Transformer + public char[] toChars(InputStream inStream) { + return toString(inStream).toCharArray(); + } + + /** + * Transform to Character. + * @param inStream Input Stream. + * @return Character. + */ + @Transformer + public Character toCharacter(InputStream inStream) { + return toString(inStream).charAt(0); + } + + /** + * Transform to byte[]. + * @param inStream Input Stream. + * @return byte[]. + */ + @Transformer + public byte[] toBytes(InputStream inStream) { + ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); + + try { + byte[] readBuffer = new byte[56]; + int readCount; + + while ((readCount = inStream.read(readBuffer)) != -1) { + byteBuffer.write(readBuffer, 0, readCount); + } + } catch (IOException e) { + LOGGER.debug("Error reading from InputStream.", e); + } finally { + try { + inStream.close(); + } catch (IOException e) { + LOGGER.debug("Failed to close InputStream instance.", e); + } + } + + return byteBuffer.toByteArray(); + } + + /** + * Transform to Double. + * @param inStream Input Stream. + * @return Double. + */ + @Transformer + public Double toDouble(InputStream inStream) { + return Double.parseDouble(toString(inStream)); + } + + /** + * Transform to Float. + * @param inStream Input Stream. + * @return Float. + */ + @Transformer + public Float toFloat(InputStream inStream) { + return Float.parseFloat(toString(inStream)); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/io/ReaderTransforms.java b/core/transform/src/main/java/org/switchyard/transform/ootb/io/ReaderTransforms.java new file mode 100644 index 000000000..e04d119a8 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/io/ReaderTransforms.java @@ -0,0 +1,178 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.ootb.io; + +import org.jboss.logging.Logger; +import org.switchyard.annotations.Transformer; +import org.xml.sax.InputSource; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; + +/** + * {@link Reader} Transforms. + *

+ * All transforms close the supplied {@link Reader} before returning. + * + * @author tom.fennelly@gmail.com + */ +public class ReaderTransforms { + + /** + * Singleton Instance. + */ + public static final ReaderTransforms TRANSFORMER = new ReaderTransforms(); + /** + * Logger. + */ + private static final Logger LOGGER = Logger.getLogger(ReaderTransforms.class); + + /** + * Transform to String. + * @param reader Input Reader. + * @return String. + */ + @Transformer + public String toString(Reader reader) { + StringBuilder builder = new StringBuilder(); + + try { + char[] readBuffer = new char[56]; + int readCount; + + while ((readCount = reader.read(readBuffer)) != -1) { + builder.append(readBuffer, 0, readCount); + } + } catch (IOException e) { + LOGGER.debug("Error reading from reader.", e); + } finally { + try { + reader.close(); + } catch (IOException e) { + LOGGER.debug("Failed to close reader instance.", e); + } + } + + return builder.toString(); + } + + /** + * Transform to InputStream. + * @param reader Input Reader. + * @return InputStream. + */ + @Transformer + public InputStream toInputStream(Reader reader) { + return new ByteArrayInputStream(toString(reader).getBytes()); + } + + /** + * Transform to InputSource. + * @param reader Input Reader. + * @return InputSource. + */ + @Transformer + public InputSource toInputSource(Reader reader) { + String string = toString(reader); + InputSource inputSource = new InputSource(); + + inputSource.setByteStream(new ByteArrayInputStream(string.getBytes())); + inputSource.setCharacterStream(new StringReader(string)); + + return inputSource; + } + + /** + * Transform to Integer. + * @param reader Input Reader. + * @return Integer. + */ + @Transformer + public Integer toInteger(Reader reader) { + return Integer.parseInt(toString(reader)); + } + + /** + * Transform to Long. + * @param reader Input Reader. + * @return Long. + */ + @Transformer + public Long toLong(Reader reader) { + return Long.parseLong(toString(reader)); + } + + /** + * Transform to Short. + * @param reader Input Reader. + * @return Short. + */ + @Transformer + public Short toShort(Reader reader) { + return Short.parseShort(toString(reader)); + } + + /** + * Transform to char[]. + * @param reader Input Reader. + * @return char[]. + */ + @Transformer + public char[] toChars(Reader reader) { + return toString(reader).toCharArray(); + } + + /** + * Transform to Character. + * @param reader Input Reader. + * @return Character. + */ + @Transformer + public Character toCharacter(Reader reader) { + return toString(reader).charAt(0); + } + + /** + * Transform to byte[]. + * @param reader Input Reader. + * @return byte[]. + */ + @Transformer + public byte[] toBytes(Reader reader) { + return toString(reader).getBytes(); + } + + /** + * Transform to Double. + * @param reader Input Reader. + * @return Double. + */ + @Transformer + public Double toDouble(Reader reader) { + return Double.parseDouble(toString(reader)); + } + + /** + * Transform to Float. + * @param reader Input Reader. + * @return Float. + */ + @Transformer + public Float toFloat(Reader reader) { + return Float.parseFloat(toString(reader)); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/lang/ByteArrayToStringTransformer.java b/core/transform/src/main/java/org/switchyard/transform/ootb/lang/ByteArrayToStringTransformer.java new file mode 100644 index 000000000..b9de6d76f --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/lang/ByteArrayToStringTransformer.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.ootb.lang; + +import javax.xml.namespace.QName; + +import org.switchyard.transform.BaseTransformer; + +/** + * SwitchYard transformer that takes care of transforming from a byte array + * to a String. + * + * @author Daniel Bevenius + * + */ +public class ByteArrayToStringTransformer extends BaseTransformer{ + + /** + * No-args constructor. + */ + public ByteArrayToStringTransformer() { + super(new QName("java:byte[]"), new QName("java:java.lang.String")); + } + + @Override + public String transform(final byte[] from) { + if (from == null) { + return null; + } + return new String(from); + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/lang/ExceptionTransforms.java b/core/transform/src/main/java/org/switchyard/transform/ootb/lang/ExceptionTransforms.java new file mode 100644 index 000000000..f36407f69 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/lang/ExceptionTransforms.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.ootb.lang; + +import org.switchyard.annotations.Transformer; + +/** + * Exception transforms. + */ +public class ExceptionTransforms { + + /** + * Singleton Instance. + */ + public static final ExceptionTransforms TRANSFORMER = new ExceptionTransforms(); + + private static final String NL = System.getProperty("line.separator"); + + /** + * Transform to String. + * @param t Exception to extract + * @return String. + */ + @Transformer + public String toString(Throwable t) { + Throwable cause = t; + StringBuilder result = new StringBuilder(cause.getClass().getName() + ": " + cause.getMessage()); + while ((cause = cause.getCause()) != null) { + result.append(NL + " --- Caused by " + cause.getClass().getName() + ": " + cause.getMessage()); + } + return result.toString(); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/lang/NumberTransforms.java b/core/transform/src/main/java/org/switchyard/transform/ootb/lang/NumberTransforms.java new file mode 100644 index 000000000..7aed8567a --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/lang/NumberTransforms.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.ootb.lang; + +import org.switchyard.annotations.Transformer; +import org.xml.sax.InputSource; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; + +/** + * + * + * @author tom.fennelly@gmail.com + */ +public class NumberTransforms { + + /** + * Singleton Instance. + */ + public static final NumberTransforms TRANSFORMER = new NumberTransforms(); + + /** + * Transform to String. + * @param number Input Number. + * @return String. + */ + @Transformer + public String toString(Number number) { + return number.toString(); + } + + /** + * Transform to Reader. + * @param number Input Number. + * @return Reader. + */ + @Transformer + public Reader toReader(Number number) { + return new StringReader(number.toString()); + } + + /** + * Transform to InputStream. + * @param number Input Number. + * @return InputStream. + */ + @Transformer + public InputStream toInputStream(Number number) { + return new ByteArrayInputStream(number.toString().getBytes()); + } + + /** + * Transform to InputSource. + * @param number Input Number. + * @return InputSource. + */ + @Transformer + public InputSource toInputSource(Number number) { + String string = toString(number); + InputSource inputSource = new InputSource(); + + inputSource.setByteStream(new ByteArrayInputStream(string.getBytes())); + inputSource.setCharacterStream(new StringReader(string)); + + return inputSource; + } + + /** + * Transform to char[]. + * @param number Input Number. + * @return char[]. + */ + @Transformer + public char[] toChars(Number number) { + return toString(number).toCharArray(); + } + + /** + * Transform to Character. + * @param number Input Number. + * @return Character. + */ + @Transformer + public Character toCharacter(Number number) { + return toString(number).charAt(0); + } + + /** + * Transform to byte[]. + * @param number Input Number. + * @return byte[]. + */ + @Transformer + public byte[] toBytes(Number number) { + return toString(number).getBytes(); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/lang/StringTransforms.java b/core/transform/src/main/java/org/switchyard/transform/ootb/lang/StringTransforms.java new file mode 100644 index 000000000..72c21f48a --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/lang/StringTransforms.java @@ -0,0 +1,152 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.ootb.lang; + +import org.switchyard.annotations.Transformer; +import org.xml.sax.InputSource; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; + +/** + * String Transformations. + * + * @author tom.fennelly@gmail.com + */ +public class StringTransforms { + + /** + * Singleton Instance. + */ + public static final StringTransforms TRANSFORMER = new StringTransforms(); + + /** + * Transform to Reader. + * @param string Input String. + * @return Reader. + */ + @Transformer + public Reader toReader(String string) { + return new StringReader(string); + } + + /** + * Transform to InputStream. + * @param string Input String. + * @return InputStream. + */ + @Transformer + public InputStream toInputStream(String string) { + return new ByteArrayInputStream(string.getBytes()); + } + + /** + * Transform to InputSource. + * @param string Input String. + * @return InputSource. + */ + @Transformer + public InputSource toInputSource(String string) { + InputSource inputSource = new InputSource(); + inputSource.setByteStream(new ByteArrayInputStream(string.getBytes())); + inputSource.setCharacterStream(new StringReader(string)); + return inputSource; + } + + /** + * Transform to Integer. + * @param string Input String. + * @return Integer. + */ + @Transformer + public Integer toInteger(String string) { + return Integer.parseInt(string); + } + + /** + * Transform to Long. + * @param string Input String. + * @return Long. + */ + @Transformer + public Long toLong(String string) { + return Long.parseLong(string); + } + + /** + * Transform to Short. + * @param string Input String. + * @return Short. + */ + @Transformer + public Short toShort(String string) { + return Short.parseShort(string); + } + + /** + * Transform to char[]. + * @param string Input String. + * @return char[]. + */ + @Transformer + public char[] toChars(String string) { + return string.toCharArray(); + } + + /** + * Transform to Character. + * @param string Input String. + * @return Character. + */ + @Transformer + public Character toCharacter(String string) { + if (string.length() > 0) { + return string.charAt(0); + } else { + return null; + } + } + + /** + * Transform to byte[]. + * @param string Input String. + * @return byte[]. + */ + @Transformer + public byte[] toBytes(String string) { + return string.getBytes(); + } + + /** + * Transform to Double. + * @param string Input String. + * @return Double. + */ + @Transformer + public Double toDouble(String string) { + return Double.parseDouble(string); + } + + /** + * Transform to Float. + * @param string Input String. + * @return Float. + */ + @Transformer + public Float toFloat(String string) { + return Float.parseFloat(string); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/map/FromMapToJava.java b/core/transform/src/main/java/org/switchyard/transform/ootb/map/FromMapToJava.java new file mode 100644 index 000000000..1576cf6ef --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/map/FromMapToJava.java @@ -0,0 +1,297 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.map; + +import org.jboss.logging.Logger; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.internal.TransformMessages; + +import javax.xml.namespace.QName; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Transformer that takes a Map graph and from it, builds a Java object + * graph. + * + * @param From Type + * @param To Type. + * + * @author tom.fennelly@gmail.com + */ +public class FromMapToJava extends BaseTransformer { + + private static Logger _logger = Logger.getLogger(FromMapToJava.class); + + private GraphBuilder _graphBuilder; + + private static Map primitives = new HashMap(); { + primitives.put(Integer.TYPE, Integer.class); + primitives.put(Long.TYPE, Long.class); + primitives.put(Double.TYPE, Double.class); + primitives.put(Float.TYPE, Float.class); + primitives.put(Boolean.TYPE, Boolean.class); + primitives.put(Character.TYPE, Character.class); + primitives.put(Byte.TYPE, Byte.class); + primitives.put(Short.TYPE, Short.class); + } + + @Override + public Transformer setTo(QName toType) { + super.setTo(toType); + + if (!QNameUtil.isJavaMessageType(toType)) { + throw TransformMessages.MESSAGES.invalidToTypeNotJavaObject(toType.toString()); + } + + Class javaType = QNameUtil.toJavaMessageType(toType); + if (javaType == null) { + throw TransformMessages.MESSAGES.invalidToTypeClassNotFound(toType.toString()); + } + + _graphBuilder = new ComplexTypeBuilder(javaType, null, null); + return this; + } + + @Override + public Object transform(Map from) { + + return _graphBuilder.build(from); + } + + private abstract class GraphBuilder { + + private Class _javaType; + private String _parentPropertyName; + private GraphBuilder _parentNode; + private Method _parentSetterMethod; + private BeanInfo _beanInfo; + + private GraphBuilder(Class javaType, GraphBuilder parentBuilder, Method parentSetterMethod) { + this._javaType = javaType; + this._parentNode = parentBuilder; + this._parentSetterMethod = parentSetterMethod; + try { + _beanInfo = Introspector.getBeanInfo(_javaType); + } catch (IntrospectionException e) { + throw TransformMessages.MESSAGES.failedToExtractBeanInfo(_javaType.getName(), e); + } + } + + public Class getJavaType() { + return _javaType; + } + + public String getParentPropertyName() { + return _parentPropertyName; + } + + public void setParentPropertyName(String parentPropertyName) { + this._parentPropertyName = parentPropertyName; + } + + abstract Object build(Object value); + + protected void setPropertyValue(Object instance, Object propertyVal, Method parentSetterMethod) throws IllegalAccessException, InvocationTargetException { + Class paramType = parentSetterMethod.getParameterTypes()[0]; + + if (paramType.isInstance(propertyVal)) { + parentSetterMethod.invoke(instance, propertyVal); + return; + } + + if (paramType.isPrimitive()) { + paramType = primitives.get(paramType); + } + + // Try building from a String ... + try { + Constructor stringConstructor = paramType.getConstructor(String.class); + parentSetterMethod.invoke(instance, stringConstructor.newInstance(propertyVal.toString())); + return; + } catch (Exception e) { + if (_logger.isDebugEnabled()) { + _logger.debug("Unable to set property '" + _parentPropertyName + "' on bean instance of type '" + instance.getClass().getName() + "'.", e); + } + } + } + + protected GraphBuilder newBuilder(String propertyName, Class mapType) { + Method propertySetter = getSetter(propertyName); + Class propertyType = propertySetter.getParameterTypes()[0]; + GraphBuilder builder = newBuilder(mapType, propertyType, propertySetter); + + builder.setParentPropertyName(propertyName); + + return builder; + } + + protected GraphBuilder newBuilder(Class mapType, Class javaType, Method parentSetter) { + GraphBuilder nodeBuilder = null; + + if (Collection.class.isAssignableFrom(mapType)) { + Type[] generics = parentSetter.getGenericParameterTypes(); + + if (Collection.class.isAssignableFrom(javaType)) { + if (generics != null && generics.length == 1 && generics[0] != null) { + ParameterizedType genericType = (ParameterizedType) generics[0]; + Type collectionEntryType = genericType.getActualTypeArguments()[0]; + + nodeBuilder = new CollectionTypeBuilder(javaType, (Class) collectionEntryType, this, parentSetter); + } + } + } else { + if (Map.class.isAssignableFrom(mapType)) { + nodeBuilder = new ComplexTypeBuilder(javaType, this, parentSetter); + } else { + nodeBuilder = new SimpleTypeBuilder(javaType, this, parentSetter); + } + } + + return nodeBuilder; + } + + private Method getSetter(String propertyName) { + Method setterMethod = null; + + for (PropertyDescriptor propertyDesc : _beanInfo.getPropertyDescriptors()) { + if (propertyDesc.getName().equals(propertyName)) { + setterMethod = propertyDesc.getWriteMethod(); + break; + } + } + + if (setterMethod == null) { + throw TransformMessages.MESSAGES.noSetterMethodForProperty(propertyName, _javaType.getName()); + } + + return setterMethod; + } + + protected Object newInstance() { + if (_javaType == Collection.class) { + return new ArrayList(); + } + if (_javaType == List.class) { + return new ArrayList(); + } + try { + return _javaType.newInstance(); + } catch (Exception e) { + throw TransformMessages.MESSAGES.unableToCreateInstance(_javaType.getName(), e); + } + } + } + + private final class SimpleTypeBuilder extends GraphBuilder { + + private SimpleTypeBuilder(Class javaType, GraphBuilder parentBuilder, Method parentSetterMethod) { + super(javaType, parentBuilder, parentSetterMethod); + } + + @Override + Object build(Object value) { + return value; + } + } + + private final class ComplexTypeBuilder extends GraphBuilder { + + private Map _childNodes = new ConcurrentHashMap(); + + private ComplexTypeBuilder(Class javaType, GraphBuilder parentBuilder, Method parentSetterMethod) { + super(javaType, parentBuilder, parentSetterMethod); + } + + @Override + Object build(Object value) { + Object instance = newInstance(); + + if (value instanceof Map && !((Map) value).isEmpty()) { + Set properties = ((Map) value).entrySet(); + Iterator propertyIterator = properties.iterator(); + + while (propertyIterator.hasNext()) { + Map.Entry entry = (Map.Entry) propertyIterator.next(); + String propertyName = (String) entry.getKey(); + Object propertyValue = entry.getValue(); + GraphBuilder nodeBuilder = _childNodes.get(propertyName); + + if (nodeBuilder == null) { + nodeBuilder = newBuilder(propertyName, propertyValue.getClass()); + _childNodes.put(propertyName, nodeBuilder); + } + + Object propertyVal = nodeBuilder.build(propertyValue); + try { + setPropertyValue(instance, propertyVal, nodeBuilder._parentSetterMethod); + } catch (Exception e) { + throw TransformMessages.MESSAGES.errorInvokingSetter(nodeBuilder._parentSetterMethod.getName(), + getJavaType().getName(), e); + } + } + } + + return instance; + } + } + + private final class CollectionTypeBuilder extends GraphBuilder { + + private volatile GraphBuilder _collectionEntryBuilder; + private Class _collectionEntryType; + + private CollectionTypeBuilder(Class collectionType, Class collectionEntryType, GraphBuilder parentBuilder, Method parentSetterMethod) { + super(collectionType, parentBuilder, parentSetterMethod); + this._collectionEntryType = collectionEntryType; + } + + @Override + Object build(Object value) { + synchronized (this) { + Collection instance = (Collection) newInstance(); + + if (value instanceof Collection) { + for (Object arrayEntry : (Collection)value) { + if (_collectionEntryBuilder == null) { + _collectionEntryBuilder = newBuilder(arrayEntry.getClass(), _collectionEntryType, null); + } + instance.add(_collectionEntryBuilder.build(arrayEntry)); + } + } + + return instance; + } + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/xml/AbstractDOMTransformer.java b/core/transform/src/main/java/org/switchyard/transform/ootb/xml/AbstractDOMTransformer.java new file mode 100644 index 000000000..7432da34d --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/xml/AbstractDOMTransformer.java @@ -0,0 +1,153 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.xml; + +import org.jboss.logging.Logger; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.internal.TransformLogger; +import org.switchyard.transform.internal.TransformMessages; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringWriter; + +/** + * Abstract DOM transformer. + * + * @param Java type representing the from, or source, format + * @param Java type representing the to, or target, format + * + * @author tom.fennelly@gmail.com + */ +public abstract class AbstractDOMTransformer extends BaseTransformer { + + private static final Logger LOGGER = Logger.getLogger(AbstractDOMTransformer.class); + private Logger _log; + + private static DocumentBuilderFactory _docBuilderFactory; + private static TransformerFactory _transformerFactory = TransformerFactory.newInstance(); + + static { + _docBuilderFactory = DocumentBuilderFactory.newInstance(); + _docBuilderFactory.setNamespaceAware(true); + try { + _transformerFactory.setAttribute("indent-number", Integer.valueOf(4)); + } catch (Exception e) { + // Ignore... Xalan may throw on this!! + // We handle Xalan indentation separately (see serialize method). + Logger.getLogger(AbstractDOMTransformer.class).debug( + "Failed to set indent on transformer.", e); + } + } + + /** + * Constructor. + */ + protected AbstractDOMTransformer() { + _log = Logger.getLogger(getClass()); + } + + /** + * Get the logger for the Transformer. + * @return Transformer Logger instance. + */ + public Logger getLogger() { + return _log; + } + + /** + * Parse the specified source and produce a {@link Document}. + * @param source The source. + * @return The {@link Document}. + */ + public static Document parse(InputSource source) { + DocumentBuilder docBuilder; + + try { + docBuilder = _docBuilderFactory.newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw TransformMessages.MESSAGES.unexpectedDOMParserConfigException(e); + } + + try { + return docBuilder.parse(source); + } catch (SAXException e) { + throw TransformMessages.MESSAGES.errorReadingDOMSourceSAX(e); + } catch (IOException e) { + throw TransformMessages.MESSAGES.errorReadingDOMSourceIO(e); + } finally { + InputStream stream = source.getByteStream(); + Reader reader = source.getCharacterStream(); + try { + try { + if (stream != null) { + stream.close(); + } + } finally { + if (reader != null) { + reader.close(); + } + } + } catch (IOException e) { + TransformLogger.ROOT_LOGGER.exceptionClosingDOMInputSource(e.getMessage()); + } + } + } + + /** + * Serialize the supplied DOM node to a String. + * @param node The DOM node. + * @return The serialized XML. + */ + public static String serialize(Node node) { + Transformer transformer; + + try { + transformer = _transformerFactory.newTransformer(); + } catch (TransformerConfigurationException e) { + throw TransformMessages.MESSAGES.unexpectedExceptionCreatingJDKTransformer(e); + } + + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "4"); + + StringWriter writer = new StringWriter(); + + try { + transformer.transform(new DOMSource(node), new StreamResult(writer)); + } catch (TransformerException e) { + throw TransformMessages.MESSAGES.errorSerializingDOMNode(e); + } + + return writer.toString(); + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/ootb/xml/BasicDOMTransformer.java b/core/transform/src/main/java/org/switchyard/transform/ootb/xml/BasicDOMTransformer.java new file mode 100644 index 000000000..db63cdafb --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/ootb/xml/BasicDOMTransformer.java @@ -0,0 +1,162 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.xml; + +import org.switchyard.config.model.Scannable; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; + +import javax.xml.namespace.QName; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; + +/** + * Basic DOM transformations. + * + * @author tom.fennelly@gmail.com + */ +@Scannable(false) +public class BasicDOMTransformer extends AbstractDOMTransformer { + + private static final QName TYPE_DOCUMENT = toMessageType(Document.class); + private static final QName TYPE_ELEMENT = toMessageType(Element.class); + private static final QName TYPE_STRING = toMessageType(String.class); + private static final QName TYPE_CHAR_ARRAY = toMessageType(char[].class); + private static final QName TYPE_INPUTSOURCE = toMessageType(InputSource.class); + private static final QName TYPE_READER = toMessageType(Reader.class); + private static final QName TYPE_INPUTSTREAM = toMessageType(InputStream.class); + private static final QName TYPE_NODE = toMessageType(Node.class); + private static final QName TYPE_DOMSOURCE = toMessageType(DOMSource.class); + + @Override + public Object transform(Object from) { + if (from instanceof Node) { + return transformFromDOMNode((Node) from); + } else if (from instanceof String) { + return transformFromInputSource(new InputSource(new StringReader((String) from))); + } else if (from instanceof char[]) { + return transformFromInputSource(new InputSource(new StringReader(new String((char[]) from)))); + } else if (from instanceof byte[]) { + return transformFromInputSource(new InputSource(new ByteArrayInputStream((byte[]) from))); + } else if (from instanceof Reader) { + return transformFromInputSource(new InputSource((Reader) from)); + } else if (from instanceof InputStream) { + return transformFromInputSource(new InputSource((InputStream) from)); + } else if (from instanceof InputSource) { + return transformFromInputSource((InputSource) from); + } else if (from instanceof DOMSource) { + return transformFromDOMSource((DOMSource) from); + } + + return null; + } + + private Object transformFromDOMNode(Node from) { + if (getTo().equals(TYPE_DOCUMENT)) { + return from.getOwnerDocument(); + } + if (getTo().equals(TYPE_ELEMENT)) { + if (from.getNodeType() == Node.ELEMENT_NODE) { + return from; + } + if (from.getNodeType() == Node.ATTRIBUTE_NODE) { + return from.getParentNode(); + } + if (from.getNodeType() == Node.DOCUMENT_NODE) { + return ((Document)from).getDocumentElement(); + } + } + if (getTo().equals(TYPE_STRING)) { + return serialize(from); + } + if (getTo().equals(TYPE_CHAR_ARRAY)) { + return serialize(from).toCharArray(); + } + if (getTo().equals(TYPE_INPUTSOURCE)) { + return new InputSource(new StringReader(serialize(from))); + } + if (getTo().equals(TYPE_READER)) { + return new StringReader(serialize(from)); + } + if (getTo().equals(TYPE_INPUTSTREAM)) { + return new ByteArrayInputStream(serialize(from).getBytes()); + } + + return null; + } + + private Object transformFromInputSource(InputSource from) { + Document document = parse(from); + + if (getTo().equals(TYPE_DOCUMENT)) { + return document; + } else if (getTo().equals(TYPE_ELEMENT)) { + return document.getDocumentElement(); + } else if (getTo().equals(TYPE_NODE)) { + return document.getDocumentElement(); + } else if (getTo().equals(TYPE_DOMSOURCE)) { + return new DOMSource(document); + } + + return null; + } + + private Object transformFromDOMSource(DOMSource source) { + if (getTo().equals(TYPE_NODE)) { + return source.getNode(); + } else if (getTo().equals(TYPE_DOCUMENT)) { + final Node sourceNode = source.getNode(); + if (sourceNode instanceof Document) { + return sourceNode; + } else if (sourceNode instanceof Element) { + return ((Element)sourceNode).getOwnerDocument(); + } else { + return null; + } + } else if (getTo().equals(TYPE_ELEMENT)) { + final Node sourceNode = source.getNode(); + if (sourceNode instanceof Element) { + return sourceNode; + } else if (sourceNode instanceof Document) { + return ((Document)sourceNode).getDocumentElement(); + } else { + return null; + } + } else if (getTo().equals(TYPE_STRING)) { + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + try { + TransformerFactory.newInstance().newTransformer().transform(source, result); + } catch (TransformerException e) { + return null; + } + return writer.toString(); + } else if (getTo().equals(TYPE_INPUTSOURCE)) { + return new InputSource(new StringReader(serialize(source.getNode()))); + } else { + return null; + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/osgi/internal/TransformSource.java b/core/transform/src/main/java/org/switchyard/transform/osgi/internal/TransformSource.java new file mode 100644 index 000000000..30250fca5 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/osgi/internal/TransformSource.java @@ -0,0 +1,22 @@ +package org.switchyard.transform.osgi.internal; + +import java.net.URL; + +/** + * Service registered by bundles which contain transformer definitions. Used primarily + * by SwitchYard runtime components to indicate they have OOTB transformers that need + * to be registered by the SwitchYard container. + */ +public interface TransformSource { + + /** + * Default location of transformer definition. + */ + String TRANSFORMS_XML = "META-INF/switchyard/transforms.xml"; + + /** + * URL pointing to the absolute location of a transformer definition. + * @return transformer descriptor URL + */ + URL getTransformsURL(); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/osgi/internal/TransformSourceImpl.java b/core/transform/src/main/java/org/switchyard/transform/osgi/internal/TransformSourceImpl.java new file mode 100644 index 000000000..0b253c4d6 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/osgi/internal/TransformSourceImpl.java @@ -0,0 +1,28 @@ +package org.switchyard.transform.osgi.internal; + +import java.net.URL; + +import org.osgi.framework.Bundle; + +/** + * Implementation of TransformSource. + */ +public class TransformSourceImpl implements TransformSource { + + private Bundle _bundle; + + /** + * Create a new TransformSourceImpl. + * @param bundle a bundle containing a transform definition + */ + public TransformSourceImpl(Bundle bundle) { + _bundle = bundle; + } + + @Override + public URL getTransformsURL() { + return _bundle.getEntry(TRANSFORMS_XML); + } + + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/smooks/internal/OsgiSmooksProducer.java b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/OsgiSmooksProducer.java new file mode 100644 index 000000000..53e417b57 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/OsgiSmooksProducer.java @@ -0,0 +1,38 @@ +package org.switchyard.transform.smooks.internal; + +import org.jboss.logging.Logger; +import org.milyn.Smooks; +import org.milyn.SmooksOSGIFactory; +import org.osgi.framework.Bundle; +import org.switchyard.ServiceDomain; + +/** + * Smooks producer to create Smooks instance through the SmooksOSGIFactory. + */ +public class OsgiSmooksProducer implements SmooksProducer { + + private static final String SWITCHYARD_DEPLOYMENT_BUNDLE = "switchyard.deployment.bundle"; + private static Logger _logger = Logger.getLogger(OsgiSmooksProducer.class); + + @Override + public Smooks createSmooks(ServiceDomain domain, String config) { + if (_logger.isDebugEnabled()) { + _logger.debug("Creating Smooks instance - Domain: " + domain + ", Smooks Config: " + config); + } + + if (domain != null && domain.getProperties() != null) { + Bundle bundle = (Bundle)domain.getProperty(SWITCHYARD_DEPLOYMENT_BUNDLE); + if (bundle != null) { + try { + return new SmooksOSGIFactory(bundle).createInstance(config); + } catch (Exception e) { + if (_logger.isDebugEnabled()) { + _logger.debug(e); + } + } + } + } + return null; + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksProducer.java b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksProducer.java new file mode 100644 index 000000000..917892a30 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksProducer.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.smooks.internal; + +import org.milyn.Smooks; +import org.switchyard.ServiceDomain; + +/** + * Smooks producer interface to be used for creating Smooks instance. + */ +public interface SmooksProducer { + + /** + * Creates Smooks instance. + * @param domain SwitchYard ServiceDomain + * @param config Smooks config + * @return Smooks instance + */ + Smooks createSmooks(ServiceDomain domain, String config); +} diff --git a/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksTransformFactory.java b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksTransformFactory.java new file mode 100644 index 000000000..a61becd39 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksTransformFactory.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.smooks.internal; + +import org.milyn.Smooks; +import org.milyn.javabean.binding.model.ModelSet; +import org.switchyard.ServiceDomain; +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.SmooksTransformModel; +import org.switchyard.transform.config.model.SmooksTransformType; +import org.switchyard.transform.internal.TransformMessages; +import org.switchyard.transform.internal.TransformerFactory; + +import javax.xml.namespace.QName; + +/** + * Smooks Transformer factory. + * + * @author tom.fennelly@gmail.com + */ +public class SmooksTransformFactory implements TransformerFactory { + + /** + * Create a {@link Transformer} instance from the supplied {@link SmooksTransformModel}. + * @param domain ServiceDomain instance. + * @param model The model. + * @return The Transformer instance. + */ + public Transformer newTransformer(ServiceDomain domain, SmooksTransformModel model) { + String transformType = model.getTransformType(); + String config = model.getConfig(); + QName from = model.getFrom(); + QName to = model.getTo(); + + if (transformType == null || transformType.trim().length() == 0) { + throw TransformMessages.MESSAGES.invalidSmooksConfigurationModelNullType(); + } + if (config == null || config.trim().length() == 0) { + throw TransformMessages.MESSAGES.invalidSmooksConfigurationModelNullConfig(); + } + if (from == null) { + throw TransformMessages.MESSAGES.invalidSmooksConfigurationModelNullFrom(); + } + if (to == null) { + throw TransformMessages.MESSAGES.invalidSmooksConfigurationModelNullTo(); + } + + SmooksTransformType transformationType = SmooksTransformType.valueOf(transformType); + + Smooks smooks = null; + try { + SmooksProducer producer = ProviderRegistry.getProvider(SmooksProducer.class); + if (producer != null) { + smooks = producer.createSmooks(domain, config); + } + if (smooks == null) { + smooks = new Smooks(config); + } + smooks.createExecutionContext(); + } catch (Exception e) { + throw TransformMessages.MESSAGES.failedToCreateSmooksInstance(config, e); + } + + Transformer transformer; + + if (transformationType == SmooksTransformType.JAVA2XML) { + transformer = newXMLBindingTransformer(from, to, smooks, XMLBindingTransformer.BindingDirection.JAVA2XML); + } else if (transformationType == SmooksTransformType.XML2JAVA) { + transformer = newXMLBindingTransformer(from, to, smooks, XMLBindingTransformer.BindingDirection.XML2JAVA); + } else if (transformationType == SmooksTransformType.SMOOKS) { + transformer = new SmooksTransformer(from, to, smooks, model); + } else { + throw TransformMessages.MESSAGES.unhandledSmooksTransformationType(transformationType.toString()); + } + + transformer.setFrom(model.getFrom()); + transformer.setTo(model.getTo()); + + return transformer; + } + + private static Transformer newXMLBindingTransformer(final QName from, final QName to, Smooks smooks, XMLBindingTransformer.BindingDirection direction) { + ModelSet beanModel = ModelSet.get(smooks.getApplicationContext()); + if (beanModel != null && !beanModel.getModels().isEmpty()) { + return new XMLBindingTransformer(from, to, smooks, beanModel, direction); + } else { + throw TransformMessages.MESSAGES.invalidBindingConfiguration(direction.toString()); + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksTransformer.java b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksTransformer.java new file mode 100644 index 000000000..f9c78003d --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/SmooksTransformer.java @@ -0,0 +1,132 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.smooks.internal; + +import javax.xml.namespace.QName; +import javax.xml.transform.Result; +import javax.xml.transform.Source; + +import org.jboss.logging.Logger; +import org.milyn.Smooks; +import org.milyn.container.plugin.SourceFactory; +import org.milyn.payload.Export; +import org.milyn.payload.Exports; +import org.milyn.payload.JavaResult; +import org.milyn.payload.StringResult; +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.config.model.SmooksTransformModel; +import org.switchyard.transform.internal.TransformMessages; + +/** + * Smooks {@link org.switchyard.transform.Transformer}. + * @author tom.fennelly@gmail.com + */ +@Scannable(false) +public class SmooksTransformer extends BaseTransformer { + + private static Logger _log = Logger.getLogger(SmooksTransformer.class); + + private Smooks _smooks; + private String _reportPath; + private Export _export; + + /** + * Constructor. + * @param from From type. + * @param to To type. + * @param smooks Smooks instance. + */ + protected SmooksTransformer(final QName from, final QName to, Smooks smooks, SmooksTransformModel model) { + super(from, to); + _smooks = smooks; + _reportPath = model.getReportPath(); + init(model); + } + + /** + * {@inheritDoc} + */ + @Override + public Object transform(Object from) { + if (from == null) { + _log.debug("Null from payload passed to SmooksTransformer. Returning null."); + return null; + } + + Source source = SourceFactory.getInstance().createSource(from); + if (_export != null) { + Result result = newResultInstance(); + _smooks.filterSource(source, result); + return extractResultData(result); + } else { + _smooks.filterSource(source); + return from; + } + } + + /** + * Set the report path. + *

+ * Only use for debugging purposes. + * + * @param reportPath Report path. + */ + public void setReportPath(String reportPath) { + this._reportPath = reportPath; + } + + private void init(SmooksTransformModel model) { + Exports exports = Exports.getExports(_smooks.getApplicationContext()); + + // Must define 1 exported result type + if (exports == null) { + _log.debug("Smooks configuration '" + model.getConfig() + "'will not make updates to the Exchange Message payload because it does not define any . See Smooks User Guide."); + return; + } + if (exports.getExports().size() != 1) { + throw TransformMessages.MESSAGES.smooksConfigurationNoExports(); + } + + _export = exports.getExports().iterator().next(); + + // Only support String (character based) or Java Results for now... + Class exportType = _export.getType(); + if (StringResult.class.isAssignableFrom(exportType)) { + return; + } else if (JavaResult.class.isAssignableFrom(exportType)) { + return; + } + + throw TransformMessages.MESSAGES.unsupportedSmooksExport(exportType.getName()); + } + + private Result newResultInstance() { + Class resultType = _export.getType(); + try { + return (Result) resultType.newInstance(); + } catch (Exception e) { + throw TransformMessages.MESSAGES.unsupportedExceptionCreatingResult(resultType.getName(), e); + } + } + + private Object extractResultData(Result result) { + if (result instanceof StringResult) { + return ((StringResult) result).getResult(); + } else if (result instanceof JavaResult) { + return ((JavaResult) result).extractFromResult((JavaResult) result, _export); + } + return null; + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/smooks/internal/XMLBindingTransformer.java b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/XMLBindingTransformer.java new file mode 100644 index 000000000..ab489a908 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/smooks/internal/XMLBindingTransformer.java @@ -0,0 +1,98 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.smooks.internal; + +import org.jboss.logging.Logger; +import org.milyn.Smooks; +import org.milyn.container.plugin.SourceFactory; +import org.milyn.javabean.binding.model.Bean; +import org.milyn.javabean.binding.model.ModelSet; +import org.milyn.javabean.binding.xml.XMLBinding; +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.internal.TransformMessages; + +import javax.xml.namespace.QName; +import javax.xml.transform.Source; + +import java.io.IOException; + +/** + * Smooks XMLBinding {@link org.switchyard.transform.Transformer}. + * + * @author tom.fennelly@gmail.com + */ +@Scannable(false) +public class XMLBindingTransformer extends BaseTransformer { + + private static Logger _log = Logger.getLogger(XMLBindingTransformer.class); + + private XMLBinding _xmlBinding; + private Bean _bean; + private BindingDirection _direction; + + /** + * Binding direction. + */ + public static enum BindingDirection { + /** The xml to java binding direction. */ + XML2JAVA, + /** The java to xml binding directionx. */ + JAVA2XML + } + + /** + * Constructor. + * @param from From type. + * @param to To type. + * @param smooks Smooks instance. + * @param beanModel Bean model. + * @param direction Binding direction. + */ + protected XMLBindingTransformer(final QName from, final QName to, Smooks smooks, ModelSet beanModel, BindingDirection direction) { + super(from, to); + _xmlBinding = new XMLBinding(smooks); + _xmlBinding.setOmitXMLDeclaration(true); // XML decl causes problems for StAX code used by SOAP handler + _xmlBinding.intiailize(); + _bean = beanModel.getModels().values().iterator().next(); + _direction = direction; + } + + /** + * {@inheritDoc} + */ + @Override + public Object transform(Object from) { + if (from == null) { + _log.debug("Null from payload passed to XMLBindingTransformer. Returning null."); + return null; + } + + if (_direction == BindingDirection.XML2JAVA) { + Source source = SourceFactory.getInstance().createSource(from); + try { + return _xmlBinding.fromXML(source, _bean.getBeanClass()); + } catch (IOException e) { + throw TransformMessages.MESSAGES.exceptionTransformingFromXML(_bean.getBeanClass().getName(), e); + } + } else { + if (!_bean.getBeanClass().isInstance(from)) { + throw TransformMessages.MESSAGES.cannotTransformToXML(from.getClass().getName(), _bean.getBeanClass().getName()); + } + + return _xmlBinding.toXML(from); + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/xslt/internal/TransformerPool.java b/core/transform/src/main/java/org/switchyard/transform/xslt/internal/TransformerPool.java new file mode 100644 index 000000000..3c3ebc347 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/xslt/internal/TransformerPool.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.xslt.internal; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.transform.ErrorListener; +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; + +import org.jboss.logging.Logger; + +/** + * Provides a pool of javax.xml.transform.Transformer instances which are + * created on demand and bounded by a pool maxSize. If a pooled instance + * is not available, clients block FIFO style until a transformer is returned + * to the pool. + */ +public class TransformerPool { + private Logger _logger = Logger.getLogger(TransformerPool.class); + + private BlockingQueue _pool; + private Templates _templates; + private AtomicInteger _count = new AtomicInteger(0); + private int _maxSize; + private ErrorListener _errorListener; + + /** + * Create a new Transformer pool. + * @param templates template used to create a new Transformer instance + * @param maxSize maximum size of the pool + */ + public TransformerPool(Templates templates, int maxSize) { + this(templates, maxSize, null); + } + + /** + * Create a new Transformer pool. + * @param templates template used to create a new Transformer instance + * @param maxSize maximum size of the pool + * @param errorListener error listener + */ + public TransformerPool(Templates templates, int maxSize, ErrorListener errorListener) { + _templates = templates; + _maxSize = maxSize; + _errorListener = errorListener; + _pool = new ArrayBlockingQueue(maxSize, true); + + } + + /** + * Asks the pool for an available Transformer instance. If a pooled + * instance is available, then it is returned immediately. If not, + * a new instance will be created and added to the pool if the pool + * has not grown to maxSize yet. Blocked clients are served in + * FIFO order. + * @return Transformer instance + * @throws Exception failed during creation of a transformer instance + */ + public Transformer take() throws Exception { + Transformer t = _pool.poll(); + if (t != null) { + return t; + } + + // nothing available - so we need to create or wait + if (_count.get() < _maxSize) { + addTransformer(); + } + return _pool.take(); + } + + /** + * Returns a pooled Transformer instance to the pool. + * @param transformer pooled transformer + * @return true if the transformer was added to the pool, false otherwise + */ + public boolean give(Transformer transformer) { + return _pool.offer(transformer); + } + + private void addTransformer() throws Exception { + Transformer transformer = _templates.newTransformer(); + if (_errorListener != null) { + transformer.setErrorListener(_errorListener); + } + _count.incrementAndGet(); + boolean result = _pool.offer(transformer); + if ((!result) && (_logger.isDebugEnabled())) { + _logger.debug("Unable to add " + transformer.toString() + " to blocking queue"); + } + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltTransformFactory.java b/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltTransformFactory.java new file mode 100644 index 000000000..ed661df01 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltTransformFactory.java @@ -0,0 +1,131 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.xslt.internal; + +import java.io.IOException; +import java.io.InputStream; + +import javax.xml.namespace.QName; +import javax.xml.transform.ErrorListener; +import javax.xml.transform.Templates; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.stream.StreamSource; + +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.XsltTransformModel; +import org.switchyard.transform.internal.TransformLogger; +import org.switchyard.transform.internal.TransformMessages; +import org.switchyard.transform.internal.TransformerFactory; + +/** + * @author Alejandro Montenegro aamonten@gmail.com + */ +public final class XsltTransformFactory implements TransformerFactory{ + + /** + * Property used in a domain property to configure max transformer pool size. + */ + public static final String MAX_POOL_SIZE = "org.switchyard.transform.xslt.maxPoolSize"; + /** + * Default max size for transformer pool. + */ + public static final int DEFAULT_MAX_POOL_SIZE = 50; + + /** + * Create a {@link Transformer} instance from the supplied {@link XsltTransformModel}. + * @param domain ServiceDomain instance. + * @param model the JSON transformer model. + * @return the Transformer instance. + */ + public Transformer newTransformer(ServiceDomain domain, XsltTransformModel model) { + + String xsltFileUri = model.getXsltFile(); + boolean failOnWarning = model.failOnWarning(); + QName to = model.getTo(); + QName from = model.getFrom(); + + if (xsltFileUri == null || xsltFileUri.equals("")) { + throw TransformMessages.MESSAGES.noXSLFileDefined(); + } + + try { + InputStream stylesheetStream = Classes.getResourceAsStream(xsltFileUri); + + if (stylesheetStream == null) { + TransformMessages.MESSAGES.failedToLoadXSLFile(xsltFileUri); + } + javax.xml.transform.TransformerFactory tFactory = javax.xml.transform.TransformerFactory.newInstance(); + tFactory.setErrorListener(new XsltTransformFactoryErrorListener(failOnWarning)); + tFactory.setURIResolver(new XsltUriResolver()); + Templates templates = tFactory.newTemplates(new StreamSource(stylesheetStream)); + + return new XsltTransformer(from, to, templates, failOnWarning, getTransformPoolSize(model)); + } catch (TransformerConfigurationException e) { + throw TransformMessages.MESSAGES.unexpectedErrorOcurred(e); + } catch (IOException e) { + throw TransformMessages.MESSAGES.unableToLocateXSLTFile(model.getXsltFile().toString(), e); + } + } + + // This method looks for the MAX_POOL_SIZE property within switchyard.xml to + // configure the default transformer pool size + int getTransformPoolSize(XsltTransformModel model) { + int poolSize = DEFAULT_MAX_POOL_SIZE; + // attempt to navigate to parent + Model root = model.getModelRoot(); + if (root instanceof SwitchYardModel) { + SwitchYardModel syModel = (SwitchYardModel)root; + if (syModel.getDomain() != null && syModel.getDomain().getProperties() != null) { + String poolProp = syModel.getDomain().getProperties().getPropertyValue(MAX_POOL_SIZE); + if (poolProp != null) { + poolSize = Integer.parseInt(poolProp); + } + } + } + return poolSize; + } + + private class XsltTransformFactoryErrorListener implements ErrorListener { + private boolean _failOnWarning; + + public XsltTransformFactoryErrorListener(boolean failOnWarning) { + this._failOnWarning = failOnWarning; + } + + @Override + public void warning(TransformerException ex) throws TransformerException { + if (_failOnWarning) { + throw ex; + } else { + TransformLogger.ROOT_LOGGER.warningDuringCompilation(ex); + } + } + + @Override + public void error(TransformerException ex) throws TransformerException { + throw ex; + } + + @Override + public void fatalError(TransformerException ex) throws TransformerException { + throw ex; + } + } + +} diff --git a/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltTransformer.java b/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltTransformer.java new file mode 100644 index 000000000..c15df927f --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltTransformer.java @@ -0,0 +1,126 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.xslt.internal; + +import javax.xml.namespace.QName; +import javax.xml.transform.ErrorListener; +import javax.xml.transform.Templates; +import javax.xml.transform.TransformerException; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.dom.DOMResult; + +import org.jboss.logging.Logger; +import org.switchyard.Message; +import org.switchyard.config.model.Scannable; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.internal.TransformLogger; +import org.switchyard.transform.internal.TransformMessages; +import org.w3c.dom.Document; + +/** + * XSLT Transformer {@link org.switchyard.transform.Transformer}. + * + * @author Alejandro Montenegro + * @param From Type + * @param To Type. + */ +@Scannable(false) +public class XsltTransformer extends BaseTransformer { + + private static final Logger LOGGER = Logger.getLogger(XsltTransformer.class); + private Templates _templates; + private TransformerPool _transformerPool; + private boolean _failOnWarning; + + /** + * Public constructor. + * + * @param from From type. + * @param to To type. + * @param templates XSL Template instance + * @param failOnWarning whether a warning should be reported as an SwitchYardException or just log + * @param maxPoolSize maximum size for the transformer pool + */ + public XsltTransformer(QName from, QName to, Templates templates, boolean failOnWarning, int maxPoolSize) { + super(from, to); + this._templates = templates; + this._failOnWarning = failOnWarning; + // max pool size < 0 indicates that pooling should be disabled + if (maxPoolSize > 0) { + _transformerPool = new TransformerPool( + templates, maxPoolSize, new XsltTransformerErrorListener(_failOnWarning)); + } + } + + @Override + public Message transform(Message message) { + javax.xml.transform.Transformer transformer = null; + + try { + DOMSource source = message.getContent(DOMSource.class); + DOMResult result = new DOMResult(); + + if (_transformerPool != null) { + transformer = _transformerPool.take(); + } else { + // if no pool is configured, then just create a new transformer for each request + transformer = _templates.newTransformer(); + transformer.setErrorListener(new XsltTransformerErrorListener(_failOnWarning)); + } + + transformer.transform(source, result); + message.setContent(((Document)result.getNode()).getDocumentElement()); + + } catch (Exception e) { + throw TransformMessages.MESSAGES.errorDuringXsltTransformation(e); + } finally { + if (_transformerPool != null && transformer != null) { + _transformerPool.give(transformer); + } + } + return message; + } + + TransformerPool getTransformerPool() { + return _transformerPool; + } + + private class XsltTransformerErrorListener implements ErrorListener { + private boolean _failOnWarning; + + public XsltTransformerErrorListener(boolean failOnWarning) { + this._failOnWarning = failOnWarning; + } + + @Override + public void warning(TransformerException ex) throws TransformerException { + if (_failOnWarning) { + throw ex; + } else { + TransformLogger.ROOT_LOGGER.warningDuringTransformation(ex); + } + } + + @Override + public void error(TransformerException ex) throws TransformerException { + throw ex; + } + + @Override + public void fatalError(TransformerException ex) throws TransformerException { + throw ex; + } + } +} diff --git a/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltUriResolver.java b/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltUriResolver.java new file mode 100644 index 000000000..d05b08436 --- /dev/null +++ b/core/transform/src/main/java/org/switchyard/transform/xslt/internal/XsltUriResolver.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.xslt.internal; + +import java.io.InputStream; + +import javax.xml.transform.Source; +import javax.xml.transform.TransformerException; +import javax.xml.transform.URIResolver; +import javax.xml.transform.stream.StreamSource; + +import org.switchyard.common.type.Classes; + +/** + * Allows stylesheet resources to be resolved from the class loader chain using + * relative paths in a stylesheet include. + */ +public class XsltUriResolver implements URIResolver { + + @Override + public Source resolve(String href, String base) throws TransformerException { + InputStream inputStream = Classes.getClassLoader().getResourceAsStream(href); + return new StreamSource(inputStream); + } +} diff --git a/core/transform/src/main/resources/META-INF/switchyard/transforms.xml b/core/transform/src/main/resources/META-INF/switchyard/transforms.xml new file mode 100644 index 000000000..6b96deb37 --- /dev/null +++ b/core/transform/src/main/resources/META-INF/switchyard/transforms.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/transform/src/main/resources/OSGI-INF/blueprint/transformers.xml b/core/transform/src/main/resources/OSGI-INF/blueprint/transformers.xml new file mode 100644 index 000000000..33dcf4e82 --- /dev/null +++ b/core/transform/src/main/resources/OSGI-INF/blueprint/transformers.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/core/transform/src/main/resources/org/switchyard/config/model/descriptor.properties b/core/transform/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..177d64751 --- /dev/null +++ b/core/transform/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +trfm_1_0.section=urn:switchyard-config:transform +trfm_1_0.version=1.0 +trfm_1_0.namespace=urn:switchyard-config:transform:1.0 +trfm_1_0.schema=transform_1_0.xsd +trfm_1_0.location=/org/switchyard/transform/config/model/v1/ +trfm_1_0.marshaller=org.switchyard.transform.config.model.v1.V1TransformMarshaller + +trfm_1_1.section=urn:switchyard-config:transform +trfm_1_1.version=1.1 +trfm_1_1.namespace=urn:switchyard-config:transform:1.1 +trfm_1_1.schema=transform_1_1.xsd +trfm_1_1.location=/org/switchyard/transform/config/model/v1/ +trfm_1_1.marshaller=org.switchyard.transform.config.model.v1.V1TransformMarshaller + +trfm_2_0.section=urn:switchyard-config:transform +trfm_2_0.version=2.0 +trfm_2_0.namespace=urn:switchyard-config:transform:2.0 +trfm_2_0.schema=transform_2_0.xsd +trfm_2_0.location=/org/switchyard/transform/config/model/v2/ +trfm_2_0.marshaller=org.switchyard.transform.config.model.v2.V2TransformMarshaller diff --git a/core/transform/src/main/resources/org/switchyard/transform/config/model/v1/transform_1_0.xsd b/core/transform/src/main/resources/org/switchyard/transform/config/model/v1/transform_1_0.xsd new file mode 100644 index 000000000..dcfb2d4f4 --- /dev/null +++ b/core/transform/src/main/resources/org/switchyard/transform/config/model/v1/transform_1_0.xsd @@ -0,0 +1,204 @@ + + + + + + + + + + + JSON Transformer Configuration. + + + + + + + + + + + + + XSLT Transformer Configuration. + + + + + + + + Path to a file containing the XSL definition. + + + + + + + whether a warning should be reported as an SwitchYardException or just log. default is false + + + + + + + + + + + + Generic/Custom Java Transformer Configuration. + + + + + + + + The name of the Java Transformer implementation class. + + + + + + + The name of the Java Transformer CDI bean. + + + + + + + + + + + + Smooks Transformer Configuration. + + + + + + + + Smooks Configuration file path. + + + + + + + Smooks Configuration file path. + + + + + + + Smooks Execution Report filesystem path. +

+ An Execution Report is a HTML file showing how all the input message + fragments were processed by Smooks, including the contents of the Smooks + ExecutionContext at each stage in the processing. +

+ Use for debug purposes only. Adds significant processing overhead. + + + + + + + + + + + + + Basic Smooks Transformation. +

+ The result type is defined through the <core:exports> + section of the configuration. +

+ See the Smooks User Guide. + + + + + + + XML to Java Transformation via Smooks Java Binding configurations. +

+ See the Smooks User Guide. + + + + + + + Java to XML Transformation via Smooks Java Binding configurations. +

+ See the Smooks User Guide. + + + + + + + + + + + + XML to Java Transformation. + + + + + + + Java to XML Transformation. + + + + + + + + + + + JAXB Transformer Configuration. + + + + + + + + The JAXB Context Path containing an ObjectFactory definition. + + + + + + + + diff --git a/core/transform/src/main/resources/org/switchyard/transform/config/model/v1/transform_1_1.xsd b/core/transform/src/main/resources/org/switchyard/transform/config/model/v1/transform_1_1.xsd new file mode 100644 index 000000000..3fc682b60 --- /dev/null +++ b/core/transform/src/main/resources/org/switchyard/transform/config/model/v1/transform_1_1.xsd @@ -0,0 +1,203 @@ + + + + + + + + + + + JSON Transformer Configuration. + + + + + + + + + + + + + XSLT Transformer Configuration. + + + + + + + + Path to a file containing the XSL definition. + + + + + + + whether a warning should be reported as an SwitchYardException or just log. default is false + + + + + + + + + + + + Generic/Custom Java Transformer Configuration. + + + + + + + + The name of the Java Transformer implementation class. + + + + + + + The name of the Java Transformer CDI bean. + + + + + + + + + + + + Smooks Transformer Configuration. + + + + + + + + Smooks Configuration file path. + + + + + + + Smooks Configuration file path. + + + + + + + Smooks Execution Report filesystem path. +

+ An Execution Report is a HTML file showing how all the input message + fragments were processed by Smooks, including the contents of the Smooks + ExecutionContext at each stage in the processing. +

+ Use for debug purposes only. Adds significant processing overhead. + + + + + + + + + + + + + Basic Smooks Transformation. +

+ The result type is defined through the <core:exports> + section of the configuration. +

+ See the Smooks User Guide. + + + + + + + XML to Java Transformation via Smooks Java Binding configurations. +

+ See the Smooks User Guide. + + + + + + + Java to XML Transformation via Smooks Java Binding configurations. +

+ See the Smooks User Guide. + + + + + + + + + + + + XML to Java Transformation. + + + + + + + Java to XML Transformation. + + + + + + + + + + + JAXB Transformer Configuration. + + + + + + + + The JAXB Context Path containing an ObjectFactory definition. + + + + + + + diff --git a/core/transform/src/main/resources/org/switchyard/transform/config/model/v2/transform_2_0.xsd b/core/transform/src/main/resources/org/switchyard/transform/config/model/v2/transform_2_0.xsd new file mode 100644 index 000000000..d9f4b7748 --- /dev/null +++ b/core/transform/src/main/resources/org/switchyard/transform/config/model/v2/transform_2_0.xsd @@ -0,0 +1,232 @@ + + + + + + + + + + + JSON Transformer Configuration. + + + + + + + + + + + + + XSLT Transformer Configuration. + + + + + + + + Path to a file containing the XSL definition. + + + + + + + whether a warning should be reported as an SwitchYardException or just log. default is false + + + + + + + + + + + + Generic/Custom Java Transformer Configuration. + + + + + + + + The name of the Java Transformer implementation class. + + + + + + + The name of the Java Transformer CDI bean. + + + + + + + + + + + + Smooks Transformer Configuration. + + + + + + + + Smooks Configuration file path. + + + + + + + Smooks Configuration file path. + + + + + + + Smooks Execution Report filesystem path. +

+ An Execution Report is a HTML file showing how all the input message + fragments were processed by Smooks, including the contents of the Smooks + ExecutionContext at each stage in the processing. +

+ Use for debug purposes only. Adds significant processing overhead. + + + + + + + + + + + + + Basic Smooks Transformation. +

+ The result type is defined through the <core:exports> + section of the configuration. +

+ See the Smooks User Guide. + + + + + + + XML to Java Transformation via Smooks Java Binding configurations. +

+ See the Smooks User Guide. + + + + + + + Java to XML Transformation via Smooks Java Binding configurations. +

+ See the Smooks User Guide. + + + + + + + + + + + + XML to Java Transformation. + + + + + + + Java to XML Transformation. + + + + + + + + + + + JAXB Transformer Configuration. + + + + + + + + The JAXB Context Path containing an ObjectFactory definition. + + + + + + + + + + + + Dozer Transformer Configuration. + + + + + + + + + + + + + + Dozer mapping file configuration. + + + + + + + + + + diff --git a/core/transform/src/test/java/org/switchyard/transform/AbstractTransformerTestCase.java b/core/transform/src/test/java/org/switchyard/transform/AbstractTransformerTestCase.java new file mode 100644 index 000000000..de0591b75 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/AbstractTransformerTestCase.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Assert; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.transform.internal.TransformerRegistryLoader; + +/** + * @author tom.fennelly@gmail.com + */ +public abstract class AbstractTransformerTestCase { + + protected Transformer getTransformer(String config) throws IOException { + InputStream swConfigStream = Classes.getResourceAsStream(config, getClass()); + + if (swConfigStream == null) { + Assert.fail("null config stream."); + } + + SwitchYardModel switchyardConfig; + try { + switchyardConfig = new ModelPuller().pull(swConfigStream); + } finally { + swConfigStream.close(); + } + + TransformsModel transforms = switchyardConfig.getTransforms(); + + TransformModel transformModel = transforms.getTransforms().get(0); + + if (transformModel == null) { + Assert.fail("No smooks config."); + } + TransformerRegistryLoader trl = new TransformerRegistryLoader(new BaseTransformerRegistry()); + return trl.newTransformer(transformModel); + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/BaseTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/BaseTransformerTest.java new file mode 100644 index 000000000..c39401c61 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/BaseTransformerTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; + +class StringToIntegerTransformer extends BaseTransformer { + public Integer transform(String num) { + return 5; + } +} + +class UntypedTransformer extends BaseTransformer { + public Object transform(Object obj) { + return null; + } +} + +class ImplementsTransfomer implements Transformer { + + @Override + public QName getFrom() { + return null; + } + + @Override + public Class getFromType() { + return String.class; + } + + @Override + public QName getTo() { + return null; + } + + @Override + public Class getToType() { + return Boolean.class; + } + + @Override + public Transformer setFrom(QName fromType) { + return null; + } + + @Override + public Transformer setTo(QName toType) { + return null; + } + + @Override + public Object transform(Object from) { + return null; + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/Message2MessageTransformer.java b/core/transform/src/test/java/org/switchyard/transform/Message2MessageTransformer.java new file mode 100644 index 000000000..f7c2e2441 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/Message2MessageTransformer.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import org.switchyard.Message; + +/** + * @author tom.fennelly@gmail.com + */ +public class Message2MessageTransformer extends BaseTransformer { + + private Message _message; + + @Override + public Message transform(Message message) { + this._message = message; + return message; + } + + public Message getMessage() { + return _message; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/Message2NullTransformer.java b/core/transform/src/test/java/org/switchyard/transform/Message2NullTransformer.java new file mode 100644 index 000000000..787a19f8c --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/Message2NullTransformer.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + + +/** + * @author tom.fennelly@gmail.com + * @author jpechane@redhat.com + */ +public class Message2NullTransformer extends BaseTransformer { + + private String _content; + + @Override + public String transform(String content) { + _content = content; + return null; + } + + public String getContent() { + return _content; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/MessageTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/MessageTransformerTest.java new file mode 100644 index 000000000..1356641db --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/MessageTransformerTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform; + +import java.io.IOException; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.internal.transform.BaseTransformerRegistry; + +/** + * @author tom.fennelly@gmail.com + */ +public class MessageTransformerTest { + + @Test + public void test() throws IOException { + final QName A = new QName("a"); + final QName B = new QName("b"); + + BaseTransformerRegistry xformReg = new BaseTransformerRegistry(); + TransformSequence transSequence = TransformSequence.from(A).to(B); + + DefaultMessage message = new DefaultMessage().setContent(A); + Message2MessageTransformer transformer = new Message2MessageTransformer(); + + xformReg.addTransformer(transformer, A, B); + transSequence.apply(message, xformReg); + + Assert.assertEquals(message, transformer.getMessage()); + } + + @Test + public void testNullOutputFromTransformation() throws IOException { + final QName A = new QName("a"); + final QName B = new QName("b"); + + BaseTransformerRegistry xformReg = new BaseTransformerRegistry(); + TransformSequence transSequence = TransformSequence.from(A).to(B); + + DefaultMessage message = new DefaultMessage().setContent("testNull"); + Message2NullTransformer transformer = new Message2NullTransformer(); + + xformReg.addTransformer(transformer, A, B); + transSequence.apply(message, xformReg); + System.out.println(message.getContent()); + Assert.assertNull(message.getContent()); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/TransformerRegistryLoaderTest.java b/core/transform/src/test/java/org/switchyard/transform/TransformerRegistryLoaderTest.java new file mode 100644 index 000000000..29c02c29d --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/TransformerRegistryLoaderTest.java @@ -0,0 +1,38 @@ +package org.switchyard.transform; + +import junit.framework.Assert; + +import org.junit.Before; +import org.junit.Test; +import org.switchyard.SwitchYardException; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.transform.internal.TransformerRegistryLoader; + +public class TransformerRegistryLoaderTest { + + private static final String MISSING_TRANSFORM_XML = + "/org/switchyard/transform/MissingTransformerTest.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void transformerClassNotFound() throws Exception { + SwitchYardModel switchyard = _puller.pull(MISSING_TRANSFORM_XML, getClass()); + TransformerRegistryLoader loader = new TransformerRegistryLoader(new BaseTransformerRegistry()); + try { + loader.newTransformers(switchyard.getTransforms().getTransforms().get(0)); + // the above should have resulted in an exception + Assert.fail("missing transformer class should result in SwitchYardException"); + } catch (SwitchYardException syEx) { + // expected outcome + return; + } + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/config/model/TransformModelTests.java b/core/transform/src/test/java/org/switchyard/transform/config/model/TransformModelTests.java new file mode 100644 index 000000000..d5e6ac631 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/config/model/TransformModelTests.java @@ -0,0 +1,132 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.config.model.transform.v1.V1TransformsModel; +import org.switchyard.transform.config.model.v1.V1JavaTransformModel; +import org.switchyard.transform.config.model.v1.V1SmooksTransformModel; + +/** + * TransformModelTests. + * + * @author David Ward <dward@jboss.org> (C) 2011 Red Hat Inc. + */ +public class TransformModelTests { + + private static final String XML = "/org/switchyard/transform/config/model/TransformModelTests.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void testCreateEmptyModel() throws Exception { + String namespace = TransformNamespace.DEFAULT.uri(); + String name = TransformModel.TRANSFORM + '.' + JavaTransformModel.JAVA; + Model model = new ModelPuller().pull(XMLHelper.createQName(namespace, name)); + Assert.assertTrue(model instanceof JavaTransformModel); + Assert.assertEquals(name, model.getModelConfiguration().getName()); + Assert.assertEquals(new QName(namespace, name), model.getModelConfiguration().getQName()); + } + + @Test + public void testCreate() throws Exception { + SwitchYardModel switchyard = new V1SwitchYardModel(SwitchYardNamespace.V_1_0.uri()); + TransformsModel transforms = new V1TransformsModel(SwitchYardNamespace.V_1_0.uri()); + JavaTransformModel javaTransform = new V1JavaTransformModel(TransformNamespace.V_1_0.uri()); + javaTransform.setFrom(new QName("msgA")); + javaTransform.setTo(new QName("msgB")); + javaTransform.setClazz("org.examples.transform.AtoBTransform"); + transforms.addTransform(javaTransform); + SmooksTransformModel smooksTransform = new V1SmooksTransformModel(TransformNamespace.V_1_0.uri()); + smooksTransform.setFrom(new QName("msgC")); + smooksTransform.setTo(new QName("msgD")); + smooksTransform.setTransformType("XML2JAVA"); + smooksTransform.setConfig("/trasnforms/xxx.xml"); + smooksTransform.setReportPath("/tmp/smooksreport.html"); + transforms.addTransform(smooksTransform); + switchyard.setTransforms(transforms); + String new_xml = switchyard.toString(); + String old_xml = new ModelPuller().pull(XML, getClass()).toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testRead() throws Exception { + SwitchYardModel switchyard = _puller.pull(XML, getClass()); + TransformsModel transforms = switchyard.getTransforms(); + JavaTransformModel java_transform = (JavaTransformModel)transforms.getTransforms().get(0); + Assert.assertEquals("msgA", java_transform.getFrom().getLocalPart()); + Assert.assertEquals("msgB", java_transform.getTo().getLocalPart()); + Assert.assertEquals("org.examples.transform.AtoBTransform", java_transform.getClazz()); + SmooksTransformModel smooks_transform = (SmooksTransformModel)transforms.getTransforms().get(1); + Assert.assertEquals("msgC", smooks_transform.getFrom().getLocalPart()); + Assert.assertEquals("msgD", smooks_transform.getTo().getLocalPart()); + Assert.assertEquals("/trasnforms/xxx.xml", smooks_transform.getConfig()); + Assert.assertEquals("/tmp/smooksreport.html", smooks_transform.getReportPath()); + + } + + @Test + public void testWrite() throws Exception { + String old_xml = new StringPuller().pull(XML, getClass()); + SwitchYardModel switchyard = _puller.pull(new StringReader(old_xml)); + String new_xml = switchyard.toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testParenthood() throws Exception { + SwitchYardModel switchyard_1 = _puller.pull(XML, getClass()); + TransformsModel transforms_1 = switchyard_1.getTransforms(); + TransformModel transform = transforms_1.getTransforms().get(0); + TransformsModel transforms_2 = transform.getTransforms(); + SwitchYardModel switchyard_2 = transforms_2.getSwitchYard(); + Assert.assertEquals(transforms_1, transforms_2); + Assert.assertEquals(switchyard_1, switchyard_2); + } + + @Test + public void testValidation() throws Exception { + SwitchYardModel switchyard = _puller.pull(XML, getClass()); + switchyard.assertModelValid(); + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/config/model/TransformSwitchYardScannerTest.java b/core/transform/src/test/java/org/switchyard/transform/config/model/TransformSwitchYardScannerTest.java new file mode 100644 index 000000000..7488bea8d --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/config/model/TransformSwitchYardScannerTest.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Named; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.transform.config.model.transformers.ATransformer; +import org.switchyard.transform.config.model.transformers.BTransformer; +import org.switchyard.transform.config.model.transformers.BeanTransformer; + +/** + * @author tom.fennelly@gmail.com + */ +public class TransformSwitchYardScannerTest { + + @Test + public void test() throws IOException { + TransformSwitchYardScanner scanner = new TransformSwitchYardScanner(); + List urls = new ArrayList(); + + // If running this test inside your IDE... you need to set the cwd to be the + // root of the transform module !! + urls.add(new File("./target/test-classes").toURI().toURL()); + + ScannerInput input = new ScannerInput().setURLs(urls); + SwitchYardModel switchyard = scanner.scan(input).getModel(); + List models = switchyard.getTransforms().getTransforms(); + + Assert.assertEquals(11, models.size()); + assertModelInstanceOK((JavaTransformModel) models.get(0)); + assertModelInstanceOK((JavaTransformModel) models.get(1)); + assertModelInstanceOK((JavaTransformModel) models.get(2)); + } + + private void assertModelInstanceOK(JavaTransformModel model) { + if (model.getFrom().toString().equals("{urn:switchyard-transform:test-transformers:1.0}a")) { + Assert.assertEquals(ATransformer.class.getName(), model.getClazz()); + Assert.assertEquals("{urn:switchyard-transform:test-transformers:1.0}b", model.getTo().toString()); + } else if (model.getFrom().toString().equals("{urn:switchyard-transform:test-transformers:1.0}b")) { + Assert.assertEquals(BTransformer.class.getName(), model.getClazz()); + Assert.assertEquals("{urn:switchyard-transform:test-transformers:1.0}c", model.getTo().toString()); + } else if (model.getFrom().toString().equals("{urn:switchyard-transform:test-transformers:1.0}c")) { + Assert.assertEquals(BeanTransformer.class.getAnnotation(Named.class).value(), model.getBean()); + Assert.assertNull(model.getClazz()); + Assert.assertEquals("{urn:switchyard-transform:test-transformers:1.0}a", model.getTo().toString()); + } + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/config/model/TransformerUtilTest.java b/core/transform/src/test/java/org/switchyard/transform/config/model/TransformerUtilTest.java new file mode 100644 index 000000000..fbcae322d --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/config/model/TransformerUtilTest.java @@ -0,0 +1,150 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model; + +import java.util.List; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.annotations.Transformer; +import org.switchyard.extensions.java.JavaService; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.BaseTransformer; +import org.switchyard.transform.internal.TransformerTypes; +import org.switchyard.transform.internal.TransformerUtil; + +/** + * @author tom.fennelly@gmail.com + */ +public class TransformerUtilTest { + + @Test + public void test_listTransformations() { + List transformTypes = TransformerUtil.listTransformations(TestTransformer.class); + + Assert.assertEquals(5, transformTypes.size()); + Assert.assertEquals(QName.valueOf("X"), transformTypes.get(0).getFrom()); + Assert.assertEquals(QName.valueOf("Y"), transformTypes.get(0).getTo()); + Assert.assertEquals(QName.valueOf("Z"), transformTypes.get(1).getFrom()); + Assert.assertEquals(JavaTypes.toMessageType(A.class), transformTypes.get(1).getTo()); + Assert.assertEquals(JavaTypes.toMessageType(A.class), transformTypes.get(2).getFrom()); + Assert.assertEquals(JavaTypes.toMessageType(B.class), transformTypes.get(2).getTo()); + Assert.assertEquals(JavaTypes.toMessageType(B.class), transformTypes.get(3).getFrom()); + Assert.assertEquals(QName.valueOf("Z"), transformTypes.get(3).getTo()); + Assert.assertEquals(JavaTypes.toMessageType(B.class), transformTypes.get(4).getFrom()); + Assert.assertEquals(JavaTypes.toMessageType(A.class), transformTypes.get(4).getTo()); + } + + @Test + public void test_transform_interface_impl() { + org.switchyard.transform.Transformer transformer = TransformerUtil.newTransformer(TestTransformer.class, JavaTypes.toMessageType(A.class), JavaTypes.toMessageType(B.class)); + + Assert.assertTrue(transformer instanceof TestTransformer); + Assert.assertTrue(transformer.transform(new A()) instanceof B); + } + + @Test + public void test_transform_anno_no_types_defined() { + org.switchyard.transform.Transformer transformer = TransformerUtil.newTransformer(TestTransformer.class, JavaTypes.toMessageType(B.class), JavaTypes.toMessageType(A.class)); + + Assert.assertTrue(!(transformer instanceof TestTransformer)); + Assert.assertTrue(transformer.transform(new B()) instanceof A); + } + + @Test + public void test_transform_unknown() { + try { + TransformerUtil.newTransformer(TestTransformer.class, QName.valueOf("AAA"), QName.valueOf("BBB")); + Assert.fail("Expected Exception"); + } catch(RuntimeException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016855"); + Assert.assertTrue(exceptionMatch); + } + } + + @Test + public void test_transform_anno_types_defined() { + org.switchyard.transform.Transformer transformer = TransformerUtil.newTransformer(TestTransformer.class, QName.valueOf("X"), QName.valueOf("Y")); + + Assert.assertTrue(!(transformer instanceof TestTransformer)); + Assert.assertEquals("Y", transformer.transform("X")); + } + + + @Test + public void test_listNSdTransformations() { + List transformTypes = TransformerUtil.listTransformations(NSdTestTransformer.class); + + Assert.assertEquals(1, transformTypes.size()); + Assert.assertEquals(new QName("http://b", "B"), transformTypes.get(0).getFrom()); + Assert.assertEquals(new QName("http://a", "A"), transformTypes.get(0).getTo()); + } + + public static class TestTransformer extends BaseTransformer { + + public TestTransformer() { + super(JavaTypes.toMessageType(A.class), JavaTypes.toMessageType(B.class)); + } + + // A to B + @Override + public Object transform(Object from) { + return new B(); + } + + // B to A + @Transformer + public A bToA(B b) { + return new A(); + } + + // X to Y + @Transformer(from = "X", to = "Y") + public String xToY(String x) { + return "Y"; + } + + // Z to A + @Transformer(from = "Z") + public A zToA(B z) { + return new A(); + } + + // B to Z + @Transformer(to = "Z") + public A bToZ(B b) { + return new A(); + } + } + + public static class NSdTestTransformer { + + @Transformer(from = "{http://b}B", to = "{http://a}A") + public A bToA(B b) { + return new A(); + } + } + + public static class A { + + } + + public static class B { + + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/ATransformer.java b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/ATransformer.java new file mode 100644 index 000000000..86ccf9abc --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/ATransformer.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.transformers; + +import javax.xml.namespace.QName; + +import org.switchyard.transform.BaseTransformer; + +/** + * @author tom.fennelly@gmail.com + */ +@SuppressWarnings("rawtypes") +public class ATransformer extends BaseTransformer { + + @Override + public Object transform(Object from) { + return from; + } + + @Override + public QName getFrom() { + return new QName("urn:switchyard-transform:test-transformers:1.0", "a"); + } + + @Override + public QName getTo() { + return new QName("urn:switchyard-transform:test-transformers:1.0", "b"); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/BTransformer.java b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/BTransformer.java new file mode 100644 index 000000000..9583565b7 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/BTransformer.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.transformers; + +import javax.xml.namespace.QName; + +import org.switchyard.transform.BaseTransformer; + +/** + * @author tom.fennelly@gmail.com + */ +@SuppressWarnings("rawtypes") +public class BTransformer extends BaseTransformer { + + @Override + public Object transform(Object from) { + return from; + } + + @Override + public QName getFrom() { + return new QName("urn:switchyard-transform:test-transformers:1.0", "b"); + } + + @Override + public QName getTo() { + return new QName("urn:switchyard-transform:test-transformers:1.0", "c"); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/BeanTransformer.java b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/BeanTransformer.java new file mode 100644 index 000000000..c4c757999 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/BeanTransformer.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.transformers; + +import javax.inject.Named; +import javax.xml.namespace.QName; + +import org.switchyard.transform.BaseTransformer; + +@SuppressWarnings("rawtypes") +@Named("BeanTransformer") +public class BeanTransformer extends BaseTransformer { + + @Override + public Object transform(Object from) { + return from; + } + + @Override + public QName getFrom() { + return new QName("urn:switchyard-transform:test-transformers:1.0", "c"); + } + + @Override + public QName getTo() { + return new QName("urn:switchyard-transform:test-transformers:1.0", "a"); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/XAbstractTransformer.java b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/XAbstractTransformer.java new file mode 100644 index 000000000..9ec271021 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/XAbstractTransformer.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.transformers; + +import org.switchyard.transform.Transformer; + +/** + * @author tom.fennelly@gmail.com + */ +@SuppressWarnings("rawtypes") +public abstract class XAbstractTransformer implements Transformer { + // Should be skipped by the scanner because it is abstract +} diff --git a/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/XTransformerInterface.java b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/XTransformerInterface.java new file mode 100644 index 000000000..bcaab436a --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/config/model/transformers/XTransformerInterface.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.config.model.transformers; + +import org.switchyard.transform.Transformer; + +/** + * @author tom.fennelly@gmail.com + */ +@SuppressWarnings("rawtypes") +public interface XTransformerInterface extends Transformer { + // Should be skipped by the scanner because it's an interface +} diff --git a/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassA.java b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassA.java new file mode 100644 index 000000000..e69f9ed47 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassA.java @@ -0,0 +1,19 @@ +package org.switchyard.transform.dozer.internal; + +public class ClassA { + private String fieldA; + private String fieldB; + + public String getFieldA() { + return fieldA; + } + public void setFieldA(String fieldA) { + this.fieldA = fieldA; + } + public String getFieldB() { + return fieldB; + } + public void setFieldB(String fieldB) { + this.fieldB = fieldB; + } +} \ No newline at end of file diff --git a/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassB.java b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassB.java new file mode 100644 index 000000000..2c210e495 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassB.java @@ -0,0 +1,19 @@ +package org.switchyard.transform.dozer.internal; + +public class ClassB { + private String fieldA; + private String fieldB_mod; + + public String getFieldA() { + return fieldA; + } + public void setFieldA(String fieldA) { + this.fieldA = fieldA; + } + public String getFieldB_mod() { + return fieldB_mod; + } + public void setFieldB_mod(String fieldB_mod) { + this.fieldB_mod = fieldB_mod; + } +} \ No newline at end of file diff --git a/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassC.java b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassC.java new file mode 100644 index 000000000..0d0787c87 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassC.java @@ -0,0 +1,19 @@ +package org.switchyard.transform.dozer.internal; + +public class ClassC { + private ClassA fieldA; + private String fieldC; + + public ClassA getFieldA() { + return fieldA; + } + public void setFieldA(ClassA fieldA) { + this.fieldA = fieldA; + } + public String getFieldC() { + return fieldC; + } + public void setFieldC(String fieldC) { + this.fieldC = fieldC; + } +} \ No newline at end of file diff --git a/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassD.java b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassD.java new file mode 100644 index 000000000..f501e4216 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/ClassD.java @@ -0,0 +1,19 @@ +package org.switchyard.transform.dozer.internal; + +public class ClassD { + private ClassB fieldB; + private String fieldD; + + public ClassB getFieldB() { + return fieldB; + } + public void setFieldB(ClassB fieldB) { + this.fieldB = fieldB; + } + public String getFieldD() { + return fieldD; + } + public void setFieldD(String fieldD) { + this.fieldD = fieldD; + } +} \ No newline at end of file diff --git a/core/transform/src/test/java/org/switchyard/transform/dozer/internal/DozerTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/DozerTransformerTest.java new file mode 100644 index 000000000..c1f15f63b --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/dozer/internal/DozerTransformerTest.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.dozer.internal; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.transform.AbstractTransformerTestCase; +import org.switchyard.transform.Transformer; + +/** + * Dozer transformer tests. + */ +public class DozerTransformerTest extends AbstractTransformerTestCase { + + @Test + public void test_no_mapping_file() throws IOException { + Transformer transformer = getTransformer("sw-config-nofile.xml"); + Assert.assertTrue(transformer instanceof DozerTransformer); + DozerTransformer dozer = DozerTransformer.class.cast(transformer); + ClassA a = new ClassA(); + a.setFieldA("testa"); + a.setFieldB("testb"); + + Object result = dozer.transform(a); + Assert.assertTrue(result instanceof ClassB); + ClassB b = ClassB.class.cast(result); + Assert.assertEquals("testa", b.getFieldA()); + Assert.assertNull(b.getFieldB_mod()); + } + + @Test + public void test_mapping_file() throws IOException { + Transformer transformer = getTransformer("sw-config-file.xml"); + Assert.assertTrue(transformer instanceof DozerTransformer); + DozerTransformer dozer = DozerTransformer.class.cast(transformer); + ClassA a = new ClassA(); + a.setFieldA("testa"); + a.setFieldB("testb"); + Object result = dozer.transform(a); + Assert.assertTrue(result instanceof ClassB); + ClassB b = ClassB.class.cast(result); + Assert.assertEquals("testa", b.getFieldA()); + Assert.assertEquals("testb", b.getFieldB_mod()); + } + + @Test + public void test_multi_mapping_file() throws IOException { + Transformer transformer = getTransformer("sw-config-multi-file.xml"); + Assert.assertTrue(transformer instanceof DozerTransformer); + DozerTransformer dozer = DozerTransformer.class.cast(transformer); + ClassA a = new ClassA(); + a.setFieldA("testa"); + a.setFieldB("testb"); + ClassC c = new ClassC(); + c.setFieldA(a); + c.setFieldC("testc"); + + Object result = dozer.transform(c); + Assert.assertTrue(result instanceof ClassD); + ClassD d = ClassD.class.cast(result); + ClassB b = d.getFieldB(); + Assert.assertEquals("testa", b.getFieldA()); + Assert.assertEquals("testb", b.getFieldB_mod()); + Assert.assertEquals("testc", d.getFieldD()); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/internal/json/JSONTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/internal/json/JSONTransformerTest.java new file mode 100644 index 000000000..4a6ad9fe8 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/internal/json/JSONTransformerTest.java @@ -0,0 +1,200 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal.json; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.transform.Message2MessageTransformer; +import org.switchyard.transform.TransformSequence; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.transform.config.model.JSONTransformModel; +import org.switchyard.transform.internal.TransformerRegistryLoader; +import org.switchyard.transform.internal.json.User.Gender; +import org.switchyard.transform.internal.json.User.Name; +import org.switchyard.transform.json.internal.JSON2JavaTransformer; +import org.switchyard.transform.json.internal.JSONTransformFactory; +import org.switchyard.transform.json.internal.Java2JSONTransformer; + +/** + * @author Alejandro Montenegro <aamonten@gmail.com> + */ +@SuppressWarnings({"unchecked","rawtypes"}) +public class JSONTransformerTest { + + private final static String JSON_PERSON = "{\"age\":31,\"name\":\"Alejandro\"}"; + private final static String JSON_USER = "{\"verified\":false,\"gender\":\"MALE\",\"name\":{\"first\":\"Joe\",\"last\":\"Sixpack\"}}"; + private final static String JSON_USER_LIST = "[{\"name\":{\"first\":\"Joe\",\"last\":\"Sixpack\"},\"gender\":\"MALE\",\"verified\":false}]"; + private TransformerRegistry xformReg; + + public JSONTransformerTest() { + xformReg = new BaseTransformerRegistry(); + new TransformerRegistryLoader(xformReg).loadOOTBTransforms(); + } + + @Test + public void test_JSONResultPerson() { + try { + + Transformer transformer = getTransformer("switchyard-config-01.xml"); + Object expected = toObject(JSON_PERSON, Person.class); + Object result = toObject((String)transformer.transform(new Person("Alejandro", 31)), Person.class); + assertEquals(expected, result); + + } catch (Exception e) { + Assert.fail("caught an exception " + e.getMessage()); + } + } + + @Test + public void test_JAVAResultPerson() { + try { + DefaultMessage message = newMessage(JSON_PERSON); + Transformer transformer = getTransformer("switchyard-config-02.xml"); + + transformer.transform(message); + assertEquals(new Person("Alejandro", 31), message.getContent()); + } catch (Exception e) { + Assert.fail("caught an exception " + e.getMessage()); + } + } + + private DefaultMessage newMessage(Object content) { + DefaultMessage message = new DefaultMessage().setContent(content); + message.setTransformerRegistry(xformReg); + return message; + } + + @Test + public void test_JSONResultUser() { + try { + Transformer transformer = getTransformer("switchyard-config-03.xml"); + Object expected = toObject(JSON_USER,User.class); + Object result = toObject((String)transformer.transform(getUser()), User.class); + assertEquals(expected, result); + } catch (Exception e) { + Assert.fail("caught an exception " + e.getMessage()); + } + } + + @Test + public void test_JAVAResultUser() { + try { + DefaultMessage message = newMessage(JSON_USER); + Transformer transformer = getTransformer("switchyard-config-04.xml"); + transformer.transform(message); + assertEquals(getUser(), message.getContent()); + } catch (Exception e) { + Assert.fail("caught an exception " + e.getMessage()); + } + } + + @Test + public void test_JAVAResultList() { + try { + DefaultMessage message = newMessage(JSON_USER_LIST); + Transformer transformer = getTransformer("switchyard-config-05.xml"); + transformer.transform(message); + assertEquals(toObject(JSON_USER_LIST, List.class), message.getContent()); + } catch (Exception e) { + Assert.fail("caught an exception " + e.getMessage()); + } + } + + @Test + public void test_JAVAResultMap() { + try { + DefaultMessage message = newMessage(JSON_USER); + Transformer transformer = getTransformer("switchyard-config-06.xml"); + transformer.transform(message); + assertEquals(toObject(JSON_USER, Map.class), message.getContent()); + } catch (Exception e) { + Assert.fail("caught an exception " + e.getMessage()); + } + } + + @Test + public void test_WrongFromInstance() { + try { + Transformer transformer = getTransformer("switchyard-config-03.xml"); + Object expected = toObject(JSON_USER,User.class); + Object result = toObject((String)transformer.transform(new Person()), User.class); + assertEquals(expected, result); + } catch (Exception e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD016828"); + Assert.assertTrue(exceptionMatches); + } + } + + private Transformer getTransformer(String config) throws IOException { + InputStream swConfigStream = getClass().getResourceAsStream(config); + + if (swConfigStream == null) { + Assert.fail("null config stream."); + } + + SwitchYardModel switchyardConfig = (SwitchYardModel) new ModelPuller() + .pull(swConfigStream); + TransformsModel transforms = switchyardConfig.getTransforms(); + + List trans = transforms.getTransforms(); + JSONTransformModel jsonTransformModel = (JSONTransformModel) trans + .get(0); + + if (jsonTransformModel == null) { + Assert.fail("No json config."); + } + + Transformer transformer = new JSONTransformFactory().newTransformer(null, jsonTransformModel); + + if (!(transformer instanceof JSON2JavaTransformer ||transformer instanceof Java2JSONTransformer)) { + Assert.fail("Not an instance of a JSONTransformer."); + } + + return transformer; + } + + private User getUser(){ + User user = new User(); + Name name = new Name(); + name.setFirst("Joe"); + name.setLast("Sixpack"); + user.setName(name); + user.setVerified(false); + user.setGender(Gender.MALE); + return user; + } + + private Object toObject(String jsonString, Class clazz) throws JsonParseException, JsonMappingException, IOException{ + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(jsonString, clazz); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/internal/json/Person.java b/core/transform/src/test/java/org/switchyard/transform/internal/json/Person.java new file mode 100644 index 000000000..65cb53e4d --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/internal/json/Person.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal.json; + +/** + * @author Alejandro Montenegro <aamonten@gmail.com> + */ +public class Person { + + private String name; + private int age; + + public Person(){} + /** + * @param string + * @param string2 + */ + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public Person setName(String name) { + this.name = name; + return this; + } + + public int getAge() { + return age; + } + + public Person setAge(int age) { + this.age = age; + return this; + } + + public boolean equals(Object object){ + + if(object instanceof Person){ + Person person = (Person) object; + if( (person.getAge() == this.age ) && (person.getName().equals(this.name)) ){ + return true; + } + } + return false; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/internal/json/User.java b/core/transform/src/test/java/org/switchyard/transform/internal/json/User.java new file mode 100644 index 000000000..06e2b18c4 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/internal/json/User.java @@ -0,0 +1,94 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal.json; + +import org.mvel2.util.ThisLiteral; + +/** + * @author Alejandro Montenegro <aamonten@gmail.com> + */ +public class User { + public enum Gender { + MALE, FEMALE + }; + + public static class Name { + private String _first, _last; + + public String getFirst() { + return _first; + } + + public String getLast() { + return _last; + } + + public void setFirst(String s) { + _first = s; + } + + public void setLast(String s) { + _last = s; + } + + public boolean equals(Object o){ + if(o instanceof Name){ + Name name = (Name)o; + if(name.getFirst().equals(_first) && name.getLast().equals(_last)) + return true; + } + return false; + } + } + + private Gender _gender; + private Name _name; + private boolean _isVerified; + + public Name getName() { + return _name; + } + + public boolean isVerified() { + return _isVerified; + } + + public Gender getGender() { + return _gender; + } + + public void setName(Name n) { + _name = n; + } + + public void setVerified(boolean b) { + _isVerified = b; + } + + public void setGender(Gender g) { + _gender = g; + } + + public boolean equals(Object o){ + + if(o instanceof User){ + User user = (User)o; + + if(user.getGender().equals(this._gender) && (user._isVerified == this._isVerified) && user.getName().equals(this._name)) + return true; + } + return false; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/internal/smooks/Person.java b/core/transform/src/test/java/org/switchyard/transform/internal/smooks/Person.java new file mode 100644 index 000000000..4917e7388 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/internal/smooks/Person.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal.smooks; + +/** + * @author tom.fennelly@gmail.com + */ +public class Person { + + private String name; + private int age; + + public String getName() { + return name; + } + + public Person setName(String name) { + this.name = name; + return this; + } + + public int getAge() { + return age; + } + + public Person setAge(int age) { + this.age = age; + return this; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/internal/smooks/SmooksTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/internal/smooks/SmooksTransformerTest.java new file mode 100644 index 000000000..304c44f2e --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/internal/smooks/SmooksTransformerTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal.smooks; + +import java.io.IOException; +import java.io.InputStream; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.transform.AbstractTransformerTestCase; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.SmooksTransformModel; +import org.switchyard.transform.smooks.internal.SmooksTransformFactory; +import org.switchyard.transform.smooks.internal.SmooksTransformer; +import org.xml.sax.SAXException; + +/** + * @author tom.fennelly@gmail.com + */ +public class SmooksTransformerTest extends AbstractTransformerTestCase { + + @Test + public void test_no_export() throws IOException { + try { + getTransformer("sw-config-01.xml"); + } catch(RuntimeException e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD016814"); + Assert.assertTrue(exceptionMatches); + } + } + + @Test + public void test_invalid_export() throws IOException, SAXException { + try { + getTransformer("sw-config-02.xml"); + } catch(RuntimeException e) { + boolean exceptionMatches = e.getMessage().contains("SWITCHYARD016815"); + Assert.assertTrue(exceptionMatches); + } + } + + @Test + public void test_StringResult() throws IOException, SAXException { + Transformer transformer = getTransformer("sw-config-03.xml"); + + XMLUnit.setIgnoreWhitespace(true); + XMLAssert.assertXMLEqual("", transformer.transform("").toString()); + } + + @Test + public void test_JavaResult() throws IOException, SAXException { + Transformer transformer = getTransformer("sw-config-04.xml"); + + Person person = (Person) transformer.transform(""); + Assert.assertEquals("Max", person.getName()); + Assert.assertEquals(50, person.getAge()); + } + + protected Transformer getTransformer(String config) throws IOException { + Transformer transformer = super.getTransformer(config); + + if(!(transformer instanceof SmooksTransformer)) { + Assert.fail("Not an instance of SmooksTransformer."); + } + + return transformer; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/internal/smooks/XMLBindingTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/internal/smooks/XMLBindingTransformerTest.java new file mode 100644 index 000000000..c90642e08 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/internal/smooks/XMLBindingTransformerTest.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.internal.smooks; + +import java.io.IOException; + +import javax.xml.namespace.QName; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.transform.AbstractTransformerTestCase; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.TransformNamespace; +import org.switchyard.transform.config.model.v1.V1SmooksTransformModel; +import org.switchyard.transform.smooks.internal.SmooksTransformFactory; +import org.xml.sax.SAXException; + +/** + * @author tom.fennelly@gmail.com + */ +public class XMLBindingTransformerTest extends AbstractTransformerTestCase { + + @Test + public void test_xml2java() throws IOException, SAXException { + Transformer transformer = getTransformer("sw-config-xmlb-01.xml"); + + // XML to Java + Person person = (Person) transformer.transform(""); + Assert.assertEquals("Max", person.getName()); + Assert.assertEquals(50, person.getAge()); + } + + @Test + public void test_java2xml() throws IOException, SAXException { + Transformer transformer = getTransformer("sw-config-xmlb-02.xml"); + + // Java to XML + Person person = new Person().setName("George").setAge(80); + String xml = (String) transformer.transform(person); + XMLUnit.setIgnoreWhitespace(true); + XMLAssert.assertXMLEqual("", xml); + } + + @Test + public void test_invalid_xml2java_config() throws IOException, SAXException { + V1SmooksTransformModel model = (V1SmooksTransformModel)new V1SmooksTransformModel(TransformNamespace.DEFAULT.uri()).setTransformType("XML2JAVA").setFrom(new QName("a")).setTo(new QName("b")); + model.setConfig("/org/switchyard/transform/internal/smooks/smooks-config-01.xml"); + try { + new SmooksTransformFactory().newTransformer(null, model); + } catch (RuntimeException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016812"); + Assert.assertTrue(exceptionMatch); + } + } + + @Test + public void test_invalid_java2xml_config() throws IOException, SAXException { + V1SmooksTransformModel model = (V1SmooksTransformModel)new V1SmooksTransformModel(TransformNamespace.DEFAULT.uri()).setTransformType("JAVA2XML").setFrom(new QName("a")).setTo(new QName("b")); + model.setConfig("/org/switchyard/transform/internal/smooks/smooks-config-01.xml"); + try { + new SmooksTransformFactory().newTransformer(null, model); + } catch (RuntimeException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016812"); + Assert.assertTrue(exceptionMatch); + } + } + + @Test + public void test_java2xml_invalid_type() throws IOException, SAXException { + Transformer transformer = getTransformer("sw-config-xmlb-02.xml"); + + try { + transformer.transform("wrong type"); + } catch (RuntimeException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016806"); + Assert.assertTrue(exceptionMatch); + } + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Adapter1.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Adapter1.java new file mode 100644 index 000000000..0f841e668 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Adapter1.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2.3-3- +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.06.10 at 06:39:45 PM IST +// + + +package org.switchyard.transform.jaxb.internal; + +import javax.xml.bind.annotation.adapters.XmlAdapter; + +public class Adapter1 + extends XmlAdapter +{ + + + public Integer unmarshal(String value) { + return (javax.xml.bind.DatatypeConverter.parseInt(value)); + } + + public String marshal(Integer value) { + if (value == null) { + return null; + } + return (javax.xml.bind.DatatypeConverter.printInt(value)); + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Adapter2.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Adapter2.java new file mode 100644 index 000000000..6ee4274da --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Adapter2.java @@ -0,0 +1,29 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2.3-3- +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.06.10 at 06:39:45 PM IST +// + + +package org.switchyard.transform.jaxb.internal; + +import javax.xml.bind.annotation.adapters.XmlAdapter; + +public class Adapter2 + extends XmlAdapter +{ + + + public Short unmarshal(String value) { + return (javax.xml.bind.DatatypeConverter.parseShort(value)); + } + + public String marshal(Short value) { + if (value == null) { + return null; + } + return (javax.xml.bind.DatatypeConverter.printShort(value)); + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/InvalidAddressService.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/InvalidAddressService.java new file mode 100644 index 000000000..f6e12c834 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/InvalidAddressService.java @@ -0,0 +1,24 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.jaxb.internal; + +/** + * @author tom.fennelly@gmail.com + */ +public interface InvalidAddressService { + + // USAddress is invalid here because it is not defined in the ObjectFactory + void createAddress(USAddress address); +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Items.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Items.java new file mode 100644 index 000000000..64149c159 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/Items.java @@ -0,0 +1,306 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2.3-3- +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.06.10 at 06:39:45 PM IST +// + + +package org.switchyard.transform.jaxb.internal; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigDecimal; +import java.util.List; +import java.util.Vector; + + +/** + *

Java class for Items complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="Items">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="item" maxOccurs="unbounded">
+ *           <complexType>
+ *             <complexContent>
+ *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *                 <sequence>
+ *                   <element name="productName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *                   <element name="quantity">
+ *                     <simpleType>
+ *                       <restriction base="{http://www.w3.org/2001/XMLSchema}positiveInteger">
+ *                         <maxExclusive value="100"/>
+ *                       </restriction>
+ *                     </simpleType>
+ *                   </element>
+ *                   <element name="USPrice" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
+ *                   <element ref="{}comment" minOccurs="0"/>
+ *                   <element name="shipDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
+ *                 </sequence>
+ *                 <attribute name="partNum" use="required" type="{}SKU" />
+ *               </restriction>
+ *             </complexContent>
+ *           </complexType>
+ *         </element>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "Items", propOrder = { + "item" +}) +public class Items { + + @XmlElement(required = true) + protected List item = new Vector(); + + /** + * Gets the value of the item property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the item property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getItem().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Items.Item } + * + * + */ + public List getItem() { + if (item == null) { + item = new Vector(); + } + return this.item; + } + + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *       <sequence>
+     *         <element name="productName" type="{http://www.w3.org/2001/XMLSchema}string"/>
+     *         <element name="quantity">
+     *           <simpleType>
+     *             <restriction base="{http://www.w3.org/2001/XMLSchema}positiveInteger">
+     *               <maxExclusive value="100"/>
+     *             </restriction>
+     *           </simpleType>
+     *         </element>
+     *         <element name="USPrice" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
+     *         <element ref="{}comment" minOccurs="0"/>
+     *         <element name="shipDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
+     *       </sequence>
+     *       <attribute name="partNum" use="required" type="{}SKU" />
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
+     * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + "productName", + "quantity", + "price", + "comment", + "shipDate" + }) + public static class Item { + + @XmlElement(required = true) + protected String productName; + @XmlElement(required = true, type = String.class, defaultValue = "10") + @XmlJavaTypeAdapter(Adapter2.class) + protected Short quantity; + @XmlElement(name = "USPrice", required = true) + protected BigDecimal price; + protected String comment; + @XmlSchemaType(name = "date") + protected XMLGregorianCalendar shipDate; + @XmlAttribute(name = "partNum", required = true) + protected String partNumber; + + /** + * Gets the value of the productName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getProductName() { + return productName; + } + + /** + * Sets the value of the productName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setProductName(String value) { + this.productName = value; + } + + /** + * Gets the value of the quantity property. + * + * @return + * possible object is + * {@link String } + * + */ + public Short getQuantity() { + return quantity; + } + + /** + * Sets the value of the quantity property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setQuantity(Short value) { + this.quantity = value; + } + + public boolean isSetQuantity() { + return (this.quantity!= null); + } + + /** + * Gets the value of the price property. + * + * @return + * possible object is + * {@link java.math.BigDecimal } + * + */ + public BigDecimal getPrice() { + return price; + } + + /** + * Sets the value of the price property. + * + * @param value + * allowed object is + * {@link java.math.BigDecimal } + * + */ + public void setPrice(BigDecimal value) { + this.price = value; + } + + /** + * Gets the value of the comment property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getComment() { + return comment; + } + + /** + * Sets the value of the comment property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setComment(String value) { + this.comment = value; + } + + /** + * Gets the value of the shipDate property. + * + * @return + * possible object is + * {@link javax.xml.datatype.XMLGregorianCalendar } + * + */ + public XMLGregorianCalendar getShipDate() { + return shipDate; + } + + /** + * Sets the value of the shipDate property. + * + * @param value + * allowed object is + * {@link javax.xml.datatype.XMLGregorianCalendar } + * + */ + public void setShipDate(XMLGregorianCalendar value) { + this.shipDate = value; + } + + /** + * Gets the value of the partNumber property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPartNumber() { + return partNumber; + } + + /** + * Sets the value of the partNumber property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPartNumber(String value) { + this.partNumber = value; + } + + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/JAXBTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/JAXBTransformerTest.java new file mode 100644 index 000000000..a743c9127 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/JAXBTransformerTest.java @@ -0,0 +1,125 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.jaxb.internal; + +import java.io.IOException; +import java.io.StringReader; + +import javax.xml.namespace.QName; +import javax.xml.transform.stream.StreamSource; + +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformModel; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.AbstractTransformerTestCase; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.config.model.JAXBTransformModel; +import org.xml.sax.SAXException; + +/** + * @author tom.fennelly@gmail.com + */ +public class JAXBTransformerTest extends AbstractTransformerTestCase { + + @Test + public void test_createFromClass() throws IOException, SAXException { + JAXBUnmarshalTransformer unmarshalTransformer = new JAXBUnmarshalTransformer( + new QName("purchaseOrder"), JavaTypes.toMessageType(POType.class), null); + + JAXBMarshalTransformer marshalTransformer = new JAXBMarshalTransformer( + JavaTypes.toMessageType(POType.class), new QName("purchaseOrder"), null); + + DefaultMessage message = new DefaultMessage(); + message.setContent(new StreamSource(new StringReader(PO_XML))); + + // Transform XML to Java POType and back to XML... + unmarshalTransformer.transform(message); + marshalTransformer.transform(message); + + // Check the round trip... + String resultXML = message.getContent(String.class); + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.compareXML(PO_XML, resultXML); + } + + @Test + public void test_configRead() throws IOException { + Transformer unmarshalingTransformer = getTransformer("switchyard-config-01.xml"); + Assert.assertEquals("A", unmarshalingTransformer.getFrom().toString()); + Assert.assertEquals("java:org.switchyard.transform.jaxb.internal.POType", unmarshalingTransformer.getTo().toString()); + + Transformer marshalingTransformer = getTransformer("switchyard-config-02.xml"); + Assert.assertEquals("java:org.switchyard.transform.jaxb.internal.POType", marshalingTransformer.getFrom().toString()); + Assert.assertEquals("A", marshalingTransformer.getTo().toString()); + } + + @Test + public void test_configReadContextPath() throws IOException { + SwitchYardModel config = new ModelPuller().pull("org/switchyard/transform/jaxb/internal/switchyard-config-03.xml", JAXBTransformerTest.class); + for (TransformModel tm : config.getTransforms().getTransforms()) { + Assert.assertTrue(tm instanceof JAXBTransformModel); + Assert.assertEquals("org.switchyard.transform.jaxb.internal", ((JAXBTransformModel)tm).getContextPath()); + } + } + + @Test + public void test_createMissingFactoryMethodMessage() throws IOException, SAXException { + String message = JAXBTransformerFactory.createMissingFactoryMethodMessage( + USAddress.class, + ObjectFactory.class); + boolean messageContains = message.contains("SWITCHYARD016840"); + Assert.assertTrue(messageContains); + } + + private static final String PO_XML = "\n" + + "\n" + + " \n" + + " Alice Smith\n" + + " 123 Maple Street\n" + + " Cambridge\n" + + " MA\n" + + " 12345\n" + + " \n" + + " \n" + + " Robert Smith\n" + + " 8 Oak Avenue\n" + + " Cambridge\n" + + " MA\n" + + " 12345\n" + + " \n" + + " \n" + + " \n" + + " Nosferatu - Special Edition (1929)\n" + + " 5\n" + + " 19.99\n" + + " \n" + + " \n" + + " The Mummy (1959)\n" + + " 3\n" + + " 19.98\n" + + " \n" + + " \n" + + " Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora\n" + + " 3\n" + + " 27.95\n" + + " \n" + + " \n" + + ""; +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/ObjectFactory.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/ObjectFactory.java new file mode 100644 index 000000000..c4918a568 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/ObjectFactory.java @@ -0,0 +1,108 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2.3-3- +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.06.10 at 06:39:45 PM IST +// + + +package org.switchyard.transform.jaxb.internal; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlElementDecl; +import javax.xml.bind.annotation.XmlRegistry; +import javax.xml.namespace.QName; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the primer.myPo package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + private final static QName _PurchaseOrder_QNAME = new QName("", "purchaseOrder"); + private final static QName _Comment_QNAME = new QName("", "comment"); + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: primer.myPo + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Items } + * + */ + public Items createItems() { + return new Items(); + } + + /** + * Create an instance of {@link POType } + * + */ + public POType createPOType() { + return new POType(); + } + + /** + * Create an instance of {@link USAddress } + * + */ + public USAddress createUSAddress() { + return new USAddress(); + } + + /** + * Create an instance of {@link Items.Item } + * + */ + public Items.Item createItemsItem() { + return new Items.Item(); + } + + /** + * Create an instance of {@link javax.xml.bind.JAXBElement }{@code <}{@link POType }{@code >}} + * + */ + @XmlElementDecl(namespace = "", name = "purchaseOrder") + public JAXBElement createPurchaseOrder(POType value) { + return new JAXBElement(_PurchaseOrder_QNAME, POType.class, null, value); + } + + /** + * Create an instance of {@link javax.xml.bind.JAXBElement }{@code <}{@link String }{@code >}} + * + */ + @XmlElementDecl(namespace = "", name = "comment") + public JAXBElement createComment(String value) { + return new JAXBElement(_Comment_QNAME, String.class, null, value); + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/OrderService.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/OrderService.java new file mode 100644 index 000000000..e814103d5 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/OrderService.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.jaxb.internal; + +/** + * @author tom.fennelly@gmail.com + */ +public interface OrderService { + + POType createOrder(POType po); +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/POType.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/POType.java new file mode 100644 index 000000000..ed3b19f12 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/POType.java @@ -0,0 +1,182 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2.3-3- +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.06.10 at 06:39:45 PM IST +// + + +package org.switchyard.transform.jaxb.internal; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.datatype.XMLGregorianCalendar; + + +/** + * A Purchase Order consists of addresses and items. + * + * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "PurchaseOrderType", propOrder = { + "shipTo", + "billTo", + "comment", + "items" +}) +@XmlRootElement(name = "purchaseOrder") +public class POType { + + @XmlElement(required = true) + protected USAddress shipTo; + @XmlElement(required = true) + protected USAddress billTo; + protected String comment; + @XmlElement(required = true) + protected Items items; + @XmlAttribute(name = "orderDate") + @XmlSchemaType(name = "date") + protected XMLGregorianCalendar orderDate; + + /** + * Gets the value of the shipTo property. + * + * @return + * possible object is + * {@link USAddress } + * + */ + public USAddress getShipTo() { + return shipTo; + } + + /** + * Sets the value of the shipTo property. + * + * @param value + * allowed object is + * {@link USAddress } + * + */ + public void setShipTo(USAddress value) { + this.shipTo = value; + } + + /** + * Gets the value of the billTo property. + * + * @return + * possible object is + * {@link USAddress } + * + */ + public USAddress getBillTo() { + return billTo; + } + + /** + * Sets the value of the billTo property. + * + * @param value + * allowed object is + * {@link USAddress } + * + */ + public void setBillTo(USAddress value) { + this.billTo = value; + } + + /** + * Gets the value of the comment property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getComment() { + return comment; + } + + /** + * Sets the value of the comment property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setComment(String value) { + this.comment = value; + } + + /** + * Gets the value of the items property. + * + * @return + * possible object is + * {@link Items } + * + */ + public Items getItems() { + return items; + } + + /** + * Sets the value of the items property. + * + * @param value + * allowed object is + * {@link Items } + * + */ + public void setItems(Items value) { + this.items = value; + } + + /** + * Gets the value of the orderDate property. + * + * @return + * possible object is + * {@link javax.xml.datatype.XMLGregorianCalendar } + * + */ + public XMLGregorianCalendar getOrderDate() { + return orderDate; + } + + /** + * Sets the value of the orderDate property. + * + * @param value + * allowed object is + * {@link javax.xml.datatype.XMLGregorianCalendar } + * + */ + public void setOrderDate(XMLGregorianCalendar value) { + this.orderDate = value; + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/USAddress.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/USAddress.java new file mode 100644 index 000000000..33d0b5aee --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/USAddress.java @@ -0,0 +1,215 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2.3-3- +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.06.10 at 06:39:45 PM IST +// + + +package org.switchyard.transform.jaxb.internal; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + + +/** + * First line of documentation for a USAddress. + * + * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "USAddress", propOrder = { + "toName", + "street", + "city", + "state", + "zipCode" +}) +public class USAddress { + + @XmlElement(name = "name", required = true) + protected String toName; + @XmlElement(required = true) + protected String street; + @XmlElement(required = true) + protected String city; + @XmlElement(required = true) + protected USState state; + @XmlElement(name = "zip", required = true, type = String.class) + @XmlJavaTypeAdapter(Adapter1.class) + protected Integer zipCode; + @XmlAttribute(name = "country") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "NMTOKEN") + protected String country; + + /** + * Gets the value of the toName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getToName() { + return toName; + } + + /** + * Sets the value of the toName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setToName(String value) { + this.toName = value; + } + + /** + * Gets the value of the street property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getStreet() { + return street; + } + + /** + * Sets the value of the street property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setStreet(String value) { + this.street = value; + } + + /** + * Gets the value of the city property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCity() { + return city; + } + + /** + * Sets the value of the city property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCity(String value) { + this.city = value; + } + + /** + * Gets the value of the state property. + * + * @return + * possible object is + * {@link USState } + * + */ + public USState getState() { + return state; + } + + /** + * Sets the value of the state property. + * + * @param value + * allowed object is + * {@link USState } + * + */ + public void setState(USState value) { + this.state = value; + } + + /** + * Gets the value of the zipCode property. + * + * @return + * possible object is + * {@link String } + * + */ + public Integer getZipCode() { + return zipCode; + } + + /** + * Sets the value of the zipCode property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setZipCode(Integer value) { + this.zipCode = value; + } + + /** + * Gets the value of the country property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCountry() { + if (country == null) { + return "US"; + } else { + return country; + } + } + + /** + * Sets the value of the country property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCountry(String value) { + this.country = value; + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/USState.java b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/USState.java new file mode 100644 index 000000000..173ee20b1 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/jaxb/internal/USState.java @@ -0,0 +1,51 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.3-hudson-jaxb-ri-2.2.3-3- +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2011.06.10 at 06:39:45 PM IST +// + + +package org.switchyard.transform.jaxb.internal; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for USState. + * + *

The following schema fragment specifies the expected content contained within this class. + *

+ *

+ * <simpleType name="USState">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="AK"/>
+ *     <enumeration value="AL"/>
+ *     <enumeration value="AR"/>
+ *     <enumeration value="CA"/>
+ *     <enumeration value="MA"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "USState") +@XmlEnum +public enum USState { + + AK, + AL, + AR, + CA, + MA; + + public String value() { + return name(); + } + + public static USState fromValue(String v) { + return valueOf(v); + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/AbstractTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/AbstractTransformerTest.java new file mode 100644 index 000000000..956bc9f6b --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/AbstractTransformerTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb; + +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Before; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.transform.internal.TransformerRegistryLoader; + +/** + * @author tom.fennelly@gmail.com + */ +public class AbstractTransformerTest { + + private BaseTransformerRegistry _transformerRegistry; + + @Before + public void setUp() { + _transformerRegistry = new BaseTransformerRegistry(); + new TransformerRegistryLoader(_transformerRegistry).loadOOTBTransforms(); + XMLUnit.setIgnoreWhitespace(true); + } + + protected DefaultMessage newMessage() { + DefaultMessage message = new DefaultMessage(); + message.setTransformerRegistry(_transformerRegistry); + return message; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/OutOfTheBoxTransformersLoadingTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/OutOfTheBoxTransformersLoadingTest.java new file mode 100644 index 000000000..72a929cb0 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/OutOfTheBoxTransformersLoadingTest.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb; + +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.FilterInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.internal.TransformerRegistryLoader; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; + +/** + * @author tom.fennelly@gmail.com + */ +public class OutOfTheBoxTransformersLoadingTest { + + private BaseTransformerRegistry registry; + + public OutOfTheBoxTransformersLoadingTest() { + registry = new BaseTransformerRegistry(); + new TransformerRegistryLoader(registry).loadOOTBTransforms(); + } + + @Test + public void test_DOM_Transforms_Loaded() { + Assert.assertNotNull(registry.getTransformer(qName(String.class), qName(Element.class))); + Assert.assertNotNull(registry.getTransformer(qName(Element.class), qName(char[].class))); + } + + @Test + public void test_String_Transforms_Loaded() { + Assert.assertNotNull(registry.getTransformer(qName(String.class), qName(Reader.class))); + Assert.assertNotNull(registry.getTransformer(qName(String.class), qName(byte[].class))); + Assert.assertNotNull(registry.getTransformer(qName(String.class), qName(char[].class))); + Assert.assertNotNull(registry.getTransformer(qName(String.class), qName(InputSource.class))); + } + + @Test + public void test_Number_Transforms_Loaded() { + Assert.assertNotNull(registry.getTransformer(qName(Number.class), qName(Reader.class))); + Assert.assertNotNull(registry.getTransformer(qName(Number.class), qName(byte[].class))); + Assert.assertNotNull(registry.getTransformer(qName(Number.class), qName(char[].class))); + Assert.assertNotNull(registry.getTransformer(qName(Number.class), qName(InputSource.class))); + + Assert.assertNotNull(registry.getTransformer(qName(Integer.class), qName(Reader.class))); + Assert.assertNotNull(registry.getTransformer(qName(Integer.class), qName(byte[].class))); + Assert.assertNotNull(registry.getTransformer(qName(Integer.class), qName(char[].class))); + Assert.assertNotNull(registry.getTransformer(qName(Integer.class), qName(InputSource.class))); + + Assert.assertNotNull(registry.getTransformer(qName(Double.class), qName(String.class))); + Assert.assertNotNull(registry.getTransformer(qName(Double.class), qName(Reader.class))); + Assert.assertNotNull(registry.getTransformer(qName(Double.class), qName(byte[].class))); + Assert.assertNotNull(registry.getTransformer(qName(Double.class), qName(char[].class))); + Assert.assertNotNull(registry.getTransformer(qName(Double.class), qName(InputSource.class))); + } + + @Test + public void test_Reader_Transforms_Loaded() { + Assert.assertNotNull(registry.getTransformer(qName(Reader.class), qName(String.class))); + Assert.assertNotNull(registry.getTransformer(qName(InputStreamReader.class), qName(String.class))); + Assert.assertNotNull(registry.getTransformer(qName(Reader.class), qName(byte[].class))); + Assert.assertNotNull(registry.getTransformer(qName(FileReader.class), qName(byte[].class))); + Assert.assertNotNull(registry.getTransformer(qName(Reader.class), qName(char[].class))); + Assert.assertNotNull(registry.getTransformer(qName(Reader.class), qName(InputSource.class))); + Assert.assertNotNull(registry.getTransformer(qName(FileReader.class), qName(InputSource.class))); + Assert.assertNotNull(registry.getTransformer(qName(StringReader.class), qName(InputSource.class))); + } + + @Test + public void test_InputStream_Transforms_Loaded() { + Assert.assertNotNull(registry.getTransformer(qName(InputStream.class), qName(String.class))); + Assert.assertNotNull(registry.getTransformer(qName(FilterInputStream.class), qName(String.class))); + Assert.assertNotNull(registry.getTransformer(qName(InputStream.class), qName(byte[].class))); + Assert.assertNotNull(registry.getTransformer(qName(FileInputStream.class), qName(byte[].class))); + } + + @Test + public void test_InputSource_Transforms_Loaded() { + Assert.assertNotNull(registry.getTransformer(qName(InputSource.class), qName(String.class))); + Assert.assertNotNull(registry.getTransformer(qName(InputSource.class), qName(String.class))); + Assert.assertNotNull(registry.getTransformer(qName(InputSource.class), qName(byte[].class))); + Assert.assertNotNull(registry.getTransformer(qName(InputSource.class), qName(byte[].class))); + } + + private QName qName(Class aClass) { + return JavaTypes.toMessageType(aClass); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/io/InputSourceTransformsTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/io/InputSourceTransformsTest.java new file mode 100644 index 000000000..c668c62e9 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/io/InputSourceTransformsTest.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.io; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.transform.ootb.lang.StringTransforms; +import org.xml.sax.InputSource; + +/** + * @author tom.fennelly@gmail.com + */ +public class InputSourceTransformsTest { + + @Test + public void testToString() throws Exception { + Assert.assertEquals("Hello SwitchYard", InputSourceTransforms.TRANSFORMER.toString(newInputSource("Hello SwitchYard"))); + } + + @Test + public void testToReader() throws Exception { + Assert.assertNotNull(InputSourceTransforms.TRANSFORMER.toReader(newInputSource("Hello SwitchYard"))); + } + + @Test + public void testToInputStream() throws Exception { + Assert.assertNotNull(InputSourceTransforms.TRANSFORMER.toInputStream(newInputSource("Hello SwitchYard"))); + } + + @Test + public void testToInteger() throws Exception { + Assert.assertEquals((Integer)1, InputSourceTransforms.TRANSFORMER.toInteger(newInputSource("1"))); + } + + @Test + public void testToLong() throws Exception { + Assert.assertEquals((Long)1L, InputSourceTransforms.TRANSFORMER.toLong(newInputSource("1"))); + } + + @Test + public void testToShort() throws Exception { + Assert.assertEquals(new Short("1"), InputSourceTransforms.TRANSFORMER.toShort(newInputSource("1"))); + } + + @Test + public void testToChars() throws Exception { + Assert.assertEquals("12345", new String(InputSourceTransforms.TRANSFORMER.toChars(newInputSource("12345")))); + } + + @Test + public void testToCharacter() throws Exception { + Assert.assertEquals((Character) '1', InputSourceTransforms.TRANSFORMER.toCharacter(newInputSource("12345"))); + } + + @Test + public void testToBytes() throws Exception { + Assert.assertNotNull(new String(InputSourceTransforms.TRANSFORMER.toBytes(newInputSource("12345")))); + } + + @Test + public void testToDouble() throws Exception { + Assert.assertEquals((Double)1D, InputSourceTransforms.TRANSFORMER.toDouble(newInputSource("1"))); + } + + @Test + public void testToFloat() throws Exception { + Assert.assertEquals((Float)1F, InputSourceTransforms.TRANSFORMER.toFloat(newInputSource("1"))); + } + + private InputSource newInputSource(String s) { + return StringTransforms.TRANSFORMER.toInputSource(s); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/io/InputStreamTransformsTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/io/InputStreamTransformsTest.java new file mode 100644 index 000000000..8e381e5cb --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/io/InputStreamTransformsTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.io; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +/** + * @author tom.fennelly@gmail.com + */ +public class InputStreamTransformsTest { + + @Test + public void testToString() throws Exception { + Assert.assertEquals("Hello SwitchYard", InputStreamTransforms.TRANSFORMER.toString(newInputStream("Hello SwitchYard"))); + } + + @Test + public void testToReader() throws Exception { + Assert.assertNotNull(InputStreamTransforms.TRANSFORMER.toReader(newInputStream("Hello SwitchYard"))); + } + + @Test + public void testToInputSource() throws Exception { + Assert.assertNotNull(InputStreamTransforms.TRANSFORMER.toInputSource(newInputStream("Hello SwitchYard"))); + } + + @Test + public void testToInteger() throws Exception { + Assert.assertEquals((Integer)1, InputStreamTransforms.TRANSFORMER.toInteger(newInputStream("1"))); + } + + @Test + public void testToLong() throws Exception { + Assert.assertEquals((Long)1L, InputStreamTransforms.TRANSFORMER.toLong(newInputStream("1"))); + } + + @Test + public void testToShort() throws Exception { + Assert.assertEquals(new Short("1"), InputStreamTransforms.TRANSFORMER.toShort(newInputStream("1"))); + } + + @Test + public void testToChars() throws Exception { + Assert.assertEquals("12345", new String(InputStreamTransforms.TRANSFORMER.toChars(newInputStream("12345")))); + } + + @Test + public void testToCharacter() throws Exception { + Assert.assertEquals((Character) '1', InputStreamTransforms.TRANSFORMER.toCharacter(newInputStream("12345"))); + } + + @Test + public void testToBytes() throws Exception { + Assert.assertNotNull(new String(InputStreamTransforms.TRANSFORMER.toBytes(newInputStream("12345")))); + } + + @Test + public void testToDouble() throws Exception { + Assert.assertEquals((Double)1D, InputStreamTransforms.TRANSFORMER.toDouble(newInputStream("1"))); + } + + @Test + public void testToFloat() throws Exception { + Assert.assertEquals((Float)1F, InputStreamTransforms.TRANSFORMER.toFloat(newInputStream("1"))); + } + + private InputStream newInputStream(String s) { + return new ByteArrayInputStream(s.getBytes()); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/io/ReaderTransformsTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/io/ReaderTransformsTest.java new file mode 100644 index 000000000..b7cbf19d4 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/io/ReaderTransformsTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.io; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.transform.ootb.lang.NumberTransforms; + +import java.io.Reader; +import java.io.StringReader; + +/** + * @author tom.fennelly@gmail.com + */ +public class ReaderTransformsTest { + + @Test + public void testToString() throws Exception { + Assert.assertEquals("Hello SwitchYard", ReaderTransforms.TRANSFORMER.toString(newReader("Hello SwitchYard"))); + } + + @Test + public void testToInputStream() throws Exception { + Assert.assertNotNull(ReaderTransforms.TRANSFORMER.toInputStream(newReader("Hello SwitchYard"))); + } + + @Test + public void testToInputSource() throws Exception { + Assert.assertNotNull(ReaderTransforms.TRANSFORMER.toInputSource(newReader("Hello SwitchYard"))); + } + + @Test + public void testToInteger() throws Exception { + Assert.assertEquals((Integer)1, ReaderTransforms.TRANSFORMER.toInteger(newReader("1"))); + } + + @Test + public void testToLong() throws Exception { + Assert.assertEquals((Long)1L, ReaderTransforms.TRANSFORMER.toLong(newReader("1"))); + } + + @Test + public void testToShort() throws Exception { + Assert.assertEquals(new Short("1"), ReaderTransforms.TRANSFORMER.toShort(newReader("1"))); + } + + @Test + public void testToChars() throws Exception { + Assert.assertEquals("12345", new String(ReaderTransforms.TRANSFORMER.toChars(newReader("12345")))); + } + + @Test + public void testToCharacter() throws Exception { + Assert.assertEquals((Character) '1', ReaderTransforms.TRANSFORMER.toCharacter(newReader("12345"))); + } + + @Test + public void testToBytes() throws Exception { + Assert.assertNotNull(new String(ReaderTransforms.TRANSFORMER.toBytes(newReader("12345")))); + } + + @Test + public void testToDouble() throws Exception { + Assert.assertEquals((Double)1D, ReaderTransforms.TRANSFORMER.toDouble(newReader("1"))); + } + + @Test + public void testToFloat() throws Exception { + Assert.assertEquals((Float)1F, ReaderTransforms.TRANSFORMER.toFloat(newReader("1"))); + } + + private Reader newReader(String s) { + return new StringReader(s); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/lang/ByteArrayToStringTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/lang/ByteArrayToStringTransformerTest.java new file mode 100644 index 000000000..1be438e19 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/lang/ByteArrayToStringTransformerTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.ootb.lang; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +import javax.xml.namespace.QName; + +import org.junit.Test; + +/** + * Unit test for {@link ByteArrayToStringTransformer}. + * + * @author Daniel Bevenius + * + */ +public class ByteArrayToStringTransformerTest { + + @Test + public void transformNullByteArray() { + final ByteArrayToStringTransformer transformer = new ByteArrayToStringTransformer(); + final String transformed = transformer.transform(null); + assertThat(transformed, is(nullValue())); + } + + @Test + public void transformByteArray() { + final ByteArrayToStringTransformer transformer = new ByteArrayToStringTransformer(); + final String payload = "some message body"; + final String transformed = transformer.transform(payload.getBytes()); + assertThat(transformed, is(equalTo(payload))); + } + + @Test + public void getFromType() { + final ByteArrayToStringTransformer transformer = new ByteArrayToStringTransformer(); + final QName fromType = transformer.getFrom(); + assertThat(fromType, is(equalTo(new QName("java:byte[]")))); + } + + @Test + public void getToType() { + final ByteArrayToStringTransformer transformer = new ByteArrayToStringTransformer(); + final QName toType = transformer.getTo(); + assertThat(toType, is(equalTo(new QName("java:java.lang.String")))); + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/lang/ExceptionTransformsTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/lang/ExceptionTransformsTest.java new file mode 100644 index 000000000..8877e5f18 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/lang/ExceptionTransformsTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.lang; + +import org.junit.Assert; +import org.junit.Test; + +/** + * ExceptionTransforms test. + */ +public class ExceptionTransformsTest { + + private static final String NL = System.getProperty("line.separator"); + + @Test + public void testToString() throws Exception { + Assert.assertEquals( + "java.lang.Exception: level-1" + NL + + " --- Caused by java.lang.IllegalStateException: level-2" + NL + + " --- Caused by java.lang.NullPointerException: level-3", + new ExceptionTransforms().toString( + new Exception("level-1", + new IllegalStateException("level-2", + new NullPointerException("level-3"))))); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/lang/NumberTransformsTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/lang/NumberTransformsTest.java new file mode 100644 index 000000000..b8594704a --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/lang/NumberTransformsTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.lang; + +import org.junit.Assert; +import org.junit.Test; + +/** + * @author tom.fennelly@gmail.com + */ +public class NumberTransformsTest { + + @Test + public void testToString() throws Exception { + Assert.assertEquals("1", new NumberTransforms().toString(1)); + Assert.assertEquals("1", new NumberTransforms().toString(1L)); + Assert.assertEquals("1.0", new NumberTransforms().toString(1D)); + } + + @Test + public void testToReader() throws Exception { + Assert.assertNotNull(NumberTransforms.TRANSFORMER.toReader(1D)); + } + + @Test + public void testToInputStream() throws Exception { + Assert.assertNotNull(NumberTransforms.TRANSFORMER.toInputStream(1D)); + } + + @Test + public void testToInputSource() throws Exception { + Assert.assertNotNull(NumberTransforms.TRANSFORMER.toInputSource(1D)); + } + + @Test + public void testToChars() throws Exception { + Assert.assertEquals("12345.0", new String(NumberTransforms.TRANSFORMER.toChars(12345D))); + } + + @Test + public void testToCharacter() throws Exception { + Assert.assertEquals((Character)'1', NumberTransforms.TRANSFORMER.toCharacter(12345D)); + } + + @Test + public void testToBytes() throws Exception { + Assert.assertEquals("12345.0", new String(NumberTransforms.TRANSFORMER.toBytes(12345D))); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/lang/StringTransformsTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/lang/StringTransformsTest.java new file mode 100644 index 000000000..35a35c15f --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/lang/StringTransformsTest.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.lang; + +import org.junit.Assert; +import org.junit.Test; + +/** + * @author tom.fennelly@gmail.com + */ +public class StringTransformsTest { + + @Test + public void testToReader() throws Exception { + Assert.assertNotNull(StringTransforms.TRANSFORMER.toReader("reader")); + } + + @Test + public void testToInputStream() throws Exception { + Assert.assertNotNull(StringTransforms.TRANSFORMER.toInputStream("stream")); + } + + @Test + public void testToInputSource() throws Exception { + Assert.assertNotNull(StringTransforms.TRANSFORMER.toInputSource("source")); + } + + @Test + public void testToInteger() throws Exception { + Assert.assertEquals(new Integer(1), StringTransforms.TRANSFORMER.toInteger("1")); + } + + @Test + public void testToLong() throws Exception { + Assert.assertEquals(new Long(1), StringTransforms.TRANSFORMER.toLong("1")); + } + + @Test + public void testToShort() throws Exception { + Assert.assertNotNull(StringTransforms.TRANSFORMER.toShort("1")); + } + + @Test + public void testToChars() throws Exception { + Assert.assertEquals("ccc", new String(StringTransforms.TRANSFORMER.toChars("ccc"))); + } + + @Test + public void testToCharacter() throws Exception { + Assert.assertNotNull(StringTransforms.TRANSFORMER.toCharacter("c")); + } + + @Test + public void testToDouble() throws Exception { + Assert.assertEquals(new Double(1), StringTransforms.TRANSFORMER.toDouble("1")); + } + + @Test + public void testToFloat() throws Exception { + Assert.assertEquals(new Float(1), StringTransforms.TRANSFORMER.toFloat("1")); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/map/FromMapToJavaTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/map/FromMapToJavaTest.java new file mode 100644 index 000000000..45ee31a84 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/map/FromMapToJavaTest.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.map; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.internal.TransformerUtil; +import org.switchyard.transform.ootb.map.ordermodel.Item; +import org.switchyard.transform.ootb.map.ordermodel.Order; + +/** + * @author tom.fennelly@gmail.com + */ +public class FromMapToJavaTest { + + @Test + public void test_factory_creation() { + QName from = JavaTypes.toMessageType(Map.class); + QName to = JavaTypes.toMessageType(Order.class); + + Transformer transformer = TransformerUtil.newTransformer(FromMapToJava.class, from, to); + Assert.assertTrue(transformer instanceof FromMapToJava); + } + + @Test + public void test_transform() { + Map orderHash = buildOrderMap(); + FromMapToJava transformer = new FromMapToJava(); + + transformer.setTo(JavaTypes.toMessageType(Order.class)); + + Order order = (Order) transformer.transform(orderHash); + + Assert.assertEquals(1234, order.getHeader().getOrderId()); + Assert.assertEquals("catalog", order.getHeader().getOriginType()); + Assert.assertEquals(1234, order.getHeader().getCustomerDetails().getCustId()); + Assert.assertEquals("Seamus Ungabunga", order.getHeader().getCustomerDetails().getName()); + List items = order.getItems(); + Assert.assertEquals(2, items.size()); + Assert.assertEquals((Integer) 1234, items.get(0).getItemId()); + Assert.assertEquals("X", items.get(0).getProductId()); + Assert.assertEquals((Integer) 1235, items.get(1).getItemId()); + Assert.assertEquals("Y", items.get(1).getProductId()); + } + + private Map buildOrderMap() { + Map order = new HashMap(); + Map header = new HashMap(); + Map customerDetails = new HashMap(); + List items = new ArrayList(); + Map item1 = new HashMap(); + Map item2 = new HashMap(); + + order.put("header", header); + header.put("orderId", 1234); + header.put("originType", "catalog"); + header.put("customerDetails", customerDetails); + customerDetails.put("custId", 1234); + customerDetails.put("name", "Seamus Ungabunga"); + order.put("items", items); + items.add(item1); + items.add(item2); + item1.put("itemId", 1234); + item1.put("productId", "X"); + item2.put("itemId", 1235); + item2.put("productId", "Y"); + + return order; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Customer.java b/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Customer.java new file mode 100644 index 000000000..8bd17119f --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Customer.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.map.ordermodel; + +/** + * @author tom.fennelly@gmail.com + */ +public class Customer { + + private int custId; + private String name; + + public int getCustId() { + return custId; + } + + public void setCustId(int custId) { + this.custId = custId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Header.java b/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Header.java new file mode 100644 index 000000000..4f35b319a --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Header.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.map.ordermodel; + +/** + * @author tom.fennelly@gmail.com + */ +public class Header { + + private long orderId; + private String originType; + private Customer customerDetails; + + public long getOrderId() { + return orderId; + } + + public void setOrderId(long orderId) { + this.orderId = orderId; + } + + public String getOriginType() { + return originType; + } + + public void setOriginType(String originType) { + this.originType = originType; + } + + public Customer getCustomerDetails() { + return customerDetails; + } + + public void setCustomerDetails(Customer customerDetails) { + this.customerDetails = customerDetails; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Item.java b/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Item.java new file mode 100644 index 000000000..359b47002 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Item.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.map.ordermodel; + +/** + * @author tom.fennelly@gmail.com + */ +public class Item { + + private Integer itemId; + private String productId; + + public Integer getItemId() { + return itemId; + } + + public void setItemId(Integer itemId) { + this.itemId = itemId; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Order.java b/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Order.java new file mode 100644 index 000000000..90bd34f8a --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/map/ordermodel/Order.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.map.ordermodel; + +import java.util.List; + +/** + * @author tom.fennelly@gmail.com + */ +public class Order { + + private Header header; + private List items; + + public Header getHeader() { + return header; + } + + public void setHeader(Header header) { + this.header = header; + } + + public List getItems() { + return items; + } + + public void setItems(List items) { + this.items = items; + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/ootb/xml/BasicDOMTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/ootb/xml/BasicDOMTransformerTest.java new file mode 100644 index 000000000..7fccd57af --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/ootb/xml/BasicDOMTransformerTest.java @@ -0,0 +1,222 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.transform.ootb.xml; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.transform.ootb.AbstractTransformerTest; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; + +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +/** + * @author tom.fennelly@gmail.com + */ +public class BasicDOMTransformerTest extends AbstractTransformerTest { + + @Test + public void test_Document2Document() throws IOException, SAXException { + Document docIn = XMLUnit.buildTestDocument(""); + DefaultMessage message = newMessage(); + + message.setContent(docIn); + Document docOut = message.getContent(Document.class); + + Assert.assertTrue(docIn == docOut); + } + + @Test + public void test_Document2Element() throws IOException, SAXException { + Document docIn = XMLUnit.buildTestDocument(""); + DefaultMessage message = newMessage(); + + message.setContent(docIn); + Element elementOut = message.getContent(Element.class); + + Assert.assertTrue(docIn == elementOut.getParentNode()); + } + + @Test + public void test_Document2String() throws IOException, SAXException { + Document docIn = XMLUnit.buildTestDocument(""); + DefaultMessage message = newMessage(); + + message.setContent(docIn); + String stringOut = message.getContent(String.class); + + XMLAssert.assertXMLEqual("", stringOut); + } + + @Test + public void test_Element2String() throws IOException, SAXException { + Document docIn = XMLUnit.buildTestDocument(""); + DefaultMessage message = newMessage(); + + message.setContent(docIn); + char[] charsOut = message.getContent(char[].class); + + XMLAssert.assertXMLEqual("", new String(charsOut)); + } + + @Test + public void test_DOMSource2String() throws IOException, SAXException { + Document docIn = XMLUnit.buildTestDocument(""); + DefaultMessage message = newMessage(); + + message.setContent(new DOMSource(docIn)); + String stringOut = message.getContent(String.class); + + XMLAssert.assertXMLEqual("", new String(stringOut)); + } + + @Test + public void test_DOMSourceToDocument() throws IOException, SAXException { + final Document docIn = XMLUnit.buildTestDocument(""); + testFromDOM(new DOMSource(docIn), Document.class) ; + testFromDOM(new DOMSource(docIn.getDocumentElement()), Document.class) ; + } + + @Test + public void test_DOMSourceToElement() throws IOException, SAXException { + final Document docIn = XMLUnit.buildTestDocument(""); + testFromDOM(new DOMSource(docIn), Element.class) ; + testFromDOM(new DOMSource(docIn.getDocumentElement()), Element.class) ; + } + + @Test + public void test_DOMSourceToNode() throws IOException, SAXException { + final Document docIn = XMLUnit.buildTestDocument(""); + testFromDOM(new DOMSource(docIn), Node.class, Document.class) ; + testFromDOM(new DOMSource(docIn.getDocumentElement()), Node.class, Element.class) ; + } + + @Test + public void test_String2Document() throws IOException, SAXException { + testToDOM("", Document.class); + } + + @Test + public void test_String2Element() throws IOException, SAXException { + testToDOM("", Element.class); + } + + @Test + public void test_String2Node() throws IOException, SAXException { + testToDOM("", Node.class, Element.class); + } + + @Test + public void test_String2DOMSource() throws IOException, SAXException, TransformerException { + DefaultMessage message = newMessage(); + + message.setContent(""); + DOMSource doms = message.getContent(DOMSource.class); + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + TransformerFactory.newInstance().newTransformer().transform(doms, result); + XMLAssert.assertXMLEqual("", writer.toString()); + } + + @Test + public void test_Reader2Document() throws IOException, SAXException { + testToDOM(new StringReader(""), Document.class); + } + + @Test + public void test_Reader2Element() throws IOException, SAXException { + testToDOM(new StringReader(""), Element.class); + } + + @Test + public void test_InputStream2Document() throws IOException, SAXException { + testToDOM(new ByteArrayInputStream("".getBytes()), Document.class); + } + + @Test + public void test_InputStream2Element() throws IOException, SAXException { + testToDOM(new ByteArrayInputStream("".getBytes()), Element.class); + } + + @Test + public void test_InputSource2Document() throws IOException, SAXException { + testToDOM(new InputSource(new StringReader("")), Document.class); + } + + @Test + public void test_InputSource2Element() throws IOException, SAXException { + testToDOM(new InputSource(new StringReader("")), Element.class); + } + + @Test + public void test_Chars2Document() throws IOException, SAXException { + testToDOM("".toCharArray(), Document.class); + } + + @Test + public void test_Chars2Element() throws IOException, SAXException { + testToDOM("".getBytes(), Element.class); + } + + @Test + public void test_Bytes2Document() throws IOException, SAXException { + testToDOM("".getBytes(), Document.class); + } + + @Test + public void test_Bytes2Element() throws IOException, SAXException { + testToDOM("".toCharArray(), Element.class); + } + + private void testToDOM(Object fromXmlContent, Class toNodeType) throws IOException, SAXException { + testToDOM(fromXmlContent, toNodeType, toNodeType) ; + } + + private void testToDOM(Object fromXmlContent, Class toNodeType, Class nodeResultType) throws IOException, SAXException { + DefaultMessage message = newMessage(); + + message.setContent(fromXmlContent); + T node = message.getContent(toNodeType); + Assert.assertTrue(nodeResultType.isInstance(node)); + + XMLAssert.assertXMLEqual("", AbstractDOMTransformer.serialize(node)); + } + + private void testFromDOM(DOMSource source, Class toNodeType) throws IOException, SAXException { + testFromDOM(source, toNodeType, toNodeType); + } + + private void testFromDOM(DOMSource source, Class toNodeType, Class nodeReultType) throws IOException, SAXException { + final BasicDOMTransformer transformer = new BasicDOMTransformer(); + transformer.setTo(JavaTypes.toMessageType(toNodeType)); + final Object result = transformer.transform(source); + Assert.assertTrue(nodeReultType.isInstance(result)); + } +} diff --git a/core/transform/src/test/java/org/switchyard/transform/xslt/internal/TransformerPoolTest.java b/core/transform/src/test/java/org/switchyard/transform/xslt/internal/TransformerPoolTest.java new file mode 100644 index 000000000..abc0250a7 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/xslt/internal/TransformerPoolTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.xslt.internal; + +import java.io.InputStream; + +import javax.xml.transform.Templates; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamSource; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.transform.xslt.internal.TransformerPool; +import org.switchyard.transform.xslt.internal.XsltUriResolver; + +public class TransformerPoolTest { + + private static final String XSLT = "org/switchyard/transform/xslt/internal/topics.xslt"; + + private Templates templates; + + public TransformerPoolTest() throws Exception { + TransformerFactory tFactory = TransformerFactory.newInstance(); + tFactory.setURIResolver(new XsltUriResolver()); + InputStream xsltStream = this.getClass().getClassLoader().getResourceAsStream(XSLT); + templates = tFactory.newTemplates(new StreamSource(xsltStream)); + } + + @Test + public void takeAndGive() throws Exception { + TransformerPool pool = new TransformerPool(templates, 1); + Transformer t1 = pool.take(); + Assert.assertNotNull(t1); + pool.give(t1); + Transformer t2 = pool.take(); + Assert.assertNotNull(t2); + Assert.assertEquals(t1, t2); + } + + @Test + public void blockOnTake() throws Exception { + final TransformerPool pool = new TransformerPool(templates, 3); + // draw down the pool + pool.take(); + pool.take(); + final Transformer t = pool.take(); + + // spin up a thread to offer back + new Thread() { + public void run() { + try { + Thread.sleep(2000); + pool.give(t); + } catch (Exception ex) { + ex.printStackTrace(); + Assert.fail(); + } + } + }.start(); + + // This will block until the give from our thread above + Transformer t2 = pool.take(); + Assert.assertEquals(t, t2); + } + +} diff --git a/core/transform/src/test/java/org/switchyard/transform/xslt/internal/XsltTransformerTest.java b/core/transform/src/test/java/org/switchyard/transform/xslt/internal/XsltTransformerTest.java new file mode 100644 index 000000000..b1aa5c385 --- /dev/null +++ b/core/transform/src/test/java/org/switchyard/transform/xslt/internal/XsltTransformerTest.java @@ -0,0 +1,209 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.transform.xslt.internal; + +import java.io.IOException; +import java.io.InputStream; + +import javax.xml.namespace.QName; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.SwitchYardException; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.transform.AbstractTransformerTestCase; +import org.switchyard.transform.Transformer; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.transform.config.model.TransformNamespace; +import org.switchyard.transform.config.model.XsltTransformModel; +import org.switchyard.transform.config.model.v1.V1XsltTransformModel; +import org.switchyard.transform.internal.TransformerRegistryLoader; +import org.xml.sax.SAXException; + +/** + * @author Alejandro Montenegro aamonten@gmail.com + */ +public class XsltTransformerTest extends AbstractTransformerTestCase { + + private TransformerRegistry xformReg; + + private final static String INITIAL = "Switchyardhttp://www.jboss.org/switchyard" + + "Arquillianhttp://www.jboss.org/arquillianDrools" + + "http://www.jboss.org/droolsJBoss Toolshttp://www.jboss.org/tools" + + ""; + + private final static String INITIAL_FAIL = "Switchyardhttp://www.jboss.org/switchyard" + + "Arquillianhttp://www.jboss.org/arquillianDrools" + + "http://www.jboss.org/droolsJBoss Toolshttp://www.jboss.org/tools"; + + private final static String EXPECTED = "" + + "JBoss Project's'" + + "" + + "" + + "
TitleURL
Switchyardhttp://www.jboss.org/switchyard
Arquillianhttp://www.jboss.org/arquillian
Droolshttp://www.jboss.org/drools
JBoss Toolshttp://www.jboss.org/tools
"; + + public XsltTransformerTest() { + xformReg = new BaseTransformerRegistry(); + new TransformerRegistryLoader(xformReg).loadOOTBTransforms(); + } + + @Test + public void test_no_validation() throws IOException { + try { + getTransformer("xslt-config-01.xml"); + } catch (RuntimeException e) { + Assert.fail("failed to load configuration file xslt-config-01.xml"); + } + } + + @Test + public void test_validation() throws Exception { + InputStream swConfigStream = Classes.getResourceAsStream("xslt-config-01.xml", getClass()); + try { + SwitchYardModel switchyardConfig = new ModelPuller().pull(swConfigStream); + switchyardConfig.assertModelValid(); + } finally { + swConfigStream.close(); + } + } + + @Test + public void test_no_xslt_file() throws IOException { + try { + getTransformer("xslt-config-02.xml"); + Assert.fail("the configuration file should be invalid"); + } catch (RuntimeException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016801"); + Assert.assertTrue(exceptionMatch); + } + } + + @Test + public void test_xslt_result() throws IOException, SAXException { + Transformer transformer = getTransformer("xslt-config-03.xml"); + DefaultMessage message = newMessage(INITIAL); + transformer.transform(message); + String result = message.getContent(String.class); + + XMLUnit.setIgnoreWhitespace(true); + Diff diff = new Diff(EXPECTED, result); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void test_local_xslt_file_fail() throws IOException { + try { + Transformer transformer = getTransformer("xslt-config-03.xml"); + DefaultMessage message = newMessage(INITIAL_FAIL); + Object result = transformer.transform(message); + Assert.fail("xml to transform should be invalid"); + } catch (SwitchYardException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016800"); + Assert.assertTrue(exceptionMatch); + } + } + + @Test + public void test_factoryLoad() { + V1XsltTransformModel model = new V1XsltTransformModel(TransformNamespace.DEFAULT.uri()); + + model.setXsltFile("org/switchyard/transform/xslt/internal/topics.xslt"); + model.setFrom(new QName("A")); + model.setTo(new QName("B")); + + TransformerRegistryLoader trl = new TransformerRegistryLoader(new BaseTransformerRegistry()); + Transformer transformer = trl.newTransformer(model); + + Assert.assertTrue(transformer instanceof XsltTransformer); + } + + @Test + public void test_failonwarn_false_warn() throws IOException, SAXException { + Transformer transformer = getTransformer("xslt-config-failonwarn-false-warn.xml"); + DefaultMessage message = newMessage(INITIAL); + transformer.transform(message); + String result = message.getContent(String.class); + + XMLUnit.setIgnoreWhitespace(true); + Diff diff = new Diff(EXPECTED, result); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void test_failonwarn_true_warn() throws IOException, SAXException { + try { + Transformer transformer = getTransformer("xslt-config-failonwarn-true-warn.xml"); + + Assert.fail("No SwitchYardException has been thrown"); + } catch (SwitchYardException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016802"); + Assert.assertTrue(exceptionMatch); + } + } + + @Test + public void test_xsl_include_with_href() throws IOException, SAXException { + try { + Transformer transformer = getTransformer("xslt-config-include-href.xml"); + + Assert.assertTrue(transformer instanceof XsltTransformer); + } catch (SwitchYardException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016802"); + Assert.assertTrue(exceptionMatch); + } + } + + @Test + public void test_xsl_include_with_invalid_href() throws IOException, SAXException { + try { + Transformer transformer = getTransformer("xslt-config-include-invalid-href.xml"); + + Assert.fail("No SwitchYardException has been thrown"); + } catch (SwitchYardException e) { + boolean exceptionMatch = e.getMessage().contains("SWITCHYARD016802"); + Assert.assertTrue(exceptionMatch); + } + } + + @Test + public void testPoolSizeConfiguration() throws Exception { + XsltTransformFactory factory = new XsltTransformFactory(); + SwitchYardModel switchyard = new ModelPuller().pull( + "xslt-config-06.xml", getClass()); + XsltTransformModel model = (XsltTransformModel) + switchyard.getTransforms().getTransforms().get(0); + int maxSize = factory.getTransformPoolSize(model); + Assert.assertEquals(123, maxSize); + } + + @Test + public void testNoPool() throws Exception { + XsltTransformer xslt = (XsltTransformer)getTransformer("xslt-config-07.xml"); + Assert.assertNull(xslt.getTransformerPool()); + } + + private DefaultMessage newMessage(Object content) { + DefaultMessage message = new DefaultMessage().setContent(content); + message.setTransformerRegistry(xformReg); + return message; + } + +} diff --git a/core/transform/src/test/resources/org/switchyard/transform/MessageTransformerTest.xml b/core/transform/src/test/resources/org/switchyard/transform/MessageTransformerTest.xml new file mode 100644 index 000000000..e65931d43 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/MessageTransformerTest.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/MissingTransformerTest.xml b/core/transform/src/test/resources/org/switchyard/transform/MissingTransformerTest.xml new file mode 100644 index 000000000..ef9c3b878 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/MissingTransformerTest.xml @@ -0,0 +1,21 @@ + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/config/model/TransformModelTests.xml b/core/transform/src/test/resources/org/switchyard/transform/config/model/TransformModelTests.xml new file mode 100644 index 000000000..08d5dc68c --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/config/model/TransformModelTests.xml @@ -0,0 +1,20 @@ + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/mapping-A-B.xml b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/mapping-A-B.xml new file mode 100644 index 000000000..009033e32 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/mapping-A-B.xml @@ -0,0 +1,14 @@ + + + + org.switchyard.transform.dozer.internal.ClassA + org.switchyard.transform.dozer.internal.ClassB + + fieldB + fieldB_mod + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/mapping-C-D.xml b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/mapping-C-D.xml new file mode 100644 index 000000000..5254953a7 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/mapping-C-D.xml @@ -0,0 +1,18 @@ + + + + org.switchyard.transform.dozer.internal.ClassC + org.switchyard.transform.dozer.internal.ClassD + + fieldA + fieldB + + + fieldC + fieldD + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-file.xml b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-file.xml new file mode 100644 index 000000000..12c124902 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-file.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-multi-file.xml b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-multi-file.xml new file mode 100644 index 000000000..aca8e3b3c --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-multi-file.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-nofile.xml b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-nofile.xml new file mode 100644 index 000000000..b2e032262 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/dozer/internal/sw-config-nofile.xml @@ -0,0 +1,21 @@ + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-01.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-01.xml new file mode 100644 index 000000000..7f05c31cb --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-01.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-02.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-02.xml new file mode 100644 index 000000000..f212aad43 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-02.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-03.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-03.xml new file mode 100644 index 000000000..084e04076 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-03.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-04.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-04.xml new file mode 100644 index 000000000..ff6305ae2 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-04.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-05.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-05.xml new file mode 100644 index 000000000..6eb8b6875 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-05.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-06.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-06.xml new file mode 100644 index 000000000..24a018203 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/json/switchyard-config-06.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-01.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-01.xml new file mode 100644 index 000000000..84b9a02ab --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-01.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-02.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-02.xml new file mode 100644 index 000000000..924aae4d0 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-02.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-03.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-03.xml new file mode 100644 index 000000000..64eb08bfd --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-03.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-04.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-04.xml new file mode 100644 index 000000000..8f9825fc5 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-04.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-xmlb-01.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-xmlb-01.xml new file mode 100644 index 000000000..5ea531add --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/smooks-config-xmlb-01.xml @@ -0,0 +1,23 @@ + + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-01.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-01.xml new file mode 100644 index 000000000..aa242af22 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-01.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-02.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-02.xml new file mode 100644 index 000000000..1c19c77ef --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-02.xml @@ -0,0 +1,20 @@ + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-03.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-03.xml new file mode 100644 index 000000000..899ac8ba2 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-03.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-04.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-04.xml new file mode 100644 index 000000000..edcbac8ee --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-04.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-xmlb-01.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-xmlb-01.xml new file mode 100644 index 000000000..ec8687d98 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-xmlb-01.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-xmlb-02.xml b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-xmlb-02.xml new file mode 100644 index 000000000..f13cc5bfe --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/internal/smooks/sw-config-xmlb-02.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/po.xml b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/po.xml new file mode 100644 index 000000000..b66f36127 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/po.xml @@ -0,0 +1,34 @@ + + + + Alice Smith + 123 Maple Street + Cambridge + MA + 12345 + + + Robert Smith + 8 Oak Avenue + Cambridge + MA + 12345 + + + + Nosferatu - Special Edition (1929) + 5 + 19.99 + + + The Mummy (1959) + 3 + 19.98 + + + Godzilla and Mothra: Battle for Earth/Godzilla vs. King Ghidora + 3 + 27.95 + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/po.xsd b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/po.xsd new file mode 100644 index 000000000..85a678c56 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/po.xsd @@ -0,0 +1,233 @@ + + + + + jxb:globalBindings element documentation: + To illustrate all global controllable settings, listed all + attributes with their default values except for + @fixedAttributeAsConstantProperty and @collectionType. + + @fixedAttributeAsConstantProperty set to true indicates that + all fixed attributes should be bound to Java constants. By + default, fixed attributes are just mapped to either simple + or collection property, which ever is more appropriate. + + @collectionType set to java.util.Vector specifies that all + lists in the generated implementation classes should be represented + internally as vectors. + + If @typesafeEnumBase was set to"xsd:string", it is a global way to specify + that all simple type definitions deriving directly or indirectly + from "xsd:string" and having enumeration facets should be bound + to a typesafe enum. The typesafeEnumClass customization in simple + type definition of USState would be redundant with this suggested + change. If @typesafeEnumBase was set to empty string, "", no simple + type definitions would ever be bound to a typesafe enum class by + default binding. + + jxb:schemaBindings documentation: + child element jxb:package specifes a java package for the Java + representation generated for this schema. + + child element jxb:nameXmlTransform/jxb:elementName specifies that + all Java element interfaces generated should have "Element" + appended to names generated by default. For this schema, + customization results in element interfaces CommentElement and + PurchaseOrderElement being generated. Default binding would + generate element interface Comment and PurchaseOrderElement. + jxb:nameXmlTransform has children elements for the symbol space + typeName, anonymousTypeName and modelGroupName. + + + + + + Package level documentation for generated package primer.po.]]> + + + + + + + + + + + + + + + A <b>Purchase Order</b> consists of addresses and items. + + + + + + + + + + + + + + + + + + USAddress.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + JAXB customization documentation: + jaxb:property @generateIsSetMethod results in additional property + methods,isSetQuantity and unsetQuantity, being generated to + to be able to distinguish between schema defaulted value + and values occuring explicitly within an instance document. + + + + + + + + +By default, JAXB specification maps an xsd:positiveInteger to +a java.math.BigInteger. Since this simpleType is constrained to +be a value between 0..100, it is more natural for the Java +program to map this to a "short" Java datatype. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This is a localized way to map this simple type definition + to a typesafe enum class. See jxb:globalBindings + @typesafeEnumBase above for a global way to accomplish this + for all simple type definitions similar to this one. + + + + + + + + + + + + + + + + Legal zip codes are limited to 5 digits, extended Zip Code not + supported. + + JAXB customization: jaxb:javaType binding declaration overrides + default binding of this type to a java.lang.Integer. The + constraint facets for this type restrict the valid values of this + type to easily fit within Java primitive datatype int. + + + Given the value range of an xsd:integer, it is mapped to + java.math.BigInteger by default. When one considers the + constaining facets for this type are between 10000..99999, + it is safe to bind this simple type directly to the + Java datatype "int" using the following customization. + + + + + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-01.xml b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-01.xml new file mode 100644 index 000000000..1db733bff --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-01.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-02.xml b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-02.xml new file mode 100644 index 000000000..5dfd62750 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-02.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-03.xml b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-03.xml new file mode 100644 index 000000000..37bd05588 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/jaxb/internal/switchyard-config-03.xml @@ -0,0 +1,20 @@ + + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-include-with-invalid-href.xslt b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-include-with-invalid-href.xslt new file mode 100644 index 000000000..f93821354 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-include-with-invalid-href.xslt @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-include.xslt b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-include.xslt new file mode 100644 index 000000000..203765c20 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-include.xslt @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-warn.xslt b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-warn.xslt new file mode 100644 index 000000000..b37a968ba --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics-warn.xslt @@ -0,0 +1,30 @@ + + + + + + + JBoss Project's' + + + + + + + + + + + + + +
TitleURL
+ + + +
+ +
+
+
+ diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics.xslt b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics.xslt new file mode 100644 index 000000000..a0e3c1200 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/topics.xslt @@ -0,0 +1,28 @@ + + + + + + JBoss Project's' + + + + + + + + + + + + + +
TitleURL
+ + + +
+ +
+
+
\ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-01.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-01.xml new file mode 100644 index 000000000..da70b4662 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-01.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-02.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-02.xml new file mode 100644 index 000000000..bb7df8430 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-02.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-03.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-03.xml new file mode 100644 index 000000000..da70b4662 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-03.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-04.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-04.xml new file mode 100644 index 000000000..da70b4662 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-04.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-05.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-05.xml new file mode 100644 index 000000000..da70b4662 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-05.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-06.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-06.xml new file mode 100644 index 000000000..38d990ebc --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-06.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-07.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-07.xml new file mode 100644 index 000000000..112439dc7 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-07.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-failonwarn-false-warn.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-failonwarn-false-warn.xml new file mode 100644 index 000000000..d5c5e94a9 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-failonwarn-false-warn.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-failonwarn-true-warn.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-failonwarn-true-warn.xml new file mode 100644 index 000000000..b8646f830 --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-failonwarn-true-warn.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-include-href.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-include-href.xml new file mode 100644 index 000000000..3a804a2cf --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-include-href.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-include-invalid-href.xml b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-include-invalid-href.xml new file mode 100644 index 000000000..6cd09a3ba --- /dev/null +++ b/core/transform/src/test/resources/org/switchyard/transform/xslt/internal/xslt-config-include-invalid-href.xml @@ -0,0 +1,19 @@ + + + + + + + \ No newline at end of file diff --git a/core/validate/pom.xml b/core/validate/pom.xml new file mode 100644 index 000000000..326ed504d --- /dev/null +++ b/core/validate/pom.xml @@ -0,0 +1,88 @@ + + + + 4.0.0 + + org.switchyard + switchyard-core-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-validate + bundle + SwitchYard: Validate + The SwitchYard Validate library. + http://switchyard.org + + + org.switchyard.validate.config.*; + org.switchyard.validate.internal.*; + org.switchyard.validate.xml.* + + + javax.enterprise.inject.spi;resolution:=optional, + org.switchyard.common.cdi;resolution:=optional;${switchyard.osgi.import.switchyard.version}, + org.switchyard.config.model;org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-cdi + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-runtime + test + + + + xml-resolver + xml-resolver + + + junit + junit + test + + + xmlunit + xmlunit + test + + + org.codehaus.jackson + jackson-mapper-asl + + + org.codehaus.jackson + jackson-core-asl + + + diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/FileEntryModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/FileEntryModel.java new file mode 100644 index 000000000..f4ec8e66b --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/FileEntryModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import org.switchyard.config.model.Model; + +/** + * A "entry" configuration model. + */ +public interface FileEntryModel extends Model { + + /** entry. */ + public static final String ENTRY = "entry"; + + /** file. */ + public static final String FILE = "file"; + + /** + * Get file. + * @return file + */ + String getFile(); + + /** + * Set file. + * @param file file + * @return model representation + */ + FileEntryModel setFile(String file); + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/JavaValidateModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/JavaValidateModel.java new file mode 100644 index 000000000..10e819061 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/JavaValidateModel.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import org.switchyard.config.model.validate.ValidateModel; + +/** + * A "transform.java" configuration model. + * + * @author Tomohisa Igarashi + */ +public interface JavaValidateModel extends ValidateModel { + + /** The "java" name. */ + public static final String JAVA = "java"; + + /** The "class" name. */ + public static final String CLASS = "class"; + + /** The "bean" name. */ + public static final String BEAN = "bean"; + + /** + * Gets the class attribute. + * @return the class attribute + */ + public String getClazz(); + + /** + * Sets the class attribute. + * @param clazz the class attribute + * @return this JavaValidateModel (useful for chaining) + */ + public JavaValidateModel setClazz(String clazz); + + /** + * Gets the bean attribute. + * @return the bean attribute + */ + public String getBean(); + + /** + * Sets the bean attribute. + * @param bean the bean attribute + * @return this JavaValidateModel (useful for chaining) + */ + public JavaValidateModel setBean(String bean); +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/SchemaCatalogsModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/SchemaCatalogsModel.java new file mode 100644 index 000000000..02add2507 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/SchemaCatalogsModel.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A "schemaCatalogs" configuration model. + */ +public interface SchemaCatalogsModel extends Model { + + /** schema catalog. */ + public static final String SCHEMA_CATALOGS = "schemaCatalogs"; + + /** + * Get file entries. + * @return file entries + */ + List getEntries(); + + /** + * Set a file entry. + * @param entry file entry + * @return model representation + */ + SchemaCatalogsModel addEntry(FileEntryModel entry); + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/SchemaFilesModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/SchemaFilesModel.java new file mode 100644 index 000000000..684269792 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/SchemaFilesModel.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import java.util.List; + +import org.switchyard.config.model.Model; + +/** + * A "schemaFiles" configuration model. + */ +public interface SchemaFilesModel extends Model { + + /** schema file. */ + public static final String SCHEMA_FILES = "schemaFiles"; + + /** + * Get file entries. + * @return file entries + */ + List getEntries(); + + /** + * Set a file entry. + * @param entry file entry + * @return model representation + */ + SchemaFilesModel addEntry(FileEntryModel entry); + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/ValidateNamespace.java b/core/validate/src/main/java/org/switchyard/validate/config/model/ValidateNamespace.java new file mode 100644 index 000000000..a8422bffc --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/ValidateNamespace.java @@ -0,0 +1,111 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.validate.config.model; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Namespace; + +/** + * A Vadliate config model namespace. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public enum ValidateNamespace implements Namespace { + + /** The 1.0 namespace. */ + V_1_0("1.0"), + /** The 1.1 namespace. */ + V_1_1("1.1"), + /** The 2.0 namespace. */ + V_2_0("2.0"), + /** The default namespace. */ + DEFAULT(null); + + private final Util _util; + + /** + * Constructs a new ValidateNamespace with the specified version. + * @param version the specified version, or null to discover the default + */ + ValidateNamespace(String version) { + _util = new Util(version); + } + + /** + * {@inheritDoc} + */ + @Override + public String section() { + return _util.section(); + } + + /** + * {@inheritDoc} + */ + @Override + public String version() { + return _util.version(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean versionMatches(Namespace namespace) { + return _util.versionMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public String uri() { + return _util.uri(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean uriMatches(Namespace namespace) { + return _util.uriMatches(namespace); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDefault() { + return this == DEFAULT || uriMatches(DEFAULT); + } + + /** + * Gets the ValidateNamespace for the specified uri, or null if no matching uris are found. + * @param uri the uri + * @return the ValidateNamespace + */ + public static ValidateNamespace fromUri(String uri) { + return Util.fromUri(ValidateNamespace.class, uri); + } + + @SuppressWarnings("serial") + private static final class Util extends Namespace.Util { + // static final since we only want to do the somewhat expensive work of instantiating this once! + private static final Descriptor DESCRIPTOR = new Descriptor(ValidateNamespace.class); + private Util(String version) { + super(DESCRIPTOR, "urn:switchyard-config:validate", version); + } + } + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/ValidateSwitchYardScanner.java b/core/validate/src/main/java/org/switchyard/validate/config/model/ValidateSwitchYardScanner.java new file mode 100644 index 000000000..14fa01dea --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/ValidateSwitchYardScanner.java @@ -0,0 +1,108 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import java.io.IOException; +import java.net.URL; +import java.util.List; + +import org.switchyard.common.cdi.CDIUtil; +import org.switchyard.common.type.classpath.AbstractTypeFilter; +import org.switchyard.common.type.classpath.ClasspathScanner; +import org.switchyard.config.model.Scannable; +import org.switchyard.config.model.Scanner; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.ScannerOutput; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.config.model.validate.ValidatesModel; +import org.switchyard.config.model.validate.v1.V1ValidatesModel; +import org.switchyard.validate.config.model.v1.V1JavaValidateModel; +import org.switchyard.validate.internal.ValidatorTypes; +import org.switchyard.validate.internal.ValidatorUtil; + +/** + * Scanner for {@link org.switchyard.validate.Validator} implementations. + * + * @author Tomohisa Igarashi + */ +public class ValidateSwitchYardScanner implements Scanner { + + /** + * {@inheritDoc} + */ + @Override + public ScannerOutput scan(ScannerInput input) throws IOException { + SwitchYardNamespace switchyardNamespace = input.getSwitchyardNamespace(); + SwitchYardModel switchyardModel = new V1SwitchYardModel(switchyardNamespace.uri()); + ValidatesModel validatesModel = null; + + ValidateNamespace validateNamespace = ValidateNamespace.DEFAULT; + for (ValidateNamespace value : ValidateNamespace.values()) { + if (value.versionMatches(switchyardNamespace)) { + validateNamespace = value; + break; + } + } + + List> validatorClasses = scanForValidators(input.getURLs()); + for (Class validator : validatorClasses) { + List supportedValidators = ValidatorUtil.listValidations(validator); + + for (ValidatorTypes supportedValidate : supportedValidators) { + JavaValidateModel validateModel = new V1JavaValidateModel(validateNamespace.uri()); + + String bean = CDIUtil.getNamedAnnotationValue(validator); + if (bean != null) { + validateModel.setBean(bean); + } else { + validateModel.setClazz(validator.getName()); + } + validateModel.setName(supportedValidate.getName()); + + if (validatesModel == null) { + validatesModel = new V1ValidatesModel(switchyardNamespace.uri()); + switchyardModel.setValidates(validatesModel); + } + validatesModel.addValidate(validateModel); + } + } + + return new ScannerOutput().setModel(switchyardModel); + } + + private List> scanForValidators(List urls) throws IOException { + AbstractTypeFilter filter = new ValidatorInstanceOfFilter(); + ClasspathScanner scanner = new ClasspathScanner(filter); + for (URL url : urls) { + scanner.scan(url); + } + + return filter.getMatchedTypes(); + } + + private class ValidatorInstanceOfFilter extends AbstractTypeFilter { + @Override + public boolean matches(Class clazz) { + Scannable scannable = clazz.getAnnotation(Scannable.class); + if (scannable != null && !scannable.value()) { + // Marked as being non-scannable... + return false; + } + return ValidatorUtil.isValidator(clazz); + } + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/XmlSchemaType.java b/core/validate/src/main/java/org/switchyard/validate/config/model/XmlSchemaType.java new file mode 100644 index 000000000..7ac8a16e1 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/XmlSchemaType.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +/** + * Schema type for XML validation. + * + * @author Tomohisa Igarashi + */ +public enum XmlSchemaType { + /** + * DTD. + */ + DTD, + /** + * W3C XML Schema. + */ + XML_SCHEMA, + /** + * RELAX NG. + */ + RELAX_NG +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/XmlValidateModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/XmlValidateModel.java new file mode 100644 index 000000000..46512fab6 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/XmlValidateModel.java @@ -0,0 +1,109 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import org.switchyard.config.model.validate.ValidateModel; + +/** + * A "validate.xml" configuration model. + * + * @author Tomohisa Igarashi + */ +public interface XmlValidateModel extends ValidateModel { + + /** The "xml" name. */ + public static final String XML = "xml"; + + /** schema file. */ + public static final String SCHEMA_FILE_URI = "schemaFile"; + + /** schema language. */ + public static final String SCHEMA_TYPE = "schemaType"; + + /** whether a warning should be reported as Exception or just log. */ + public static final String FAIL_ON_WARNING = "failOnWarning"; + + /** whether the validator should be namespace aware or not. */ + public static final String NAMESPACE_AWARE = "namespaceAware"; + + /** + * Return whether a warning should be reported as an SwitchYardException. + * If failOnWarning attribute is "true", then a warning should be reported + * as an SwitchYardException, otherwise just log. + * @return true if a warning should be reported as an SwitchYardException, otherwise false + */ + boolean failOnWarning(); + + /** + * Set whether a warning should be reported as an SwitchYardException. + * If failOnWarning attribute is "true", then a warning should be reported + * as an SwitchYardException, otherwise just log. + * @param failOnWarning true if a warning should be reported as an SwitchYardException, otherwise false + * @return model representation + */ + XmlValidateModel setFailOnWarning(boolean failOnWarning); + + /** + * Return whether the validator should be namespace aware or not. + * @return true if namespace aware + */ + boolean namespaceAware(); + + /** + * Set whether the validator should be namespace aware or not. + * @param namespaceAware true if namespace aware + * @return model representation + */ + XmlValidateModel setNamespaceAware(boolean namespaceAware); + + /** + * Get a SchemaFiles model. + * @return a SchemaFiles model + */ + SchemaFilesModel getSchemaFiles(); + + /** + * Set a SchemaFiles model. + * @param schemaFiles a SchemaFiles model + * @return model representation + */ + XmlValidateModel setSchemaFiles(SchemaFilesModel schemaFiles); + + /** + * Get a SchemaCatalogs model. + * @return a SchemaCatalogs model + */ + SchemaCatalogsModel getSchemaCatalogs(); + + /** + * Set a SchemaCatalogs model. + * @param schemaCatalogs a SchemaCatalogs model + * @return model representation + */ + XmlValidateModel setSchemaCatalogs(SchemaCatalogsModel schemaCatalogs); + + /** + * Get schema type. + * @return schema type + */ + XmlSchemaType getSchemaType(); + + /** + * Set schema type. + * @param type schema type + * @return model representation + */ + XmlValidateModel setSchemaType(XmlSchemaType type); +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1FileEntryModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1FileEntryModel.java new file mode 100644 index 000000000..da69eda53 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1FileEntryModel.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.validate.config.model.FileEntryModel; + +/** + * A version 1 FileEntryModel. + */ +public class V1FileEntryModel extends BaseModel implements FileEntryModel { + + /** + * Constructs a new V1SchemaCatalogsModel. + * @param namespace namespace + */ + public V1FileEntryModel(String namespace) { + super(new QName(namespace, FileEntryModel.ENTRY)); + } + + /** + * Constructs a new V1FileEntryModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1FileEntryModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + @Override + public String getFile() { + return getModelAttribute(FileEntryModel.FILE); + } + + @Override + public FileEntryModel setFile(String file) { + setModelAttribute(FileEntryModel.FILE, file); + return this; + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1JavaValidateModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1JavaValidateModel.java new file mode 100644 index 000000000..397521254 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1JavaValidateModel.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.v1.V1BaseValidateModel; +import org.switchyard.validate.config.model.JavaValidateModel; + +/** + * A version 1 JavaValidateModel. + * + * @author Tomohisa Igarashi + */ +public class V1JavaValidateModel extends V1BaseValidateModel implements JavaValidateModel { + + /** + * Constructs a new V1JavaValidateModel. + * @param namespace namespace + */ + public V1JavaValidateModel(String namespace) { + super(new QName(namespace, ValidateModel.VALIDATE + '.' + JAVA)); + } + + /** + * Constructs a new V1JavaValidateModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1JavaValidateModel(Configuration config, Descriptor desc) { + super(config, desc); + } + + /** + * {@inheritDoc} + */ + @Override + public String getClazz() { + return getModelAttribute(CLASS); + } + + /** + * {@inheritDoc} + */ + @Override + public JavaValidateModel setClazz(String clazz) { + setModelAttribute(CLASS, clazz); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public String getBean() { + return getModelAttribute(BEAN); + } + + /** + * {@inheritDoc} + */ + @Override + public JavaValidateModel setBean(String bean) { + setModelAttribute(BEAN, bean); + return this; + } + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1SchemaCatalogsModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1SchemaCatalogsModel.java new file mode 100644 index 000000000..5342ce49e --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1SchemaCatalogsModel.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.v1; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.validate.config.model.FileEntryModel; +import org.switchyard.validate.config.model.SchemaCatalogsModel; + +/** + * A version 1 SchemaCatalogsModel. + */ +public class V1SchemaCatalogsModel extends BaseModel implements SchemaCatalogsModel { + + private List _entries = new ArrayList(); + + /** + * Constructs a new V1SchemaCatalogsModel. + * @param namespace namespace + */ + public V1SchemaCatalogsModel(String namespace) { + super(new QName(namespace, SchemaCatalogsModel.SCHEMA_CATALOGS)); + } + + /** + * Constructs a new V1SchemaCatalogsModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1SchemaCatalogsModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration entryConfig : config.getChildrenStartsWith(FileEntryModel.ENTRY)) { + FileEntryModel entry = (FileEntryModel)readModel(entryConfig); + if (entry != null) { + _entries.add(entry); + } + } + setModelChildrenOrder(FileEntryModel.ENTRY); + } + + /** + * {@inheritDoc} + */ + @Override + public List getEntries() { + return _entries; + } + + /** + * {@inheritDoc} + */ + @Override + public SchemaCatalogsModel addEntry(FileEntryModel entry) { + addChildModel(entry); + _entries.add(entry); + return this; + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1SchemaFilesModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1SchemaFilesModel.java new file mode 100644 index 000000000..8e5b63240 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1SchemaFilesModel.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.v1; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseModel; +import org.switchyard.config.model.Descriptor; +import org.switchyard.validate.config.model.FileEntryModel; +import org.switchyard.validate.config.model.SchemaFilesModel; + +/** + * A version 1 SchemaFilesModel. + */ +public class V1SchemaFilesModel extends BaseModel implements SchemaFilesModel { + + private List _entries = new ArrayList(); + + /** + * Constructs a new V1SchemaCatalogsModel. + * @param namespace namespace + */ + public V1SchemaFilesModel(String namespace) { + super(new QName(namespace, SchemaFilesModel.SCHEMA_FILES)); + } + + /** + * Constructs a new V1SchemaFilesModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1SchemaFilesModel(Configuration config, Descriptor desc) { + super(config, desc); + for (Configuration entryConfig : config.getChildrenStartsWith(FileEntryModel.ENTRY)) { + FileEntryModel entry = (FileEntryModel)readModel(entryConfig); + if (entry != null) { + _entries.add(entry); + } + } + setModelChildrenOrder(FileEntryModel.ENTRY); + } + + /** + * {@inheritDoc} + */ + @Override + public List getEntries() { + return _entries; + } + + /** + * {@inheritDoc} + */ + @Override + public SchemaFilesModel addEntry(FileEntryModel entry) { + addChildModel(entry); + _entries.add(entry); + return this; + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1ValidateMarshaller.java b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1ValidateMarshaller.java new file mode 100644 index 000000000..12182d2e9 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1ValidateMarshaller.java @@ -0,0 +1,69 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.v1; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.BaseMarshaller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.validate.config.model.FileEntryModel; +import org.switchyard.validate.config.model.JavaValidateModel; +import org.switchyard.validate.config.model.SchemaCatalogsModel; +import org.switchyard.validate.config.model.SchemaFilesModel; +import org.switchyard.validate.config.model.XmlValidateModel; + +/** + * Marshalls validate Models. + * + * @author Tomohisa Igarashi + */ +public class V1ValidateMarshaller extends BaseMarshaller { + + private static final String VALIDATE_JAVA = ValidateModel.VALIDATE + "." + JavaValidateModel.JAVA; + private static final String VALIDATE_XML = ValidateModel.VALIDATE + "." + XmlValidateModel.XML; + + /** + * Constructs a new V1ValidateMarshaller with the specified Descriptor. + * @param desc the Descriptor + */ + public V1ValidateMarshaller(Descriptor desc) { + super(desc); + } + + /** + * {@inheritDoc} + */ + @Override + public Model read(Configuration config) { + String name = config.getName(); + Descriptor desc = getDescriptor(); + + if (name.equals(VALIDATE_JAVA)) { + return new V1JavaValidateModel(config, desc); + } else if (name.equals(VALIDATE_XML)) { + return new V1XmlValidateModel(config, desc); + } else if (name.equals(SchemaFilesModel.SCHEMA_FILES)) { + return new V1SchemaFilesModel(config, desc); + } else if (name.equals(SchemaCatalogsModel.SCHEMA_CATALOGS)) { + return new V1SchemaCatalogsModel(config, desc); + } else if (name.equals(FileEntryModel.ENTRY)) { + return new V1FileEntryModel(config, desc); + } + + return null; + } + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1XmlValidateModel.java b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1XmlValidateModel.java new file mode 100644 index 000000000..597b402c2 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/config/model/v1/V1XmlValidateModel.java @@ -0,0 +1,156 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.v1; + +import javax.xml.namespace.QName; + +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.v1.V1BaseValidateModel; +import org.switchyard.validate.config.model.SchemaCatalogsModel; +import org.switchyard.validate.config.model.SchemaFilesModel; +import org.switchyard.validate.config.model.XmlSchemaType; +import org.switchyard.validate.config.model.XmlValidateModel; +import org.switchyard.validate.internal.ValidatorFactoryClass; +import org.switchyard.validate.xml.internal.XmlValidatorFactory; + +/** + * A version 1 XmlValidateModel. + * + * @author Tomohisa Igarashi + */ +@ValidatorFactoryClass(XmlValidatorFactory.class) +public class V1XmlValidateModel extends V1BaseValidateModel implements XmlValidateModel { + + private SchemaFilesModel _schemaList; + private SchemaCatalogsModel _catalogList; + + /** + * Constructs a new V1XmlValidateModel. + * @param namespace namespace + */ + public V1XmlValidateModel(String namespace) { + super(new QName(namespace, ValidateModel.VALIDATE + '.' + XML)); + } + + /** + * Constructs a new V1XmlValidateModel with the specified Configuration and Descriptor. + * @param config the Configuration + * @param desc the Descriptor + */ + public V1XmlValidateModel(Configuration config, Descriptor desc) { + super(config, desc); + setModelChildrenOrder(SchemaFilesModel.SCHEMA_FILES, SchemaCatalogsModel.SCHEMA_CATALOGS); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean failOnWarning() { + String fow = getModelAttribute(FAIL_ON_WARNING); + return Boolean.parseBoolean(fow); + } + + /** + * {@inheritDoc} + */ + @Override + public XmlValidateModel setFailOnWarning(boolean failOnWarning) { + setModelAttribute(FAIL_ON_WARNING, Boolean.toString(failOnWarning)); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean namespaceAware() { + String na = getModelAttribute(NAMESPACE_AWARE); + return Boolean.parseBoolean(na); + } + + /** + * {@inheritDoc} + */ + @Override + public XmlValidateModel setNamespaceAware(boolean namespaceAware) { + setModelAttribute(NAMESPACE_AWARE, Boolean.toString(namespaceAware)); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SchemaFilesModel getSchemaFiles() { + if (_schemaList == null) { + _schemaList = (SchemaFilesModel)getFirstChildModelStartsWith(SchemaFilesModel.SCHEMA_FILES); + } + return _schemaList; + } + + /** + * {@inheritDoc} + */ + @Override + public XmlValidateModel setSchemaFiles(SchemaFilesModel schemas) { + setChildModel(schemas); + _schemaList = schemas; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public SchemaCatalogsModel getSchemaCatalogs() { + if (_catalogList == null) { + _catalogList = (SchemaCatalogsModel)getFirstChildModelStartsWith(SchemaCatalogsModel.SCHEMA_CATALOGS); + } + return _catalogList; + } + + /** + * {@inheritDoc} + */ + @Override + public XmlValidateModel setSchemaCatalogs(SchemaCatalogsModel catalogs) { + setChildModel(catalogs); + _catalogList = catalogs; + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public XmlSchemaType getSchemaType() { + String type = getModelAttribute(SCHEMA_TYPE); + return type != null ? XmlSchemaType.valueOf(type) : null; + } + + /** + * {@inheritDoc} + */ + @Override + public XmlValidateModel setSchemaType(XmlSchemaType type) { + if (type != null) { + setModelAttribute(SCHEMA_TYPE, type.toString()); + } + return this; + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/internal/DuplicateValidatorException.java b/core/validate/src/main/java/org/switchyard/validate/internal/DuplicateValidatorException.java new file mode 100644 index 000000000..3c3aa3924 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/internal/DuplicateValidatorException.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.internal; + +import org.switchyard.SwitchYardException; + +/** + * A DuplicateValidatorException is thrown by SwitchYard when a duplicate validator + * is trying to be registered for a 'name' type for which there already exists + * a validator in the validator registry. + * + * @author Tomohisa Igarashi + */ +public class DuplicateValidatorException extends SwitchYardException { + + /** + * Serial version unique id. + */ + private static final long serialVersionUID = -8937972965502786027L; + + /** + * Public constructor. + * @param message Exception message. + */ + public DuplicateValidatorException(final String message) { + super(message); + } + + /** + * Public constructor. + * @param message Exception message. + * @param cause Throwable cause. + */ + public DuplicateValidatorException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/internal/ValidateLogger.java b/core/validate/src/main/java/org/switchyard/validate/internal/ValidateLogger.java new file mode 100644 index 000000000..b77d15583 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/internal/ValidateLogger.java @@ -0,0 +1,74 @@ +package org.switchyard.validate.internal; + +import static org.jboss.logging.Logger.Level.WARN; + +import org.jboss.logging.Logger; +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; + +/** + *

+ * This file is using the subset 17000-17199 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface ValidateLogger { + /** + * Default root logger. + */ + ValidateLogger ROOT_LOGGER = Logger.getMessageLogger(ValidateLogger.class, ValidateLogger.class.getPackage().getName()); + + /** + * schemaCatalogNotLocated method definition. + * @param file file + */ + @LogMessage(level = WARN) + @Message(id = 17000, value = "Schema catalog %s could not be located. Ignoring.") + void schemaCatalogNotLocated(String file); + + /** + * schemaFileNotLocated method definition. + * @param file file + */ + @LogMessage(level = WARN) + @Message(id = 17001, value = "Schema file %s could not be located. Ignoring.") + void schemaFileNotLocated(String file); + + /** + * warningDuringValidation method definition. + * @param warning warning + */ + @LogMessage(level = WARN) + @Message(id = 17002, value = "Warning during validation: %s") + void warningDuringValidation(String warning); + + /** + * schemaCatalogNotParsed method definition. + * @param file file + * @param msg message + */ + @LogMessage(level = WARN) + @Message(id = 17003, value = "Schema catalog %s could not be parsed. Ignoring: %s") + void schemaCatalogNotParsed(String file, String msg); + + /** + * malformedURLDuringResolution method definition. + * @param resolved file + */ + @LogMessage(level = WARN) + @Message(id = 17004, value = "Could not create URL for file : %s") + void malformedURLDuringResolution(String resolved); + + /** + * openStreamIssue method definition. + * @param file file + */ + @LogMessage(level = WARN) + @Message(id = 17005, value = "Schema catalog %s could not be parsed.") + void openStreamIssue(String file); + + + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/internal/ValidateMessages.java b/core/validate/src/main/java/org/switchyard/validate/internal/ValidateMessages.java new file mode 100644 index 000000000..dbce742aa --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/internal/ValidateMessages.java @@ -0,0 +1,230 @@ +package org.switchyard.validate.internal; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; + +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Cause; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 17200-17399 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface ValidateMessages { + /** + * Default messages. + */ + ValidateMessages MESSAGES = Messages.getBundle(ValidateMessages.class); + + /** + * nullValidatorRegistryArgument method definition. + * @return IllegalArgumentException + */ + @Message(id=17200, value = "Null 'validatorRegistry' argument.") + IllegalArgumentException nullValidatorRegistryArgument(); + + /** + * errorReadingValidator method definition. + * @param validatesXML validatesXML + * @param ioe ioe + * @return SwitchYardException + */ + @Message(id=17201, value = "Error reading out-of-the-box Validator configurations from classpath (%s).") + SwitchYardException errorReadingValidator(String validatesXML, @Cause IOException ioe); + + /** + * failedToRegisterValidator method definition. + * @param validator validator + * @param registeredValidator registeredValidator + * @return DuplicateValidatorException + */ + @Message(id=17202, value = "Failed to register Validator '%s'. A Validator for these types " + + "is already registered: '%s'.") + DuplicateValidatorException failedToRegisterValidator(String validator, String registeredValidator); + + /** + * cdiBeanManagerNotFound method definition. + * @return SwitchYardException + */ + @Message(id=17203, value = "CDI BeanManager couldn't be found. A Java validator class name must be specified if CDI is not enabled.") + SwitchYardException cdiBeanManagerNotFound(); + + /** + * validatorBeanNotFound method definition. + * @param validatorBean validatorBean + * @return SwitchYardException + */ + @Message(id=17204, value = "The Java validator bean '%s' couldn't be found in CDI registry.") + SwitchYardException validatorBeanNotFound(String validatorBean); + + /** + * beanOrClassRequired method definition. + * @return SwitchYardException + */ + @Message(id=17205, value = "'bean' or 'class' must be specified for Java validator definition.") + SwitchYardException beanOrClassRequired(); + + /** + * errorConstructingValidator method definition. + * @param className className + * @param e e + * @return SwitchYardException + */ + @Message(id=17206, value = "Error constructing Validator instance for class '%s'.") + SwitchYardException errorConstructingValidator(String className, @Cause Exception e); + + /** + * unknownValidateModel method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id=17207, value = "Unknown ValidateModel type '%s'.") + SwitchYardException unknownValidateModel(String className); + + /** + * invalidValidatorClass method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id=17208, value = "Invalid Validator class '%s'. Must implement the Validator interface, or have methods annotated with the @Validator annotation.") + SwitchYardException invalidValidatorClass(String className); + + /** + * errorConstructingValidatorConstructorRequired method definition. + * @param className className + * @param e e + * @return SwitchYardException + */ + @Message(id=17209, value = "Error constructing Validator instance for class '%s'. Class must have a public default constructor.") + SwitchYardException errorConstructingValidatorConstructorRequired(String className, @Cause Exception e); + + /** + * errorConstructingValidatorClassNotSupported method definition. + * @param className className + * @param typeName typeName + * @return SwitchYardException + */ + @Message(id=17210, value = "Error constructing Validator instance for class '%s'. Class does not support a validation for type '%s'.") + SwitchYardException errorConstructingValidatorClassNotSupported(String className, String typeName); + + /** + * errorConstructingValidatorMustHavePublicConstructor method definition. + * @param className className + * @param e e + * @return SwitchYardException + */ + @Message(id=17211, value = "Error constructing Validator instance for class '%s'. Class must have a public default constructor.") + SwitchYardException errorConstructingValidatorMustHavePublicConstructor(String className, @Cause Exception e); + + /** + * invalidMethodSignatureMustReturnValidationResult method definition. + * @param methodName methodName + * @param className className + * @return SwitchYardException + */ + @Message(id=17212, value = "Invalid method signature: @Validator method '%s' on class '%s' must return org.switchyard.validate.ValidationResult.") + SwitchYardException invalidMethodSignatureMustReturnValidationResult(String methodName, String className); + + /** + * errorExecutingValidatorInvocationTargetException method definition. + * @param method method + * @param className className + * @param ite ite + * @return SwitchYardException + */ + @Message(id=17213, value = "Error executing @Validator method '%s' on class '%s'.") + SwitchYardException errorExecutingValidatorInvocationTargetException(String method, String className, + @Cause InvocationTargetException ite); + + /** + * errorExecutingValidatorException method definition. + * @param method method + * @param className className + * @param ite ite + * @return SwitchYardException + */ + @Message(id=17214, value = "Error executing @Validator method '%s' on class '%s'.") + SwitchYardException errorExecutingValidatorException(String method, String className, + @Cause Exception ite); + + /** + * invalidValidatorOneParameter method definition. + * @param methodName methodName + * @param className className + * @return SwitchYardException + */ + @Message(id=17215, value = "Invalid @Validator method '%s' on class '%s'. Must have exactly 1 parameter.") + SwitchYardException invalidValidatorOneParameter(String methodName, String className); + + /** + * validateModelNotAnnotated method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id=17216, value = "ValidateModel type '%s' is not annotated with an @ValidatorFactoryClass annotation.") + SwitchYardException validateModelNotAnnotated(String className); + + /** + * invalidValidatorFactoryImplementation method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id=17217, value = "Invalid ValidatorFactory implementation. Must implement '%s'.") + SwitchYardException invalidValidatorFactoryImplementation(String className); + + /** + * failedToInstantiateValidatorFactory method definition. + * @param className className + * @return SwitchYardException + */ + @Message(id=17218, value = "Failed to create an instance of ValidatorFactory '%s'. Class must have a public default constructor and not be abstract.") + SwitchYardException failedToInstantiateValidatorFactory(String className); + + /** + * couldNotInstantiateXmlValidator method definition. + * @return SwitchYardException + */ + @Message(id=17219, value = "Could not instantiate XmlValidator: schemaType must be specified.") + SwitchYardException couldNotInstantiateXmlValidator(); + + /** + * couldNotInstantiateXmlValidatorBadSchemaType method definition. + * @param schemaType schemaType + * @param values values + * @return SwitchYardException + */ + @Message(id=17220, value = "Could not instantiate XmlValidator: schemaType '%s' is invalid." + + "It must be the one of %s.") + SwitchYardException couldNotInstantiateXmlValidatorBadSchemaType(String schemaType, String values); + + /** + * schemaFileMustBeSpecified method definition. + * @param schemaType schemaType + * @return SwitchYardException + */ + @Message(id=17221, value = "Schema file must be specified for %s validation.") + SwitchYardException schemaFileMustBeSpecified(String schemaType); + + /** + * noValidSchemaFileFound method definition. + * @return SwitchYardException + */ + @Message(id=17222, value = "No valid schema file was found.") + SwitchYardException noValidSchemaFileFound(); + + /** + * nullValidatorRegistryArgument method definition. + * @param fileEntryModel fileEntryModel + * @return IllegalArgumentException + */ + @Message(id=17223, value = "Please check the switchyard validator configuration. No DTD file is specified : %s") + IOException noDTDFile(String fileEntryModel); + + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorFactory.java b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorFactory.java new file mode 100644 index 000000000..386993133 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorFactory.java @@ -0,0 +1,36 @@ +package org.switchyard.validate.internal; +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.validate.Validator; + +/** + * Validator Factory. + * + * @author Tomohisa Igarashi + * + * @param ValidatorModel type. + */ +public interface ValidatorFactory { + + /** + * Create a new {@link Validator} instance. + * @param model The Validator config model. + * @return The Validator instance. + */ + Validator newValidator(T model); +} diff --git a/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorFactoryClass.java b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorFactoryClass.java new file mode 100644 index 000000000..1aa15ab55 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorFactoryClass.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.internal; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Transformer factory class annotation. + * + * @author Tomohisa Igarashi + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +public @interface ValidatorFactoryClass { + + /** + * The component factory class. + */ + Class value(); +} diff --git a/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorRegistryLoader.java b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorRegistryLoader.java new file mode 100644 index 000000000..819e96538 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorRegistryLoader.java @@ -0,0 +1,142 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import org.jboss.logging.Logger; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.ValidatesModel; +import org.switchyard.validate.Validator; +import org.switchyard.validate.ValidatorRegistry; + +/** + * {@link ValidatorRegistry} loader class. + * + * @author Tomohisa Igarashi + */ +public class ValidatorRegistryLoader { + + /** + * Logger. + */ + private static Logger _log = Logger.getLogger(ValidatorRegistryLoader.class); + /** + * Classpath location for out-of-the-box validation configurations. + */ + public static final String VALIDATES_XML = "META-INF/switchyard/validates.xml"; + + /** + * Validators + */ + private List _validators = new LinkedList(); + /** + * The registry instance into which the validates were loaded. + */ + private ValidatorRegistry _validatorRegistry; + + /** + * Public constructor. + * @param validatorRegistry The registry instance. + */ + public ValidatorRegistryLoader(ValidatorRegistry validatorRegistry) { + if (validatorRegistry == null) { + throw ValidateMessages.MESSAGES.nullValidatorRegistryArgument(); + } + this._validatorRegistry = validatorRegistry; + } + + /** + * Register a set of validators in the validate registry associated with this deployment. + * @param validates The validates model. + * @throws DuplicateValidatorException an existing validator has already been registered for the from and to types + */ + public void registerValidators(ValidatesModel validates) throws DuplicateValidatorException { + if (validates == null) { + return; + } + + try { + for (ValidateModel validateModel : validates.getValidates()) { + Collection> validators = ValidatorUtil.newValidators(validateModel); + + for (Validator validator : validators) { + if (_validatorRegistry.hasValidator(validator.getName())) { + Validator registeredValidator = _validatorRegistry.getValidator(validator.getName()); + throw ValidateMessages.MESSAGES.failedToRegisterValidator(toDescription(validator), toDescription(registeredValidator)); + } + + _log.debug("Adding validator =>" + + ", Name:" + validator.getName()); + _validatorRegistry.addValidator(validator); + _validators.add(validator); + } + } + } catch (DuplicateValidatorException e) { + throw e; + } catch (RuntimeException e) { + // If there was an exception for any reason... remove all Validator instance that have + // already been registered with the domain... + unregisterValidators(); + throw e; + } + } + + /** + * Unregister all validators. + */ + public void unregisterValidators() { + for (Validator validator : _validators) { + _validatorRegistry.removeValidator(validator); + } + } + + /** + * Load the out of the box validators. + *

+ * Scans the classpath for {@link #VALIDATES_XML} runtime configuration resources. + */ + public void loadOOTBValidates() { + try { + List resources = Classes.getResources(VALIDATES_XML, getClass()); + + for (URL resource : resources) { + InputStream configStream = resource.openStream(); + + try { + ValidatesModel validatesModel = new ModelPuller().pull(configStream); + registerValidators(validatesModel); + } catch (final DuplicateValidatorException e) { + _log.debug(e.getMessage(), e); + } finally { + configStream.close(); + } + } + } catch (IOException e) { + throw ValidateMessages.MESSAGES.errorReadingValidator(VALIDATES_XML, e); + } + } + + private String toDescription(Validator validator) { + return validator.getClass().getName() + "(" + validator.getName() + ")"; + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorTypes.java b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorTypes.java new file mode 100644 index 000000000..f218edce4 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorTypes.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.validate.internal; + +import javax.xml.namespace.QName; + +/** + * Validator data types. + * + * @author Tomohisa Igarashi + */ +public class ValidatorTypes { + + private QName _name; + + /** + * Public constructor. + * + * @param name type. + */ + ValidatorTypes(QName name) { + this._name = name; + } + + /** + * Get name. + * + * @return name. + */ + public QName getName() { + return _name; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("%s [name=%s]", getClass().getSimpleName(), getName()); + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorUtil.java b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorUtil.java new file mode 100644 index 000000000..9b1298211 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/internal/ValidatorUtil.java @@ -0,0 +1,420 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.internal; + +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.jboss.logging.Logger; +import org.switchyard.common.cdi.CDIUtil; +import org.switchyard.common.type.Classes; +import org.switchyard.common.xml.QNameUtil; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.Validator; +import org.switchyard.validate.config.model.JavaValidateModel; + +/** + * Validator Utility methods. + * + * @author Tomohisa Igarashi + */ +public final class ValidatorUtil { + + private static final Logger LOGGER = Logger.getLogger(ValidatorUtil.class); + + private static final QName OBJECT_TYPE = JavaTypes.toMessageType(Object.class); + + private ValidatorUtil() {} + + /** + * Create a new {@link org.switchyard.validate.Validator} instance from the supplied {@link ValidateModel} instance. + * @param validateModel The ValidateModel instance. + * @return The Validator instance. + */ + public static Validator newValidator(ValidateModel validateModel) { + return newValidators(validateModel).iterator().next(); + } + + /** + * Create a Collection of {@link Validator} instances from the supplied {@link ValidateModel} instance. + * @param validateModel The ValidateModel instance. + * @return The Validator instance. + */ + public static Collection> newValidators(ValidateModel validateModel) { + + Collection> validators = null; + + if (validateModel instanceof JavaValidateModel) { + JavaValidateModel javaValidateModel = JavaValidateModel.class.cast(validateModel); + String bean = javaValidateModel.getBean(); + if (bean != null) { + if (CDIUtil.lookupBeanManager() == null) { + throw ValidateMessages.MESSAGES.cdiBeanManagerNotFound(); + } + Object validator = CDIUtil.lookupBean(bean); + if (validator == null) { + throw ValidateMessages.MESSAGES.validatorBeanNotFound(bean); + } + validators = newValidators(validator, validateModel.getName()); + + } else { + String className = ((JavaValidateModel) validateModel).getClazz(); + if (className == null) { + throw ValidateMessages.MESSAGES.beanOrClassRequired(); + } + try { + Class validateClass = Classes.forName(className, ValidatorUtil.class); + validators = newValidators(validateClass, validateModel.getName()); + } catch (Exception e) { + throw ValidateMessages.MESSAGES.errorConstructingValidator(className, e); + } + } + } else { + ValidatorFactory factory = newValidatorFactory(validateModel); + + validators = new ArrayList>(); + validators.add(factory.newValidator(validateModel)); + } + + if (validators == null || validators.isEmpty()) { + throw ValidateMessages.MESSAGES.unknownValidateModel(validateModel.getClass().getName()); + } + + return validators; + } + + /** + * Create a new {@link org.switchyard.validate.Validator} instance from the supplied + * Class and supporting the specified name. + * @param clazz The Class representing the Validator. + * @param name The name of type. + * @return The collection of Validator instances. + * @see #isValidator(Class) + */ + public static Validator newValidator(Class clazz, QName name) { + return newValidators(clazz, name).iterator().next(); + } + + /** + * Create a Collection of {@link Validator} instances from the supplied + * Class and supporting the specified name. + * @param clazz The Class representing the Validator. + * @param name The name of type. + * @return The collection of Validator instances. + * @see #isValidator(Class) + */ + public static Collection> newValidators(Class clazz, QName name) { + if (!isValidator(clazz)) { + throw ValidateMessages.MESSAGES.invalidValidatorClass(clazz.getName()); + } + + final Object validatorObject; + + try { + validatorObject = clazz.newInstance(); + } catch (Exception e) { + throw ValidateMessages.MESSAGES.errorConstructingValidatorConstructorRequired(clazz.getName(), e); + } + + return newValidators(validatorObject, name); + } + + /** + * Create a Collection of {@link Validator} instances from the supplied + * object and supporting the specified name. + * @param validatorObject The Validator instance + * @param name The name of type. + * @return The collection of Validator instances. + * @see #isValidator(Class) + */ + public static Collection> newValidators(Object validatorObject, QName name) { + boolean nameIsWild = isWildcardType(name); + Collection> validators = new ArrayList>(); + + Method[] publicMethods = validatorObject.getClass().getMethods(); + for (Method publicMethod : publicMethods) { + org.switchyard.annotations.Validator validatorAnno = publicMethod.getAnnotation(org.switchyard.annotations.Validator.class); + if (validatorAnno != null) { + ValidatorMethod validatorMethod = toValidatorMethod(publicMethod, validatorAnno); + + if ((nameIsWild || validatorMethod.getName().equals(name))) { + validators.add(newValidator(validatorObject, validatorMethod.getMethod(), validatorMethod.getName())); + } + } + } + + if (validatorObject instanceof Validator) { + Validator validator = (Validator) validatorObject; + QName vldName = validator.getName(); + + if (vldName.equals(OBJECT_TYPE)) { + // Type info not specified on validator, so assuming it's a generic/multi-type validator... + validators.add(validator); + } else if ((nameIsWild || vldName.equals(name))) { + // Matching (specific) or wildcard type info specified... + validators.add(validator); + } else if (isAssignableFrom(vldName, name)) { + // Compatible Java types... + validators.add(validator); + } + + if (!nameIsWild) { + validator.setName(name); + } + } + + if (validators.isEmpty()) { + throw ValidateMessages.MESSAGES.errorConstructingValidatorClassNotSupported(validatorObject.getClass().getName(), + name.toString()); + } + + return validators; + } + + /** + * Create a list of all the possible validations that the supplied Class offers. + * @param clazz The Class to be analyzed. + * @return A Map containing the validation types, with the key/value representing the to/from. + */ + public static List listValidations(Class clazz) { + Object validatorObject; + List validations = new ArrayList(); + + try { + validatorObject = clazz.newInstance(); + } catch (Exception e) { + throw ValidateMessages.MESSAGES.errorConstructingValidatorMustHavePublicConstructor(clazz.getName(), e); + } + + // If the class itself implements the Validator interface.... + if (validatorObject instanceof org.switchyard.validate.Validator) { + QName name = ((Validator) validatorObject).getName(); + if (name != null) { + ValidatorTypes validatorTypes = new ValidatorTypes(name); + validations.add(validatorTypes); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("added: " + validatorTypes); + } + } + } + + // If some of the class methods are annotated with the @Validator annotation... + Method[] publicMethods = clazz.getMethods(); + for (Method publicMethod : publicMethods) { + org.switchyard.annotations.Validator validatorAnno = publicMethod.getAnnotation(org.switchyard.annotations.Validator.class); + if (validatorAnno != null) { + ValidatorMethod validatorMethod = toValidatorMethod(publicMethod, validatorAnno); + ValidatorTypes validatorTypes= new ValidatorTypes(validatorMethod.getName()); + validations.add(validatorTypes); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("added: " + validatorTypes); + } + } + } + + Collections.sort(validations, new ValidatorTypesComparator()); + if (LOGGER.isDebugEnabled()) { + for (ValidatorTypes validatorTypes : validations) { + LOGGER.debug("sorted: " + validatorTypes); + } + } + + return validations; + } + + /** + * Is the supplied Class a SwitchYard Validator class. + *

+ * A SwitchYard Validator class is any class that either implements the {@link org.switchyard.validate.Validator} + * interface, or has one or more methods annotated with the {@link org.switchyard.annotations.Validator @Validator} annotation. + * + * @param clazz The Class instance. + * @return True if the class can be used as a SwitchYard Validator, otherwise false. + */ + public static boolean isValidator(Class clazz) { + if (clazz.isInterface()) { + return false; + } + if (clazz.isAnnotation()) { + return false; + } + if (Modifier.isAbstract(clazz.getModifiers())) { + return false; + } + try { + // Must have a default constructor... + clazz.getConstructor(); + } catch (NoSuchMethodException e) { + return false; + } + if (org.switchyard.validate.Validator.class.isAssignableFrom(clazz)) { + return true; + } + + Method[] publicMethods = clazz.getMethods(); + for (Method publicMethod : publicMethods) { + if (publicMethod.isAnnotationPresent(org.switchyard.annotations.Validator.class)) { + return true; + } + } + + return false; + } + + private static Validator newValidator(final Object validatorObject, final Method publicMethod, QName name) { + if (!ValidationResult.class.isAssignableFrom(publicMethod.getReturnType())) { + throw ValidateMessages.MESSAGES.invalidMethodSignatureMustReturnValidationResult(publicMethod.getName(), + publicMethod.getDeclaringClass().getName()); + } + + Validator validator = new BaseValidator(name) { + @Override + public ValidationResult validate(Object subject) { + try { + return ValidationResult.class.cast(publicMethod.invoke(validatorObject, subject)); + } catch (InvocationTargetException e) { + throw ValidateMessages.MESSAGES.errorExecutingValidatorInvocationTargetException(publicMethod.getName(), + publicMethod.getDeclaringClass().getName(), e); + } catch (Exception e) { + throw ValidateMessages.MESSAGES.errorExecutingValidatorException(publicMethod.getName(), + publicMethod.getDeclaringClass().getName(), e); + } + } + + @Override + public Class getType() { + return publicMethod.getParameterTypes()[0]; + } + }; + + return validator; + } + + private static boolean isAssignableFrom(QName a, QName b) { + if (QNameUtil.isJavaMessageType(a) && QNameUtil.isJavaMessageType(b)) { + Class aType = QNameUtil.toJavaMessageType(a); + Class bType = QNameUtil.toJavaMessageType(b); + + if (aType == null || bType == null) { + return false; + } + + return aType.isAssignableFrom(bType); + } + + return false; + } + + private static boolean isWildcardType(QName type) { + return type.toString().equals("*"); + } + + private static ValidatorMethod toValidatorMethod(Method publicMethod, org.switchyard.annotations.Validator validatorAnno) { + + QName name; + Class type; + + Class[] params = publicMethod.getParameterTypes(); + if (params.length != 1) { + throw ValidateMessages.MESSAGES.invalidValidatorOneParameter(publicMethod.getName(), + publicMethod.getDeclaringClass().getName()); + } + type = params[0]; + + if (!validatorAnno.name().trim().equals("")) { + name = QName.valueOf(validatorAnno.name().trim()); + } else { + name = JavaTypes.toMessageType(type); + } + + return new ValidatorMethod(name, publicMethod); + } + + private static ValidatorFactory newValidatorFactory(ValidateModel validateModel) { + ValidatorFactoryClass validatorFactoryClass = validateModel.getClass().getAnnotation(ValidatorFactoryClass.class); + + if (validatorFactoryClass == null) { + throw ValidateMessages.MESSAGES.validateModelNotAnnotated(validateModel.getClass().getName()); + } + + Class factoryClass = validatorFactoryClass.value(); + + if (!org.switchyard.validate.internal.ValidatorFactory.class.isAssignableFrom(factoryClass)) { + throw ValidateMessages.MESSAGES.invalidValidatorFactoryImplementation(org.switchyard.validate.internal.ValidatorFactory.class.getName()); + } + + try { + return (org.switchyard.validate.internal.ValidatorFactory) factoryClass.newInstance(); + } catch (Exception e) { + throw ValidateMessages.MESSAGES.failedToInstantiateValidatorFactory(factoryClass.getName()); + } + } + + private static class ValidatorMethod extends ValidatorTypes { + + private Method _method; + + /** + * Public constructor. + * + * @param name name of type. + * @param publicMethod + */ + ValidatorMethod(QName name, Method publicMethod) { + super(name); + this._method = publicMethod; + } + + private Method getMethod() { + return _method; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return String.format("%s [name=%s, method=%s]", getClass().getSimpleName(), getName(), getMethod()); + } + } + + private static final class ValidatorTypesComparator implements Comparator, Serializable { + /** + * {@inheritDoc} + */ + @Override + public int compare(ValidatorTypes vt1, ValidatorTypes vt2) { + int c = String.valueOf(vt1.getName()).compareTo(String.valueOf(vt2.getName())); + if (c == 0 && vt1 instanceof ValidatorMethod && vt2 instanceof ValidatorMethod) { + ValidatorMethod vm1 = (ValidatorMethod)vt1; + ValidatorMethod vm2 = (ValidatorMethod)vt2; + c = String.valueOf(vm1.getMethod()).compareTo(String.valueOf(vm2.getMethod())); + } + return c; + } + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidator.java b/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidator.java new file mode 100644 index 000000000..d989f0985 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidator.java @@ -0,0 +1,593 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.xml.internal; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.jboss.logging.Logger; +import org.apache.xml.resolver.CatalogManager; +import org.apache.xml.resolver.tools.CatalogResolver; +import org.switchyard.Message; +import org.switchyard.SwitchYardException; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.Scannable; +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.config.model.FileEntryModel; +import org.switchyard.validate.config.model.XmlSchemaType; +import org.switchyard.validate.config.model.XmlValidateModel; +import org.switchyard.validate.internal.ValidateLogger; +import org.switchyard.validate.internal.ValidateMessages; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSResourceResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.DefaultHandler; + +/** + * XML Validator {@link org.switchyard.validate.Validator}. + * + * @author Tomohisa Igarashi + */ +@Scannable(false) +public class XmlValidator extends BaseValidator { + + private static final Logger LOGGER = Logger.getLogger(XmlValidator.class); + private XmlSchemaType _schemaType; + private String _schemaTypeUri; + private boolean _failOnWarning; + private boolean _isNamespaceAware; + private List _schemaConfig; + private List _catalogConfig; + private SAXParserFactory _parserFactory; + private XmlValidatorCatalogResolver _catalogResolver; + private XmlValidatorDTDResolver _dtdResolver; + private List _schemaFileNames = new ArrayList(); + private List _catalogFileNames = new ArrayList(); + + /** + * constructor. + * @param name name + * @param model model + */ + public XmlValidator(QName name, XmlValidateModel model) { + super(name); + + _schemaType = model.getSchemaType(); + if (_schemaType == null) { + throw ValidateMessages.MESSAGES.couldNotInstantiateXmlValidator(); + } + + switch(_schemaType) { + case DTD: + _schemaTypeUri = XMLConstants.XML_DTD_NS_URI; + break; + case XML_SCHEMA: + _schemaTypeUri = XMLConstants.W3C_XML_SCHEMA_NS_URI; + break; + case RELAX_NG: + _schemaTypeUri = XMLConstants.RELAXNG_NS_URI; + break; + default: + StringBuilder builder = new StringBuilder(); + for (XmlSchemaType s : XmlSchemaType.values()) { + builder.append(s.name() + ", "); + } + if (builder.length() >= 2) { + builder.delete(builder.length()-2, builder.length()); + } + throw ValidateMessages.MESSAGES.couldNotInstantiateXmlValidatorBadSchemaType(_schemaType.toString(), + builder.toString()); + } + + _failOnWarning = model.failOnWarning(); + _isNamespaceAware = model.namespaceAware(); + if (model.getSchemaFiles() != null) { + _schemaConfig = model.getSchemaFiles().getEntries(); + } + if (model.getSchemaCatalogs() != null) { + _catalogConfig = model.getSchemaCatalogs().getEntries(); + } + + setup(); + } + + protected void setup() { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(new StringBuffer("Setting up XmlValidator:[").append(formatUnparsedConfigs()).append("]")); + } + + _parserFactory = SAXParserFactory.newInstance(); + _parserFactory.setXIncludeAware(true); + _parserFactory.setNamespaceAware(_isNamespaceAware); + + if (_catalogConfig != null) { + List foundCatalogs = new ArrayList(); + for (FileEntryModel entry : _catalogConfig) { + URL located = locateFile(entry.getFile()); + if (located != null) { + foundCatalogs.add(located); + } else { + ValidateLogger.ROOT_LOGGER.schemaCatalogNotLocated(entry.getFile()); + } + } + if (foundCatalogs.size() > 0) { + CatalogManager manager = new CatalogManager(); + manager.setIgnoreMissingProperties(true); + manager.setAllowOasisXMLCatalogPI(true); + manager.setPreferPublic(true); + manager.setRelativeCatalogs(false); + manager.setUseStaticCatalog(false); + manager.setVerbosity(0); + _catalogResolver = new XmlValidatorCatalogResolver(manager); + _catalogResolver.namespaceAware = _isNamespaceAware; + + _catalogFileNames = new ArrayList(); + for (URL catalog : foundCatalogs) { + try { + _catalogResolver.getCatalog().parseCatalog(catalog); + _catalogFileNames.add(catalog.toString()); + } catch (Exception e) { + ValidateLogger.ROOT_LOGGER.schemaCatalogNotParsed(catalog.toString(), e.getMessage()); + } + } + } + } + + if (XMLConstants.XML_DTD_NS_URI.equals(_schemaTypeUri)) { + // set up for DTD validation - DTD file is located by DOCTYPE element in the Document itself + _parserFactory.setValidating(true); + + if (_schemaConfig != null) { + for (FileEntryModel entry : _schemaConfig) { + if (entry.getFile() != null) { + _schemaFileNames.add(entry.getFile()); + } + } + } + + _dtdResolver = new XmlValidatorDTDResolver(_schemaFileNames); + } else { + // setup for XML Schema or Relax NG validation + if (_schemaConfig == null) { + throw ValidateMessages.MESSAGES.schemaFileMustBeSpecified(_schemaType.toString()); + } + + SchemaFactory schemaFactory = SchemaFactory.newInstance(_schemaTypeUri); + if (_catalogResolver != null) { + schemaFactory.setResourceResolver(_catalogResolver); + } + + List foundSchemas = new ArrayList(); + for (FileEntryModel entry : _schemaConfig) { + URL located = locateFile(entry.getFile()); + if (located != null) { + _schemaFileNames.add(located.toString()); + foundSchemas.add(new StreamSource(located.toExternalForm())); + } else { + ValidateLogger.ROOT_LOGGER.schemaFileNotLocated(entry.getFile()); + } + } + + _dtdResolver = new XmlValidatorDTDResolver(_schemaFileNames); + + if (foundSchemas.size() == 0) { + throw ValidateMessages.MESSAGES.noValidSchemaFileFound(); + } + + try { + Schema schema = schemaFactory.newSchema(foundSchemas.toArray(new Source[0])); + _parserFactory.setSchema(schema); + } catch (SAXException e) { + throw new SwitchYardException(e); + } + } + } + + @Override + public ValidationResult validate(Message msg) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(new StringBuffer("Entering XML validation:[") + .append(formatUnparsedConfigs()).append(" / ").append(formatParsedConfigs()).append("]")); + } + + try { + XMLReader validatingParser = createValidatingParser(); + XmlValidationErrorHandler errorHandler = new XmlValidationErrorHandler(_failOnWarning); + validatingParser.setErrorHandler(errorHandler); + String input = msg.getContent(String.class); + + if ((_schemaFileNames != null) && (_schemaFileNames.size() > 0)) { + validatingParser.setEntityResolver(_dtdResolver); + } + + if (InputStream.class.isAssignableFrom(msg.getContent().getClass())) { + msg.setContent(new ByteArrayInputStream(input.getBytes())); + } else if (Reader.class.isAssignableFrom(msg.getContent().getClass())) { + msg.setContent(new StringReader(input)); + } + validatingParser.parse(new InputSource(new StringReader(input))); + if (errorHandler.validationFailed()) { + return invalidResult(formatErrorMessage(errorHandler.getErrors()).toString()); + } + } catch (SAXException e) { + throw new SwitchYardException(e); + } catch (ParserConfigurationException pce) { + throw new SwitchYardException(pce); + } catch (IOException ioe) { + throw new SwitchYardException(ioe); + } + return validResult(); + } + + protected XMLReader createValidatingParser() throws SAXException, ParserConfigurationException { + XMLReader validatingParser = _parserFactory.newSAXParser().getXMLReader(); + if (XMLConstants.XML_DTD_NS_URI.equals(_schemaTypeUri) && _catalogResolver != null) { + validatingParser.setEntityResolver(_catalogResolver); + } + return validatingParser; + } + + protected URL locateFile(String path) { + if (path == null) { + return null; + } + + if (new File(path).exists()) { + try { + return new File(path).toURI().toURL(); + } catch (Exception e) { + return null; + } + } else { + try { + URL res = Classes.getResource(path); + if (res != null) { + return res; + } + } catch (IOException e) { + e.getMessage(); + } + } + return null; + } + + + protected StringBuffer formatErrorMessage(List errors) { + String nl = System.getProperty("line.separator"); + StringBuffer buf = new StringBuffer().append(errors.size()).append(" validation error(s): ").append(nl); + for (Exception e : errors) { + buf.append(formatRootCause(e)).append(nl); + } + return buf; + } + + protected StringBuffer formatRootCause(Throwable t) { + Throwable cause = t; + StringBuffer buf = new StringBuffer(cause.getClass().getName()).append(": ").append(cause.getMessage()); + while ((cause = cause.getCause()) != null) { + buf.append(" --- Caused by ").append(cause.getClass().getName()).append(": ").append(cause.getMessage()); + } + return buf; + } + + protected StringBuffer formatUnparsedConfigs() { + StringBuffer buf = new StringBuffer(); + buf.append("schema type=").append(_schemaType); + if (_schemaConfig != null && _schemaConfig.size() > 0) { + buf.append(", schema files=").append(_schemaConfig.toString()); + } + if (_catalogConfig != null && _catalogConfig.size() > 0) { + buf.append(", catalogs=").append(_catalogConfig.toString()); + } + return buf; + } + + protected StringBuffer formatParsedConfigs() { + StringBuffer buf = new StringBuffer(); + buf.append("schema type=").append(_schemaType); + if (_schemaFileNames.size() > 0) { + buf.append(", schema files=").append(_schemaFileNames.toString()); + } + if (_catalogFileNames.size() > 0) { + buf.append(", catalogs=").append(_catalogFileNames.toString()); + } + return buf; + } + + protected class XmlValidationErrorHandler extends DefaultHandler { + private boolean _validationFailed; + private boolean _failOnWarning; + private List _errors = new ArrayList(); + + public XmlValidationErrorHandler(boolean failOnWarning) { + _failOnWarning = failOnWarning; + _validationFailed = false; + } + + @Override + public void fatalError(SAXParseException e) throws SAXException { + _validationFailed = true; + _errors.add(e); + } + + @Override + public void error(SAXParseException e) throws SAXException { + _validationFailed = true; + _errors.add(e); + } + + @Override + public void warning(SAXParseException e) throws SAXException { + if (_failOnWarning) { + _validationFailed = true; + _errors.add(e); + } else { + StringBuffer warning = new StringBuffer(); + warning.append(formatParsedConfigs()).append(": ").append(e.getMessage()); + ValidateLogger.ROOT_LOGGER.warningDuringValidation(warning.toString()); + } + } + + public boolean validationFailed() { + return _validationFailed; + } + + public List getErrors() { + return Collections.unmodifiableList(_errors); + } + } + + private class XmlValidatorCatalogResolver extends CatalogResolver implements LSResourceResolver { + public XmlValidatorCatalogResolver(CatalogManager manager) { + super(manager); + } + + @Override + public InputSource resolveEntity(String publicId, String systemId) { + String resolved = this.getResolvedEntity(publicId, systemId); + URL fileUrl = null; + File testFile = null; + + if (resolved != null) { + try { + fileUrl = new URL(resolved); + testFile = new File(fileUrl.getPath()); + } catch (MalformedURLException mue) { + ValidateLogger.ROOT_LOGGER.malformedURLDuringResolution(resolved); + } + } + if ((fileUrl == null) || (!testFile.exists())) { + // Check to see if the systemId has been resolved to the user directory + // If it has, strip it to the filename and attempt to resolve. + String userDir = System.getProperty("user.dir"); + if (systemId.contains(userDir)) { + File systemFile = new File(systemId); + + String systemFileName = systemFile.getName(); + fileUrl = locateFile(systemFileName); + } + } + + if (fileUrl != null) { + try { + return new InputSource(fileUrl.openStream()); + } catch (IOException ioe) { + ValidateLogger.ROOT_LOGGER.openStreamIssue(fileUrl.toString()); + } + } + return null; + } + + @Override + public LSInput resolveResource(String type, String namespaceURI, + String publicId, String systemId, String baseURI) { + return new XmlValidatorLSInput(this.resolveEntity(publicId, systemId), publicId, systemId, baseURI); + } + } + + private final class XmlValidatorLSInput implements LSInput { + + private Reader _characterStream; + private InputStream _byteStream; + private InputSource _inputSource; + private String _publicId; + private String _systemId; + private String _baseURI; + private String _encoding; + private boolean _certifiedText; + + private XmlValidatorLSInput(InputSource xsd, String publicId, String systemId, String baseURI) { + _inputSource = xsd; + setPublicId(publicId); + setSystemId(systemId); + setBaseURI(baseURI); + setEncoding("UTF-8"); + setCertifiedText(false); + } + + /** + * {@inheritDoc} + */ + @Override + public Reader getCharacterStream() { + if (_inputSource != null) { + return _inputSource.getCharacterStream(); + } else { + return _characterStream; + } + } + + /** + * {@inheritDoc} + */ + @Override + public void setCharacterStream(Reader characterStream) { + _characterStream = characterStream; + } + + /** + * {@inheritDoc} + */ + @Override + public InputStream getByteStream() { + if (_inputSource != null) { + return _inputSource.getByteStream(); + } else { + return _byteStream; + } + } + + /** + * {@inheritDoc} + */ + @Override + public void setByteStream(InputStream byteStream) { + _byteStream = byteStream; + } + + /** + * {@inheritDoc} + */ + @Override + public String getStringData() { + if (_inputSource == null) { + return null; + } + Reader r = _inputSource.getCharacterStream(); + int c; + StringBuilder buf = new StringBuilder(); + try { + while ((c = r.read()) != -1) { + buf.append((char)c); + } + } catch (Exception e) { + return null; + } + return buf.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setStringData(String stringData) { + _inputSource = new InputSource(new StringReader(stringData)); + } + + /** + * {@inheritDoc} + */ + @Override + public String getSystemId() { + return _systemId; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPublicId() { + return _publicId; + } + + /** + * {@inheritDoc} + */ + @Override + public void setPublicId(String publicId) { + _publicId = publicId; + } + + /** + * {@inheritDoc} + */ + @Override + public void setSystemId(String systemId) { + _systemId = systemId; + } + + /** + * {@inheritDoc} + */ + @Override + public String getBaseURI() { + return _baseURI; + } + + /** + * {@inheritDoc} + */ + @Override + public void setBaseURI(String baseURI) { + _baseURI = baseURI; + } + + /** + * {@inheritDoc} + */ + @Override + public String getEncoding() { + return _encoding; + } + + /** + * {@inheritDoc} + */ + @Override + public void setEncoding(String encoding) { + _encoding = encoding; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean getCertifiedText() { + return _certifiedText; + } + + /** + * {@inheritDoc} + */ + @Override + public void setCertifiedText(boolean certifiedText) { + _certifiedText = certifiedText; + } + + } + +} diff --git a/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidatorDTDResolver.java b/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidatorDTDResolver.java new file mode 100644 index 000000000..51c8f502e --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidatorDTDResolver.java @@ -0,0 +1,123 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.validate.xml.internal; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.switchyard.common.type.Classes; + +/** + * DTDResolver is an entity resolver that helps locate the DTD. + * + * @author Tom Cunningham + */ +public class XmlValidatorDTDResolver implements EntityResolver { + private List _schemaFileNames = null; + + /** + * DTDResolver constructor. + */ + public XmlValidatorDTDResolver() { + _schemaFileNames = new ArrayList(); + } + + /** + * DTDResolver constructor. + * @param schemaFileNames schemaFileNames + */ + public XmlValidatorDTDResolver(List schemaFileNames) { + this(); + + if (schemaFileNames != null) { + for (Iterator iter = schemaFileNames.iterator(); iter.hasNext();) { + String fem = iter.next(); + _schemaFileNames.add(fem); + } + } + } + + /** + * Locate the file or throw an exception. + * @param path + * @return + */ + protected URL locateFile(String path) throws IOException { + if (path == null) { + return null; + } + + if (new File(path).exists()) { + try { + return new File(path).toURI().toURL(); + } catch (Exception e) { + return null; + } + } else { + URL res = Classes.getResource(path); + if (res != null) { + return res; + } + } + return null; + } + + /* (non-Javadoc) + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + */ + @Override + public InputSource resolveEntity(String publicId, String systemId) + throws SAXException, IOException { + if (_schemaFileNames != null) { + for (Iterator iter = _schemaFileNames.iterator(); iter.hasNext();) { + String validatorFileName = iter.next(); + + URL url = null; + url = locateFile(systemId); + + if (url == null) { + // Test to see if we're dealing with a local file. If so, + // see if the directory was not specified in the file entry and + // if so try to find the file with Classes.getResource() + URL temp = new URL(systemId); + if (temp.getProtocol().equals("file")) { + File systemFile = new File(systemId); + String systemFileName = systemFile.getName(); + + File localFile = new File(validatorFileName); + if (localFile.getParentFile() == null) { + if (systemFileName.equals(validatorFileName)) { + URL res = Classes.getResource(validatorFileName); + if (res != null) { + return new InputSource(res.openStream()); + } + } + } + } + } + if (url != null) { + return new InputSource(url.openStream()); + } + } + } + return null; + } +} diff --git a/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidatorFactory.java b/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidatorFactory.java new file mode 100644 index 000000000..b9c937da4 --- /dev/null +++ b/core/validate/src/main/java/org/switchyard/validate/xml/internal/XmlValidatorFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.validate.xml.internal; + +import org.jboss.logging.Logger; +import org.switchyard.validate.Validator; +import org.switchyard.validate.config.model.XmlValidateModel; +import org.switchyard.validate.internal.ValidatorFactory; + +/** + * @author Tomohisa Igarashi + */ +public final class XmlValidatorFactory implements ValidatorFactory{ + + private static final Logger LOGGER = Logger.getLogger(XmlValidatorFactory.class); + + /** + * Create a {@link Validator} instance from the supplied {@link XmlValidateModel}. + * @param model the XML Validator model. + * @return the Transformer instance. + */ + public Validator newValidator(XmlValidateModel model) { + return new XmlValidator(model.getName(), model); + } + +} diff --git a/core/validate/src/main/resources/org/switchyard/config/model/descriptor.properties b/core/validate/src/main/resources/org/switchyard/config/model/descriptor.properties new file mode 100644 index 000000000..3ab2aae99 --- /dev/null +++ b/core/validate/src/main/resources/org/switchyard/config/model/descriptor.properties @@ -0,0 +1,32 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +vldt_1_0.section=urn:switchyard-config:validate +vldt_1_0.version=1.0 +vldt_1_0.namespace=urn:switchyard-config:validate:1.0 +vldt_1_0.schema=validate_1_0.xsd +vldt_1_0.location=/org/switchyard/validate/config/model/v1/ +vldt_1_0.marshaller=org.switchyard.validate.config.model.v1.V1ValidateMarshaller + +vldt_1_1.section=urn:switchyard-config:validate +vldt_1_1.version=1.1 +vldt_1_1.namespace=urn:switchyard-config:validate:1.1 +vldt_1_1.schema=validate_1_1.xsd +vldt_1_1.location=/org/switchyard/validate/config/model/v1/ +vldt_1_1.marshaller=org.switchyard.validate.config.model.v1.V1ValidateMarshaller + +vldt_2_0.section=urn:switchyard-config:validate +vldt_2_0.version=2.0 +vldt_2_0.namespace=urn:switchyard-config:validate:2.0 +vldt_2_0.schema=validate_2_0.xsd +vldt_2_0.location=/org/switchyard/validate/config/model/v2/ +vldt_2_0.marshaller=org.switchyard.validate.config.model.v1.V1ValidateMarshaller diff --git a/core/validate/src/main/resources/org/switchyard/validate/config/model/v1/validate_1_0.xsd b/core/validate/src/main/resources/org/switchyard/validate/config/model/v1/validate_1_0.xsd new file mode 100644 index 000000000..6b9075542 --- /dev/null +++ b/core/validate/src/main/resources/org/switchyard/validate/config/model/v1/validate_1_0.xsd @@ -0,0 +1,138 @@ + + + + + + + + + + + XML Validator Configuration. + + + + + + + + + + + + XML schema type. + + + + + + + whether a warning should be reported as an SwitchYardException or just log. default is false + + + + + + + whether the validator should be namespace aware or not. + + + + + + + + + + + Schema file configuration. + + + + + + + + + + Schema catalog configuration. + + + + + + + + + + + + + + + Generic/Custom Java Validator Configuration. + + + + + + + + The name of the Java Validator implementation class. + + + + + + + The name of the Java Validator CDI bean. + + + + + + + + + + + + + DTD. + + + + + + + W3C XML Schema. + + + + + + + RELAX NG. + + + + + + + diff --git a/core/validate/src/main/resources/org/switchyard/validate/config/model/v1/validate_1_1.xsd b/core/validate/src/main/resources/org/switchyard/validate/config/model/v1/validate_1_1.xsd new file mode 100644 index 000000000..e3cf1ad08 --- /dev/null +++ b/core/validate/src/main/resources/org/switchyard/validate/config/model/v1/validate_1_1.xsd @@ -0,0 +1,138 @@ + + + + + + + + + + + XML Validator Configuration. + + + + + + + + + + + + XML schema type. + + + + + + + whether a warning should be reported as an SwitchYardException or just log. default is false + + + + + + + whether the validator should be namespace aware or not. + + + + + + + + + + + Schema file configuration. + + + + + + + + + + Schema catalog configuration. + + + + + + + + + + + + + + + Generic/Custom Java Validator Configuration. + + + + + + + + The name of the Java Validator implementation class. + + + + + + + The name of the Java Validator CDI bean. + + + + + + + + + + + + + DTD. + + + + + + + W3C XML Schema. + + + + + + + RELAX NG. + + + + + + + diff --git a/core/validate/src/main/resources/org/switchyard/validate/config/model/v2/validate_2_0.xsd b/core/validate/src/main/resources/org/switchyard/validate/config/model/v2/validate_2_0.xsd new file mode 100644 index 000000000..c98d2a1a4 --- /dev/null +++ b/core/validate/src/main/resources/org/switchyard/validate/config/model/v2/validate_2_0.xsd @@ -0,0 +1,138 @@ + + + + + + + + + + + XML Validator Configuration. + + + + + + + + + + + + XML schema type. + + + + + + + whether a warning should be reported as an SwitchYardException or just log. default is false + + + + + + + whether the validator should be namespace aware or not. + + + + + + + + + + + Schema file configuration. + + + + + + + + + + Schema catalog configuration. + + + + + + + + + + + + + + + Generic/Custom Java Validator Configuration. + + + + + + + + The name of the Java Validator implementation class. + + + + + + + The name of the Java Validator CDI bean. + + + + + + + + + + + + + DTD. + + + + + + + W3C XML Schema. + + + + + + + RELAX NG. + + + + + + + diff --git a/core/validate/src/test/java/org/switchyard/validate/AbstractValidatorTestCase.java b/core/validate/src/test/java/org/switchyard/validate/AbstractValidatorTestCase.java new file mode 100644 index 000000000..5462fd17e --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/AbstractValidatorTestCase.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +import org.junit.Assert; +import org.switchyard.common.type.Classes; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.ValidatesModel; +import org.switchyard.validate.internal.ValidatorUtil; + +import java.io.IOException; +import java.io.InputStream; + +/** + * @author Tomohisa Igarashi + */ +public abstract class AbstractValidatorTestCase { + + protected Validator getValidator(String config) throws IOException { + InputStream swConfigStream = Classes.getResourceAsStream(config, getClass()); + + if (swConfigStream == null) { + Assert.fail("null config stream."); + } + + SwitchYardModel switchyardConfig; + try { + switchyardConfig = new ModelPuller().pull(swConfigStream); + } finally { + swConfigStream.close(); + } + + ValidatesModel validates = switchyardConfig.getValidates(); + + ValidateModel validateModel = validates.getValidates().get(0); + + if (validateModel == null) { + Assert.fail("No validate config."); + } + + return ValidatorUtil.newValidator(validateModel); + } +} diff --git a/core/validate/src/test/java/org/switchyard/validate/BaseValidatorTest.java b/core/validate/src/test/java/org/switchyard/validate/BaseValidatorTest.java new file mode 100644 index 000000000..fb4a0fd53 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/BaseValidatorTest.java @@ -0,0 +1,100 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; + +public class BaseValidatorTest { + + @Test + public void testTypedValidator() throws Exception { + Validator t = new StringValidator(); + Assert.assertEquals(String.class, t.getType()); + } + + @Test + public void testUntypedValidator() throws Exception { + Validator t = new UntypedValidator(); + Assert.assertEquals(Object.class, t.getType()); + } + + @Test + public void testImplementsValidator() throws Exception { + Validator t = new ImplementsValidator(); + Assert.assertEquals(String.class, t.getType()); + } +} + +class StringValidator extends BaseValidator { + public ValidationResult validate(String num) { + return new ValidationResult() { + public boolean isValid() { + return false; + } + public String getDetail() { + return "error"; + } + }; + } +} + +class UntypedValidator extends BaseValidator { + public ValidationResult validate(Object obj) { + return new ValidationResult() { + public boolean isValid() { + return false; + } + public String getDetail() { + return "error"; + } + }; + } +} + +class ImplementsValidator implements Validator { + + @Override + public QName getName() { + return null; + } + + @Override + public Class getType() { + return String.class; + } + + @Override + public Validator setName(QName name) { + return null; + } + + @Override + public ValidationResult validate(Object name) { + return new ValidationResult() { + public boolean isValid() { + return false; + } + public String getDetail() { + return "error"; + } + }; + } + +} + diff --git a/core/validate/src/test/java/org/switchyard/validate/MessageValidator.java b/core/validate/src/test/java/org/switchyard/validate/MessageValidator.java new file mode 100644 index 000000000..9d64b3687 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/MessageValidator.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +import org.switchyard.Message; + +/** + * @author Tomohisa Igarashi + */ +public class MessageValidator extends BaseValidator { + + private Message _message; + + @Override + public ValidationResult validate(Message message) { + this._message = message; + if (message != null) { + return validResult(); + } else { + return invalidResult("Message is null"); + } + } + + public Message getMessage() { + return _message; + } +} diff --git a/core/validate/src/test/java/org/switchyard/validate/MessageValidatorTest.java b/core/validate/src/test/java/org/switchyard/validate/MessageValidatorTest.java new file mode 100644 index 000000000..f785ca12d --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/MessageValidatorTest.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.Message; +import org.switchyard.internal.DefaultMessage; + +import javax.xml.namespace.QName; +import java.io.IOException; + +/** + * @author Tomohisa Igarashi + */ +public class MessageValidatorTest { + + @Test + public void test() throws IOException { + final QName A = new QName("a"); + + DefaultMessage message = new DefaultMessage().setContent(A); + MessageValidator validator = new MessageValidator(); + + ValidationResult result = validator.validate(message); + Assert.assertTrue(result.isValid()); + Assert.assertNull(result.getDetail()); + Assert.assertEquals(message, validator.getMessage()); + } +} diff --git a/core/validate/src/test/java/org/switchyard/validate/config/model/ValidateModelTests.java b/core/validate/src/test/java/org/switchyard/validate/config/model/ValidateModelTests.java new file mode 100644 index 000000000..e32d58366 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/config/model/ValidateModelTests.java @@ -0,0 +1,133 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.custommonkey.xmlunit.Diff; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.Before; +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.config.model.Model; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.switchyard.SwitchYardNamespace; +import org.switchyard.config.model.switchyard.v1.V1SwitchYardModel; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.config.model.validate.ValidatesModel; +import org.switchyard.config.model.validate.v1.V1ValidatesModel; +import org.switchyard.validate.config.model.v1.V1FileEntryModel; +import org.switchyard.validate.config.model.v1.V1JavaValidateModel; +import org.switchyard.validate.config.model.v1.V1SchemaFilesModel; +import org.switchyard.validate.config.model.v1.V1XmlValidateModel; + +/** + * ValidateModelTests. + * + * @author Tomohisa Igarashi + */ +public class ValidateModelTests { + + private static final String XML = "/org/switchyard/validate/config/model/ValidateModelTests.xml"; + + private ModelPuller _puller; + + @Before + public void before() throws Exception { + _puller = new ModelPuller(); + } + + @Test + public void testCreateEmptyModel() throws Exception { + String namespace = ValidateNamespace.DEFAULT.uri(); + String name = ValidateModel.VALIDATE + '.' + JavaValidateModel.JAVA; + Model model = new ModelPuller().pull(XMLHelper.createQName(namespace, name)); + Assert.assertTrue(model instanceof JavaValidateModel); + Assert.assertEquals(name, model.getModelConfiguration().getName()); + Assert.assertEquals(new QName(namespace, name), model.getModelConfiguration().getQName()); + } + + @Test + public void testCreate() throws Exception { + SwitchYardModel switchyard = new V1SwitchYardModel(SwitchYardNamespace.V_1_0.uri()); + ValidatesModel validates = new V1ValidatesModel(SwitchYardNamespace.V_1_0.uri()); + JavaValidateModel javaValidate = new V1JavaValidateModel(ValidateNamespace.V_1_0.uri()); + javaValidate.setName(new QName("msgA")); + javaValidate.setClazz("org.examples.validate.AValidate"); + validates.addValidate(javaValidate); + XmlValidateModel xmlValidate = new V1XmlValidateModel(ValidateNamespace.V_1_0.uri()); + xmlValidate.setName(new QName("msgB")); + xmlValidate.setSchemaType(XmlSchemaType.XML_SCHEMA); + FileEntryModel entry = new V1FileEntryModel(ValidateNamespace.V_1_0.uri()).setFile("/validates/xxx.xml"); + SchemaFilesModel schemaFiles = new V1SchemaFilesModel(ValidateNamespace.V_1_0.uri()); + schemaFiles.addEntry(entry); + xmlValidate.setSchemaFiles(schemaFiles); + xmlValidate.setFailOnWarning(true); + validates.addValidate(xmlValidate); + switchyard.setValidates(validates); + String new_xml = switchyard.toString(); + String old_xml = new ModelPuller().pull(XML, getClass()).toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testRead() throws Exception { + SwitchYardModel switchyard = _puller.pull(XML, getClass()); + ValidatesModel validates = switchyard.getValidates(); + JavaValidateModel java_validate = (JavaValidateModel)validates.getValidates().get(0); + Assert.assertEquals("msgA", java_validate.getName().getLocalPart()); + Assert.assertEquals("org.examples.validate.AValidate", java_validate.getClazz()); + XmlValidateModel xml_validate = (XmlValidateModel)validates.getValidates().get(1); + Assert.assertEquals("msgB", xml_validate.getName().getLocalPart()); + Assert.assertEquals("/validates/xxx.xml", xml_validate.getSchemaFiles().getEntries().get(0).getFile()); + + } + + @Test + public void testWrite() throws Exception { + String old_xml = new StringPuller().pull(XML, getClass()); + SwitchYardModel switchyard = _puller.pull(new StringReader(old_xml)); + String new_xml = switchyard.toString(); + XMLUnit.setIgnoreWhitespace(true); + Diff diff = XMLUnit.compareXML(old_xml, new_xml); + Assert.assertTrue(diff.toString(), diff.identical()); + } + + @Test + public void testParenthood() throws Exception { + SwitchYardModel switchyard_1 = _puller.pull(XML, getClass()); + ValidatesModel validates_1 = switchyard_1.getValidates(); + ValidateModel validate = validates_1.getValidates().get(0); + ValidatesModel validates_2 = validate.getValidates(); + SwitchYardModel switchyard_2 = validates_2.getSwitchYard(); + Assert.assertEquals(validates_1, validates_2); + Assert.assertEquals(switchyard_1, switchyard_2); + } + + @Test + public void testValidation() throws Exception { + SwitchYardModel switchyard = _puller.pull(XML, getClass()); + switchyard.assertModelValid(); + } + +} diff --git a/core/validate/src/test/java/org/switchyard/validate/config/model/ValidateSwitchYardScannerTest.java b/core/validate/src/test/java/org/switchyard/validate/config/model/ValidateSwitchYardScannerTest.java new file mode 100644 index 000000000..929ef14a1 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/config/model/ValidateSwitchYardScannerTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Named; + +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.config.model.ScannerInput; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.validate.ValidateModel; +import org.switchyard.validate.config.model.validators.AValidator; +import org.switchyard.validate.config.model.validators.BValidator; +import org.switchyard.validate.config.model.validators.BeanValidator; + +/** + * @author Tomohisa Igarashi + */ +public class ValidateSwitchYardScannerTest { + + @Test + public void test() throws IOException { + ValidateSwitchYardScanner scanner = new ValidateSwitchYardScanner(); + List urls = new ArrayList(); + + // If running this test inside your IDE... you need to set the cwd to be the + // root of the validate module !! + urls.add(new File("./target/test-classes").toURI().toURL()); + + ScannerInput input = new ScannerInput().setURLs(urls); + SwitchYardModel switchyard = scanner.scan(input).getModel(); + List models = switchyard.getValidates().getValidates(); + + Assert.assertEquals(9, models.size()); + assertModelInstanceOK((JavaValidateModel) models.get(0)); + assertModelInstanceOK((JavaValidateModel) models.get(1)); + assertModelInstanceOK((JavaValidateModel) models.get(2)); + } + + private void assertModelInstanceOK(JavaValidateModel model) { + if (model.getName().toString().equals("{urn:switchyard-validate:test-validators:1.0}a")) { + Assert.assertEquals(AValidator.class.getName(), model.getClazz()); + } else if (model.getName().toString().equals("{urn:switchyard-validate:test-validators:1.0}b")) { + Assert.assertEquals(BValidator.class.getName(), model.getClazz()); + } else if (model.getName().toString().equals("{urn:switchyard-validate:test-validators:1.0}c")) { + Assert.assertEquals(BeanValidator.class.getAnnotation(Named.class).value(), model.getBean()); + Assert.assertNull(model.getClazz()); + } + } +} diff --git a/core/validate/src/test/java/org/switchyard/validate/config/model/ValidatorUtilTest.java b/core/validate/src/test/java/org/switchyard/validate/config/model/ValidatorUtilTest.java new file mode 100644 index 000000000..1b38efd63 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/config/model/ValidatorUtilTest.java @@ -0,0 +1,161 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model; + +import java.util.List; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.junit.Test; +import org.switchyard.annotations.Validator; +import org.switchyard.metadata.JavaTypes; +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.internal.ValidatorTypes; +import org.switchyard.validate.internal.ValidatorUtil; + +/** + * @author Tomohisa Igarashi + */ +public class ValidatorUtilTest { + + @Test + public void test_listValidations() { + List validateTypes = ValidatorUtil.listValidations(TestValidator.class); + + Assert.assertEquals(4, validateTypes.size()); + Assert.assertEquals(QName.valueOf("X"), validateTypes.get(0).getName()); + Assert.assertEquals(QName.valueOf("Z"), validateTypes.get(1).getName()); + Assert.assertEquals(JavaTypes.toMessageType(A.class), validateTypes.get(2).getName()); + Assert.assertEquals(JavaTypes.toMessageType(B.class), validateTypes.get(3).getName()); + } + + @Test + public void test_validate_interface_impl() { + org.switchyard.validate.Validator validator = ValidatorUtil.newValidator(TestValidator.class, JavaTypes.toMessageType(A.class)); + + Assert.assertTrue(validator instanceof TestValidator); + ValidationResult result = validator.validate(new A()); + Assert.assertTrue(result.isValid()); + Assert.assertNull(result.getDetail()); + } + + @Test + public void test_validate_anno_no_types_defined() { + org.switchyard.validate.Validator validator = ValidatorUtil.newValidator(TestValidator.class, JavaTypes.toMessageType(B.class)); + + Assert.assertTrue(!(validator instanceof TestValidator)); + ValidationResult result = validator.validate(new B()); + Assert.assertTrue(result.isValid()); + Assert.assertNull(result.getDetail()); + Assert.assertEquals(B.class, validator.getType()); + } + + @Test + public void test_validate_unknown() { + try { + ValidatorUtil.newValidator(TestValidator.class, QName.valueOf("AAA")); + Assert.fail("Expected Exception"); + } catch(RuntimeException e) { + boolean messageMatches = e.getMessage().contains("SWITCHYARD017210"); + Assert.assertTrue(messageMatches); + } + } + + @Test + public void test_validate_anno_types_defined() { + org.switchyard.validate.Validator validator = ValidatorUtil.newValidator(TestValidator.class, QName.valueOf("X")); + + Assert.assertTrue(!(validator instanceof TestValidator)); + ValidationResult result = validator.validate("X"); + Assert.assertTrue(result.isValid()); + Assert.assertNull(result.getDetail()); + } + + + @Test + public void test_listNSdValidations() { + List validateTypes = ValidatorUtil.listValidations(NSdTestValidator.class); + + Assert.assertEquals(1, validateTypes.size()); + Assert.assertEquals(new QName("http://b", "B"), validateTypes.get(0).getName()); + } + + public static class TestValidator extends BaseValidator { + + public TestValidator() { + super(JavaTypes.toMessageType(A.class)); + } + + @Override + public ValidationResult validate(Object obj) { + if (obj instanceof Object) { + return validResult(); + } else { + return invalidResult("not Object"); + } + } + + @Validator + public ValidationResult validateB(B b) { + if (b instanceof B) { + return validResult(); + } else { + return invalidResult("b is not B"); + } + } + + @Validator(name = "X") + public ValidationResult validateX(String x) { + if (x.equals("X")) { + return validResult(); + } else { + return invalidResult("x is not 'X'"); + } + } + + @Validator(name = "Z") + public ValidationResult validateZ(B z) { + if (z instanceof B) { + return validResult(); + } else { + return invalidResult("z is not B"); + } + } + + } + + public static class NSdTestValidator { + + @Validator(name = "{http://b}B") + public ValidationResult validateB(B b) { + if (b instanceof B) { + return BaseValidator.validResult(); + } else { + return BaseValidator.invalidResult("b is not B"); + } + } + } + + public static class A { + + } + + public static class B { + + } +} diff --git a/core/validate/src/test/java/org/switchyard/validate/config/model/validators/AValidator.java b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/AValidator.java new file mode 100644 index 000000000..4b33e2b44 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/AValidator.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.validators; + +import javax.xml.namespace.QName; + +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; + +/** + * @author Tomohisa Igarashi + */ +@SuppressWarnings("rawtypes") +public class AValidator extends BaseValidator { + + @Override + public ValidationResult validate(Object obj) { + if (obj instanceof Object) { + return validResult(); + } else { + return invalidResult("not Object"); + } + } + + @Override + public QName getName() { + return new QName("urn:switchyard-validate:test-validators:1.0", "a"); + } + +} diff --git a/core/validate/src/test/java/org/switchyard/validate/config/model/validators/BValidator.java b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/BValidator.java new file mode 100644 index 000000000..335a8edd0 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/BValidator.java @@ -0,0 +1,42 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.validators; + +import javax.xml.namespace.QName; + +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; + +/** + * @author Tomohisa Igarashi + */ +@SuppressWarnings("rawtypes") +public class BValidator extends BaseValidator { + + @Override + public ValidationResult validate(Object obj) { + if (obj instanceof Object) { + return validResult(); + } else { + return invalidResult("not Object"); + } + } + + @Override + public QName getName() { + return new QName("urn:switchyard-validate:test-validators:1.0", "b"); + } + +} diff --git a/core/validate/src/test/java/org/switchyard/validate/config/model/validators/BeanValidator.java b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/BeanValidator.java new file mode 100644 index 000000000..09b68ba86 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/BeanValidator.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.validators; + +import javax.inject.Named; +import javax.xml.namespace.QName; + +import org.switchyard.validate.BaseValidator; +import org.switchyard.validate.ValidationResult; + +@SuppressWarnings("rawtypes") +@Named("BeanValidator") +public class BeanValidator extends BaseValidator { + + @Override + public ValidationResult validate(Object obj) { + if (obj instanceof Object) { + return validResult(); + } else { + return invalidResult("not Object"); + } + } + + @Override + public QName getName() { + return new QName("urn:switchyard-validate:test-validators:1.0", "c"); + } + +} diff --git a/core/validate/src/test/java/org/switchyard/validate/config/model/validators/XAbstractValidator.java b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/XAbstractValidator.java new file mode 100644 index 000000000..f9437563f --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/XAbstractValidator.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.validators; + +import org.switchyard.validate.Validator; + +/** + * @author Tomohisa Igarashi + */ +@SuppressWarnings("rawtypes") +public abstract class XAbstractValidator implements Validator{ + // Should be skipped by the scanner because it is abstract +} diff --git a/core/validate/src/test/java/org/switchyard/validate/config/model/validators/XValidatorInterface.java b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/XValidatorInterface.java new file mode 100644 index 000000000..427e0482f --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/config/model/validators/XValidatorInterface.java @@ -0,0 +1,25 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.config.model.validators; + +import org.switchyard.validate.Validator; + +/** + * @author Tomohisa Igarashi + */ +@SuppressWarnings("rawtypes") +public interface XValidatorInterface extends Validator{ + // Should be skipped by the scanner because it's an interface +} diff --git a/core/validate/src/test/java/org/switchyard/validate/internal/xml/XmlValidatorTest.java b/core/validate/src/test/java/org/switchyard/validate/internal/xml/XmlValidatorTest.java new file mode 100644 index 000000000..fde2b4883 --- /dev/null +++ b/core/validate/src/test/java/org/switchyard/validate/internal/xml/XmlValidatorTest.java @@ -0,0 +1,227 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.validate.internal.xml; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +import org.jboss.logging.Logger; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.SwitchYardException; +import org.switchyard.internal.DefaultMessage; +import org.switchyard.validate.ValidationResult; +import org.switchyard.validate.Validator; +import org.switchyard.validate.AbstractValidatorTestCase; +import org.switchyard.validate.xml.internal.XmlValidator; +import org.xml.sax.SAXException; + +/** + * @author Tomohisa Igarashi + */ +public class XmlValidatorTest extends AbstractValidatorTestCase { + private static final Logger LOGGER = Logger.getLogger(XmlValidatorTest.class); + + @Test + public void test_no_schematype() throws IOException { + try { + getValidator("sw-config-no-schematype.xml"); + } catch(RuntimeException e) { + boolean exceptionText = e.getMessage().contains("SWITCHYARD017219"); + Assert.assertTrue(exceptionText); + } + } + + @Test + public void test_no_schemafile() throws IOException, SAXException { + try { + getValidator("sw-config-no-schemafile.xml"); + } catch(RuntimeException e) { + boolean exceptionText = e.getMessage().contains("SWITCHYARD017221"); + Assert.assertTrue(exceptionText); + } + } + + @Test(expected=SwitchYardException.class) + public void test_invalid_schemafile() throws IOException, SAXException { + Validator validator = getValidator("sw-config-invalid-schemafile.xml"); + ValidationResult result = validator.validate(new DefaultMessage().setContent("")); + } + + @Test + public void test_valid_xml() throws IOException, SAXException { + Validator validator = getValidator("sw-config-xmlv-01.xml"); + String source = ""; + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + if (!result.isValid()) { + Assert.fail(result.getDetail()); + } + source = ""; + result = validator.validate(new DefaultMessage().setContent(source)); + if (!result.isValid()) { + Assert.fail(result.getDetail()); + } + Assert.assertNull(result.getDetail()); + } + + @Test + public void test_invalid_xml() throws IOException, SAXException { + Validator validator = getValidator("sw-config-xmlv-01.xml"); + String source = ""; + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + Assert.assertFalse(result.isValid()); + LOGGER.info(result.getDetail()); + Assert.assertTrue(result.getDetail().startsWith("1 validation error(s)")); + } + + @Test + public void test_namespaceaware_valid_xml() throws Exception { + Validator validator = getValidator("sw-config-xmlv-namespace.xml"); + String source = ""; + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + if (!result.isValid()) { + Assert.fail(result.getDetail()); + } + Assert.assertNull(result.getDetail()); + } + + @Test + public void test_namespaceaware_catalog_valid_xml() throws Exception { + Validator validator = getValidator("sw-config-xmlv-namespace-catalog.xml"); + String source = ""; + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + if (!result.isValid()) { + Assert.fail(result.getDetail()); + } + Assert.assertNull(result.getDetail()); + } + + @Test + public void test_dtd_valid_xml() throws Exception { + Validator validator = getValidator("sw-config-xmlv-dtd.xml"); + String source = " "; + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + if (!result.isValid()) { + Assert.fail(result.getDetail()); + } + Assert.assertNull(result.getDetail()); + } + + @Test + public void test_dtd_valid_xml_two() throws Exception { + Validator validator = getValidator("sw-config-xmlv-dtd-two.xml"); + String source = "" + + "" + + "Garfield" + + "Odie" + + "I love lasagna!" + + ""; + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + if (!result.isValid()) { + Assert.fail(result.getDetail()); + } + Assert.assertNull(result.getDetail()); + } + + /** + * Tests included DTD. + * @throws Exception exception + */ + @Test + public void test_dtd_valid_xml_three() throws Exception { + Validator validator = getValidator("sw-config-xmlv-dtd-two.xml"); + String source = "" + + "" + + "" + + "" + + "" + + "" + + "]>" + + "" + + "Garfield" + + "Odie" + + "I love lasagna!" + + ""; + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + if (!result.isValid()) { + Assert.fail(result.getDetail()); + } + Assert.assertNull(result.getDetail()); + } + + /** + * Negative test, tests invalid DTD. + * @throws Exception exception + */ + @Test + public void test_dtd_valid_xml_four() throws Exception { + Validator validator = getValidator("sw-config-xmlv-dtd-two.xml"); + String source = "" + + "" + + "" + + "" + + "" + + "]>" + + "" + + "Garfield" + + "Odie" + + "I love lasagna!" + + ""; + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + if (result.isValid()) { + Assert.fail(result.getDetail()); + } + } + + + /** + * Negative test, tests invalid schema name. + * @throws Exception exception + */ + @Test + public void test_dtd_valid_xml_five() throws Exception { + Validator validator = getValidator("sw-config-xmlv-dtd-two.xml"); + String source = "" + + "" + + "Garfield" + + "Odie" + + "I love lasagna!" + + ""; + + boolean flag = false; + try { + ValidationResult result = validator.validate(new DefaultMessage().setContent(source)); + } catch (Exception fnfe) { + flag = true; + } + if (!flag) { + Assert.fail("Somehow found DTD that we should not have."); + } + } + + protected Validator getValidator(String config) throws IOException { + Validator validator = super.getValidator(config); + + if(!(validator instanceof XmlValidator)) { + Assert.fail("Not an instance of XmlValidator."); + } + + return validator; + } +} diff --git a/core/validate/src/test/resources/org/switchyard/validate/MessageValidatorTest.xml b/core/validate/src/test/resources/org/switchyard/validate/MessageValidatorTest.xml new file mode 100644 index 000000000..e65931d43 --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/MessageValidatorTest.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/config/model/ValidateModelTests.xml b/core/validate/src/test/resources/org/switchyard/validate/config/model/ValidateModelTests.xml new file mode 100644 index 000000000..02462131f --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/config/model/ValidateModelTests.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/catalog.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/catalog.xml new file mode 100644 index 000000000..30fe9f5cd --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/catalog.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/memo.dtd b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/memo.dtd new file mode 100644 index 000000000..60679fb90 --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/memo.dtd @@ -0,0 +1,19 @@ + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-include.xsd b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-include.xsd new file mode 100644 index 000000000..c465e0411 --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-include.xsd @@ -0,0 +1,23 @@ + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-invalid.xsd b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-invalid.xsd new file mode 100644 index 000000000..6f89d2da0 --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-invalid.xsd @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace-base.xsd b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace-base.xsd new file mode 100644 index 000000000..715ce52a9 --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace-base.xsd @@ -0,0 +1,23 @@ + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace-catalog.xsd b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace-catalog.xsd new file mode 100644 index 000000000..92d15a0fd --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace-catalog.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace.xsd b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace.xsd new file mode 100644 index 000000000..5804144d8 --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person-namespace.xsd @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person.dtd b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person.dtd new file mode 100644 index 000000000..30abd297b --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person.dtd @@ -0,0 +1,17 @@ + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person.xsd b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person.xsd new file mode 100644 index 000000000..68f05969a --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/person.xsd @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-invalid-schemafile.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-invalid-schemafile.xml new file mode 100644 index 000000000..18e6aef0a --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-invalid-schemafile.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-no-schemafile.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-no-schemafile.xml new file mode 100644 index 000000000..d8313d80e --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-no-schemafile.xml @@ -0,0 +1,19 @@ + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-no-schematype.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-no-schematype.xml new file mode 100644 index 000000000..d744d836c --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-no-schematype.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-01.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-01.xml new file mode 100644 index 000000000..c7f79e68a --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-01.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-dtd-two.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-dtd-two.xml new file mode 100644 index 000000000..665cc4fa9 --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-dtd-two.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-dtd.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-dtd.xml new file mode 100644 index 000000000..d49c0aaae --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-dtd.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-namespace-catalog.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-namespace-catalog.xml new file mode 100644 index 000000000..6f5949ebd --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-namespace-catalog.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-namespace.xml b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-namespace.xml new file mode 100644 index 000000000..fe72d1716 --- /dev/null +++ b/core/validate/src/test/resources/org/switchyard/validate/internal/xml/sw-config-xmlv-namespace.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/demos/cluster/client/pom.xml b/demos/cluster/client/pom.xml deleted file mode 100644 index 92a4300cb..000000000 --- a/demos/cluster/client/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-cluster - 2.0.0.Final - - switchyard-demo-cluster-client - jar - Quickstart Demo: Cluster - Client - Quickstart Demo: Cluster - Client - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - org.switchyard - switchyard-remote - test - - - - ${project.artifactId} - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.demo.cluster.RemoteClient - false - - - - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.sca.client.port - 8181 - - - - - - - - - diff --git a/demos/cluster/credit/pom.xml b/demos/cluster/credit/pom.xml deleted file mode 100644 index 5176fd278..000000000 --- a/demos/cluster/credit/pom.xml +++ /dev/null @@ -1,206 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-cluster - 2.0.0.Final - - switchyard-demo-cluster-credit - bundle - Quickstart Demo: Cluster - Credit Service - Quickstart Demo: Cluster - Credit Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.cluster.credit - true - remote - 10999 - 11999 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-rules - - - org.switchyard.components - switchyard-component-sca - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${wildfly.port.node2} - ${project.build.finalName}.jar - ${deploy.skip} - - - - deploy2 - install - - deploy-only - - - ${wildfly.port.node3} - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${wildfly.port.node2} - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy2 - clean - - undeploy - - - ${wildfly.port.node3} - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - - - deploy - - false - - - - wildfly - - http-remoting - 10990 - 11990 - - - - diff --git a/demos/cluster/dealer/pom.xml b/demos/cluster/dealer/pom.xml deleted file mode 100644 index c1f8e39a0..000000000 --- a/demos/cluster/dealer/pom.xml +++ /dev/null @@ -1,179 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-cluster - 2.0.0.Final - - switchyard-demo-cluster-dealer - bundle - Quickstart Demo: Cluster - Dealer Service - Quickstart Demo: Cluster - Dealer Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.cluster.dealer - true - 9999 - remote - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-sca - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - - - deploy - - false - - - - wildfly - - http-remoting - 9990 - - - - diff --git a/demos/cluster/pom.xml b/demos/cluster/pom.xml deleted file mode 100644 index e24764783..000000000 --- a/demos/cluster/pom.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-cluster - 2.0.0.Final - pom - Quickstart Demo: Cluster - Quickstart Demo: Cluster - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - 1.3.1 - 2.4.0 - 1.0.2.Final - - - client - credit - dealer - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - diff --git a/demos/helpdesk/pom.xml b/demos/helpdesk/pom.xml deleted file mode 100644 index dfe1caa46..000000000 --- a/demos/helpdesk/pom.xml +++ /dev/null @@ -1,453 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-helpdesk - 2.0.0.Final - war - Quickstart Demo : Help Desk - Quickstart Demo : Help Desk - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.helpdesk - true - 9999 - 1.6 - 1.6 - - javax.el, - javax.faces.webapp, - javax.servlet;version="[3.0.0,4.0.0)", - javax.servlet.http;version="[3.0.0,4.0.0)", - javax.servlet.jsp;version="2.2.0", - javax.servlet.jsp.jstl.core;version="2.2", - javax.servlet.jsp.jstl.fmt;version="2.2", - javax.servlet.jsp.jstl.tlv;version="2.2", - org.apache.taglibs.standard.resources;version="1.1.2", - org.apache.taglibs.standard.tag.common.core;version="1.1.2", - org.apache.taglibs.standard.tag.rt.core;version="1.1.2", - org.apache.taglibs.standard.tei;version="1.1.2", - org.apache.taglibs.standard.tlv;version="1.1.2" - com.sun.el.lang, - com.sun.el.parser, - com.sun.el, - com.sun.el.util, - javax.faces.*, - org.apache.log4j, - org.drools.persistence.info, - org.jbpm.executor.entities, - org.jbpm.persistence.correlation, - org.jbpm.persistence.processinstance, - org.jbpm.process.audit, - org.jbpm.runtime.manager.impl.jpa, - org.jbpm.services.task.audit.impl.model, - org.jbpm.services.task.impl.model, - org.jbpm.services.task.internals.lifecycle, - org.jbpm.services.task.persistence, - org.jbpm.services.task.query, - org.kie.api.task.model, - org.kie.internal.executor.api, - org.kie.internal.task.api.model, - org.w3c.dom, - * - - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.apache.myfaces.core.bundle - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - 6.2.0.CR3 - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - org.jbpm - jbpm-bom - ${version.org.jbpm} - pom - import - - - - - - org.hibernate - hibernate-entitymanager - provided - - - org.switchyard - switchyard-api - provided - - - org.switchyard.components - switchyard-component-bean - provided - - - org.switchyard.components - switchyard-component-bpm - provided - - - org.switchyard.components - switchyard-component-soap - provided - - - - javax.enterprise - cdi-api - provided - - - - org.jboss.spec.javax.annotation - jboss-annotations-api_1.1_spec - provided - - - - org.jboss.spec.javax.faces - jboss-jsf-api_2.1_spec - provided - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - org.apache.httpcomponents - httpclient - test - - - com.h2database - h2 - test - - - org.jbpm - jbpm-executor - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - - - bundle-manifest - process-classes - - manifest - - - - - - war - - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, WEB-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - ${switchyard.osgi.require.bundle} - WEB-INF/classes/META-INF/persistence-osgi.xml - helpdesk - <_wab>src/main/webapp - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - true - - - - maven-war-plugin - - false - - WEB-INF/lib/*.jar, - WEB-INF/classes/META-INF/switchyard.xml, - WEB-INF/classes/META-INF/MANIFEST.MF, - WEB-INF/classes/META-INF/beans.xml, - WEB-INF/classes/OSGI-INF/** - - - - target/classes/META-INF - WEB-INF - - switchyard.xml - - - - target/classes/META-INF - META-INF - - beans.xml - - - - target/classes/OSGI-INF - OSGI-INF - - - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - unpack-jbpm-orm-files - generate-resources - - unpack - - - - - org.jbpm - jbpm-human-task-audit - jar - - - org.jbpm - jbpm-human-task-jpa - jar - - - org.jbpm - jbpm-persistence-jpa - jar - - - org.jbpm - jbpm-executor - jar - - - org.jbpm - jbpm-kie-services - jar - - - META-INF/*orm.xml - ${project.build.outputDirectory} - true - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.war - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.war - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demos.helpdesk.HelpDeskMain - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/demos/library/pom.xml b/demos/library/pom.xml deleted file mode 100644 index c67de5c57..000000000 --- a/demos/library/pom.xml +++ /dev/null @@ -1,238 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-library - 2.0.0.Final - bundle - Quickstart Demo : Library - Quickstart Demo : Library - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.library - true - 9999 - 1.6 - 1.6 - * - - org.switchyard,org.switchyard.* - - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bpm - - - org.switchyard.components - switchyard-component-rules - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demos.library.LibraryClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/demos/multiApp/README.md b/demos/multiApp/README.md deleted file mode 100644 index cb78f88ee..000000000 --- a/demos/multiApp/README.md +++ /dev/null @@ -1,72 +0,0 @@ -# MultiApp Demo Quickstart - -This quickstart provides an example of a multi-project application structure with SwitchYard. The quickstart consists of the following pieces: - -* artifacts : contains XSDs, WSDLs, and Java domain objects which are used by service providers and consumers across application projects -* order-service : provides two services - OrderService and InventoryService -* order-consumer : consumes OrderService through a SOAP/HTTP binding -* web : consumes InventoryService using it's Java service interface - -The MultiApp quickstart can also be used to demonstrate design-time repository integration with SwitchYard. Individual service artifacts in the artifacts project can be uploaded to a service repository (e.g. Guvnor) and exported as a service module for use within projects which consume the service. Additional detail can be found in the SwitchYard Repository Integration wiki article. - -Consult the README.md in each individual project for more info. - -## Running the Example - - -EAP ----------- -1. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy - -4. Use one or both of the consuming application projects: - * Web: Visit . - * JMS: Use 'mvn exec:java' in the order-consumer project to submit a JMS order message via the OrderIntake service. - -5. Check the server console for output from the service. - -6. Undeploy the quickstart: - - mvn clean -Pdeploy - - - -Wildfly ----------- -1. Start Wildfly in standalone mode: - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy -Pwildfly - -4. Use one or both of the consuming application projects: - * Web: Visit . - * JMS: Use 'mvn exec:java -Pwildfly' in the order-consumer project to submit a JMS order message via the OrderIntake service. - -5. Check the server console for output from the service. - -6. Undeploy the quickstart: - - mvn clean -Pdeploy -Pwildfly - - - -## Further Reading - -1. [SwitchYard Repository Integration](https://community.jboss.org/wiki/SwitchYardRepositoryIntegration) diff --git a/demos/multiApp/artifacts/pom.xml b/demos/multiApp/artifacts/pom.xml deleted file mode 100644 index c1918e9fb..000000000 --- a/demos/multiApp/artifacts/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp - 2.0.0.Final - - switchyard-demo-multiApp-artifacts - jar - Quickstart Demo: Multiple Applications - Service Artifacts - Quickstart Demo: Multiple Applications - Service Artifacts - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - ${project.artifactId} - - - maven-jar-plugin - - - classes - - jar - - package - - classes - - **/*.class - - - - - all - - jar - - package - - - **/* - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - diff --git a/demos/multiApp/order-consumer/pom.xml b/demos/multiApp/order-consumer/pom.xml deleted file mode 100644 index 922e07b90..000000000 --- a/demos/multiApp/order-consumer/pom.xml +++ /dev/null @@ -1,241 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp - 2.0.0.Final - - switchyard-demo-multiApp-order-consumer - jar - Quickstart Demo: Multiple Applications - Order Consumer - Quickstart Demo: Multiple Applications - Order Consumer - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 2.4.1.Final - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-camel-core - - - org.switchyard.components - switchyard-component-soap - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-hornetq - test - - - junit - junit - test - - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp-artifacts - - - org.switchyard.quickstarts.demos - - switchyard-demo-multiApp-order-service - - - - org.switchyard.quickstarts.demos - - switchyard-demo-multiApp-web - - war - - - - ${project.artifactId} - - - org.apache.maven.plugins - maven-jar-plugin - - - - deployment.switchyard-demo-multiApp-artifacts.jar - - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - org.switchyard.quickstarts.demo.multiapp.consumer.OrderIntakeClient - - ${project.build.directory}/test-classes/order.xml - - test - false - - - - - - - wildfly - - true - 8080 - - - - org.hornetq - hornetq-core-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-commons - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-journal - ${version.wildfly.hornetq} - test - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - hornetqmixin.port - 8080 - - - hornetqmixin.http.upgrade.enabled - true - - - - - - - - - diff --git a/demos/multiApp/order-service/pom.xml b/demos/multiApp/order-service/pom.xml deleted file mode 100644 index 910ab37ba..000000000 --- a/demos/multiApp/order-service/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp - 2.0.0.Final - - switchyard-demo-multiApp-order-service - jar - Quickstart Demo: Multiple Applications - Order Service - Quickstart Demo: Multiple Applications - Order Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp-artifacts - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - - ${project.artifactId} - - - org.apache.maven.plugins - maven-jar-plugin - - - - deployment.switchyard-demo-multiApp-artifacts.jar - - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - diff --git a/demos/multiApp/pom.xml b/demos/multiApp/pom.xml deleted file mode 100644 index 29c546468..000000000 --- a/demos/multiApp/pom.xml +++ /dev/null @@ -1,157 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-multiApp - 2.0.0.Final - pom - Quickstart Demo: Multiple Applications - Quickstart Demo: Multiple Applications - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 9999 - 1.6 - 1.6 - 1.3.1 - 1.0.2.Final - - - artifacts - order-service - order-consumer - web - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp-artifacts - ${project.version} - - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp-order-service - ${project.version} - - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp-web - war - ${project.version} - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/demos/multiApp/web/pom.xml b/demos/multiApp/web/pom.xml deleted file mode 100644 index 505d3a568..000000000 --- a/demos/multiApp/web/pom.xml +++ /dev/null @@ -1,152 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp - 2.0.0.Final - - switchyard-demo-multiApp-web - war - Quickstart Demo: Multiple Applications - Web App - Quickstart Demo: Multiple Applications - Web App - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - org.switchyard.quickstarts.demos - switchyard-demo-multiApp-artifacts - - - org.switchyard - switchyard-api - provided - - - org.switchyard.components - switchyard-component-bean - provided - - - - javax.enterprise - cdi-api - provided - - - - org.jboss.spec.javax.annotation - jboss-annotations-api_1.1_spec - provided - - - - org.jboss.spec.javax.faces - jboss-jsf-api_2.1_spec - provided - - - org.switchyard - switchyard-test - test - - - junit - junit - test - - - org.apache.httpcomponents - httpclient - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - ${project.build.directory}/${project.build.finalName}/WEB-INF/switchyard.xml - - - - maven-war-plugin - - - false - - - deployment.switchyard-demo-multiApp-artifacts.jar - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.war - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.war - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - diff --git a/demos/orders/pom.xml b/demos/orders/pom.xml deleted file mode 100644 index 95b5bd5ac..000000000 --- a/demos/orders/pom.xml +++ /dev/null @@ -1,242 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-orders - 2.0.0.Final - war - Quickstart Demo : Orders - Quickstart Demo : Orders - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 9999 - 1.6 - 1.6 - 1.3.1 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - provided - - - org.switchyard.components - switchyard-component-bean - provided - - - org.switchyard.components - switchyard-component-soap - provided - - - org.switchyard - switchyard-test - provided - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - javax.enterprise - cdi-api - provided - - - - org.jboss.spec.javax.annotation - jboss-annotations-api_1.1_spec - provided - - - - org.jboss.spec.javax.faces - jboss-jsf-api_2.1_spec - provided - - - junit - junit - test - - - org.apache.httpcomponents - httpclient - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - ${project.build.directory}/${project.build.finalName}/WEB-INF/switchyard.xml - - - - - configure - - - - - - maven-war-plugin - - - false - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.war - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.war - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.demos.orders.OrdersClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/demos/policy-security-basic/Readme.md b/demos/policy-security-basic/Readme.md deleted file mode 100644 index eb7b70d02..000000000 --- a/demos/policy-security-basic/Readme.md +++ /dev/null @@ -1,125 +0,0 @@ -Introduction -============ -This quickstart demonstrates how policy can be used to control the security characteristics of a -service invocation. The only service in the application is a Bean service called "WorkService". -SSL is used for "confidentiality", and Basic Authentication is used for "clientAuthentication". - - -Running the quickstart -====================== - -EAP ----------- - -1. Create an application user: - - ${AS}/bin/add-user.sh - - realm=ApplicationRealm Username=kermit Password=the-frog-1 group=friend - -2. Start EAP in standalone mode: - - ${AS}/bin/standalone.sh - -3. Build and deploy the quickstart - - mvn install -Pdeploy - -4. Execute the test. (See "Options" section below.) - -5. Check the server console for output from the service. - -6. Undeploy the application - - mvn clean -Pdeploy - -Karaf ------ -Instead of steps 1-3,6 above for EAP... - -1. Create a ${KARAF}/quickstarts/demos/policy-security-basic/ directory, and copy connector.jks into it. - -2. Create a ${KARAF}/etc/org.ops4j.pax.web.cfg file, with the following contents: - -org.osgi.service.http.enabled=true -org.osgi.service.http.port=8181 -org.osgi.service.http.secure.enabled=true -org.osgi.service.http.port.secure=8183 -org.ops4j.pax.web.ssl.keystore=quickstarts/demos/policy-security-basic/connector.jks -org.ops4j.pax.web.ssl.keystore.type=JKS -org.ops4j.pax.web.ssl.password=changeit -org.ops4j.pax.web.ssl.keypassword=changeit -org.ops4j.pax.web.ssl.clientauthwanted=false -org.ops4j.pax.web.ssl.clientauthneeded=false - -3. Add this line to ${KARAF}/etc/users.properties: - - kermit = the-frog-1,_g_:friend - _g_\:friend = group,friend - -4. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} -with the version of SwitchYard that you are using (ex. 2.0.0): - -karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features - -5. Install the feature for the bean-service quickstart : - -karaf@root> features:install switchyard-demo-policy-security-basic - -6. When executing the test (as directed below), add the following system property: -Dorg.switchyard.component.soap.client.port=8183 - - -Wildfly ----------- - - -1. Create an application user: - - ${WILDFLY}/bin/add-user.sh - - realm=ApplicationRealm Username=kermit Password=the-frog-1 group=friend - -2. Start Wildfly in standalone mode : - - ${WILDFLY}/bin/standalone.sh - -3. Build and deploy the demo : - - mvn install -Pdeploy -Pwildfly - -4. Execute the test. (See "Options" section below.) - -5. Check the server console for output from the service. - -6. Undeploy the application - - mvn clean -Pdeploy -Pwildfly - -Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. - - - - - -Options -======= - -When running with no options: - - mvn exec:java - -You will be hitting the http (non-SSL) URL, and see this in your log: - - Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: authorization clientAuthentication confidentiality - -When running with this option: - - mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks - -You will be hitting the https (SSL) URL and providing authentication information, and see this in your log: - - :: WorkService :: Received work command => CMD-1398262304944 (caller principal=kermit, in roles? 'friend'=true 'enemy'=false) - - (Because the WorkService is secured, you will see the not-null principal, and true for the expected security role.) - -You can play with the exec.args and only specify one of "confidentiality" or "clientAuthentication". I bet you can guess what will happen... ;) diff --git a/demos/policy-security-basic/pom.xml b/demos/policy-security-basic/pom.xml deleted file mode 100644 index d27687729..000000000 --- a/demos/policy-security-basic/pom.xml +++ /dev/null @@ -1,253 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-policy-security-basic - 2.0.0.Final - bundle - Quickstart Demo : Security Policy : Basic Authentication (+SSL) - Quickstart Demo : Security Policy : Basic Authentication (+SSL) - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.policy.security.basic - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - config.cli - unconfig.cli - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.apache.commons - not-yet-commons-ssl - test - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demo.policy.security.basic.WorkServiceMain - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - config_wildfly.cli - unconfig_wildfly.cli - 9990 - - - - diff --git a/demos/policy-security-cert/Readme.md b/demos/policy-security-cert/Readme.md deleted file mode 100644 index 519a572c9..000000000 --- a/demos/policy-security-cert/Readme.md +++ /dev/null @@ -1,102 +0,0 @@ -Introduction -============ -This quickstart demonstrates how policy can be used to control the security characteristics of a -service invocation. The only service in the application is a Bean service called "WorkService". -SSL is used for "confidentiality", and Certificate Authentication is used for "clientAuthentication". - - -Running the quickstart -====================== - -1. Start EAP in standalone mode: - - ${AS}/bin/standalone.sh - -2. Build and deploy the quickstart - - mvn install -Pdeploy - -3. Execute the test. (See "Options" section below.) - -4. Check the server console for output from the service. - -5. Undeploy the application - - mvn clean -Pdeploy - -Karaf ------ -Instead of steps 1,2,5 above for EAP... - -1. Create a ${KARAF}/quickstarts/demos/policy-security-cert/ directory, and copy users.jks, roles.properties, and connector.jks into it. - -2. Create a ${KARAF}/etc/org.ops4j.pax.web.cfg file, with the following contents: - -org.osgi.service.http.enabled=true -org.osgi.service.http.port=8181 -org.osgi.service.http.secure.enabled=true -org.osgi.service.http.port.secure=8183 -org.ops4j.pax.web.ssl.keystore=quickstarts/demos/policy-security-cert/connector.jks -org.ops4j.pax.web.ssl.keystore.type=JKS -org.ops4j.pax.web.ssl.password=changeit -org.ops4j.pax.web.ssl.keypassword=changeit -org.ops4j.pax.web.ssl.clientauthwanted=false -org.ops4j.pax.web.ssl.clientauthneeded=false - -3. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} -with the version of SwitchYard that you are using (ex. 2.0.0): - -karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features - -4. Install the feature for the bean-service quickstart : - -karaf@root> features:install switchyard-demo-policy-security-cert - -5. When executing the test (as directed below in the "Options" section), add the following system property: -Dorg.switchyard.component.soap.client.port=8183 - - -Wildfly ----------- - - -1. Start Wildfly in standalone mode : - - ${WILDFLY}/bin/standalone.sh - -2. Build and deploy the demo : - - mvn install -Pdeploy -Pwildfly - -3. Execute the test. (See "Options" section below.) - -4. Check the server console for output from the service. - -5. Undeploy the application - - mvn clean -Pdeploy -Pwildfly - -Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. - - -Options -======= - -When running with no options: - - mvn exec:java - -You will be hitting the http (non-SSL) URL, and see this in your log: - - Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: authorization clientAuthentication confidentiality - -When running with this option: - - mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks - -You will be hitting the https (SSL) URL and providing authentication information, and see this in your log: - - :: WorkService :: Received work command => CMD-1398262622127 (caller principal=UserPrincipal@640268438[name=kermit], in roles? 'friend'=true 'enemy'=false) - - (Because the WorkService is secured, you will see the not-null principal, and true for the expected security role.) - -You can play with the exec.args and only specify one of "confidentiality" or "clientAuthentication". I bet you can guess what will happen... ;) diff --git a/demos/policy-security-cert/pom.xml b/demos/policy-security-cert/pom.xml deleted file mode 100644 index 57b9312c4..000000000 --- a/demos/policy-security-cert/pom.xml +++ /dev/null @@ -1,253 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-policy-security-cert - 2.0.0.Final - bundle - Quickstart Demo : Security Policy : Certificate Authentication (+SSL) - Quickstart Demo : Security Policy : Certificate Authentication (+SSL) - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.policy.security.cert - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - config.cli - unconfig.cli - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.apache.commons - not-yet-commons-ssl - test - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demo.policy.security.cert.WorkServiceMain - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - config_wildfly.cli - unconfig_wildfly.cli - - - - diff --git a/demos/policy-security-saml/Readme.md b/demos/policy-security-saml/Readme.md deleted file mode 100644 index 75aed265b..000000000 --- a/demos/policy-security-saml/Readme.md +++ /dev/null @@ -1,76 +0,0 @@ -Introduction -============ -This quickstart demonstrates how policy can be used to control the security characteristics of a -service invocation. The only service in the application is a Bean service called "WorkService". -SSL is used for "confidentiality", and SAML Assertion is used for "clientAuthentication". - - -Running the quickstart -====================== - -EAP ----------- -1. Start JBoss EAP in standalone mode: - - ${AS}/bin/standalone.sh - -2. Build and deploy the quickstart - - mvn install -Pdeploy - -3. Execute the test. (See "Options" section below.) - -4. Check the server console for output from the service. - -5. Undeploy the application - - mvn clean -Pdeploy - - - -Wildfly ----------- - - -1. Start Wildfly in standalone mode : - - ${WILDFLY}/bin/standalone.sh - -2. Build and deploy the demo : - - mvn install -Pdeploy -Pwildfly - -3. Execute the test. (See "Options" section below.) - -4. Check the server console for output from the service. - -5. Undeploy the application - - mvn clean -Pdeploy -Pwildfly - -Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. - - - -Options -======= - -When running with no options: - - mvn exec:java - -You will be hitting the http (non-SSL) URL, and see this in your log: - - Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: clientAuthentication confidentiality - -When running with this option: - - mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks - -You will be hitting the https (SSL) URL and providing authentication information, and see this in your log: - - :: WorkService :: Received work command => CMD-1398967051060 (caller principal=UserPrincipal@1045975928[name=admin]) - - (Because the WorkService is secured, you will see the not-null principal.) - -You can play with the exec.args and only specify one of "confidentiality" or "clientAuthentication". I bet you can guess what will happen... ;) diff --git a/demos/policy-security-saml/pom.xml b/demos/policy-security-saml/pom.xml deleted file mode 100644 index 9072153dc..000000000 --- a/demos/policy-security-saml/pom.xml +++ /dev/null @@ -1,280 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-policy-security-saml - 2.0.0.Final - bundle - Quickstart Demo : Security Policy : SAML Assertion (+SSL) - Quickstart Demo : Security Policy : SAML Assertion (+SSL) - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.policy.security.saml - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - config.cli - unconfig.cli - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.wildfly - wildfly-picketlink - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.apache.commons - not-yet-commons-ssl - test - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - deploy-picketlink - install - - deploy-only - - - ../picketlink-sts.war - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy-picketlink - clean - - undeploy - - - - - - - - ../picketlink-sts.war - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demo.policy.security.saml.WorkServiceMain - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - config_wildfly.cli - unconfig_wildfly.cli - - - - diff --git a/demos/policy-security-wss-signencrypt/Readme.md b/demos/policy-security-wss-signencrypt/Readme.md deleted file mode 100644 index 9e2d6f26e..000000000 --- a/demos/policy-security-wss-signencrypt/Readme.md +++ /dev/null @@ -1,93 +0,0 @@ -Introduction -============ -This quickstart demonstrates how policy can be used to control the security characteristics of a -service invocation. The only service in the application is a Bean service called "WorkService". -SSL and/or WS-Security encryption can be used for "confidentiality", and WS-Security is used to verify the Signature and Encryption -of the SOAP message. - - -Running the quickstart -====================== - - -EAP ----------- - -1. Start JBoss EAP in standalone mode: - - ${AS}/bin/standalone.sh - -2. Build and deploy the quickstart - - mvn install -Pdeploy - -3. Execute the test. (See "Options" section below.) - -4. Check the server console for output from the service. - -5. Undeploy the application - - mvn clean -Pdeploy - - -Wildfly ----------- - - -1. Start Wildfly in standalone mode : - - ${WILDFLY}/bin/standalone.sh - -2. Build and deploy the demo : - - mvn install -Pdeploy -Pwildfly - -3. Execute the test. (See "Options" section below.) - -4. Check the server console for output from the service. - -5. Undeploy the application - - mvn clean -Pdeploy -Pwildfly - -Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. - - - -Options -======= - -When running with no options: - - mvn exec:java - -You will be hitting the http (non-SSL) URL while NOT providing signed and encrypted information, and see this in your log: - -``` -[org.apache.cxf.phase.PhaseInterceptorChain] (http-/127.0.0.1:8080-1) Interceptor for -{urn:switchyard-quickstart-demo:policy-security-wss-signencrypt:0.1.0}WorkService#{urn:switchyard-quickstart-demo:policy-security-wss-signencrypt:0.1.0}doWork has thrown -exception, unwinding now: org.apache.cxf.ws.policy.PolicyException: These policy alternatives can not be satisfied: -{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}X509Token: The received token does not match the token inclusion requirement -{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}SignedParts: {http://schemas.xmlsoap.org/soap/envelope/}Body not SIGNED -{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}EncryptedParts: {http://schemas.xmlsoap.org/soap/envelope/}Body not ENCRYPTED -``` - -When running with this option: - - mvn exec:java -Dexec.args="confidentiality signencrypt" -Djavax.net.ssl.trustStore=connector.jks - -You will be hitting the https (SSL) URL while providing signed and encrypted information, and see this in your log: - - :: WorkService :: Received work command => CMD-86 - -When running with this option: - - mvn exec:java -Dexec.args="signencrypt" - -You will be hitting the http (non-SSL) URL while providing signed and encrypted information, and see this in your log: - - :: WorkService :: Received work command => CMD-86 - -Wait - why did this work? Even though SSL was not used, the content of the message is encrypted, thus the confidentiality policy is still being fulfilled. - -Success! diff --git a/demos/policy-security-wss-signencrypt/pom.xml b/demos/policy-security-wss-signencrypt/pom.xml deleted file mode 100644 index d20f82f26..000000000 --- a/demos/policy-security-wss-signencrypt/pom.xml +++ /dev/null @@ -1,258 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-policy-security-wss-signencrypt - 2.0.0.Final - bundle - Quickstart Demo : Security Policy : WSS Signature+Encryption (+SSL) - Quickstart Demo : Security Policy : WSS Signature+Encryption (+SSL) - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.policy.security.wss.signencrypt - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - config.cli - unconfig.cli - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.apache.commons - not-yet-commons-ssl - test - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.apache.ws.security - wss4j - provided - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demo.policy.security.wss.signencrypt.WorkServiceMain - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - config_wildfly.cli - unconfig_wildfly.cli - - - - diff --git a/demos/policy-security-wss-username/Readme.md b/demos/policy-security-wss-username/Readme.md deleted file mode 100644 index 799060546..000000000 --- a/demos/policy-security-wss-username/Readme.md +++ /dev/null @@ -1,95 +0,0 @@ -Introduction -============ -This quickstart demonstrates how policy can be used to control the security characteristics of a -service invocation. The only service in the application is a Bean service called "WorkService". -SSL is used for "confidentiality", and WS-Security UsernameToken is used for "clientAuthentication". - - -Running the quickstart -====================== - - -EAP ----------- - -1. Create an application user: - - ${AS}/bin/add-user.sh - - realm=ApplicationRealm Username=kermit Password=the-frog-1 group=friend - -2. Start JBoss EAP in standalone mode: - - ${EAP}/bin/standalone.sh - -3. Build and deploy the quickstart - - mvn install -Pdeploy - -4. Execute the test. (See "Options" section below.) - -5. Check the server console for output from the service. - -6. Undeploy the application - - mvn clean -Pdeploy - - -Wildfly ----------- - - -1. Create an application user: - - ${WILDFLY}/bin/add-user.sh - - realm=ApplicationRealm Username=kermit Password=the-frog-1 group=friend - -2. Start Wildfly in standalone mode : - - ${WILDFLY}/bin/standalone.sh - -3. Build and deploy the demo : - - mvn install -Pdeploy -Pwildfly - -4. Execute the test. (See "Options" section below.) - -5. Check the server console for output from the service. - -6. Undeploy the application - - mvn clean -Pdeploy -Pwildfly - -Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. - -Options -======= - -When running with no options: - - mvn exec:java - -You will be hitting the http (non-SSL) URL without providing authentication information, and see this in your log: - - Caused by: org.apache.ws.security.WSSecurityException: Failed Authentication : Subject has not been created - -When running with this option: - - mvn exec:java -Dexec.args="clientAuthentication" - -You will be hitting the http (non-SSL) URL while providing authentication information, and see this in your log: - - Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: confidentiality - -When running with this option: - - mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks - -You will be hitting the https (SSL) URL while providing authentication information, and see this in your log: - - :: WorkService :: Received work command => CMD-1398262803294 (caller principal=kermit, in roles? 'friend'=true 'enemy'=false) - - (Because the WorkService is secured, you will see the not-null principal, and true for the expected security role.) - -Success! diff --git a/demos/policy-security-wss-username/pom.xml b/demos/policy-security-wss-username/pom.xml deleted file mode 100644 index 7efc90d00..000000000 --- a/demos/policy-security-wss-username/pom.xml +++ /dev/null @@ -1,232 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-policy-security-wss-username - 2.0.0.Final - bundle - Quickstart Demo : Security Policy : WSS Username (+SSL) - Quickstart Demo : Security Policy : WSS Username (+SSL) - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.policy.security.wss.username - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - config.cli - unconfig.cli - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.apache.commons - not-yet-commons-ssl - test - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demo.policy.security.wss.username.WorkServiceMain - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - config_wildfly.cli - unconfig_wildfly.cli - - - - diff --git a/demos/policy-transaction/Readme.md b/demos/policy-transaction/Readme.md deleted file mode 100644 index 5253dd962..000000000 --- a/demos/policy-transaction/Readme.md +++ /dev/null @@ -1,211 +0,0 @@ -Introduction -============ -This quickstart demonstrates how policy can be used to control the transactional characteristics -of a service invocation. This application contains 4 Bean services, called "WorkService", -"TaskAService", "TaskBService" and "TaskCService. The WorkService accepts commands and dispatch -to other 3 services. -TaskAService expects the global transaction to be propagated, and accepts the "rollback.A" command -to set rollback only flag on that global transaction. -TaskBService requires local transaction, so it suspends the propagated transaction and create new -one. It accepts the "rollback.B" command to set rollback only flang on its local transaction. -TaskCService requires no managed transaction, so it suspends the propagated transaction and run -without managed transaction - i.e. this service never has a transaction to rollback, although it -accepts "rollback.C" command. It simply prints the message saying no transaction when it gets that -command. - -![Policy Transaction Quickstart](https://github.com/jboss-switchyard/quickstarts/raw/master/demos/policy-transaction/policy-transaction.jpg) - - -Running the quickstart -====================== - -EAP ----------- - -1. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy - -4. Execute HornetQClient - - mvn exec:java - -5. Check the server console for output from the service. With the default - configuration of the quickstart, you should see the output below in the - AS server.log. - -6. Undeploy the application - - mvn clean -Pdeploy - - -Wildfly ----------- -1. Start Wildfly in standalone-full mode: - - ${WILDFLY}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${WILDFLY}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy,wildfly - -4. Execute HornetQClient - - mvn exec:java -Pwildfly - -5. Check the server console for output from the service. With the default - configuration of the quickstart, you should see the output below in the - AS server.log. - -6. Undeploy the application - - mvn clean -Pdeploy,wildfly - - -Karaf ----------- -1. Start the Karaf server : - - ${KARAF_HOME}/bin/karaf - -2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} -with the version of SwitchYard that you are using (ex. 2.0.0): - -karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features - -3. Install the feature for the policy-transaction demo : - -karaf@root> features:install switchyard-demo-policy-transaction - -4. Execute JMSClient - - mvn exec:java -Dexec.args="activemq" - -5. Check the server console for output from the service. With the default - configuration of the quickstart, you should see the output below in the - karaf console. - -6. Undeploy the demo: - -karaf@root> features:uninstall switchyard-demo-policy-transaction - - -CONSOLE ----------- -``` -:: WorkService :: Received command => rollback.A -:: TaskAService :: Received command => rollback.A -:: TaskAService :: Marked transaction to rollback! -:: TaskBService :: Received command => rollback.A -:: TaskCService :: Received command => rollback.A -:: TaskCService :: No active transaction -:: WorkService :: transaction is marked as rollback only -:: WorkService :: Received command => rollback.A -:: TaskAService :: Received command => rollback.A -:: TaskAService :: Marked transaction to rollback! -:: TaskBService :: Received command => rollback.A -:: TaskCService :: Received command => rollback.A -:: TaskCService :: No active transaction -:: WorkService :: transaction is marked as rollback only -:: WorkService :: Received command => rollback.A -:: TaskAService :: Received command => rollback.A -:: TaskAService :: Marked transaction to rollback! -:: TaskBService :: Received command => rollback.A -:: TaskCService :: Received command => rollback.A -:: TaskCService :: No active transaction -:: WorkService :: transaction is marked as rollback only -:: WorkService :: Received command => rollback.A -:: TaskAService :: Received command => rollback.A -:: TaskAService :: Rollbacks completed - will be committed -:: TaskBService :: Received command => rollback.A -:: TaskCService :: Received command => rollback.A -:: TaskCService :: No active transaction -:: WorkService :: transaction will be committed -``` - -Scenarios -========= -You can test any of these transaction policy scenarios using this quickstart: - -1) Global transaction propagated to the bean service. This is the default - configuration of the quickstart and requires the TaskAServiceBean to be - annotated with @Requires(transaction=TransactionPolicy.PROPAGATES_TRANSACTION) - and messages to be sent to the policyQSTransacted queue. - -2) Policy violation - transaction required to be propagated, but no transaction - provided by the gateway. To exercise this scenario, send a message to the - policyQSNonTransacted queue with TransactionPolicy.PROPAGATES_TRANSACTION - on the bean service. - -3) Suspend incoming transaction. Change the WorkServiceBean transaction - annotation type to TransactionPolicy.SUSPENDS_TRANSACTION and send a - message to the policyQSTransacted queue with the command "rollback.A". Check - the output and note that the rollback does not impact the transaction used - to receive the JMS message. - -4) A variety of Transaction implementation policy. Each of TaskAService, - TaskBService and TaskCService has different implementation policy. - You can see those behavior with passing combination of the "rollback.A", - "rollback.B" and "rollback.C". TaskAService accepts "rollback.A" and - set rollback only flag on global transaction, so the receiving from JMS - queue will be retried. TaskBService accepts "rollback.B" and set rollback - only flag on local transaction, but it doesn't impact the transaction used - to receive the JMS message. TaskCService accepts "rollback.C", but it doesn't - have any transaction to rollback, just print a message. - - -Options -======= -The maven exec goal in this quickstart accepts the following options: - - mvn exec:java -D exec.args="[command] [queueName]" - -Running "mvn exec:java" with no options is equivalent to: - - mvn exec:java -Dexec.args="rollback policyQSTransacted" - -If the value for 'command' contains the string "rollback", then the bean service -will attempt to rollback an existing transaction. - -The value for 'queueName' should be "policyQSTransacted" or -"policyQSNonTransacted". - -Notes -======= - -o Due to an issue with shutdown processing, server shutdown may take - more than 2 minutes when this quickstart is deployed. To avoid this - problem, undeploy the application before shutting down the server. - -Running a functional test -========================= - -Since this quickstart requires Java EE environment, the functional test -"JmsBindingTest" does not run by default. You need to execute it manually -by following steps. - -1. Build the quickstart: - - mvn clean package - -2. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -3. Execute the test: - - mvn test -DskipTests=false diff --git a/demos/policy-transaction/pom.xml b/demos/policy-transaction/pom.xml deleted file mode 100644 index def6c4eca..000000000 --- a/demos/policy-transaction/pom.xml +++ /dev/null @@ -1,370 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-policy-transaction - 2.0.0.Final - bundle - Quickstart Demo : Transaction Policy - Quickstart Demo : Transaction Policy - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.demo.policy.transaction - true - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - 2.4.1.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-camel-jms - - - org.switchyard.components - switchyard-component-test-mixin-hornetq - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - com.h2database - h2 - test - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - - - org.switchyard - switchyard-test - test - - - org.switchyard.quickstarts - switchyard-quickstart-testutil - test - - - org.jboss.as - jboss-as-arquillian-container-remote - test - - - org.jboss.as - jboss-as-cli - test - - - org.jboss.arquillian.junit - arquillian-junit-container - test - - - org.mockito - mockito-all - test - - - org.hamcrest - hamcrest-core - test - - - org.apache.activemq - activemq-client - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - META-INF/persistence.xml - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demo.policy.transaction.JMSClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipTests} - - config.cli - unconfig.cli - guest - guestp.1 - ${project.build.directory}/${project.build.finalName}.jar - - - - - - - - deploy - - false - - - - wildfly - - 9990 - true - 8080 - - - - org.hornetq - hornetq-core-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-commons - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-journal - ${version.wildfly.hornetq} - test - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - hornetqmixin.port - 8080 - - - hornetqmixin.http.upgrade.enabled - true - - - - - - - - - diff --git a/demos/security-propagation/Readme.md b/demos/security-propagation/Readme.md deleted file mode 100644 index 427494d65..000000000 --- a/demos/security-propagation/Readme.md +++ /dev/null @@ -1,117 +0,0 @@ -Introduction -============ -This quickstart builds on the policy-security-basic quickstart. There is still a Bean service -called "WorkService" which is protected by security policy (SSL is used for "confidentiality", -and Basic Authentication is used for "clientAuthentication"). However this quickstart differs -in that it calls another Bean service called "BackEndService" which is also protected by -security policy, but there is no need for re-authentication, since the current security -context is propagated from one service to the next. Furthermore, an EJB which itself is -protected via annotations is also called, and the security context is propagated there too. - - -Running the quickstart -====================== - -EAP ----------- - -1. Create an application user: - - ${AS}/bin/add-user.sh - User : kermit - Password : the-frog-1 - Group : friend - -2. Start JBoss AS in standalone mode: - - ${AS}/bin/standalone.sh - -3. Build and deploy the ejb, then the basic application - - cd ejb; mvn install -Pdeploy - cd ../basic; mvn install -Pdeploy - -4. Execute the test. (See "Options" section below.) - -5. Check the server console for output from the service. - -6. Undeploy the application, then the ejb - - mvn clean -Pdeploy - cd ../ejb; mvn clean -Pdeploy - - -Wildfly ----------- - - -1. Create an application user: - - ${WILDFLY}/bin/add-user.sh - User : kermit - Password : the-frog-1 - Group : friend - -2. Edit the standalone.xml placed on ${WILDFLY_HOME}/standalone/configuration - - Remove the default-security-domain tag inside of the ejb3 domain - - - - - - - ... -- - - - - -3. Start Wildfly in standalone mode : - - ${WILDFLY}/bin/standalone.sh - -4. Build and deploy the demo : - - cd ejb; mvn install -Pdeploy -Pwildfly - cd ../basic; mvn install -Pdeploy -Pwildfly - -5. Execute the test. (See "Options" section below.) - -6. Check the server console for output from the service. - -7. Undeploy the application, then the ejb - - mvn clean -Pdeploy -Pwildfly - cd ../ejb; mvn clean -Pdeploy -Pwildfly - -Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. - - - -Options -======= - -When running with no options: - - mvn exec:java - -You will be hitting the http (non-SSL) URL, and see this in your log: - - Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: authorization clientAuthentication confidentiality - -When running with this option: - - mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks - -You will be hitting the https (SSL) URL and providing authentication information, and see this in your log: - - :: WorkService :: Received work command => CMD-1401308184129 (caller principal=kermit, in roles? 'friend'=true 'enemy'=false) - :: BackEndService :: process => CMD-1401308184129 (caller principal=kermit, in roles? 'friend'=true 'enemy'=false) - :: WorkService :: returned from BackEndService => Processed by BackEndService: CMD-1401308184129 - :: TestEJBBean :: process => CMD-1401308184129 (caller principal=[roles=[friend],principal=kermit], in roles? 'friend'=true 'enemy'=false) - :: WorkService :: returned from TestEJBBean => Processed by TestEJBBean: CMD-1401308184129 - - (Because the WorkService, BackEndService and TestEBJBean are secured, you will see the not-null principal, and true for the expected security role.) - -You can play with the exec.args and only specify one of "confidentiality" or "clientAuthentication". I bet you can guess what will happen... ;) diff --git a/demos/security-propagation/basic/pom.xml b/demos/security-propagation/basic/pom.xml deleted file mode 100644 index 21e43ece9..000000000 --- a/demos/security-propagation/basic/pom.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-security-propagation - 2.0.0.Final - - switchyard-demo-security-propagation-basic - Quickstart Demo : Security Propagation : Basic Authentication (+SSL) to Bean + EJB - Quickstart Demo : Security Propagation : Basic Authentication (+SSL) to Bean + EJB - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 9999 - 1.6 - 1.6 - 1.0.2.Final - config.cli - unconfig.cli - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.apache.commons - not-yet-commons-ssl - test - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.quickstarts.demos - switchyard-demo-security-propagation-ejb - - - org.jboss.spec.javax.ejb - jboss-ejb-api_3.1_spec - provided - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.demo.security.propagation.basic.WorkServiceMain - false - - - - - - - deploy - - false - - - - wildfly - - 9990 - config_wildfly.cli - unconfig_wildfly.cli - - - - diff --git a/demos/security-propagation/ejb/pom.xml b/demos/security-propagation/ejb/pom.xml deleted file mode 100644 index d4a897f58..000000000 --- a/demos/security-propagation/ejb/pom.xml +++ /dev/null @@ -1,115 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-security-propagation - 2.0.0.Final - - switchyard-demo-security-propagation-ejb - ejb - Quickstart Demo : Security Propagation : EJB - Quickstart Demo : Security Propagation : EJB - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 9999 - 1.6 - 1.6 - 1.0.2.Final - - - - javax.enterprise - cdi-api - provided - - - org.jboss.spec.javax.ejb - jboss-ejb-api_3.1_spec - provided - - - org.jboss.ejb3 - jboss-ejb3-ext-api - provided - - - log4j - log4j - - - - ${project.artifactId} - - - maven-ejb-plugin - - 3.1 - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/demos/security-propagation/pom.xml b/demos/security-propagation/pom.xml deleted file mode 100644 index fea93a8b9..000000000 --- a/demos/security-propagation/pom.xml +++ /dev/null @@ -1,158 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-security-propagation - 2.0.0.Final - pom - Quickstart Demo: Security Propagation - Quickstart Demo: Security Propagation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - true - 9999 - 1.3.1 - 1.0.2.Final - - - ejb - basic - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - org.switchyard.quickstarts.demos - switchyard-demo-security-propagation-ejb - ${project.version} - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - - maven-clean-plugin - - - - ${project.build.directory} - - - - - - - - - wildfly - - 9990 - - - - diff --git a/demos/transaction-propagation/client/pom.xml b/demos/transaction-propagation/client/pom.xml deleted file mode 100644 index 50025efa7..000000000 --- a/demos/transaction-propagation/client/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-transaction-propagation - 2.0.0.Final - - switchyard-demo-transaction-propagation-client - jar - Quickstart Demo: Remote Transaction Propagation - Client - Quickstart Demo: Remote Transaction Propagation - Client - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - - - - org.switchyard - switchyard-remote - test - - - - ${project.artifactId} - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.demo.txpropagation.RemoteClient - false - - - - - diff --git a/demos/transaction-propagation/credit/pom.xml b/demos/transaction-propagation/credit/pom.xml deleted file mode 100644 index 496ece87c..000000000 --- a/demos/transaction-propagation/credit/pom.xml +++ /dev/null @@ -1,205 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-transaction-propagation - 2.0.0.Final - - switchyard-demo-transaction-propagation-credit - Quickstart Demo: Remote Transaction Propagation - Credit Service - Quickstart Demo: Remote Transaction Propagation - Credit Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - 1.3.168 - remote - 10999 - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-jca - test - - - org.switchyard.components - switchyard-component-rules - - - org.switchyard.components - switchyard-component-sca - - - org.switchyard.components - switchyard-component-camel-jpa - - - org.hibernate - hibernate-core - - - org.hibernate - hibernate-entitymanager - - - org.switchyard.components - switchyard-component-bean - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - de.juplo - hibernate4-maven-plugin - 1.0.3 - - - com.h2database - h2 - ${version.com.h2database} - - - - - create - install - - export - - - - - org.h2.Driver - org.hibernate.dialect.H2Dialect - jdbc:h2:tcp://localhost/h2db/credit - sa - sa - ${deploy.skip} - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - - - deploy - - false - - - - wildfly - - http-remoting - 10990 - - - - diff --git a/demos/transaction-propagation/dealer/pom.xml b/demos/transaction-propagation/dealer/pom.xml deleted file mode 100644 index 3c5b1ffc3..000000000 --- a/demos/transaction-propagation/dealer/pom.xml +++ /dev/null @@ -1,202 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts.demos - switchyard-demo-transaction-propagation - 2.0.0.Final - - switchyard-demo-transaction-propagation-dealer - Quickstart Demo: Remote Transaction Propagation - Dealer Service - Quickstart Demo: Remote Transaction Propagation - Dealer Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - 1.3.168 - 9999 - remote - true - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-sca - - - org.switchyard.components - switchyard-component-camel-jpa - - - org.hibernate - hibernate-core - - - org.hibernate - hibernate-entitymanager - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-jca - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - de.juplo - hibernate4-maven-plugin - 1.0.3 - - - com.h2database - h2 - ${version.com.h2database} - - - - - create - install - - export - - - - - org.h2.Driver - org.hibernate.dialect.H2Dialect - jdbc:h2:tcp://localhost/h2db/dealer - sa - sa - ${deploy.skip} - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - - - deploy - - false - - - - wildfly - - http-remoting - 9990 - - - - diff --git a/demos/transaction-propagation/pom.xml b/demos/transaction-propagation/pom.xml deleted file mode 100644 index 65067ec38..000000000 --- a/demos/transaction-propagation/pom.xml +++ /dev/null @@ -1,179 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-transaction-propagation - 2.0.0.Final - pom - Quickstart Demo: Remote Transaction Propagation - Quickstart Demo: Remote Transaction Propagation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.6 - 1.6 - true - 9999 - 1.3.1 - 1.0.2.Final - - - client - credit - dealer - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - - com.edugility - h2-maven-plugin - 1.0 - false - - ${project.build.directory} - - - - Spawn a new H2 TCP server - install - - spawn - - - - Stop a spawned H2 TCP server - pre-clean - - stop - - - - - - maven-clean-plugin - - - - ${project.build.directory} - - - - - - - - - wildfly - - 9990 - - - - diff --git a/demos/webapp-deploy/pom.xml b/demos/webapp-deploy/pom.xml deleted file mode 100644 index 6d7eea499..000000000 --- a/demos/webapp-deploy/pom.xml +++ /dev/null @@ -1,121 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts.demos - switchyard-demo-webapp-deploy - 2.0.0.Final - war - Quickstart Demo : JEE Webapp Deployment - Quickstart Demo : JEE Webapp Deployment - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 1.3.1 - 1.6 - 1.6 - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-deploy-webapp - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.jboss.weld.servlet - weld-servlet-core - - - org.switchyard - switchyard-test - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - diff --git a/ear-deployment/README.md b/ear-deployment/README.md deleted file mode 100644 index 4a6450bcb..000000000 --- a/ear-deployment/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# EAR Deployment Quickstart - -This quickstart provides an example packaging multiple SwitchYard applications, associated libraries, and a JMS destination inside an EAR archive. The quickstart consists of the following pieces: - -* artifacts : contains XSDs, WSDLs, and Java domain objects which are used by service providers and consumers across application projects -* order-service : provides two services - OrderService and InventoryService -* order-consumer : consumes OrderService through a SOAP/HTTP binding -* ear-assembly : packages all of the above into an EAR archive - - -## Deploying the EAR - -Preqrequisites -============== -Maven - - -Running the quickstart -====================== - - -EAP ----------- -1. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the EAR - - mvn install -Pdeploy - -4. Test the application - - mvn exec:java - -5. Undeploy the EAR - - mvn clean -Pdeploy - - -Wildfly ----------- -1. Start Wildfly in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the EAR - - mvn install -Pdeploy -Pwildfly - -4. Test the application - - mvn exec:java -Pwildfly - -5. Undeploy the EAR - - mvn clean -Pdeploy -Pwildfly - diff --git a/ear-deployment/artifacts/pom.xml b/ear-deployment/artifacts/pom.xml deleted file mode 100644 index 63394daae..000000000 --- a/ear-deployment/artifacts/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-ear-deployment - 2.0.0.Final - - switchyard-ear-deployment-artifacts - jar - SwitchYard Quickstart: ear-deployment - artifacts - Quickstart : EAR Deployment - Service Artifacts - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - ${project.artifactId} - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - diff --git a/ear-deployment/ear-assembly/pom.xml b/ear-deployment/ear-assembly/pom.xml deleted file mode 100644 index 09968f0c2..000000000 --- a/ear-deployment/ear-assembly/pom.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-ear-deployment - 2.0.0.Final - - switchyard-ear-deployment-ear-assembly - ear - SwitchYard Quickstart: ear-deployment - ear-assembly - Quickstart : EAR Deployment - Application Assembly - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - org.switchyard.quickstarts - switchyard-ear-deployment-artifacts - - - org.switchyard.quickstarts - switchyard-ear-deployment-order-consumer - - - org.switchyard.quickstarts - switchyard-ear-deployment-order-service - - - - ${project.parent.artifactId} - - - maven-ear-plugin - 2.8 - - true - 5 - - - org.switchyard.quickstarts - switchyard-ear-deployment-artifacts - lib - - - org.switchyard.quickstarts - switchyard-ear-deployment-order-consumer - true - - - org.switchyard.quickstarts - switchyard-ear-deployment-order-service - true - - - - switchyard-ear-*, - lib/*, - META-INF/* - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - diff --git a/ear-deployment/order-consumer/pom.xml b/ear-deployment/order-consumer/pom.xml deleted file mode 100644 index 89aa94302..000000000 --- a/ear-deployment/order-consumer/pom.xml +++ /dev/null @@ -1,198 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-ear-deployment - 2.0.0.Final - - switchyard-ear-deployment-order-consumer - SwitchYard Quickstart: ear-deployment - order-consumer - Quickstart : EAR Deployment - Order Consumer - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - 2.4.1.Final - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.quickstarts - switchyard-ear-deployment-artifacts - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-hornetq - test - - - junit - junit - test - - - org.switchyard.components - switchyard-component-camel-jms - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-sca - - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - org.switchyard.quickstarts.eardeploy.OrderIntakeClient - test - false - - ${project.build.directory}/test-classes/order.xml - - - - - - - - wildfly - - true - 8080 - - - - org.hornetq - hornetq-core-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-commons - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-journal - ${version.wildfly.hornetq} - test - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - hornetqmixin.port - 8080 - - - hornetqmixin.http.upgrade.enabled - true - - - - - - - - - diff --git a/ear-deployment/order-service/pom.xml b/ear-deployment/order-service/pom.xml deleted file mode 100644 index 5737853d5..000000000 --- a/ear-deployment/order-service/pom.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-ear-deployment - 2.0.0.Final - - switchyard-ear-deployment-order-service - SwitchYard Quickstart: ear-deployment - order-service - Quickstart : EAR Deployment - Order Service - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.quickstarts - switchyard-ear-deployment-artifacts - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - org.switchyard.components - switchyard-component-sca - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - - dummy - true - - - - - diff --git a/ear-deployment/pom.xml b/ear-deployment/pom.xml deleted file mode 100644 index 6aaa29c13..000000000 --- a/ear-deployment/pom.xml +++ /dev/null @@ -1,158 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-ear-deployment - 2.0.0.Final - pom - SwitchYard Quickstart: ear-deployment - Quickstart : EAR Deployment - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - 9999 - 1.6 - 1.6 - 1.3.1 - 2.4.0 - 1.0.2.Final - - - artifacts - order-service - order-consumer - ear-assembly - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - org.switchyard.quickstarts - switchyard-ear-deployment-artifacts - ${project.version} - - - org.switchyard.quickstarts - switchyard-ear-deployment-order-consumer - ${project.version} - - - org.switchyard.quickstarts - switchyard-ear-deployment-order-service - ${project.version} - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - false - - true - - - - org.codehaus.mojo - exec-maven-plugin - false - - dummy - true - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - - - - diff --git a/http-binding/pom.xml b/http-binding/pom.xml deleted file mode 100644 index 72f6c3ced..000000000 --- a/http-binding/pom.xml +++ /dev/null @@ -1,263 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-http-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: http-binding - Quickstart : HTTP Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.http.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-http - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.http.binding.HttpBindingClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.http.client.port - 8181 - - - - - - - - - wildfly - - 9990 - - - - diff --git a/jca-inflow-activemq/pom.xml b/jca-inflow-activemq/pom.xml deleted file mode 100644 index b9765bc71..000000000 --- a/jca-inflow-activemq/pom.xml +++ /dev/null @@ -1,275 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-jca-inflow-activemq - 2.0.0.Final - SwitchYard Quickstart: jca-inflow-activemq - Quickstart : JCA Inflow Binding for ActiveMQ - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - true - true - 9999 - 1.6 - 1.6 - 1.3.1 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-jca - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-activemq - test - - - org.apache.activemq - activemq-rar - rar - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - test - - - org.jboss.as - jboss-as-arquillian-container-remote - test - - - org.switchyard.quickstarts - switchyard-quickstart-testutil - test - - - org.jboss.arquillian.junit - arquillian-junit-container - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy-activemq - install - - deploy-artifact - - - org.apache.activemq - activemq-rar - activemq-ra.rar - - - - - - ${deploy-rar.skip} - - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy-activemq - clean - - undeploy - - - activemq-ra.rar - - - - - - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.jca.inflow.ActiveMQClient - - Skippy - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipTests} - - config.cli - unconfig.cli - ${project.build.directory}/${project.build.finalName}.jar - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - deploy-rar - - false - - - - wildfly - - 9990 - - - - diff --git a/jca-inflow-hornetq/Readme.md b/jca-inflow-hornetq/Readme.md deleted file mode 100644 index 14e0f3be7..000000000 --- a/jca-inflow-hornetq/Readme.md +++ /dev/null @@ -1,101 +0,0 @@ -Introduction -============ -This quickstart demonstrates the usage of the JCA Component and it's service -binding feature, by binding to a HornetQ Queue. When a message arrives in this -queue the service will be invoked. This quickstart is using XPath dynamic -operation selector which determines the service operation to be invoked by -reading message content. If you pass the name and language parameters at step 7 -like following: - - mvn exec:java -Dexec.args="Fernando spanish" - -then operation selector choose the spanish operation so you would get a spanish greeting like this: - - Hola Fernando :-) - - -EAP ----------- -1. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy - -4. Execute HornetQClient - - mvn exec:java - -5. Check the server console for output from the service. - -6. Undeploy the quickstart: - - mvn clean -Pdeploy - - -Wildfly ----------- -1. Start Wildfly in standalone-full mode: - - ${AS}/bin/standalone.sh -server-config standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy -Pwildfly - -4. Execute HornetQClient - - mvn exec:java -Pwildfly - -5. Check the server console for output from the service. - -6. Undeploy the quickstart: - - mvn clean -Pdeploy -Pwildfly - - -Karaf ----------- -No Karaf feature is present for this quickstart. - - -Expected Results -================ -``` -21:51:08,132 INFO [stdout] (Thread-1 (HornetQ-client-global-threads-1584009536)) Hello there Skippy :-) -``` - -Running a functional test -========================= - -Since this quickstart requires Java EE environment, the functional test -"JCAInflowBindingTest" does not run by default. You need to execute it manually -by following steps. - -1. Build the quickstart: - - mvn clean package - -2. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -3. Execute the test: - - mvn test -DskipTests=false - -## Further Reading - -1. [HornetQ Bindings Documentation](https://docs.jboss.org/author/display/SWITCHYARD/JCA) diff --git a/jca-inflow-hornetq/pom.xml b/jca-inflow-hornetq/pom.xml deleted file mode 100644 index 42f28494e..000000000 --- a/jca-inflow-hornetq/pom.xml +++ /dev/null @@ -1,302 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-jca-inflow-hornetq - 2.0.0.Final - SwitchYard Quickstart: jca-inflow-hornetq - Quickstart : JCA Inflow Binding for HornetQ - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - true - 9999 - 1.6 - 1.6 - 1.3.1 - 1.0.2.Final - 2.4.1.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-jca - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-hornetq - test - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - test - - - org.jboss.as - jboss-as-arquillian-container-remote - test - - - org.switchyard.quickstarts - switchyard-quickstart-testutil - test - - - org.jboss.arquillian.junit - arquillian-junit-container - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.jca.inflow.HornetQClient - - Skippy - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipTests} - - config.cli - unconfig.cli - guest - guestp.1 - ${project.build.directory}/${project.build.finalName}.jar - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - true - 8080 - - - - org.hornetq - hornetq-core-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-commons - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-journal - ${version.wildfly.hornetq} - test - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - hornetqmixin.port - 8080 - - - hornetqmixin.http.upgrade.enabled - true - - - - - - - - - diff --git a/jca-outbound-activemq/pom.xml b/jca-outbound-activemq/pom.xml deleted file mode 100644 index df377ee20..000000000 --- a/jca-outbound-activemq/pom.xml +++ /dev/null @@ -1,263 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-jca-outbound-activemq - 2.0.0.Final - SwitchYard Quickstart: jca-outbound-activemq - Quickstart : JCA Outbound Binding for ActiveMQ - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - true - true - 9999 - 1.6 - 1.6 - 1.3.1 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-jca - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-activemq - test - - - org.apache.activemq - activemq-rar - rar - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - - - org.apache.activemq - activemq-client - - - org.jboss.as - jboss-as-arquillian-container-remote - test - - - org.switchyard.quickstarts - switchyard-quickstart-testutil - test - - - org.jboss.arquillian.junit - arquillian-junit-container - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy-activemq - install - - deploy-artifact - - - org.apache.activemq - activemq-rar - activemq-ra.rar - - - - - - ${deploy-rar.skip} - - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy-activemq - clean - - undeploy - - - activemq-ra.rar - - - - - - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.jca.outbound.ActiveMQClient - - BREAD - PIZZA - JAM - POTATO - MILK - JAM - TOYODA RUV4 2008 SILVER - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipTests} - - config.cli - unconfig.cli - ${project.build.directory}/${project.build.finalName}.jar - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - deploy-rar - - false - - - - wildfly - - 9990 - - - - diff --git a/jca-outbound-hornetq/Readme.md b/jca-outbound-hornetq/Readme.md deleted file mode 100644 index c34b05b78..000000000 --- a/jca-outbound-hornetq/Readme.md +++ /dev/null @@ -1,108 +0,0 @@ -Introduction -============ -This quickstart demonstrates the usage of the JCA Component and it's reference binding feature, -by binding to a HornetQ Queue. When service is invoked the message will be sent to the queue. -This quickstart also has a service binding to a HornetQ Queue. When you send a message into -OrderService queue, corresponding OrderServiceBean#process() will be called. And then -OrderServiceBean will forward it to the ShippingQueue or FillingStockQueue through the reference bindings. - - -EAP ----------- -1. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy - -4. Execute HornetQClient - - mvn exec:java - -5. Check the output from the client. - -6. Undeploy the quickstart: - - mvn clean -Pdeploy - - -Wildfly ----------- -1. Start Wildfly in standalone-full mode: - - ${AS}/bin/standalone.sh -server-config standalone-full.xml - -2. Create an application user: - - ${AS}/bin/add-user.sh - realm=ApplicationRealm user=guest password=guestp.1 group=guest - -3. Build and deploy the quickstart - - mvn install -Pdeploy -Pwildfly - -4. Execute HornetQClient - - mvn exec:java -Pwildfly - -5. Check the output from the client. - -6. Undeploy the quickstart: - - mvn clean -Pdeploy -Pwildfly - - -Karaf ----------- -No Karaf feature is present for this quickstart. - - - -Expected Results -================ -``` -[INFO] --- exec-maven-plugin:1.2:java (default-cli) @ switchyard-quickstart-jca-outbound-hornetq --- -* * * SHIPPING ORDERS * * * - - JAM - - MILK - - BREAD - - JAM - -* * * PENDING ORDERS (FILLING STOCK) * * * - - PIZZA - - POTATO - - TOYODA RUV4 2008 SILVER -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -``` - -Running a functional test -========================= - -Since this quickstart requires Java EE environment, the functional test -"JCAOutboundBindingTest" does not run by default. You need to execute it manually -by following steps. - -1. Build the quickstart: - - mvn clean package - -2. Start EAP in standalone-full mode: - - ${AS}/bin/standalone.sh --server-config=standalone-full.xml - -3. Execute the test: - - mvn test -DskipTests=false - -## Further Reading - -1. [JCA Bindings Documentation](https://docs.jboss.org/author/display/SWITCHYARD/JCA) diff --git a/jca-outbound-hornetq/pom.xml b/jca-outbound-hornetq/pom.xml deleted file mode 100644 index c3b2da268..000000000 --- a/jca-outbound-hornetq/pom.xml +++ /dev/null @@ -1,286 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-jca-outbound-hornetq - 2.0.0.Final - SwitchYard Quickstart: jca-outbound-hornetq - Quickstart : JCA Outbound Binding for HornetQ - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - true - true - 9999 - 1.6 - 1.6 - 1.0.2.Final - 2.4.1.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-jca - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-hornetq - test - - - org.jboss.spec.javax.jms - jboss-jms-api_1.1_spec - test - - - org.jboss.as - jboss-as-arquillian-container-remote - test - - - org.switchyard.quickstarts - switchyard-quickstart-testutil - test - - - org.jboss.arquillian.junit - arquillian-junit-container - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - - - - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.jca.outbound.HornetQClient - - BREAD - PIZZA - JAM - POTATO - MILK - JAM - TOYODA RUV4 2008 SILVER - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipTests} - - config.cli - unconfig.cli - guest - guestp.1 - ${project.build.directory}/${project.build.finalName}.jar - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - wildfly - - 9990 - true - 8080 - - - - org.hornetq - hornetq-core-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-client - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-jms-server - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-commons - ${version.wildfly.hornetq} - test - - - org.hornetq - hornetq-journal - ${version.wildfly.hornetq} - test - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - hornetqmixin.port - 8080 - - - hornetqmixin.http.upgrade.enabled - true - - - - - - - - - diff --git a/pom.xml b/pom.xml index 4130a2248..96a39aa29 100644 --- a/pom.xml +++ b/pom.xml @@ -15,29 +15,118 @@ 4.0.0 - org.switchyard - switchyard-parent - 2.0.0.Final - ../parent + org.jboss.integration-platform + jboss-integration-platform-parent + 6.0.0.CR24 - org.switchyard.quickstarts - switchyard-quickstart-parent + org.switchyard + switchyard-parent + 2.1.0-SNAPSHOT pom - SwitchYard Quickstart: quickstarts - Quickstarts repository for SwitchYard + SwitchYard + The parent for SwitchYard modules http://switchyard.org JBoss by Red Hat http://jboss.org + + jira + http://jira.jboss.org/browse/SWITCHYARD + + + + SwitchYard committers + + Apache License, Version 2.0 - repo http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + UTF-8 + 1.5.4.Final + 6.3.0.GA + 6.0.0.CR24 + + 6.3 + 0.GA + 1.18 + 1.9 + + 6.2.0.redhat-064 + 1.6 + + 1.2.2.Final + 2.0.2.Final + 3.2.0.Final + 3.2.0.Final + 2.4.6.Final + + 9.2.1.5 + + 6.2.0.CR3 + 6.2.0.CR3 + 6.2.0.CR3 + + 4.2.0.Final + + 2.4.0 + 2.5 + 3.1 + + version="[$(version;==;${switchyard.osgi.version}),$(version;=+;${switchyard.osgi.version}))" + [$(version;==;$(@)),$(version;+;$(@))) + + true + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + org.switchyard.* + + ${switchyard.osgi.export.pkg};version="${switchyard.osgi.version}";-noimport:=true + + + + ${project.name} + ${project.groupId}.${project.artifactId} + false + {maven-resources} + + !* + + + + + + + scm:git:https://github.com/jboss-switchyard/parent.git + scm:git:ssh://git@github.com:jboss-switchyard/parent.git + http://github.com/jboss-switchyard/parent + + + jboss-enterprise-techpreview-group + JBoss Enterprise Technology Preview Maven Repository Group + http://maven.repository.redhat.com/techpreview/all/ + default + + true + never + + + true + never + + jboss-public-repository-group JBoss Public Maven Repository Group @@ -52,95 +141,1519 @@ never + + fusesource-public-release-repository-group + https://repository.jboss.org/nexus/content/repositories/fs-releases + + true + never + + + true + never + + - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - 1.6 - 1.6 - - - testutil - bean-service - bpel-jms-binding - bpel-loan-approval - bpel-say-hello - bpel-simple-correlation - bpel-xts-subordinate-wsba - bpel-xts-wsat - bpm-service - camel-atom-binding - camel-file-binding - camel-cxf-binding - camel-jaxb - camel-hl7 - camel-amqp-binding - camel-ftp-binding - camel-jms-binding - camel-netty-binding - camel-quartz-binding - camel-rss-binding - camel-jpa-binding - camel-sql-binding - camel-mail-binding - camel-mqtt-binding - camel-sap-binding - camel-service - camel-soap-proxy - camel-bus-cdi - camel-bindy - camel-saxon - ear-deployment - http-binding - remote-invoker - rest-binding - rules-camel-cbr - rules-interview - rules-interview-container - rules-interview-dtable - soap-addressing - soap-attachment - soap-binding-rpc - soap-mtom - jca-inflow-hornetq - jca-outbound-hornetq - jca-inflow-activemq - jca-outbound-activemq - transform-dozer - transform-jaxb - transform-json - transform-smooks - transform-xslt - validate-xml - demos/helpdesk - demos/library - demos/orders - demos/webapp-deploy - demos/multiApp - demos/policy-security-basic - demos/policy-security-cert - demos/policy-security-saml - demos/policy-security-wss-signencrypt - demos/policy-security-wss-username - demos/policy-transaction - demos/cluster - demos/security-propagation - demos/transaction-propagation - - + + + jboss-public-repository-group + JBoss Public Maven Repository Group + https://repository.jboss.org/nexus/content/groups/public/ + default + + never + + + never + + + + + + + + maven-enforcer-plugin + + + enforce-plugin-versions + none + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.apache.maven.plugins + maven-dependency-plugin + [2.3,) + + unpack + unpack-dependencies + copy-dependencies + + + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + [1.0,) + + enforce + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + [1.0,) + + add-resource + + + + + + + + + org.codehaus.mojo + exec-maven-plugin + [1.0,) + + java + + + + + + + + + org.apache.felix + maven-bundle-plugin + [1.0,) + + cleanVersions + + + + + + + + + + + + org.codehaus.mojo + xml-maven-plugin + 1.0 + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + ${switchyard.osgi.exclude.dependencies} + + ${switchyard.osgi.bundle.name} + ${switchyard.osgi.symbolic.name} + http://switchyard.org + ${switchyard.osgi.activator} + ${switchyard.osgi.export} + ${switchyard.osgi.import} + ${switchyard.osgi.dynamic} + ${switchyard.osgi.private} + JBoss SwitchYard + ${project.version} + ${switchyard.osgi.resource} + <_versionpolicy>${switchyard.osgi.import.default.version} + <_failok>${switchyard.osgi.failok} + ${switchyard.osgi.services.export} + ${switchyard.osgi.embed.dependency} + ${switchyard.osgi.require.bundle} + ${switchyard.osgi.fragment.host} + ${switchyard.osgi.provide.capability} + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.servicemix.tooling + depends-maven-plugin + 1.2 + + + + + + org.apache.maven.plugins + maven-site-plugin + 2.2 + + build/src/site + + + + org.apache.maven.plugins + maven-jar-plugin + 2.3.1 + + + commons-lang + commons-lang + 2.4 + + + + + true + + true + true + + + ${project.groupId} + ${project.artifactId} + ${project.packaging} + ${project.name} + ${project.description} + ${project.url} + ${project.version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + true + true + true + + + + org.apache.maven.plugins + maven-resources-plugin + 2.4.3 + + ${project.build.sourceEncoding} + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.6 + + + true + + + ${project.version} + + + **/*Test*.java + + + **/Abstract*.java + **/*$* + + + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.8 + + true + + false + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.8 + + checkstyle/checkstyle.xml + false + checkstyle/suppressions.xml + true + + + + + org.switchyard + switchyard-build + ${project.version} + + + + + check-style + site + + checkstyle + + + + + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.2 + + findbugs/findbugs-exclude.xml + Normal + Max + true + + + + org.switchyard + switchyard-build + ${project.version} + + + + + find-bugs + + findbugs + + site + + + + + maven-enforcer-plugin + + + enforce-java-version + + enforce + + + + + 1.7 + To build this project JDK 1.7 (or greater) is required. Please install it. + + + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-clean-plugin + ${version.maven.clean.plugin} + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + org.apache.maven.plugins + maven-war-plugin + 2.3 + + + org.apache.maven.plugins + maven-ejb-plugin + 2.3 + + + org.apache.maven.plugins + maven-deploy-plugin + 2.7 + + + org.apache.maven.plugins + maven-archetype-plugin + 2.2 + + + + org.apache.felix + maven-bundle-plugin + true + + + cleanVersions + generate-sources + + cleanVersions + + + + ${project.version} + + + + + + + + + maven-3 - - assembly - + false + + maven-site-plugin + true + - - assembly - + + + + maven-site-plugin + 3.0-beta-3 + + build/src/site + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.4 + + + + cim + + help + index + issue-tracking + license + mailing-list + modules + plugin-management + plugins + project-team + scm + summary + + + + + + + + + attach-descriptor + + attach-descriptor + + + + + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.8 + + checkstyle/checkstyle.xml + false + checkstyle/suppressions.xml + false + + + + + org.codehaus.mojo + findbugs-maven-plugin + 2.5.2 + + true + + target/site + + + + org.apache.maven.plugins + maven-surefire-report-plugin + 2.6 + + true + + + + + + + + + org.jboss.integration-platform + jboss-integration-platform-bom + ${version.ip.bom} + pom + import + + + org.kie + kie-bom + ${version.org.kie} + pom + import + + + org.drools + drools-bom + ${version.org.drools} + pom + import + + + org.jbpm + jbpm-bom + ${version.org.jbpm} + pom + import + + + org.jboss.bom + eap6-supported-artifacts + ${version.redhat.eap6.bom} + pom + import + + + org.jboss.as + jboss-as-parent + ${version.org.jboss.as} + pom + import + + + org.jboss.as + jboss-as-console-bom + ${version.org.jboss.as.console} + pom + import + + + + org.apache.maven.plugins + maven-plugin-plugin + ${version.maven.plugin.plugin} + provided + + + org.apache.maven.plugin-tools + maven-plugin-annotations + ${version.maven.plugin.plugin} + + + org.fusesource + camel-sap + ${version.camelsap} + + + com.sap.conn.jco + * + + + + + org.fusesource.mqtt-client + mqtt-client + ${version.org.fusesource.mqtt-client} + + + org.jboss.ws + jbossws-jboss720-server-integration + ${version.jbossws.jboss720.server.integration} + + + net.sourceforge.saxon + saxonhe + ${version.net.sourceforge.saxon} + + + + org.jboss.bpm + activity-monitor-model + ${version.activity.monitor.model} + + + org.hibernate + hibernate-annotations + + + + + org.jboss.bpm + gwt-console-rpc + ${version.riftsaw.console} + + + org.jboss.bpm + gwt-console-server-integration + ${version.riftsaw.console} + + + org.overlord + overlord-commons-services + ${version.overlord-commons} + + + org.jboss.soa.bpel + riftsaw-agents + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-bpel-api + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-bpel-compiler + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-bpel-dao + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-bpel-epr + ${version.riftsaw.ode} + + + org.jboss.javaee + jboss-javaee + + + + + org.jboss.soa.bpel + riftsaw-bpel-obj + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-bpel-ql + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-bpel-runtime + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-bpel-schemas + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-bpel-store + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-dao-jpa + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-dao-jpa-hibernate + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-jacob + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-scheduler-simple + ${version.riftsaw.ode} + + + org.jboss.soa.bpel + riftsaw-utils + ${version.riftsaw.ode} + + + org.riftsaw + engine + ${version.riftsaw.engine} + + + org.hornetq + hornetq-core + + + + + org.riftsaw.console + riftsaw-bpel2svg + ${version.riftsaw.engine} + + + org.riftsaw.console + riftsaw-console-integration + ${version.riftsaw.engine} + + + org.riftsaw.console + riftsaw-bpaf + ${version.riftsaw.engine} + + + org.riftsaw.console + switchyard-bpel-console + ${version.riftsaw.engine} + war + + + org.riftsaw.console + switchyard-bpel-console-server + ${version.riftsaw.engine} + war + + + + org.switchyard + switchyard-admin + ${project.version} + + + org.switchyard + switchyard-as7-modules + ${project.version} + zip + + + org.switchyard + switchyard-as7-standalone-bundle + ${project.version} + zip + + + org.switchyard + switchyard-api + ${project.version} + + + org.switchyard + switchyard-bus-camel + ${project.version} + + + org.switchyard + switchyard-build + ${project.version} + + + org.switchyard + switchyard-common + ${project.version} + + + org.switchyard + switchyard-common-camel + ${project.version} + + + org.switchyard + switchyard-common-cdi + ${project.version} + + + org.switchyard + switchyard-config + ${project.version} + + + org.switchyard.console + switchyard-console-application + ${project.version} + resources + + + org.switchyard.console + switchyard-console-component-core + ${project.version} + + + org.switchyard.console + switchyard-console-component-bean + ${project.version} + + + org.switchyard.console + switchyard-console-component-bpel + ${project.version} + + + org.switchyard.console + switchyard-console-component-bpm + ${project.version} + + + org.switchyard.console + switchyard-console-component-camel + ${project.version} + + + org.switchyard.console + switchyard-console-component-clojure + ${project.version} + + + org.switchyard.console + switchyard-console-component-hornetq + ${project.version} + + + org.switchyard.console + switchyard-console-component-rules + ${project.version} + + + org.switchyard.console + switchyard-console-component-soap + ${project.version} + + + org.switchyard.console + switchyard-console-extension + ${project.version} + + + org.switchyard + switchyard-deploy + ${project.version} + + + org.switchyard + switchyard-deploy-cdi + ${project.version} + + + org.switchyard + switchyard-deploy-jboss-as7 + ${project.version} + + + org.switchyard + switchyard-deploy-osgi + ${project.version} + + + org.switchyard + switchyard-deploy-wildfly + ${project.version} + + + org.switchyard + switchyard-wildfly-bundle + zip + ${project.version} + + + org.switchyard.karaf + switchyard-karaf-deploy + ${project.version} + + + org.switchyard.karaf + switchyard + xml + features + ${project.version} + + + org.switchyard + switchyard-deploy-webapp + ${project.version} + + + org.switchyard + switchyard-extensions-java + ${project.version} + + + org.switchyard + switchyard-extensions-wsdl + ${project.version} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard + switchyard-release-testutil + ${project.version} + + + org.switchyard + switchyard-release-distribution + ${project.version} + + + org.switchyard + switchyard-remote + ${project.version} + + + org.switchyard + switchyard-runtime + ${project.version} + + + org.switchyard + switchyard-runtime + test-jar + ${project.version} + + + org.switchyard + switchyard-security + ${project.version} + + + org.switchyard + switchyard-security-jboss + ${project.version} + + + org.switchyard + switchyard-security-karaf + ${project.version} + + + org.switchyard + switchyard-serial + ${project.version} + + + org.switchyard + switchyard-serial-jackson + ${project.version} + + + org.switchyard + switchyard-serial-protostuff + ${project.version} + + + org.switchyard + switchyard-transform + ${project.version} + + + org.switchyard + switchyard-test + ${project.version} + + + org.switchyard + switchyard-validate + ${project.version} + + + org.switchyard.components + switchyard-component-bean + ${project.version} + + + org.switchyard.components + switchyard-component-bpel + ${project.version} + + + org.switchyard.components + switchyard-component-bpm + ${project.version} + + + org.switchyard.components + switchyard-component-camel + ${project.version} + + + org.switchyard.components + switchyard-component-camel-amqp + ${project.version} + + + org.switchyard.components + switchyard-component-camel-atom + ${project.version} + + + org.switchyard.components + switchyard-component-camel-core + ${project.version} + + + org.switchyard.components + switchyard-component-camel-cxf + ${project.version} + + + org.switchyard.components + switchyard-component-camel-file + ${project.version} + + + org.switchyard.components + switchyard-component-camel-ftp + ${project.version} + + + org.switchyard.components + switchyard-component-camel-jms + ${project.version} + + + org.switchyard.components + switchyard-component-camel-jpa + ${project.version} + + + org.switchyard.components + switchyard-component-camel-mail + ${project.version} + + + org.switchyard.components + switchyard-component-camel-mqtt + ${project.version} + + + org.switchyard.components + switchyard-component-camel-netty + ${project.version} + + + org.switchyard.components + switchyard-component-camel-quartz + ${project.version} + + + org.switchyard.components + switchyard-component-camel-sap + ${project.version} + + + org.switchyard.components + switchyard-component-camel-rss + ${project.version} + + + org.switchyard.components + switchyard-component-camel-sql + ${project.version} + + + org.switchyard.components + switchyard-component-camel-switchyard + ${project.version} + + + org.switchyard.components + switchyard-component-camel-test + ${project.version} + test + + + org.switchyard.components + switchyard-component-clojure + ${project.version} + + + org.switchyard.components + switchyard-component-http + ${project.version} + + + org.switchyard.components + switchyard-component-common + ${project.version} + + + org.switchyard.components + switchyard-component-common-camel + ${project.version} + + + org.switchyard.components + switchyard-component-common-knowledge + ${project.version} + + + org.switchyard.components + switchyard-component-common-rest + ${project.version} + + + org.switchyard.components + switchyard-component-sca + ${project.version} + + + org.switchyard.components + switchyard-component-resteasy + ${project.version} + + + org.switchyard.components + switchyard-component-rules + ${project.version} + + + org.switchyard.components + switchyard-component-soap + ${project.version} + + + org.switchyard.components + switchyard-component-jca + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-amqp + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-activemq + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-cdi + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-http + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-jca + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-naming + ${project.version} + + + org.switchyard.components + switchyard-component-test-mixin-smooks + ${project.version} + + + org.switchyard.quickstarts + switchyard-quickstart-testutil + ${project.version} + + + org.switchyard.quickstarts + switchyard-transform-dozer + ${project.version} + + + org.switchyard.quickstarts + switchyard-transform-xslt + ${project.version} + + + org.switchyard.quickstarts + switchyard-transform-jaxb + ${project.version} + + + org.switchyard.quickstarts + switchyard-transform-json + ${project.version} + + + org.switchyard.quickstarts + switchyard-transform-smooks + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-service + ${project.version} + + + org.switchyard.quickstarts + switchyard-bean-service + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-file-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-amqp-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-bus-cdi + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-cxf-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-ftp-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-jaxb + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-hl7 + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-jpa-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-mail-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-netty-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-jms-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-mqtt-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-quartz-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-sap-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-rss-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-saxon + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-sql-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-reverse + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-reverse-service + ${project.version} + war + + + org.switchyard.quickstarts + switchyard-ear-deployment-artifacts + ${project.version} + + + org.switchyard.quickstarts + switchyard-ear-deployment-order-consumer + ${project.version} + + + org.switchyard.quickstarts + switchyard-ear-deployment-order-service + ${project.version} + + + org.switchyard.quickstarts + switchyard-ear-deployment-ear-assembly + ear + ${project.version} + + + org.switchyard.quickstarts + switchyard-http-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-remote-invoker + ${project.version} + + + org.switchyard.quickstarts + switchyard-rest-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-rules-camel-cbr + ${project.version} + + + org.switchyard.quickstarts + switchyard-rules-interview + ${project.version} + + + org.switchyard.quickstarts + switchyard-rules-interview-container + ${project.version} + + + org.switchyard.quickstarts + switchyard-rules-interview-dtable + ${project.version} + + + org.switchyard.quickstarts + switchyard-soap-addressing + ${project.version} + + + org.switchyard.quickstarts + switchyard-soap-attachment + ${project.version} + + + org.switchyard.quickstarts + switchyard-soap-binding-rpc + ${project.version} + + + org.switchyard.quickstarts + switchyard-soap-mtom + ${project.version} + + + org.switchyard.quickstarts + switchyard-bpm-service + ${project.version} + + + org.switchyard.quickstarts + switchyard-bpel-say-hello + ${project.version} + + + org.switchyard.quickstarts + switchyard-bpel-jms-binding + ${project.version} + + + org.switchyard.quickstarts + switchyard-bpel-loan-approval + ${project.version} + + + org.switchyard.quickstarts + switchyard-validate-xml + ${project.version} + + + org.switchyard.quickstarts + switchyard-jca-inflow-hornetq + ${project.version} + + + org.switchyard.quickstarts + switchyard-jca-outbound-hornetq + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-orders + war + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-helpdesk + war + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-library + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-basic + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-cert + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-saml + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-wss-signencrypt + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-wss-username + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-transaction + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-security-propagation-basic + ${project.version} + + + + + + jboss-releases-repository + JBoss Releases Repository + https://repository.jboss.org/nexus/service/local/staging/deploy/maven2/ + + + jboss-snapshots-repository + JBoss Snapshots Repository + https://repository.jboss.org/nexus/content/repositories/snapshots/ + + + + bom + core + components + console + quickstarts + release + diff --git a/quickstarts/.gitignore b/quickstarts/.gitignore new file mode 100644 index 000000000..83a414d1e --- /dev/null +++ b/quickstarts/.gitignore @@ -0,0 +1,19 @@ +.project +.classpath +.settings/ +.bpmn/ +target/ +bin/ +components-file/bin/ +core/bin/ +.checkstyle +transaction.log +*.iml +*.ipr +*.iws +.xml +.DS_Store +.metadata/ +.idea +.fbExcludeFilterFile +.factorypath diff --git a/README.md b/quickstarts/README.md similarity index 100% rename from README.md rename to quickstarts/README.md diff --git a/assembly/Readme.md b/quickstarts/assembly/Readme.md similarity index 100% rename from assembly/Readme.md rename to quickstarts/assembly/Readme.md diff --git a/assembly/assembly.xml b/quickstarts/assembly/assembly.xml similarity index 100% rename from assembly/assembly.xml rename to quickstarts/assembly/assembly.xml diff --git a/quickstarts/assembly/pom.xml b/quickstarts/assembly/pom.xml new file mode 100644 index 000000000..8c4bcd319 --- /dev/null +++ b/quickstarts/assembly/pom.xml @@ -0,0 +1,77 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-quickstart-parent + 2.1.0-SNAPSHOT + + switchyard-quickstart-distro + jar + SwitchYard : Quickstarts Distribution Assembly + SwitchYard Quickstarts Distribution Assembly + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + package + + single + + + false + SwitchYard-Quickstarts + + ${basedir}/assembly.xml + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + + diff --git a/quickstarts/bean-service/Readme.md b/quickstarts/bean-service/Readme.md new file mode 100644 index 000000000..7ec2aa01f --- /dev/null +++ b/quickstarts/bean-service/Readme.md @@ -0,0 +1,112 @@ + +Introduction +============ +This quickstart demonstrates the usage of the bean component. This example shows a bean component +service, OrderService, which is provided through the OrderServiceBean, and an InventoryService which +is provided through the InventoryServiceBean implementation. Orders are submitted through the +OrderService, and the OrderService then looks items up in the InventoryService to see if they are +in stock and the order can be processed. + +This example is invoked through a SOAP gateway binding. + +![Bean Service Quickstart](https://github.com/jboss-switchyard/quickstarts/raw/master/bean-service/bean-service.jpg) + +Running the quickstart +====================== + +EAP +---------- +1. Start EAP in standalone mode: + + ${AS}/bin/standalone.sh + +2. Build and deploy the Quickstart : + + mvn install -Pdeploy + +3. Submit a webservice request to invoke the SOAP gateway. There are a number of ways to do this : + - Submit a request with your preferred SOAP client - src/test/resources/xml contains sample + requests and the responses that you should see + - Use the simple bundled SOAP client and the sample request XML e.g. +
+``` + mvn exec:java +``` +
+ - SOAP-UI : Use the wsdl for this project (src/main/resources/wsdl/OrderService.wsdl) to create + a soap-ui project. Use the sample request (src/test/resources/xml/soap-request.xml) as an + example of a sample request. See the "Expected Output" heading for the expected results. + +4. Undeploy the quickstart: + mvn clean -Pdeploy + + +Wildfly +---------- +1. Start Wildfly in standalone mode : + + ${AS}/bin/standalone.sh + +2. Build and deploy the Quickstart : + + mvn install -Pdeploy -Pwildfly + +3. To submit a webservice request to invoke the SOAP gateway : +
+``` + mvn exec:java +``` +
+ +4. Undeploy the quickstart: + mvn clean -Pdeploy -Pwildfly + + +Karaf +---------- +1. Start the Karaf server : + + ${KARAF_HOME}/bin/karaf + +2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} +with the version of SwitchYard that you are using (ex. 2.0.0): + +karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features + +3. Install the feature for the bean-service quickstart : + +karaf@root> features:install switchyard-quickstart-bean-service + +4. To submit a webservice request to invoke the SOAP gateway, run the quickstart client : +
+``` +mvn exec:java -Pkaraf +``` +
+ +5. Undeploy the quickstart: + +karaf@root> features:uninstall switchyard-quickstart-bean-service + + +Expected Output +=============== +``` + + + + + +PO-19838-XYZ +true +Order Accepted + + + + +``` + + +## Further Reading + +1. [Bean Service Documentation](https://docs.jboss.org/author/display/SWITCHYARD/Bean) diff --git a/bean-service/bean-service.jpg b/quickstarts/bean-service/bean-service.jpg similarity index 100% rename from bean-service/bean-service.jpg rename to quickstarts/bean-service/bean-service.jpg diff --git a/quickstarts/bean-service/pom.xml b/quickstarts/bean-service/pom.xml new file mode 100644 index 000000000..cc79ed928 --- /dev/null +++ b/quickstarts/bean-service/pom.xml @@ -0,0 +1,263 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-bean-service + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: bean-service + Quickstart : Bean Service + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.bean.service + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + org.switchyard.validate.config.model.ValidateSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.bean.service.BeanClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/InventoryService.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/InventoryService.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/InventoryService.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/InventoryService.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/InventoryServiceBean.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/InventoryServiceBean.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/InventoryServiceBean.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/InventoryServiceBean.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Item.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Item.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Item.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Item.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/ItemNotFoundException.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/ItemNotFoundException.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/ItemNotFoundException.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/ItemNotFoundException.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Order.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Order.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Order.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Order.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderAck.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderAck.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderAck.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderAck.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderInterceptor.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderInterceptor.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderInterceptor.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderInterceptor.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderService.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderService.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderService.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderService.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderServiceBean.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderServiceBean.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderServiceBean.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/OrderServiceBean.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Transformers.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Transformers.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Transformers.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Transformers.java diff --git a/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Validators.java b/quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Validators.java similarity index 100% rename from bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Validators.java rename to quickstarts/bean-service/src/main/java/org/switchyard/quickstarts/bean/service/Validators.java diff --git a/bean-service/src/main/resources/META-INF/beans.xml b/quickstarts/bean-service/src/main/resources/META-INF/beans.xml similarity index 100% rename from bean-service/src/main/resources/META-INF/beans.xml rename to quickstarts/bean-service/src/main/resources/META-INF/beans.xml diff --git a/bean-service/src/main/resources/META-INF/switchyard.xml b/quickstarts/bean-service/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from bean-service/src/main/resources/META-INF/switchyard.xml rename to quickstarts/bean-service/src/main/resources/META-INF/switchyard.xml diff --git a/bean-service/src/main/resources/wsdl/OrderService.wsdl b/quickstarts/bean-service/src/main/resources/wsdl/OrderService.wsdl similarity index 100% rename from bean-service/src/main/resources/wsdl/OrderService.wsdl rename to quickstarts/bean-service/src/main/resources/wsdl/OrderService.wsdl diff --git a/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/BeanClient.java b/quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/BeanClient.java similarity index 100% rename from bean-service/src/test/java/org/switchyard/quickstarts/bean/service/BeanClient.java rename to quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/BeanClient.java diff --git a/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/InventoryServiceTest.java b/quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/InventoryServiceTest.java similarity index 100% rename from bean-service/src/test/java/org/switchyard/quickstarts/bean/service/InventoryServiceTest.java rename to quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/InventoryServiceTest.java diff --git a/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/OrderServiceTest.java b/quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/OrderServiceTest.java similarity index 100% rename from bean-service/src/test/java/org/switchyard/quickstarts/bean/service/OrderServiceTest.java rename to quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/OrderServiceTest.java diff --git a/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/TypeTransformationTest.java b/quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/TypeTransformationTest.java similarity index 100% rename from bean-service/src/test/java/org/switchyard/quickstarts/bean/service/TypeTransformationTest.java rename to quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/TypeTransformationTest.java diff --git a/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/WebServiceTest.java b/quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/WebServiceTest.java similarity index 100% rename from bean-service/src/test/java/org/switchyard/quickstarts/bean/service/WebServiceTest.java rename to quickstarts/bean-service/src/test/java/org/switchyard/quickstarts/bean/service/WebServiceTest.java diff --git a/bean-service/src/test/resources/META-INF/beans.xml b/quickstarts/bean-service/src/test/resources/META-INF/beans.xml similarity index 100% rename from bean-service/src/test/resources/META-INF/beans.xml rename to quickstarts/bean-service/src/test/resources/META-INF/beans.xml diff --git a/bean-service/src/test/resources/log4j.xml b/quickstarts/bean-service/src/test/resources/log4j.xml similarity index 100% rename from bean-service/src/test/resources/log4j.xml rename to quickstarts/bean-service/src/test/resources/log4j.xml diff --git a/bean-service/src/test/resources/xml/order.xml b/quickstarts/bean-service/src/test/resources/xml/order.xml similarity index 100% rename from bean-service/src/test/resources/xml/order.xml rename to quickstarts/bean-service/src/test/resources/xml/order.xml diff --git a/bean-service/src/test/resources/xml/orderAck.xml b/quickstarts/bean-service/src/test/resources/xml/orderAck.xml similarity index 100% rename from bean-service/src/test/resources/xml/orderAck.xml rename to quickstarts/bean-service/src/test/resources/xml/orderAck.xml diff --git a/bean-service/src/test/resources/xml/soap-request.xml b/quickstarts/bean-service/src/test/resources/xml/soap-request.xml similarity index 100% rename from bean-service/src/test/resources/xml/soap-request.xml rename to quickstarts/bean-service/src/test/resources/xml/soap-request.xml diff --git a/bean-service/src/test/resources/xml/soap-response.xml b/quickstarts/bean-service/src/test/resources/xml/soap-response.xml similarity index 100% rename from bean-service/src/test/resources/xml/soap-response.xml rename to quickstarts/bean-service/src/test/resources/xml/soap-response.xml diff --git a/quickstarts/bpel-jms-binding/Readme.md b/quickstarts/bpel-jms-binding/Readme.md new file mode 100644 index 000000000..0e36a85c9 --- /dev/null +++ b/quickstarts/bpel-jms-binding/Readme.md @@ -0,0 +1,95 @@ +Introduction +============ +This quickstart demonstrates the use of a JMS binding for a BPEL service. Also of +note : the Camel JMS binding in the quickstart uses WSDL as it's interface type +instead of Java. + + +![BPEL JMS Binding Quickstart](https://github.com/jboss-switchyard/quickstarts/raw/master/bpel-service/jms_binding/bpel-jms-binding.jpg) + + +Running the quickstart +====================== + +EAP +---------- +1. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy + +4. Execute HornetQClient. See the "Expected Output" heading for the expected results. + + mvn exec:java + +5. Undeploy the quickstart: + mvn clean -Pdeploy + + +Wildfly +---------- +1. Start Wildfly in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pwildfly -Pdeploy + +4. Execute HornetQClient. See the "Expected Output" heading for the expected results. + + mvn exec:java -Pwildfly + +5. Undeploy the quickstart: + + mvn clean -Pdeploy -Pwildfly + + +Karaf +---------- +1. Start the Karaf server : + +${KARAF_HOME}/bin/karaf + +2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} +with the version of SwitchYard that you are using (ex. 2.0.0): + +karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features + +3. Install the feature for the bpel-jms-binding quickstart : + +karaf@root> features:install switchyard-quickstart-bpel-jms-binding + +4. To submit a webservice request to invoke the SOAP gateway, run the quickstart client : +
+``` +mvn exec:java -Pkaraf +``` +
+ +5. Undeploy the quickstart: + +karaf@root> features:uninstall switchyard-quickstart-bpel-jms-binding + + + +Expected Output +=============== +``` +Message sent. Waiting for reply ... +REPLY: + +Hello Skippy + +``` diff --git a/bpel-jms-binding/bpel-jms-binding.jpg b/quickstarts/bpel-jms-binding/bpel-jms-binding.jpg similarity index 100% rename from bpel-jms-binding/bpel-jms-binding.jpg rename to quickstarts/bpel-jms-binding/bpel-jms-binding.jpg diff --git a/bpel-jms-binding/config.cli b/quickstarts/bpel-jms-binding/config.cli similarity index 100% rename from bpel-jms-binding/config.cli rename to quickstarts/bpel-jms-binding/config.cli diff --git a/quickstarts/bpel-jms-binding/pom.xml b/quickstarts/bpel-jms-binding/pom.xml new file mode 100644 index 000000000..6631e8df2 --- /dev/null +++ b/quickstarts/bpel-jms-binding/pom.xml @@ -0,0 +1,326 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-bpel-jms-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: bpel-jms-binding + Quickstart : BPEL Service : JMS Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.bpel.jms.binding + true + 9999 + 1.6 + 1.6 + * + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + 2.4.1.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bpel + + + org.switchyard.components + switchyard-component-camel-jms + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + org.apache.activemq + activemq-client + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.bpel.service.hello.JMSClient + + Skippy + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + true + 8080 + + + + org.hornetq + hornetq-core-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-commons + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-journal + ${version.wildfly.hornetq} + test + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + hornetqmixin.port + 8080 + + + hornetqmixin.http.upgrade.enabled + true + + + + + + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + activemq + Skippy + + + + + + + + diff --git a/bpel-jms-binding/src/main/resources/META-INF/beans.xml b/quickstarts/bpel-jms-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from bpel-jms-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/bpel-jms-binding/src/main/resources/META-INF/beans.xml diff --git a/bpel-jms-binding/src/main/resources/META-INF/forge.xml b/quickstarts/bpel-jms-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from bpel-jms-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/bpel-jms-binding/src/main/resources/META-INF/forge.xml diff --git a/bpel-jms-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/bpel-jms-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from bpel-jms-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/bpel-jms-binding/src/main/resources/META-INF/switchyard.xml diff --git a/bpel-jms-binding/src/main/resources/OSGI-INF/blueprint/activemq.xml b/quickstarts/bpel-jms-binding/src/main/resources/OSGI-INF/blueprint/activemq.xml similarity index 100% rename from bpel-jms-binding/src/main/resources/OSGI-INF/blueprint/activemq.xml rename to quickstarts/bpel-jms-binding/src/main/resources/OSGI-INF/blueprint/activemq.xml diff --git a/bpel-jms-binding/src/main/resources/SayHello.bpel b/quickstarts/bpel-jms-binding/src/main/resources/SayHello.bpel similarity index 100% rename from bpel-jms-binding/src/main/resources/SayHello.bpel rename to quickstarts/bpel-jms-binding/src/main/resources/SayHello.bpel diff --git a/bpel-jms-binding/src/main/resources/SayHelloArtifacts.wsdl b/quickstarts/bpel-jms-binding/src/main/resources/SayHelloArtifacts.wsdl similarity index 100% rename from bpel-jms-binding/src/main/resources/SayHelloArtifacts.wsdl rename to quickstarts/bpel-jms-binding/src/main/resources/SayHelloArtifacts.wsdl diff --git a/bpel-jms-binding/src/main/resources/deploy.xml b/quickstarts/bpel-jms-binding/src/main/resources/deploy.xml similarity index 100% rename from bpel-jms-binding/src/main/resources/deploy.xml rename to quickstarts/bpel-jms-binding/src/main/resources/deploy.xml diff --git a/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/JMSClient.java b/quickstarts/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/JMSClient.java similarity index 100% rename from bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/JMSClient.java rename to quickstarts/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/JMSClient.java diff --git a/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/JmsBindingTest.java b/quickstarts/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/JmsBindingTest.java similarity index 100% rename from bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/JmsBindingTest.java rename to quickstarts/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/JmsBindingTest.java diff --git a/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/SayHelloTest.java b/quickstarts/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/SayHelloTest.java similarity index 100% rename from bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/SayHelloTest.java rename to quickstarts/bpel-jms-binding/src/test/java/org/switchyard/quickstarts/bpel/service/hello/SayHelloTest.java diff --git a/bpel-jms-binding/src/test/resources/META-INF/beans.xml b/quickstarts/bpel-jms-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from bpel-jms-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/bpel-jms-binding/src/test/resources/META-INF/beans.xml diff --git a/bpel-jms-binding/src/test/resources/bpel.properties b/quickstarts/bpel-jms-binding/src/test/resources/bpel.properties similarity index 100% rename from bpel-jms-binding/src/test/resources/bpel.properties rename to quickstarts/bpel-jms-binding/src/test/resources/bpel.properties diff --git a/bpel-jms-binding/src/test/resources/hornetq-configuration.xml b/quickstarts/bpel-jms-binding/src/test/resources/hornetq-configuration.xml similarity index 100% rename from bpel-jms-binding/src/test/resources/hornetq-configuration.xml rename to quickstarts/bpel-jms-binding/src/test/resources/hornetq-configuration.xml diff --git a/bpel-jms-binding/src/test/resources/hornetq-jms.xml b/quickstarts/bpel-jms-binding/src/test/resources/hornetq-jms.xml similarity index 100% rename from bpel-jms-binding/src/test/resources/hornetq-jms.xml rename to quickstarts/bpel-jms-binding/src/test/resources/hornetq-jms.xml diff --git a/bpel-jms-binding/src/test/resources/log4j.xml b/quickstarts/bpel-jms-binding/src/test/resources/log4j.xml similarity index 100% rename from bpel-jms-binding/src/test/resources/log4j.xml rename to quickstarts/bpel-jms-binding/src/test/resources/log4j.xml diff --git a/bpel-jms-binding/src/test/resources/switchyard-quickstart-bpel-jms-hornetq-jms.xml b/quickstarts/bpel-jms-binding/src/test/resources/switchyard-quickstart-bpel-jms-hornetq-jms.xml similarity index 100% rename from bpel-jms-binding/src/test/resources/switchyard-quickstart-bpel-jms-hornetq-jms.xml rename to quickstarts/bpel-jms-binding/src/test/resources/switchyard-quickstart-bpel-jms-hornetq-jms.xml diff --git a/bpel-jms-binding/src/test/resources/xml/xml-request.xml b/quickstarts/bpel-jms-binding/src/test/resources/xml/xml-request.xml similarity index 100% rename from bpel-jms-binding/src/test/resources/xml/xml-request.xml rename to quickstarts/bpel-jms-binding/src/test/resources/xml/xml-request.xml diff --git a/bpel-jms-binding/src/test/resources/xml/xml-response.xml b/quickstarts/bpel-jms-binding/src/test/resources/xml/xml-response.xml similarity index 100% rename from bpel-jms-binding/src/test/resources/xml/xml-response.xml rename to quickstarts/bpel-jms-binding/src/test/resources/xml/xml-response.xml diff --git a/bpel-jms-binding/unconfig.cli b/quickstarts/bpel-jms-binding/unconfig.cli similarity index 100% rename from bpel-jms-binding/unconfig.cli rename to quickstarts/bpel-jms-binding/unconfig.cli diff --git a/bpel-loan-approval/Readme.md b/quickstarts/bpel-loan-approval/Readme.md similarity index 100% rename from bpel-loan-approval/Readme.md rename to quickstarts/bpel-loan-approval/Readme.md diff --git a/bpel-loan-approval/bpel-loan-approval.jpg b/quickstarts/bpel-loan-approval/bpel-loan-approval.jpg similarity index 100% rename from bpel-loan-approval/bpel-loan-approval.jpg rename to quickstarts/bpel-loan-approval/bpel-loan-approval.jpg diff --git a/quickstarts/bpel-loan-approval/pom.xml b/quickstarts/bpel-loan-approval/pom.xml new file mode 100644 index 000000000..995e1168f --- /dev/null +++ b/quickstarts/bpel-loan-approval/pom.xml @@ -0,0 +1,249 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-bpel-loan-approval + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: bpel-loan-approval + Quickstart : BPEL Service : Loan Approval + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.bpel.loan.approval + true + 9999 + 1.6 + 1.6 + * + + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bpel + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.bpel.service.BPELLoanClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/bpel-loan-approval/src/main/resources/META-INF/beans.xml b/quickstarts/bpel-loan-approval/src/main/resources/META-INF/beans.xml similarity index 100% rename from bpel-loan-approval/src/main/resources/META-INF/beans.xml rename to quickstarts/bpel-loan-approval/src/main/resources/META-INF/beans.xml diff --git a/bpel-loan-approval/src/main/resources/META-INF/forge.xml b/quickstarts/bpel-loan-approval/src/main/resources/META-INF/forge.xml similarity index 100% rename from bpel-loan-approval/src/main/resources/META-INF/forge.xml rename to quickstarts/bpel-loan-approval/src/main/resources/META-INF/forge.xml diff --git a/bpel-loan-approval/src/main/resources/META-INF/switchyard.xml b/quickstarts/bpel-loan-approval/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from bpel-loan-approval/src/main/resources/META-INF/switchyard.xml rename to quickstarts/bpel-loan-approval/src/main/resources/META-INF/switchyard.xml diff --git a/bpel-loan-approval/src/main/resources/deploy.xml b/quickstarts/bpel-loan-approval/src/main/resources/deploy.xml similarity index 100% rename from bpel-loan-approval/src/main/resources/deploy.xml rename to quickstarts/bpel-loan-approval/src/main/resources/deploy.xml diff --git a/quickstarts/bpel-loan-approval/src/main/resources/loanServicePT.wsdl b/quickstarts/bpel-loan-approval/src/main/resources/loanServicePT.wsdl new file mode 100644 index 000000000..6b7900bdb --- /dev/null +++ b/quickstarts/bpel-loan-approval/src/main/resources/loanServicePT.wsdl @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpel-loan-approval/src/main/resources/loan_approval.bpel b/quickstarts/bpel-loan-approval/src/main/resources/loan_approval.bpel similarity index 100% rename from bpel-loan-approval/src/main/resources/loan_approval.bpel rename to quickstarts/bpel-loan-approval/src/main/resources/loan_approval.bpel diff --git a/bpel-loan-approval/src/main/resources/riskAssessmentPT.wsdl b/quickstarts/bpel-loan-approval/src/main/resources/riskAssessmentPT.wsdl similarity index 100% rename from bpel-loan-approval/src/main/resources/riskAssessmentPT.wsdl rename to quickstarts/bpel-loan-approval/src/main/resources/riskAssessmentPT.wsdl diff --git a/bpel-loan-approval/src/main/resources/risk_assessment.bpel b/quickstarts/bpel-loan-approval/src/main/resources/risk_assessment.bpel similarity index 100% rename from bpel-loan-approval/src/main/resources/risk_assessment.bpel rename to quickstarts/bpel-loan-approval/src/main/resources/risk_assessment.bpel diff --git a/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/BPELLoanClient.java b/quickstarts/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/BPELLoanClient.java similarity index 100% rename from bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/BPELLoanClient.java rename to quickstarts/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/BPELLoanClient.java diff --git a/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/LoanApprovalTest.java b/quickstarts/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/LoanApprovalTest.java similarity index 100% rename from bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/LoanApprovalTest.java rename to quickstarts/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/LoanApprovalTest.java diff --git a/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/RiskAssessmentTest.java b/quickstarts/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/RiskAssessmentTest.java similarity index 100% rename from bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/RiskAssessmentTest.java rename to quickstarts/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/RiskAssessmentTest.java diff --git a/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java b/quickstarts/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java similarity index 100% rename from bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java rename to quickstarts/bpel-loan-approval/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java diff --git a/bpel-loan-approval/src/test/resources/META-INF/beans.xml b/quickstarts/bpel-loan-approval/src/test/resources/META-INF/beans.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/META-INF/beans.xml rename to quickstarts/bpel-loan-approval/src/test/resources/META-INF/beans.xml diff --git a/bpel-loan-approval/src/test/resources/bpel.properties b/quickstarts/bpel-loan-approval/src/test/resources/bpel.properties similarity index 100% rename from bpel-loan-approval/src/test/resources/bpel.properties rename to quickstarts/bpel-loan-approval/src/test/resources/bpel.properties diff --git a/bpel-loan-approval/src/test/resources/log4j.xml b/quickstarts/bpel-loan-approval/src/test/resources/log4j.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/log4j.xml rename to quickstarts/bpel-loan-approval/src/test/resources/log4j.xml diff --git a/bpel-loan-approval/src/test/resources/xml/soap-loanreq1.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/soap-loanreq1.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/soap-loanreq1.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/soap-loanreq1.xml diff --git a/bpel-loan-approval/src/test/resources/xml/soap-loanreq2.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/soap-loanreq2.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/soap-loanreq2.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/soap-loanreq2.xml diff --git a/bpel-loan-approval/src/test/resources/xml/soap-loanresp1.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/soap-loanresp1.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/soap-loanresp1.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/soap-loanresp1.xml diff --git a/bpel-loan-approval/src/test/resources/xml/soap-loanresp2.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/soap-loanresp2.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/soap-loanresp2.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/soap-loanresp2.xml diff --git a/bpel-loan-approval/src/test/resources/xml/xml-loanreq1.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/xml-loanreq1.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/xml-loanreq1.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/xml-loanreq1.xml diff --git a/bpel-loan-approval/src/test/resources/xml/xml-loanreq2.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/xml-loanreq2.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/xml-loanreq2.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/xml-loanreq2.xml diff --git a/bpel-loan-approval/src/test/resources/xml/xml-loanresp1.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/xml-loanresp1.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/xml-loanresp1.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/xml-loanresp1.xml diff --git a/bpel-loan-approval/src/test/resources/xml/xml-riskreq1.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/xml-riskreq1.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/xml-riskreq1.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/xml-riskreq1.xml diff --git a/bpel-loan-approval/src/test/resources/xml/xml-riskreq2.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/xml-riskreq2.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/xml-riskreq2.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/xml-riskreq2.xml diff --git a/bpel-loan-approval/src/test/resources/xml/xml-riskresp1.xml b/quickstarts/bpel-loan-approval/src/test/resources/xml/xml-riskresp1.xml similarity index 100% rename from bpel-loan-approval/src/test/resources/xml/xml-riskresp1.xml rename to quickstarts/bpel-loan-approval/src/test/resources/xml/xml-riskresp1.xml diff --git a/bpel-say-hello/Readme.md b/quickstarts/bpel-say-hello/Readme.md similarity index 100% rename from bpel-say-hello/Readme.md rename to quickstarts/bpel-say-hello/Readme.md diff --git a/bpel-say-hello/bpel-say-hello.jpg b/quickstarts/bpel-say-hello/bpel-say-hello.jpg similarity index 100% rename from bpel-say-hello/bpel-say-hello.jpg rename to quickstarts/bpel-say-hello/bpel-say-hello.jpg diff --git a/quickstarts/bpel-say-hello/pom.xml b/quickstarts/bpel-say-hello/pom.xml new file mode 100644 index 000000000..c21baf055 --- /dev/null +++ b/quickstarts/bpel-say-hello/pom.xml @@ -0,0 +1,252 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-bpel-say-hello + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: bpel-say-hello + Quickstart : BPEL Service : Say Hello + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.bpel.say.hello + true + 9999 + 1.6 + 1.6 + 1.3.1 + * + + + org.switchyard,org.switchyard.* + + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bpel + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.bpel.service.BPELHelloClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/bpel-say-hello/src/main/resources/META-INF/beans.xml b/quickstarts/bpel-say-hello/src/main/resources/META-INF/beans.xml similarity index 100% rename from bpel-say-hello/src/main/resources/META-INF/beans.xml rename to quickstarts/bpel-say-hello/src/main/resources/META-INF/beans.xml diff --git a/bpel-say-hello/src/main/resources/META-INF/forge.xml b/quickstarts/bpel-say-hello/src/main/resources/META-INF/forge.xml similarity index 100% rename from bpel-say-hello/src/main/resources/META-INF/forge.xml rename to quickstarts/bpel-say-hello/src/main/resources/META-INF/forge.xml diff --git a/bpel-say-hello/src/main/resources/META-INF/switchyard.xml b/quickstarts/bpel-say-hello/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from bpel-say-hello/src/main/resources/META-INF/switchyard.xml rename to quickstarts/bpel-say-hello/src/main/resources/META-INF/switchyard.xml diff --git a/bpel-say-hello/src/main/resources/SayHello.bpel b/quickstarts/bpel-say-hello/src/main/resources/SayHello.bpel similarity index 100% rename from bpel-say-hello/src/main/resources/SayHello.bpel rename to quickstarts/bpel-say-hello/src/main/resources/SayHello.bpel diff --git a/quickstarts/bpel-say-hello/src/main/resources/SayHelloArtifacts.wsdl b/quickstarts/bpel-say-hello/src/main/resources/SayHelloArtifacts.wsdl new file mode 100644 index 000000000..d61a80cd3 --- /dev/null +++ b/quickstarts/bpel-say-hello/src/main/resources/SayHelloArtifacts.wsdl @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpel-say-hello/src/main/resources/deploy.xml b/quickstarts/bpel-say-hello/src/main/resources/deploy.xml similarity index 100% rename from bpel-say-hello/src/main/resources/deploy.xml rename to quickstarts/bpel-say-hello/src/main/resources/deploy.xml diff --git a/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/BPELHelloClient.java b/quickstarts/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/BPELHelloClient.java similarity index 100% rename from bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/BPELHelloClient.java rename to quickstarts/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/BPELHelloClient.java diff --git a/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/SayHelloTest.java b/quickstarts/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/SayHelloTest.java similarity index 100% rename from bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/SayHelloTest.java rename to quickstarts/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/SayHelloTest.java diff --git a/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java b/quickstarts/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java similarity index 100% rename from bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java rename to quickstarts/bpel-say-hello/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java diff --git a/bpel-say-hello/src/test/resources/META-INF/beans.xml b/quickstarts/bpel-say-hello/src/test/resources/META-INF/beans.xml similarity index 100% rename from bpel-say-hello/src/test/resources/META-INF/beans.xml rename to quickstarts/bpel-say-hello/src/test/resources/META-INF/beans.xml diff --git a/bpel-say-hello/src/test/resources/bpel.properties b/quickstarts/bpel-say-hello/src/test/resources/bpel.properties similarity index 100% rename from bpel-say-hello/src/test/resources/bpel.properties rename to quickstarts/bpel-say-hello/src/test/resources/bpel.properties diff --git a/bpel-say-hello/src/test/resources/log4j.xml b/quickstarts/bpel-say-hello/src/test/resources/log4j.xml similarity index 100% rename from bpel-say-hello/src/test/resources/log4j.xml rename to quickstarts/bpel-say-hello/src/test/resources/log4j.xml diff --git a/quickstarts/bpel-say-hello/src/test/resources/xml/soap-request.xml b/quickstarts/bpel-say-hello/src/test/resources/xml/soap-request.xml new file mode 100644 index 000000000..e30cc796a --- /dev/null +++ b/quickstarts/bpel-say-hello/src/test/resources/xml/soap-request.xml @@ -0,0 +1,8 @@ + + + + + Fred + + + \ No newline at end of file diff --git a/quickstarts/bpel-say-hello/src/test/resources/xml/soap-response.xml b/quickstarts/bpel-say-hello/src/test/resources/xml/soap-response.xml new file mode 100644 index 000000000..d9ddc0683 --- /dev/null +++ b/quickstarts/bpel-say-hello/src/test/resources/xml/soap-response.xml @@ -0,0 +1,3 @@ + + Hello Fred + \ No newline at end of file diff --git a/bpel-say-hello/src/test/resources/xml/xml-request.xml b/quickstarts/bpel-say-hello/src/test/resources/xml/xml-request.xml similarity index 100% rename from bpel-say-hello/src/test/resources/xml/xml-request.xml rename to quickstarts/bpel-say-hello/src/test/resources/xml/xml-request.xml diff --git a/bpel-say-hello/src/test/resources/xml/xml-response.xml b/quickstarts/bpel-say-hello/src/test/resources/xml/xml-response.xml similarity index 100% rename from bpel-say-hello/src/test/resources/xml/xml-response.xml rename to quickstarts/bpel-say-hello/src/test/resources/xml/xml-response.xml diff --git a/bpel-simple-correlation/Readme.md b/quickstarts/bpel-simple-correlation/Readme.md similarity index 100% rename from bpel-simple-correlation/Readme.md rename to quickstarts/bpel-simple-correlation/Readme.md diff --git a/bpel-simple-correlation/bpel-correlation.jpg b/quickstarts/bpel-simple-correlation/bpel-correlation.jpg similarity index 100% rename from bpel-simple-correlation/bpel-correlation.jpg rename to quickstarts/bpel-simple-correlation/bpel-correlation.jpg diff --git a/quickstarts/bpel-simple-correlation/pom.xml b/quickstarts/bpel-simple-correlation/pom.xml new file mode 100644 index 000000000..b18c3a7d2 --- /dev/null +++ b/quickstarts/bpel-simple-correlation/pom.xml @@ -0,0 +1,248 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-bpel-simple-correlation + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: bpel-simple-correlation + Quickstart : BPEL Service : Simple Correlation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.bpel.simple.correlation + true + 9999 + 1.6 + 1.6 + * + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bpel + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + clean + + enforce + + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.bpel.service.BPELCorrelationClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/bpel-simple-correlation/src/main/resources/HelloGoodbye.bpel b/quickstarts/bpel-simple-correlation/src/main/resources/HelloGoodbye.bpel similarity index 100% rename from bpel-simple-correlation/src/main/resources/HelloGoodbye.bpel rename to quickstarts/bpel-simple-correlation/src/main/resources/HelloGoodbye.bpel diff --git a/bpel-simple-correlation/src/main/resources/HelloGoodbye.wsdl b/quickstarts/bpel-simple-correlation/src/main/resources/HelloGoodbye.wsdl similarity index 100% rename from bpel-simple-correlation/src/main/resources/HelloGoodbye.wsdl rename to quickstarts/bpel-simple-correlation/src/main/resources/HelloGoodbye.wsdl diff --git a/bpel-simple-correlation/src/main/resources/META-INF/beans.xml b/quickstarts/bpel-simple-correlation/src/main/resources/META-INF/beans.xml similarity index 100% rename from bpel-simple-correlation/src/main/resources/META-INF/beans.xml rename to quickstarts/bpel-simple-correlation/src/main/resources/META-INF/beans.xml diff --git a/bpel-simple-correlation/src/main/resources/META-INF/forge.xml b/quickstarts/bpel-simple-correlation/src/main/resources/META-INF/forge.xml similarity index 100% rename from bpel-simple-correlation/src/main/resources/META-INF/forge.xml rename to quickstarts/bpel-simple-correlation/src/main/resources/META-INF/forge.xml diff --git a/bpel-simple-correlation/src/main/resources/META-INF/switchyard.xml b/quickstarts/bpel-simple-correlation/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from bpel-simple-correlation/src/main/resources/META-INF/switchyard.xml rename to quickstarts/bpel-simple-correlation/src/main/resources/META-INF/switchyard.xml diff --git a/bpel-simple-correlation/src/main/resources/deploy.xml b/quickstarts/bpel-simple-correlation/src/main/resources/deploy.xml similarity index 100% rename from bpel-simple-correlation/src/main/resources/deploy.xml rename to quickstarts/bpel-simple-correlation/src/main/resources/deploy.xml diff --git a/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/BPELCorrelationClient.java b/quickstarts/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/BPELCorrelationClient.java similarity index 100% rename from bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/BPELCorrelationClient.java rename to quickstarts/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/BPELCorrelationClient.java diff --git a/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/HelloGoodbyeTest.java b/quickstarts/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/HelloGoodbyeTest.java similarity index 100% rename from bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/HelloGoodbyeTest.java rename to quickstarts/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/HelloGoodbyeTest.java diff --git a/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java b/quickstarts/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java similarity index 100% rename from bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java rename to quickstarts/bpel-simple-correlation/src/test/java/org/switchyard/quickstarts/bpel/service/WebServiceTest.java diff --git a/bpel-simple-correlation/src/test/resources/META-INF/beans.xml b/quickstarts/bpel-simple-correlation/src/test/resources/META-INF/beans.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/META-INF/beans.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/META-INF/beans.xml diff --git a/bpel-simple-correlation/src/test/resources/bpel.properties b/quickstarts/bpel-simple-correlation/src/test/resources/bpel.properties similarity index 100% rename from bpel-simple-correlation/src/test/resources/bpel.properties rename to quickstarts/bpel-simple-correlation/src/test/resources/bpel.properties diff --git a/bpel-simple-correlation/src/test/resources/log4j.xml b/quickstarts/bpel-simple-correlation/src/test/resources/log4j.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/log4j.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/log4j.xml diff --git a/bpel-simple-correlation/src/test/resources/xml/goodbye_request1.xml b/quickstarts/bpel-simple-correlation/src/test/resources/xml/goodbye_request1.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/xml/goodbye_request1.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/xml/goodbye_request1.xml diff --git a/bpel-simple-correlation/src/test/resources/xml/goodbye_response1.xml b/quickstarts/bpel-simple-correlation/src/test/resources/xml/goodbye_response1.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/xml/goodbye_response1.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/xml/goodbye_response1.xml diff --git a/bpel-simple-correlation/src/test/resources/xml/hello_request1.xml b/quickstarts/bpel-simple-correlation/src/test/resources/xml/hello_request1.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/xml/hello_request1.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/xml/hello_request1.xml diff --git a/bpel-simple-correlation/src/test/resources/xml/hello_response1.xml b/quickstarts/bpel-simple-correlation/src/test/resources/xml/hello_response1.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/xml/hello_response1.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/xml/hello_response1.xml diff --git a/bpel-simple-correlation/src/test/resources/xml/xml-goodbye_request1.xml b/quickstarts/bpel-simple-correlation/src/test/resources/xml/xml-goodbye_request1.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/xml/xml-goodbye_request1.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/xml/xml-goodbye_request1.xml diff --git a/bpel-simple-correlation/src/test/resources/xml/xml-goodbye_response1.xml b/quickstarts/bpel-simple-correlation/src/test/resources/xml/xml-goodbye_response1.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/xml/xml-goodbye_response1.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/xml/xml-goodbye_response1.xml diff --git a/bpel-simple-correlation/src/test/resources/xml/xml-hello_request1.xml b/quickstarts/bpel-simple-correlation/src/test/resources/xml/xml-hello_request1.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/xml/xml-hello_request1.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/xml/xml-hello_request1.xml diff --git a/bpel-simple-correlation/src/test/resources/xml/xml-hello_response1.xml b/quickstarts/bpel-simple-correlation/src/test/resources/xml/xml-hello_response1.xml similarity index 100% rename from bpel-simple-correlation/src/test/resources/xml/xml-hello_response1.xml rename to quickstarts/bpel-simple-correlation/src/test/resources/xml/xml-hello_response1.xml diff --git a/bpel-xts-subordinate-wsba/Readme.md b/quickstarts/bpel-xts-subordinate-wsba/Readme.md similarity index 100% rename from bpel-xts-subordinate-wsba/Readme.md rename to quickstarts/bpel-xts-subordinate-wsba/Readme.md diff --git a/bpel-xts-subordinate-wsba/bpel-xts-subordinate-wsba.jpg b/quickstarts/bpel-xts-subordinate-wsba/bpel-xts-subordinate-wsba.jpg similarity index 100% rename from bpel-xts-subordinate-wsba/bpel-xts-subordinate-wsba.jpg rename to quickstarts/bpel-xts-subordinate-wsba/bpel-xts-subordinate-wsba.jpg diff --git a/bpel-xts-subordinate-wsba/bpel/config.cli b/quickstarts/bpel-xts-subordinate-wsba/bpel/config.cli similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/config.cli rename to quickstarts/bpel-xts-subordinate-wsba/bpel/config.cli diff --git a/quickstarts/bpel-xts-subordinate-wsba/bpel/pom.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/pom.xml new file mode 100644 index 000000000..46511151b --- /dev/null +++ b/quickstarts/bpel-xts-subordinate-wsba/bpel/pom.xml @@ -0,0 +1,124 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-bpel-xts-subordinate-wsba + 2.1.0-SNAPSHOT + + switchyard-bpel-xts-subordinate-wsba-bpel + jar + SwitchYard Quickstart: bpel-xts-subordinate-wsba - bpel + Quickstart : BPEL Service : XTS Subordinate WSBA : Business Travel Process + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + + + + org.switchyard.components + switchyard-component-bpel + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.bpel.service.BPELClient + + ${project.build.directory}/test-classes/xml + + false + + + + + diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/AirportService.wsdl b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/AirportService.wsdl similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/AirportService.wsdl rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/AirportService.wsdl diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/BusinessTravel.bpel b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/BusinessTravel.bpel similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/BusinessTravel.bpel rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/BusinessTravel.bpel diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/BusinessTravelArtifacts.wsdl b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/BusinessTravelArtifacts.wsdl similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/BusinessTravelArtifacts.wsdl rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/BusinessTravelArtifacts.wsdl diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/DefaultBusinessTravel.bpel b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/DefaultBusinessTravel.bpel similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/DefaultBusinessTravel.bpel rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/DefaultBusinessTravel.bpel diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/DefaultBusinessTravelArtifacts.wsdl b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/DefaultBusinessTravelArtifacts.wsdl similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/DefaultBusinessTravelArtifacts.wsdl rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/DefaultBusinessTravelArtifacts.wsdl diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/beans.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/beans.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/beans.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/beans.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/forge.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/forge.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/forge.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/forge.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/jboss-deployment-structure.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/jboss-deployment-structure.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/jboss-deployment-structure.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/jboss-deployment-structure.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/switchyard.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/switchyard.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/META-INF/switchyard.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/main/resources/deploy.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/deploy.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/main/resources/deploy.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/main/resources/deploy.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/test/java/org/switchyard/quickstarts/bpel/service/BPELClient.java b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/java/org/switchyard/quickstarts/bpel/service/BPELClient.java similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/test/java/org/switchyard/quickstarts/bpel/service/BPELClient.java rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/java/org/switchyard/quickstarts/bpel/service/BPELClient.java diff --git a/bpel-xts-subordinate-wsba/bpel/src/test/resources/META-INF/beans.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/META-INF/beans.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/test/resources/META-INF/beans.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/META-INF/beans.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/test/resources/log4j.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/log4j.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/test/resources/log4j.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/log4j.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-complete-compensate-request.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-complete-compensate-request.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-complete-compensate-request.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-complete-compensate-request.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-complete-request.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-complete-request.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-complete-request.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-complete-request.xml diff --git a/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-order-request.xml b/quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-order-request.xml similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-order-request.xml rename to quickstarts/bpel-xts-subordinate-wsba/bpel/src/test/resources/xml/soap-order-request.xml diff --git a/bpel-xts-subordinate-wsba/bpel/unconfig.cli b/quickstarts/bpel-xts-subordinate-wsba/bpel/unconfig.cli similarity index 100% rename from bpel-xts-subordinate-wsba/bpel/unconfig.cli rename to quickstarts/bpel-xts-subordinate-wsba/bpel/unconfig.cli diff --git a/quickstarts/bpel-xts-subordinate-wsba/pom.xml b/quickstarts/bpel-xts-subordinate-wsba/pom.xml new file mode 100644 index 000000000..d5eef8dbf --- /dev/null +++ b/quickstarts/bpel-xts-subordinate-wsba/pom.xml @@ -0,0 +1,139 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-bpel-xts-subordinate-wsba + 2.1.0-SNAPSHOT + pom + SwitchYard Quickstart: bpel-xts-subordinate-wsba + Quickstart : BPEL Service : XTS Subordinate WSBA + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 9999 + 1.6 + 1.6 + 1.3.1 + 1.0.2.Final + + + bpel + ws + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + clean + + enforce + + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/quickstarts/bpel-xts-subordinate-wsba/ws/pom.xml b/quickstarts/bpel-xts-subordinate-wsba/ws/pom.xml new file mode 100644 index 000000000..cc35ba366 --- /dev/null +++ b/quickstarts/bpel-xts-subordinate-wsba/ws/pom.xml @@ -0,0 +1,104 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-bpel-xts-subordinate-wsba + 2.1.0-SNAPSHOT + + switchyard-bpel-xts-subordinate-wsba-ws + ejb + SwitchYard Quickstart: bpel-xts-subordinate-wsba - ws + Quickstart : BPEL Service : XTS Subordinate WSBA : Airport Web Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + + + + org.jboss.jbossts.xts + jbossxts + api + provided + + + org.jboss.spec.javax.ejb + jboss-ejb-api_3.1_spec + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-ejb-plugin + + 3.1 + + + true + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + ${project.build.finalName}.jar + + + + deploy + install + + deploy-only + + + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + diff --git a/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/AirportManager.java b/quickstarts/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/AirportManager.java similarity index 100% rename from bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/AirportManager.java rename to quickstarts/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/AirportManager.java diff --git a/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/AirportService.java b/quickstarts/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/AirportService.java similarity index 100% rename from bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/AirportService.java rename to quickstarts/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/AirportService.java diff --git a/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/OrderParticipant.java b/quickstarts/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/OrderParticipant.java similarity index 100% rename from bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/OrderParticipant.java rename to quickstarts/bpel-xts-subordinate-wsba/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsba/ws/OrderParticipant.java diff --git a/bpel-xts-subordinate-wsba/ws/src/main/resources/META-INF/jboss-deployment-structure.xml b/quickstarts/bpel-xts-subordinate-wsba/ws/src/main/resources/META-INF/jboss-deployment-structure.xml similarity index 100% rename from bpel-xts-subordinate-wsba/ws/src/main/resources/META-INF/jboss-deployment-structure.xml rename to quickstarts/bpel-xts-subordinate-wsba/ws/src/main/resources/META-INF/jboss-deployment-structure.xml diff --git a/bpel-xts-subordinate-wsba/ws/src/main/resources/context-handlers.xml b/quickstarts/bpel-xts-subordinate-wsba/ws/src/main/resources/context-handlers.xml similarity index 100% rename from bpel-xts-subordinate-wsba/ws/src/main/resources/context-handlers.xml rename to quickstarts/bpel-xts-subordinate-wsba/ws/src/main/resources/context-handlers.xml diff --git a/bpel-xts-wsat/Readme.md b/quickstarts/bpel-xts-wsat/Readme.md similarity index 100% rename from bpel-xts-wsat/Readme.md rename to quickstarts/bpel-xts-wsat/Readme.md diff --git a/bpel-xts-wsat/bpel-xts-wsat.jpg b/quickstarts/bpel-xts-wsat/bpel-xts-wsat.jpg similarity index 100% rename from bpel-xts-wsat/bpel-xts-wsat.jpg rename to quickstarts/bpel-xts-wsat/bpel-xts-wsat.jpg diff --git a/bpel-xts-wsat/bpel/config.cli b/quickstarts/bpel-xts-wsat/bpel/config.cli similarity index 100% rename from bpel-xts-wsat/bpel/config.cli rename to quickstarts/bpel-xts-wsat/bpel/config.cli diff --git a/quickstarts/bpel-xts-wsat/bpel/pom.xml b/quickstarts/bpel-xts-wsat/bpel/pom.xml new file mode 100644 index 000000000..496a65757 --- /dev/null +++ b/quickstarts/bpel-xts-wsat/bpel/pom.xml @@ -0,0 +1,121 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-bpel-xts-wsat + 2.1.0-SNAPSHOT + + switchyard-bpel-xts-wsat-bpel + jar + SwitchYard Quickstart: bpel-xts-wsat - bpel + Quickstart : BPEL Service : XTS WSAT : Business Travel Process + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + + + ${project.artifactId} + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.bpel.service.BPELClient + + ${project.build.directory}/test-classes/xml + + false + + + + + + + org.switchyard.quickstarts + switchyard-bpel-xts-wsat-ws + ${project.version} + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bpel + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + diff --git a/bpel-xts-wsat/bpel/src/main/resources/AirportService.wsdl b/quickstarts/bpel-xts-wsat/bpel/src/main/resources/AirportService.wsdl similarity index 100% rename from bpel-xts-wsat/bpel/src/main/resources/AirportService.wsdl rename to quickstarts/bpel-xts-wsat/bpel/src/main/resources/AirportService.wsdl diff --git a/bpel-xts-wsat/bpel/src/main/resources/BusinessTravel.bpel b/quickstarts/bpel-xts-wsat/bpel/src/main/resources/BusinessTravel.bpel similarity index 100% rename from bpel-xts-wsat/bpel/src/main/resources/BusinessTravel.bpel rename to quickstarts/bpel-xts-wsat/bpel/src/main/resources/BusinessTravel.bpel diff --git a/bpel-xts-wsat/bpel/src/main/resources/BusinessTravelArtifacts.wsdl b/quickstarts/bpel-xts-wsat/bpel/src/main/resources/BusinessTravelArtifacts.wsdl similarity index 100% rename from bpel-xts-wsat/bpel/src/main/resources/BusinessTravelArtifacts.wsdl rename to quickstarts/bpel-xts-wsat/bpel/src/main/resources/BusinessTravelArtifacts.wsdl diff --git a/bpel-xts-wsat/bpel/src/main/resources/META-INF/beans.xml b/quickstarts/bpel-xts-wsat/bpel/src/main/resources/META-INF/beans.xml similarity index 100% rename from bpel-xts-wsat/bpel/src/main/resources/META-INF/beans.xml rename to quickstarts/bpel-xts-wsat/bpel/src/main/resources/META-INF/beans.xml diff --git a/bpel-xts-wsat/bpel/src/main/resources/META-INF/forge.xml b/quickstarts/bpel-xts-wsat/bpel/src/main/resources/META-INF/forge.xml similarity index 100% rename from bpel-xts-wsat/bpel/src/main/resources/META-INF/forge.xml rename to quickstarts/bpel-xts-wsat/bpel/src/main/resources/META-INF/forge.xml diff --git a/bpel-xts-wsat/bpel/src/main/resources/META-INF/switchyard.xml b/quickstarts/bpel-xts-wsat/bpel/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from bpel-xts-wsat/bpel/src/main/resources/META-INF/switchyard.xml rename to quickstarts/bpel-xts-wsat/bpel/src/main/resources/META-INF/switchyard.xml diff --git a/bpel-xts-wsat/bpel/src/main/resources/deploy.xml b/quickstarts/bpel-xts-wsat/bpel/src/main/resources/deploy.xml similarity index 100% rename from bpel-xts-wsat/bpel/src/main/resources/deploy.xml rename to quickstarts/bpel-xts-wsat/bpel/src/main/resources/deploy.xml diff --git a/bpel-xts-wsat/bpel/src/test/java/org/switchyard/quickstarts/bpel/service/BPELClient.java b/quickstarts/bpel-xts-wsat/bpel/src/test/java/org/switchyard/quickstarts/bpel/service/BPELClient.java similarity index 100% rename from bpel-xts-wsat/bpel/src/test/java/org/switchyard/quickstarts/bpel/service/BPELClient.java rename to quickstarts/bpel-xts-wsat/bpel/src/test/java/org/switchyard/quickstarts/bpel/service/BPELClient.java diff --git a/bpel-xts-wsat/bpel/src/test/resources/log4j.xml b/quickstarts/bpel-xts-wsat/bpel/src/test/resources/log4j.xml similarity index 100% rename from bpel-xts-wsat/bpel/src/test/resources/log4j.xml rename to quickstarts/bpel-xts-wsat/bpel/src/test/resources/log4j.xml diff --git a/bpel-xts-wsat/bpel/src/test/resources/xml/soap-abort-request.xml b/quickstarts/bpel-xts-wsat/bpel/src/test/resources/xml/soap-abort-request.xml similarity index 100% rename from bpel-xts-wsat/bpel/src/test/resources/xml/soap-abort-request.xml rename to quickstarts/bpel-xts-wsat/bpel/src/test/resources/xml/soap-abort-request.xml diff --git a/bpel-xts-wsat/bpel/src/test/resources/xml/soap-complete-request.xml b/quickstarts/bpel-xts-wsat/bpel/src/test/resources/xml/soap-complete-request.xml similarity index 100% rename from bpel-xts-wsat/bpel/src/test/resources/xml/soap-complete-request.xml rename to quickstarts/bpel-xts-wsat/bpel/src/test/resources/xml/soap-complete-request.xml diff --git a/bpel-xts-wsat/bpel/src/test/resources/xml/soap-order-request.xml b/quickstarts/bpel-xts-wsat/bpel/src/test/resources/xml/soap-order-request.xml similarity index 100% rename from bpel-xts-wsat/bpel/src/test/resources/xml/soap-order-request.xml rename to quickstarts/bpel-xts-wsat/bpel/src/test/resources/xml/soap-order-request.xml diff --git a/bpel-xts-wsat/bpel/unconfig.cli b/quickstarts/bpel-xts-wsat/bpel/unconfig.cli similarity index 100% rename from bpel-xts-wsat/bpel/unconfig.cli rename to quickstarts/bpel-xts-wsat/bpel/unconfig.cli diff --git a/quickstarts/bpel-xts-wsat/pom.xml b/quickstarts/bpel-xts-wsat/pom.xml new file mode 100644 index 000000000..e93cb52c6 --- /dev/null +++ b/quickstarts/bpel-xts-wsat/pom.xml @@ -0,0 +1,139 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-bpel-xts-wsat + 2.1.0-SNAPSHOT + pom + SwitchYard Quickstart: bpel-xts-wsat + Quickstart : BPEL Service : XTS WSAT + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 9999 + 1.6 + 1.6 + 1.3.1 + 1.0.2.Final + + + bpel + ws + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + clean + + enforce + + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/quickstarts/bpel-xts-wsat/ws/pom.xml b/quickstarts/bpel-xts-wsat/ws/pom.xml new file mode 100644 index 000000000..f8c8a1855 --- /dev/null +++ b/quickstarts/bpel-xts-wsat/ws/pom.xml @@ -0,0 +1,104 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-bpel-xts-wsat + 2.1.0-SNAPSHOT + + switchyard-bpel-xts-wsat-ws + ejb + SwitchYard Quickstart: bpel-xts-wsat - ws + Quickstart : BPEL Service : XTS WSAT : Airport Web Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + + + + org.jboss.jbossts.xts + jbossxts + api + provided + + + org.jboss.spec.javax.ejb + jboss-ejb-api_3.1_spec + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-ejb-plugin + + 3.1 + + + true + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + ${project.build.finalName}.jar + + + + deploy + install + + deploy-only + + + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + diff --git a/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/AirportManager.java b/quickstarts/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/AirportManager.java similarity index 100% rename from bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/AirportManager.java rename to quickstarts/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/AirportManager.java diff --git a/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/AirportService.java b/quickstarts/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/AirportService.java similarity index 100% rename from bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/AirportService.java rename to quickstarts/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/AirportService.java diff --git a/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/OrderParticipant.java b/quickstarts/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/OrderParticipant.java similarity index 100% rename from bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/OrderParticipant.java rename to quickstarts/bpel-xts-wsat/ws/src/main/java/org/switchyard/quickstarts/bpel/xts/wsat/ws/OrderParticipant.java diff --git a/bpel-xts-wsat/ws/src/main/resources/META-INF/jboss-deployment-structure.xml b/quickstarts/bpel-xts-wsat/ws/src/main/resources/META-INF/jboss-deployment-structure.xml similarity index 100% rename from bpel-xts-wsat/ws/src/main/resources/META-INF/jboss-deployment-structure.xml rename to quickstarts/bpel-xts-wsat/ws/src/main/resources/META-INF/jboss-deployment-structure.xml diff --git a/bpel-xts-wsat/ws/src/main/resources/context-handlers.xml b/quickstarts/bpel-xts-wsat/ws/src/main/resources/context-handlers.xml similarity index 100% rename from bpel-xts-wsat/ws/src/main/resources/context-handlers.xml rename to quickstarts/bpel-xts-wsat/ws/src/main/resources/context-handlers.xml diff --git a/bpm-service/Readme.md b/quickstarts/bpm-service/Readme.md similarity index 100% rename from bpm-service/Readme.md rename to quickstarts/bpm-service/Readme.md diff --git a/bpm-service/bpm-service.jpg b/quickstarts/bpm-service/bpm-service.jpg similarity index 100% rename from bpm-service/bpm-service.jpg rename to quickstarts/bpm-service/bpm-service.jpg diff --git a/quickstarts/bpm-service/pom.xml b/quickstarts/bpm-service/pom.xml new file mode 100644 index 000000000..feb4648c6 --- /dev/null +++ b/quickstarts/bpm-service/pom.xml @@ -0,0 +1,260 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-bpm-service + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: bpm-service + Quickstart : BPM Service + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.bpm.service + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bpm + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-versions + clean + + enforce + + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.bpm.service.BPMClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrder.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrder.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrder.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrder.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrderBean.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrderBean.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrderBean.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/BackOrderBean.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/Inventory.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/Inventory.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/Inventory.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/Inventory.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/InventoryBean.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/InventoryBean.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/InventoryBean.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/InventoryBean.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/ProcessOrder.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/ProcessOrder.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/ProcessOrder.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/ProcessOrder.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/Shipping.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/Shipping.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/Shipping.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/Shipping.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/ShippingBean.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/ShippingBean.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/ShippingBean.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/ShippingBean.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/ObjectFactory.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/ObjectFactory.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/ObjectFactory.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/ObjectFactory.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/Order.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/Order.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/Order.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/Order.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/OrderAck.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/OrderAck.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/OrderAck.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/OrderAck.java diff --git a/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/package-info.java b/quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/package-info.java similarity index 100% rename from bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/package-info.java rename to quickstarts/bpm-service/src/main/java/org/switchyard/quickstarts/bpm/service/data/package-info.java diff --git a/bpm-service/src/main/resources/META-INF/beans.xml b/quickstarts/bpm-service/src/main/resources/META-INF/beans.xml similarity index 100% rename from bpm-service/src/main/resources/META-INF/beans.xml rename to quickstarts/bpm-service/src/main/resources/META-INF/beans.xml diff --git a/bpm-service/src/main/resources/META-INF/forge.xml b/quickstarts/bpm-service/src/main/resources/META-INF/forge.xml similarity index 100% rename from bpm-service/src/main/resources/META-INF/forge.xml rename to quickstarts/bpm-service/src/main/resources/META-INF/forge.xml diff --git a/bpm-service/src/main/resources/META-INF/switchyard.xml b/quickstarts/bpm-service/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from bpm-service/src/main/resources/META-INF/switchyard.xml rename to quickstarts/bpm-service/src/main/resources/META-INF/switchyard.xml diff --git a/bpm-service/src/main/resources/ProcessOrder.bpmn b/quickstarts/bpm-service/src/main/resources/ProcessOrder.bpmn similarity index 100% rename from bpm-service/src/main/resources/ProcessOrder.bpmn rename to quickstarts/bpm-service/src/main/resources/ProcessOrder.bpmn diff --git a/bpm-service/src/main/resources/wsdl/ProcessOrder.wsdl b/quickstarts/bpm-service/src/main/resources/wsdl/ProcessOrder.wsdl similarity index 100% rename from bpm-service/src/main/resources/wsdl/ProcessOrder.wsdl rename to quickstarts/bpm-service/src/main/resources/wsdl/ProcessOrder.wsdl diff --git a/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/BPMClient.java b/quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/BPMClient.java similarity index 100% rename from bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/BPMClient.java rename to quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/BPMClient.java diff --git a/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/BackOrderTest.java b/quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/BackOrderTest.java similarity index 100% rename from bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/BackOrderTest.java rename to quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/BackOrderTest.java diff --git a/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/InventoryTest.java b/quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/InventoryTest.java similarity index 100% rename from bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/InventoryTest.java rename to quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/InventoryTest.java diff --git a/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ProcessOrderTest.java b/quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ProcessOrderTest.java similarity index 100% rename from bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ProcessOrderTest.java rename to quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ProcessOrderTest.java diff --git a/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ShippingTest.java b/quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ShippingTest.java similarity index 100% rename from bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ShippingTest.java rename to quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/ShippingTest.java diff --git a/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/WebServiceTest.java b/quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/WebServiceTest.java similarity index 100% rename from bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/WebServiceTest.java rename to quickstarts/bpm-service/src/test/java/org/switchyard/quickstarts/bpm/service/WebServiceTest.java diff --git a/bpm-service/src/test/resources/META-INF/beans.xml b/quickstarts/bpm-service/src/test/resources/META-INF/beans.xml similarity index 100% rename from bpm-service/src/test/resources/META-INF/beans.xml rename to quickstarts/bpm-service/src/test/resources/META-INF/beans.xml diff --git a/bpm-service/src/test/resources/log4j.xml b/quickstarts/bpm-service/src/test/resources/log4j.xml similarity index 100% rename from bpm-service/src/test/resources/log4j.xml rename to quickstarts/bpm-service/src/test/resources/log4j.xml diff --git a/bpm-service/src/test/resources/xml/soap-request.xml b/quickstarts/bpm-service/src/test/resources/xml/soap-request.xml similarity index 100% rename from bpm-service/src/test/resources/xml/soap-request.xml rename to quickstarts/bpm-service/src/test/resources/xml/soap-request.xml diff --git a/bpm-service/src/test/resources/xml/soap-response.xml b/quickstarts/bpm-service/src/test/resources/xml/soap-response.xml similarity index 100% rename from bpm-service/src/test/resources/xml/soap-response.xml rename to quickstarts/bpm-service/src/test/resources/xml/soap-response.xml diff --git a/camel-amqp-binding/Readme.md b/quickstarts/camel-amqp-binding/Readme.md similarity index 100% rename from camel-amqp-binding/Readme.md rename to quickstarts/camel-amqp-binding/Readme.md diff --git a/camel-amqp-binding/camel-amqp-binding.jpg b/quickstarts/camel-amqp-binding/camel-amqp-binding.jpg similarity index 100% rename from camel-amqp-binding/camel-amqp-binding.jpg rename to quickstarts/camel-amqp-binding/camel-amqp-binding.jpg diff --git a/quickstarts/camel-amqp-binding/pom.xml b/quickstarts/camel-amqp-binding/pom.xml new file mode 100644 index 000000000..52453d778 --- /dev/null +++ b/quickstarts/camel-amqp-binding/pom.xml @@ -0,0 +1,218 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-amqp-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-amqp-binding + Quickstart : Camel AMQP Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.amqp.binding + true + org.switchyard.quickstarts.camel.amqp.binding.QpidServer + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.apache.qpid + qpid-client + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-amqp + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-test-mixin-amqp + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + test + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + org.apache.qpid + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + ${maven.exec.mainClass} + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + client + + org.switchyard.quickstarts.camel.amqp.binding.QpidClient + + + + diff --git a/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/GreetingService.java b/quickstarts/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/GreetingService.java similarity index 100% rename from camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/GreetingService.java rename to quickstarts/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/GreetingService.java diff --git a/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/GreetingServiceBean.java b/quickstarts/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/GreetingServiceBean.java similarity index 100% rename from camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/GreetingServiceBean.java rename to quickstarts/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/GreetingServiceBean.java diff --git a/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/QpidConnection.java b/quickstarts/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/QpidConnection.java similarity index 100% rename from camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/QpidConnection.java rename to quickstarts/camel-amqp-binding/src/main/java/org/switchyard/quickstarts/camel/amqp/binding/QpidConnection.java diff --git a/camel-amqp-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-amqp-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-amqp-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-amqp-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-amqp-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-amqp-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-amqp-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-amqp-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/CamelAmqpBindingTest.java b/quickstarts/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/CamelAmqpBindingTest.java similarity index 100% rename from camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/CamelAmqpBindingTest.java rename to quickstarts/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/CamelAmqpBindingTest.java diff --git a/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/QpidClient.java b/quickstarts/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/QpidClient.java similarity index 100% rename from camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/QpidClient.java rename to quickstarts/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/QpidClient.java diff --git a/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/QpidServer.java b/quickstarts/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/QpidServer.java similarity index 100% rename from camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/QpidServer.java rename to quickstarts/camel-amqp-binding/src/test/java/org/switchyard/quickstarts/camel/amqp/binding/QpidServer.java diff --git a/camel-amqp-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-amqp-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-amqp-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-amqp-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-amqp-binding/src/test/resources/amqp.properties b/quickstarts/camel-amqp-binding/src/test/resources/amqp.properties similarity index 100% rename from camel-amqp-binding/src/test/resources/amqp.properties rename to quickstarts/camel-amqp-binding/src/test/resources/amqp.properties diff --git a/camel-amqp-binding/src/test/resources/config.xml b/quickstarts/camel-amqp-binding/src/test/resources/config.xml similarity index 100% rename from camel-amqp-binding/src/test/resources/config.xml rename to quickstarts/camel-amqp-binding/src/test/resources/config.xml diff --git a/camel-amqp-binding/src/test/resources/log4j.xml b/quickstarts/camel-amqp-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-amqp-binding/src/test/resources/log4j.xml rename to quickstarts/camel-amqp-binding/src/test/resources/log4j.xml diff --git a/quickstarts/camel-amqp-binding/src/test/resources/passwd b/quickstarts/camel-amqp-binding/src/test/resources/passwd new file mode 100644 index 000000000..87b9d7170 --- /dev/null +++ b/quickstarts/camel-amqp-binding/src/test/resources/passwd @@ -0,0 +1,18 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +guest:guest +client:guest +server:guest +admin:admin + +webadmin:webadmin + diff --git a/camel-amqp-binding/src/test/resources/virtualhosts.xml b/quickstarts/camel-amqp-binding/src/test/resources/virtualhosts.xml similarity index 100% rename from camel-amqp-binding/src/test/resources/virtualhosts.xml rename to quickstarts/camel-amqp-binding/src/test/resources/virtualhosts.xml diff --git a/camel-atom-binding/Readme.md b/quickstarts/camel-atom-binding/Readme.md similarity index 100% rename from camel-atom-binding/Readme.md rename to quickstarts/camel-atom-binding/Readme.md diff --git a/quickstarts/camel-atom-binding/pom.xml b/quickstarts/camel-atom-binding/pom.xml new file mode 100644 index 000000000..19c41a28f --- /dev/null +++ b/quickstarts/camel-atom-binding/pom.xml @@ -0,0 +1,234 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-atom-binding + 2.1.0-SNAPSHOT + SwitchYard Quickstart: camel-atom-binding + Quickstart : Camel RSS Binding + bundle + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.atom.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-atom + + + org.switchyard.components + switchyard-component-bean + + + org.apache.ws.commons.axiom + axiom-api + + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.apache.abdera + abdera-core + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + org.apache.abdera.abdera-parser, org.apache.abdera.abdera-i18n, org.apache.abdera.abdera-core, org.apache.ws.commons.axiom.axiom-impl + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/AtomParseService.java b/quickstarts/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/AtomParseService.java similarity index 100% rename from camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/AtomParseService.java rename to quickstarts/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/AtomParseService.java diff --git a/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/AtomParseServiceImpl.java b/quickstarts/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/AtomParseServiceImpl.java similarity index 100% rename from camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/AtomParseServiceImpl.java rename to quickstarts/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/AtomParseServiceImpl.java diff --git a/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/PrintService.java b/quickstarts/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/PrintService.java similarity index 100% rename from camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/PrintService.java rename to quickstarts/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/PrintService.java diff --git a/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/PrintServiceImpl.java b/quickstarts/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/PrintServiceImpl.java similarity index 100% rename from camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/PrintServiceImpl.java rename to quickstarts/camel-atom-binding/src/main/java/org/switchyard/quickstarts/camel/atom/binding/PrintServiceImpl.java diff --git a/camel-atom-binding/src/main/resources/META-INF/.switchyard.xml.swp b/quickstarts/camel-atom-binding/src/main/resources/META-INF/.switchyard.xml.swp similarity index 100% rename from camel-atom-binding/src/main/resources/META-INF/.switchyard.xml.swp rename to quickstarts/camel-atom-binding/src/main/resources/META-INF/.switchyard.xml.swp diff --git a/camel-atom-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-atom-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-atom-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-atom-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-atom-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-atom-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-atom-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-atom-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-atom-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-atom-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-atom-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-atom-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-atom-binding/src/main/webapp/WEB-INF/beans.xml b/quickstarts/camel-atom-binding/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from camel-atom-binding/src/main/webapp/WEB-INF/beans.xml rename to quickstarts/camel-atom-binding/src/main/webapp/WEB-INF/beans.xml diff --git a/camel-atom-binding/src/main/webapp/WEB-INF/faces-config.xml b/quickstarts/camel-atom-binding/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from camel-atom-binding/src/main/webapp/WEB-INF/faces-config.xml rename to quickstarts/camel-atom-binding/src/main/webapp/WEB-INF/faces-config.xml diff --git a/camel-atom-binding/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/quickstarts/camel-atom-binding/src/main/webapp/WEB-INF/jboss-deployment-structure.xml similarity index 100% rename from camel-atom-binding/src/main/webapp/WEB-INF/jboss-deployment-structure.xml rename to quickstarts/camel-atom-binding/src/main/webapp/WEB-INF/jboss-deployment-structure.xml diff --git a/camel-atom-binding/src/main/webapp/WEB-INF/jboss-web.xml b/quickstarts/camel-atom-binding/src/main/webapp/WEB-INF/jboss-web.xml similarity index 100% rename from camel-atom-binding/src/main/webapp/WEB-INF/jboss-web.xml rename to quickstarts/camel-atom-binding/src/main/webapp/WEB-INF/jboss-web.xml diff --git a/camel-atom-binding/src/test/java/org/switchyard/quickstarts/camel/atom/CamelAtomPollTest.java b/quickstarts/camel-atom-binding/src/test/java/org/switchyard/quickstarts/camel/atom/CamelAtomPollTest.java similarity index 100% rename from camel-atom-binding/src/test/java/org/switchyard/quickstarts/camel/atom/CamelAtomPollTest.java rename to quickstarts/camel-atom-binding/src/test/java/org/switchyard/quickstarts/camel/atom/CamelAtomPollTest.java diff --git a/camel-atom-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-atom-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-atom-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-atom-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-atom-binding/src/test/resources/META-INF/switchyard.xml b/quickstarts/camel-atom-binding/src/test/resources/META-INF/switchyard.xml similarity index 100% rename from camel-atom-binding/src/test/resources/META-INF/switchyard.xml rename to quickstarts/camel-atom-binding/src/test/resources/META-INF/switchyard.xml diff --git a/camel-atom-binding/src/test/resources/atom.xml b/quickstarts/camel-atom-binding/src/test/resources/atom.xml similarity index 100% rename from camel-atom-binding/src/test/resources/atom.xml rename to quickstarts/camel-atom-binding/src/test/resources/atom.xml diff --git a/camel-atom-binding/src/test/resources/log4j.xml b/quickstarts/camel-atom-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-atom-binding/src/test/resources/log4j.xml rename to quickstarts/camel-atom-binding/src/test/resources/log4j.xml diff --git a/quickstarts/camel-bindy/Readme.md b/quickstarts/camel-bindy/Readme.md new file mode 100644 index 000000000..d448c806c --- /dev/null +++ b/quickstarts/camel-bindy/Readme.md @@ -0,0 +1,103 @@ +Introduction +============ +This quickstart demonstrates the usage of the Camel Bindy component within a +SwitchYard service. The service unmarshals a delimited String into Order +objects, and then makes two changes to the Orders - it sets the +price of any "Lucky Charms" order to 17, and it changes any "Grape Nuts" +orders to "Cheerios". + +This example is invoked through a File gateway binding. + +Running the quickstart +====================== + + +EAP +---------- +1. Start EAP in standalone mode: + + ${AS}/bin/standalone.sh + +2. Build and deploy the Quickstart : + + mvn install -Pdeploy + +3. +
+``` + Copy src/test/resources/file.txt to /tmp/inbox/file.txt +``` +
+* (If on Windows, change the file binding in switchyard.xml to a Windows directory path) + +4. Undeploy the quickstart: + + mvn clean -Pdeploy + + +Wildfly +---------- +1. Start Wildfly in standalone mode: + + ${AS}/bin/standalone.sh + +2. Build and deploy the Quickstart : + + mvn install -Pdeploy -Pwildfly + +3. +
+``` + Copy src/test/resources/file.txt to /tmp/inbox/file.txt +``` +
+* (If on Windows, change the file binding in switchyard.xml to a Windows directory path) + +4. Undeploy the quickstart: + + mvn clean -Pdeploy -Pwildfly + + +Karaf +---------- +1. Start the Karaf server : + +${KARAF_HOME}/bin/karaf + +2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} +with the version of SwitchYard that you are using (ex. 2.0.0): + +karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features + +3. Install the feature for the camel-bindy quickstart : + +karaf@root> features:install switchyard-quickstart-camel-bindy + +4. +
+``` +Copy src/test/resources/file.txt to /tmp/inbox/file.txt +``` +
+ +5. Undeploy the quickstart: + +karaf@root> features:uninstall switchyard-quickstart-camel-bindy + + +Expected Output +=============== +``` +[FileProcessorBean] 1|Fruit Loops|3.99 +2|Lucky Charms|4.99 +3|Grape Nuts|2.33 + +Processed Message : 1|Fruit Loops|3.99 +2|Lucky Charms|17 +3|Cheerios|2.33 +``` + + +## Further Reading + +1. [Camel Bindy](http://camel.apache.org/bindy.html) diff --git a/quickstarts/camel-bindy/pom.xml b/quickstarts/camel-bindy/pom.xml new file mode 100644 index 000000000..e918d25eb --- /dev/null +++ b/quickstarts/camel-bindy/pom.xml @@ -0,0 +1,262 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-bindy + 2.1.0-SNAPSHOT + SwitchYard Quickstart: camel-bindy + bundle + Quickstart : Camel Bindy + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.bindy + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-camel-file + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-bean + + + org.apache.camel + camel-bindy + + + + + jboss-public-repository + JBoss Public Maven Repository + http://repository.jboss.org/nexus/content/groups/public + + + + + jboss-public-repository + JBoss Public Maven Repository + http://repository.jboss.org/nexus/content/groups/public + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + false + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + org.apache.camel.bindy + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + clean + + enforce + + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/BindyRoute.java b/quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/BindyRoute.java similarity index 100% rename from camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/BindyRoute.java rename to quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/BindyRoute.java diff --git a/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/CamelServiceRoute.java b/quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/CamelServiceRoute.java similarity index 100% rename from camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/CamelServiceRoute.java rename to quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/CamelServiceRoute.java diff --git a/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/FileProcessor.java b/quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/FileProcessor.java similarity index 100% rename from camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/FileProcessor.java rename to quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/FileProcessor.java diff --git a/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/FileProcessorBean.java b/quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/FileProcessorBean.java similarity index 100% rename from camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/FileProcessorBean.java rename to quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/FileProcessorBean.java diff --git a/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/Order.java b/quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/Order.java similarity index 100% rename from camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/Order.java rename to quickstarts/camel-bindy/src/main/java/org/switchyard/quickstarts/camel/bindy/Order.java diff --git a/camel-bindy/src/main/resources/META-INF/beans.xml b/quickstarts/camel-bindy/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-bindy/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-bindy/src/main/resources/META-INF/beans.xml diff --git a/camel-bindy/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-bindy/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-bindy/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-bindy/src/main/resources/META-INF/switchyard.xml diff --git a/camel-bindy/src/test/java/org/switchyard/quickstarts/camel/bindy/CamelBindyTest.java b/quickstarts/camel-bindy/src/test/java/org/switchyard/quickstarts/camel/bindy/CamelBindyTest.java similarity index 100% rename from camel-bindy/src/test/java/org/switchyard/quickstarts/camel/bindy/CamelBindyTest.java rename to quickstarts/camel-bindy/src/test/java/org/switchyard/quickstarts/camel/bindy/CamelBindyTest.java diff --git a/camel-bindy/src/test/resources/META-INF/beans.xml b/quickstarts/camel-bindy/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-bindy/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-bindy/src/test/resources/META-INF/beans.xml diff --git a/camel-bindy/src/test/resources/file.txt b/quickstarts/camel-bindy/src/test/resources/file.txt similarity index 100% rename from camel-bindy/src/test/resources/file.txt rename to quickstarts/camel-bindy/src/test/resources/file.txt diff --git a/camel-bindy/src/test/resources/request.txt b/quickstarts/camel-bindy/src/test/resources/request.txt similarity index 100% rename from camel-bindy/src/test/resources/request.txt rename to quickstarts/camel-bindy/src/test/resources/request.txt diff --git a/camel-bindy/src/test/resources/response.txt b/quickstarts/camel-bindy/src/test/resources/response.txt similarity index 100% rename from camel-bindy/src/test/resources/response.txt rename to quickstarts/camel-bindy/src/test/resources/response.txt diff --git a/camel-bus-cdi/Readme.md b/quickstarts/camel-bus-cdi/Readme.md similarity index 100% rename from camel-bus-cdi/Readme.md rename to quickstarts/camel-bus-cdi/Readme.md diff --git a/camel-bus-cdi/camel-bus-cdi.jpg b/quickstarts/camel-bus-cdi/camel-bus-cdi.jpg similarity index 100% rename from camel-bus-cdi/camel-bus-cdi.jpg rename to quickstarts/camel-bus-cdi/camel-bus-cdi.jpg diff --git a/quickstarts/camel-bus-cdi/pom.xml b/quickstarts/camel-bus-cdi/pom.xml new file mode 100644 index 000000000..9370df7f0 --- /dev/null +++ b/quickstarts/camel-bus-cdi/pom.xml @@ -0,0 +1,257 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-bus-cdi + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-bus-cdi + Quickstart : Camel Exchange Bus CDI + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.bus.cdi + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.camel.bus.CDIBusClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/CountingProcessor.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/CountingProcessor.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/CountingProcessor.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/CountingProcessor.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/InterceptStrategyImpl.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/InterceptStrategyImpl.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/InterceptStrategyImpl.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/InterceptStrategyImpl.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/ObjectFactory.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/ObjectFactory.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/ObjectFactory.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/ObjectFactory.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/Order.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/Order.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/Order.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/Order.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderAck.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderAck.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderAck.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderAck.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderService.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderService.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderService.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderService.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderServiceBean.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderServiceBean.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderServiceBean.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/OrderServiceBean.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/SelectiveAuditor.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/SelectiveAuditor.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/SelectiveAuditor.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/SelectiveAuditor.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/SimpleAuditor.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/SimpleAuditor.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/SimpleAuditor.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/SimpleAuditor.java diff --git a/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/package-info.java b/quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/package-info.java similarity index 100% rename from camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/package-info.java rename to quickstarts/camel-bus-cdi/src/main/java/org/switchyard/quickstarts/camel/bus/package-info.java diff --git a/camel-bus-cdi/src/main/resources/META-INF/beans.xml b/quickstarts/camel-bus-cdi/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-bus-cdi/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-bus-cdi/src/main/resources/META-INF/beans.xml diff --git a/camel-bus-cdi/src/main/resources/META-INF/forge.xml b/quickstarts/camel-bus-cdi/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-bus-cdi/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-bus-cdi/src/main/resources/META-INF/forge.xml diff --git a/camel-bus-cdi/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-bus-cdi/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-bus-cdi/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-bus-cdi/src/main/resources/META-INF/switchyard.xml diff --git a/camel-bus-cdi/src/main/resources/wsdl/OrderService.wsdl b/quickstarts/camel-bus-cdi/src/main/resources/wsdl/OrderService.wsdl similarity index 100% rename from camel-bus-cdi/src/main/resources/wsdl/OrderService.wsdl rename to quickstarts/camel-bus-cdi/src/main/resources/wsdl/OrderService.wsdl diff --git a/camel-bus-cdi/src/test/java/org/switchyard/quickstarts/camel/bus/AuditingTest.java b/quickstarts/camel-bus-cdi/src/test/java/org/switchyard/quickstarts/camel/bus/AuditingTest.java similarity index 100% rename from camel-bus-cdi/src/test/java/org/switchyard/quickstarts/camel/bus/AuditingTest.java rename to quickstarts/camel-bus-cdi/src/test/java/org/switchyard/quickstarts/camel/bus/AuditingTest.java diff --git a/camel-bus-cdi/src/test/java/org/switchyard/quickstarts/camel/bus/CDIBusClient.java b/quickstarts/camel-bus-cdi/src/test/java/org/switchyard/quickstarts/camel/bus/CDIBusClient.java similarity index 100% rename from camel-bus-cdi/src/test/java/org/switchyard/quickstarts/camel/bus/CDIBusClient.java rename to quickstarts/camel-bus-cdi/src/test/java/org/switchyard/quickstarts/camel/bus/CDIBusClient.java diff --git a/camel-bus-cdi/src/test/resources/META-INF/beans.xml b/quickstarts/camel-bus-cdi/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-bus-cdi/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-bus-cdi/src/test/resources/META-INF/beans.xml diff --git a/camel-bus-cdi/src/test/resources/log4j.xml b/quickstarts/camel-bus-cdi/src/test/resources/log4j.xml similarity index 100% rename from camel-bus-cdi/src/test/resources/log4j.xml rename to quickstarts/camel-bus-cdi/src/test/resources/log4j.xml diff --git a/camel-bus-cdi/src/test/resources/xml/soap-request.xml b/quickstarts/camel-bus-cdi/src/test/resources/xml/soap-request.xml similarity index 100% rename from camel-bus-cdi/src/test/resources/xml/soap-request.xml rename to quickstarts/camel-bus-cdi/src/test/resources/xml/soap-request.xml diff --git a/camel-bus-cdi/src/test/resources/xml/soap-response1.xml b/quickstarts/camel-bus-cdi/src/test/resources/xml/soap-response1.xml similarity index 100% rename from camel-bus-cdi/src/test/resources/xml/soap-response1.xml rename to quickstarts/camel-bus-cdi/src/test/resources/xml/soap-response1.xml diff --git a/camel-bus-cdi/src/test/resources/xml/soap-response2.xml b/quickstarts/camel-bus-cdi/src/test/resources/xml/soap-response2.xml similarity index 100% rename from camel-bus-cdi/src/test/resources/xml/soap-response2.xml rename to quickstarts/camel-bus-cdi/src/test/resources/xml/soap-response2.xml diff --git a/camel-cxf-binding/Readme.md b/quickstarts/camel-cxf-binding/Readme.md similarity index 100% rename from camel-cxf-binding/Readme.md rename to quickstarts/camel-cxf-binding/Readme.md diff --git a/quickstarts/camel-cxf-binding/pom.xml b/quickstarts/camel-cxf-binding/pom.xml new file mode 100644 index 000000000..5e37905c2 --- /dev/null +++ b/quickstarts/camel-cxf-binding/pom.xml @@ -0,0 +1,239 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-cxf-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: CXF consumer + Quickstart : CXF based Webservice consumer + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.cxf.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-camel-cxf + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-soap + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.camel.cxf.CamelCxfClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/ClientProcessor.java b/quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/ClientProcessor.java similarity index 100% rename from camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/ClientProcessor.java rename to quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/ClientProcessor.java diff --git a/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/ItemNotAvailable.java b/quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/ItemNotAvailable.java similarity index 100% rename from camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/ItemNotAvailable.java rename to quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/ItemNotAvailable.java diff --git a/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/Order.java b/quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/Order.java similarity index 100% rename from camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/Order.java rename to quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/Order.java diff --git a/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/OrderResponse.java b/quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/OrderResponse.java similarity index 100% rename from camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/OrderResponse.java rename to quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/OrderResponse.java diff --git a/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/WarehouseProcessor.java b/quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/WarehouseProcessor.java similarity index 100% rename from camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/WarehouseProcessor.java rename to quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/WarehouseProcessor.java diff --git a/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/WarehouseService.java b/quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/WarehouseService.java similarity index 100% rename from camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/WarehouseService.java rename to quickstarts/camel-cxf-binding/src/main/java/org/switchyard/quickstarts/camel/cxf/WarehouseService.java diff --git a/camel-cxf-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-cxf-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-cxf-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-cxf-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-cxf-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-cxf-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-cxf-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-cxf-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-cxf-binding/src/main/resources/OrderService.wsdl b/quickstarts/camel-cxf-binding/src/main/resources/OrderService.wsdl similarity index 100% rename from camel-cxf-binding/src/main/resources/OrderService.wsdl rename to quickstarts/camel-cxf-binding/src/main/resources/OrderService.wsdl diff --git a/camel-cxf-binding/src/main/resources/WarehouseService.wsdl b/quickstarts/camel-cxf-binding/src/main/resources/WarehouseService.wsdl similarity index 100% rename from camel-cxf-binding/src/main/resources/WarehouseService.wsdl rename to quickstarts/camel-cxf-binding/src/main/resources/WarehouseService.wsdl diff --git a/camel-cxf-binding/src/main/resources/route.xml b/quickstarts/camel-cxf-binding/src/main/resources/route.xml similarity index 100% rename from camel-cxf-binding/src/main/resources/route.xml rename to quickstarts/camel-cxf-binding/src/main/resources/route.xml diff --git a/camel-cxf-binding/src/main/resources/route2.xml b/quickstarts/camel-cxf-binding/src/main/resources/route2.xml similarity index 100% rename from camel-cxf-binding/src/main/resources/route2.xml rename to quickstarts/camel-cxf-binding/src/main/resources/route2.xml diff --git a/camel-cxf-binding/src/test/java/org/switchyard/quickstarts/camel/cxf/CamelCxfClient.java b/quickstarts/camel-cxf-binding/src/test/java/org/switchyard/quickstarts/camel/cxf/CamelCxfClient.java similarity index 100% rename from camel-cxf-binding/src/test/java/org/switchyard/quickstarts/camel/cxf/CamelCxfClient.java rename to quickstarts/camel-cxf-binding/src/test/java/org/switchyard/quickstarts/camel/cxf/CamelCxfClient.java diff --git a/camel-cxf-binding/src/test/java/org/switchyard/quickstarts/camel/cxf/CamelCxfTest.java b/quickstarts/camel-cxf-binding/src/test/java/org/switchyard/quickstarts/camel/cxf/CamelCxfTest.java similarity index 100% rename from camel-cxf-binding/src/test/java/org/switchyard/quickstarts/camel/cxf/CamelCxfTest.java rename to quickstarts/camel-cxf-binding/src/test/java/org/switchyard/quickstarts/camel/cxf/CamelCxfTest.java diff --git a/camel-cxf-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-cxf-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-cxf-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-cxf-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-cxf-binding/src/test/resources/log4j.xml b/quickstarts/camel-cxf-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-cxf-binding/src/test/resources/log4j.xml rename to quickstarts/camel-cxf-binding/src/test/resources/log4j.xml diff --git a/camel-cxf-binding/src/test/resources/xml/soap-request.xml b/quickstarts/camel-cxf-binding/src/test/resources/xml/soap-request.xml similarity index 100% rename from camel-cxf-binding/src/test/resources/xml/soap-request.xml rename to quickstarts/camel-cxf-binding/src/test/resources/xml/soap-request.xml diff --git a/camel-cxf-binding/src/test/resources/xml/soap-response.xml b/quickstarts/camel-cxf-binding/src/test/resources/xml/soap-response.xml similarity index 100% rename from camel-cxf-binding/src/test/resources/xml/soap-response.xml rename to quickstarts/camel-cxf-binding/src/test/resources/xml/soap-response.xml diff --git a/camel-file-binding/Readme.md b/quickstarts/camel-file-binding/Readme.md similarity index 100% rename from camel-file-binding/Readme.md rename to quickstarts/camel-file-binding/Readme.md diff --git a/camel-file-binding/camel-binding.jpg b/quickstarts/camel-file-binding/camel-binding.jpg similarity index 100% rename from camel-file-binding/camel-binding.jpg rename to quickstarts/camel-file-binding/camel-binding.jpg diff --git a/quickstarts/camel-file-binding/pom.xml b/quickstarts/camel-file-binding/pom.xml new file mode 100644 index 000000000..0145f363f --- /dev/null +++ b/quickstarts/camel-file-binding/pom.xml @@ -0,0 +1,224 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-file-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-file-binding + Quickstart : Camel Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.file.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-file + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-file-binding/src/main/java/org/switchyard/quickstarts/camel/binding/GreetingService.java b/quickstarts/camel-file-binding/src/main/java/org/switchyard/quickstarts/camel/binding/GreetingService.java similarity index 100% rename from camel-file-binding/src/main/java/org/switchyard/quickstarts/camel/binding/GreetingService.java rename to quickstarts/camel-file-binding/src/main/java/org/switchyard/quickstarts/camel/binding/GreetingService.java diff --git a/camel-file-binding/src/main/java/org/switchyard/quickstarts/camel/binding/GreetingServiceBean.java b/quickstarts/camel-file-binding/src/main/java/org/switchyard/quickstarts/camel/binding/GreetingServiceBean.java similarity index 100% rename from camel-file-binding/src/main/java/org/switchyard/quickstarts/camel/binding/GreetingServiceBean.java rename to quickstarts/camel-file-binding/src/main/java/org/switchyard/quickstarts/camel/binding/GreetingServiceBean.java diff --git a/camel-file-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-file-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-file-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-file-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-file-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-file-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-file-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-file-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-file-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-file-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-file-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-file-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-file-binding/src/test/java/org/switchyard/quickstarts/camel/binding/CamelBindingTest.java b/quickstarts/camel-file-binding/src/test/java/org/switchyard/quickstarts/camel/binding/CamelBindingTest.java similarity index 100% rename from camel-file-binding/src/test/java/org/switchyard/quickstarts/camel/binding/CamelBindingTest.java rename to quickstarts/camel-file-binding/src/test/java/org/switchyard/quickstarts/camel/binding/CamelBindingTest.java diff --git a/camel-file-binding/src/test/resources/log4j.xml b/quickstarts/camel-file-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-file-binding/src/test/resources/log4j.xml rename to quickstarts/camel-file-binding/src/test/resources/log4j.xml diff --git a/camel-file-binding/src/test/resources/test.txt b/quickstarts/camel-file-binding/src/test/resources/test.txt similarity index 100% rename from camel-file-binding/src/test/resources/test.txt rename to quickstarts/camel-file-binding/src/test/resources/test.txt diff --git a/camel-ftp-binding/Readme.md b/quickstarts/camel-ftp-binding/Readme.md similarity index 100% rename from camel-ftp-binding/Readme.md rename to quickstarts/camel-ftp-binding/Readme.md diff --git a/camel-ftp-binding/camel-ftp-binding.jpg b/quickstarts/camel-ftp-binding/camel-ftp-binding.jpg similarity index 100% rename from camel-ftp-binding/camel-ftp-binding.jpg rename to quickstarts/camel-ftp-binding/camel-ftp-binding.jpg diff --git a/quickstarts/camel-ftp-binding/pom.xml b/quickstarts/camel-ftp-binding/pom.xml new file mode 100644 index 000000000..b01ae7f97 --- /dev/null +++ b/quickstarts/camel-ftp-binding/pom.xml @@ -0,0 +1,291 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-ftp-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-ftp-binding + Quickstart : Camel FTP Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.ftp.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + org.apache.sshd + sshd-core + 0.9.0 + + + org.apache.sshd + sshd-sftp + 0.9.0 + + + com.jcraft + jsch + 0.1.51 + + + org.bouncycastle + bcpg-jdk15on + 1.49 + + + org.bouncycastle + bcpkix-jdk15on + 1.49 + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-ftp + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.apache.ftpserver + ftpserver-core + test + + + commons-io + commons-io + test + + + org.hamcrest + hamcrest-core + test + + + org.apache.sshd + sshd-core + test + + + org.apache.sshd + sshd-sftp + test + + + com.jcraft + jsch + test + + + org.bouncycastle + bcpg-jdk15on + test + + + org.bouncycastle + bcpkix-jdk15on + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + false + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-ftp-binding/src/main/java/org/switchyard/quickstarts/camel/ftp/binding/GreetingService.java b/quickstarts/camel-ftp-binding/src/main/java/org/switchyard/quickstarts/camel/ftp/binding/GreetingService.java similarity index 100% rename from camel-ftp-binding/src/main/java/org/switchyard/quickstarts/camel/ftp/binding/GreetingService.java rename to quickstarts/camel-ftp-binding/src/main/java/org/switchyard/quickstarts/camel/ftp/binding/GreetingService.java diff --git a/camel-ftp-binding/src/main/java/org/switchyard/quickstarts/camel/ftp/binding/GreetingServiceBean.java b/quickstarts/camel-ftp-binding/src/main/java/org/switchyard/quickstarts/camel/ftp/binding/GreetingServiceBean.java similarity index 100% rename from camel-ftp-binding/src/main/java/org/switchyard/quickstarts/camel/ftp/binding/GreetingServiceBean.java rename to quickstarts/camel-ftp-binding/src/main/java/org/switchyard/quickstarts/camel/ftp/binding/GreetingServiceBean.java diff --git a/camel-ftp-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-ftp-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-ftp-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-ftp-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-ftp-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-ftp-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-ftp-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-ftp-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-ftp-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-ftp-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-ftp-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-ftp-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-ftp-binding/src/test/java/org/switchyard/quickstarts/camel/ftp/binding/CamelFtpBindingTest.java b/quickstarts/camel-ftp-binding/src/test/java/org/switchyard/quickstarts/camel/ftp/binding/CamelFtpBindingTest.java similarity index 100% rename from camel-ftp-binding/src/test/java/org/switchyard/quickstarts/camel/ftp/binding/CamelFtpBindingTest.java rename to quickstarts/camel-ftp-binding/src/test/java/org/switchyard/quickstarts/camel/ftp/binding/CamelFtpBindingTest.java diff --git a/camel-ftp-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-ftp-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-ftp-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-ftp-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-ftp-binding/src/test/resources/ftpclient.cer b/quickstarts/camel-ftp-binding/src/test/resources/ftpclient.cer similarity index 100% rename from camel-ftp-binding/src/test/resources/ftpclient.cer rename to quickstarts/camel-ftp-binding/src/test/resources/ftpclient.cer diff --git a/camel-ftp-binding/src/test/resources/ftpclient.jks b/quickstarts/camel-ftp-binding/src/test/resources/ftpclient.jks similarity index 100% rename from camel-ftp-binding/src/test/resources/ftpclient.jks rename to quickstarts/camel-ftp-binding/src/test/resources/ftpclient.jks diff --git a/camel-ftp-binding/src/test/resources/ftpserver.cer b/quickstarts/camel-ftp-binding/src/test/resources/ftpserver.cer similarity index 100% rename from camel-ftp-binding/src/test/resources/ftpserver.cer rename to quickstarts/camel-ftp-binding/src/test/resources/ftpserver.cer diff --git a/camel-ftp-binding/src/test/resources/ftpserver.jks b/quickstarts/camel-ftp-binding/src/test/resources/ftpserver.jks similarity index 100% rename from camel-ftp-binding/src/test/resources/ftpserver.jks rename to quickstarts/camel-ftp-binding/src/test/resources/ftpserver.jks diff --git a/camel-ftp-binding/src/test/resources/hostkey.pem b/quickstarts/camel-ftp-binding/src/test/resources/hostkey.pem similarity index 100% rename from camel-ftp-binding/src/test/resources/hostkey.pem rename to quickstarts/camel-ftp-binding/src/test/resources/hostkey.pem diff --git a/camel-ftp-binding/src/test/resources/id_sftp_rsa b/quickstarts/camel-ftp-binding/src/test/resources/id_sftp_rsa similarity index 100% rename from camel-ftp-binding/src/test/resources/id_sftp_rsa rename to quickstarts/camel-ftp-binding/src/test/resources/id_sftp_rsa diff --git a/camel-ftp-binding/src/test/resources/id_sftp_rsa.pub b/quickstarts/camel-ftp-binding/src/test/resources/id_sftp_rsa.pub similarity index 100% rename from camel-ftp-binding/src/test/resources/id_sftp_rsa.pub rename to quickstarts/camel-ftp-binding/src/test/resources/id_sftp_rsa.pub diff --git a/camel-ftp-binding/src/test/resources/known_hosts_sftp b/quickstarts/camel-ftp-binding/src/test/resources/known_hosts_sftp similarity index 100% rename from camel-ftp-binding/src/test/resources/known_hosts_sftp rename to quickstarts/camel-ftp-binding/src/test/resources/known_hosts_sftp diff --git a/camel-ftp-binding/src/test/resources/log4j.xml b/quickstarts/camel-ftp-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-ftp-binding/src/test/resources/log4j.xml rename to quickstarts/camel-ftp-binding/src/test/resources/log4j.xml diff --git a/camel-ftp-binding/src/test/resources/users.properties b/quickstarts/camel-ftp-binding/src/test/resources/users.properties similarity index 100% rename from camel-ftp-binding/src/test/resources/users.properties rename to quickstarts/camel-ftp-binding/src/test/resources/users.properties diff --git a/camel-hl7/Readme.md b/quickstarts/camel-hl7/Readme.md similarity index 100% rename from camel-hl7/Readme.md rename to quickstarts/camel-hl7/Readme.md diff --git a/quickstarts/camel-hl7/pom.xml b/quickstarts/camel-hl7/pom.xml new file mode 100644 index 000000000..113bc8320 --- /dev/null +++ b/quickstarts/camel-hl7/pom.xml @@ -0,0 +1,252 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-hl7 + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-hl7 + Quickstart : Camel HL7 + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.hl7 + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-camel-core + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.apache.camel + camel-hl7 + + + org.apache.camel + camel-mina2 + + + + ca.uhn.hapi + hapi-osgi-base + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + org.apache.mina, org.apache.camel.mina2, org.apache.camel.hl7, ca.uhn.hapi-osgi-base + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.camel.hl7example.HL7Client + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/CamelServiceRoute.java b/quickstarts/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/CamelServiceRoute.java similarity index 100% rename from camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/CamelServiceRoute.java rename to quickstarts/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/CamelServiceRoute.java diff --git a/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/HL7ExampleCodec.java b/quickstarts/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/HL7ExampleCodec.java similarity index 100% rename from camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/HL7ExampleCodec.java rename to quickstarts/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/HL7ExampleCodec.java diff --git a/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/HL7Route.java b/quickstarts/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/HL7Route.java similarity index 100% rename from camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/HL7Route.java rename to quickstarts/camel-hl7/src/main/java/org/switchyard/quickstarts/camel/hl7example/HL7Route.java diff --git a/camel-hl7/src/main/resources/META-INF/MANIFEST.MF b/quickstarts/camel-hl7/src/main/resources/META-INF/MANIFEST.MF similarity index 100% rename from camel-hl7/src/main/resources/META-INF/MANIFEST.MF rename to quickstarts/camel-hl7/src/main/resources/META-INF/MANIFEST.MF diff --git a/camel-hl7/src/main/resources/META-INF/beans.xml b/quickstarts/camel-hl7/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-hl7/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-hl7/src/main/resources/META-INF/beans.xml diff --git a/camel-hl7/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-hl7/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-hl7/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-hl7/src/main/resources/META-INF/switchyard.xml diff --git a/camel-hl7/src/test/java/org/switchyard/quickstarts/camel/hl7example/HL7Client.java b/quickstarts/camel-hl7/src/test/java/org/switchyard/quickstarts/camel/hl7example/HL7Client.java similarity index 100% rename from camel-hl7/src/test/java/org/switchyard/quickstarts/camel/hl7example/HL7Client.java rename to quickstarts/camel-hl7/src/test/java/org/switchyard/quickstarts/camel/hl7example/HL7Client.java diff --git a/camel-hl7/src/test/java/org/switchyard/quickstarts/camel/hl7example/HL7ServiceTest.java b/quickstarts/camel-hl7/src/test/java/org/switchyard/quickstarts/camel/hl7example/HL7ServiceTest.java similarity index 100% rename from camel-hl7/src/test/java/org/switchyard/quickstarts/camel/hl7example/HL7ServiceTest.java rename to quickstarts/camel-hl7/src/test/java/org/switchyard/quickstarts/camel/hl7example/HL7ServiceTest.java diff --git a/camel-hl7/src/test/resources/META-INF/beans.xml b/quickstarts/camel-hl7/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-hl7/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-hl7/src/test/resources/META-INF/beans.xml diff --git a/camel-hl7/src/test/resources/META-INF/switchyard.xml b/quickstarts/camel-hl7/src/test/resources/META-INF/switchyard.xml similarity index 100% rename from camel-hl7/src/test/resources/META-INF/switchyard.xml rename to quickstarts/camel-hl7/src/test/resources/META-INF/switchyard.xml diff --git a/camel-hl7/src/test/resources/hl7.file b/quickstarts/camel-hl7/src/test/resources/hl7.file similarity index 100% rename from camel-hl7/src/test/resources/hl7.file rename to quickstarts/camel-hl7/src/test/resources/hl7.file diff --git a/camel-jaxb/Readme.md b/quickstarts/camel-jaxb/Readme.md similarity index 100% rename from camel-jaxb/Readme.md rename to quickstarts/camel-jaxb/Readme.md diff --git a/camel-jaxb/camel-jaxb.jpg b/quickstarts/camel-jaxb/camel-jaxb.jpg similarity index 100% rename from camel-jaxb/camel-jaxb.jpg rename to quickstarts/camel-jaxb/camel-jaxb.jpg diff --git a/quickstarts/camel-jaxb/pom.xml b/quickstarts/camel-jaxb/pom.xml new file mode 100644 index 000000000..b91133d8c --- /dev/null +++ b/quickstarts/camel-jaxb/pom.xml @@ -0,0 +1,258 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-jaxb + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-jaxb + Quickstart : Camel JAXB + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.jaxb + true + 9999 + 1.6 + 1.6 + * + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.apache.camel + camel-jaxb + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-http + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + commons-io + commons-io + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.camel.jaxb.JAXBClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.http.client.port + 8181 + + + + + + + + + wildfly + + 9990 + + + + diff --git a/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingRequest.java b/quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingRequest.java similarity index 100% rename from camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingRequest.java rename to quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingRequest.java diff --git a/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingResponse.java b/quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingResponse.java similarity index 100% rename from camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingResponse.java rename to quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingResponse.java diff --git a/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingService.java b/quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingService.java similarity index 100% rename from camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingService.java rename to quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingService.java diff --git a/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingServiceRoute.java b/quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingServiceRoute.java similarity index 100% rename from camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingServiceRoute.java rename to quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/GreetingServiceRoute.java diff --git a/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/ObjectFactory.java b/quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/ObjectFactory.java similarity index 100% rename from camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/ObjectFactory.java rename to quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/ObjectFactory.java diff --git a/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/package-info.java b/quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/package-info.java similarity index 100% rename from camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/package-info.java rename to quickstarts/camel-jaxb/src/main/java/org/switchyard/quickstarts/camel/jaxb/package-info.java diff --git a/camel-jaxb/src/main/resources/META-INF/beans.xml b/quickstarts/camel-jaxb/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-jaxb/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-jaxb/src/main/resources/META-INF/beans.xml diff --git a/camel-jaxb/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-jaxb/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-jaxb/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-jaxb/src/main/resources/META-INF/switchyard.xml diff --git a/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBCamelTest.java b/quickstarts/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBCamelTest.java similarity index 100% rename from camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBCamelTest.java rename to quickstarts/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBCamelTest.java diff --git a/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBClient.java b/quickstarts/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBClient.java similarity index 100% rename from camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBClient.java rename to quickstarts/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBClient.java diff --git a/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBUtil.java b/quickstarts/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBUtil.java similarity index 100% rename from camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBUtil.java rename to quickstarts/camel-jaxb/src/test/java/org/switchyard/quickstarts/camel/jaxb/JAXBUtil.java diff --git a/camel-jaxb/src/test/resources/META-INF/beans.xml b/quickstarts/camel-jaxb/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-jaxb/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-jaxb/src/test/resources/META-INF/beans.xml diff --git a/camel-jaxb/src/test/resources/log4j.xml b/quickstarts/camel-jaxb/src/test/resources/log4j.xml similarity index 100% rename from camel-jaxb/src/test/resources/log4j.xml rename to quickstarts/camel-jaxb/src/test/resources/log4j.xml diff --git a/quickstarts/camel-jms-binding/Readme.md b/quickstarts/camel-jms-binding/Readme.md new file mode 100644 index 000000000..f2c137fb0 --- /dev/null +++ b/quickstarts/camel-jms-binding/Readme.md @@ -0,0 +1,93 @@ +Introduction +============ +This quickstart demonstrates the usage of the Camel Component and it's binding feature, by binding +to a JMS Queue. When a message arrives in this queue the service will be invoked. + +![Camel JMS Binding Quickstart](https://github.com/jboss-switchyard/quickstarts/raw/master/camel-jms-binding/camel-jms-binding.jpg) + + +Running the quickstart +====================== + + +EAP +---------- +1. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy + +4. Execute HornetQClient + + mvn exec:java + +5. Check the server console for output from the service. + +6. Undeploy the quickstart: + + mvn clean -Pdeploy + + +Wildfly +---------- +1. Start Wildfly in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy -Pwildfly + +4. Execute HornetQClient + + mvn exec:java -Pwildfly + +5. Check the server console for output from the service. + +6. Undeploy the quickstart: + + mvn clean -Pdeploy -Pwildfly + + +Karaf +---------- +1. Start the Karaf server : + + ${KARAF_HOME}/bin/karaf + +2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} +with the version of SwitchYard that you are using (ex. 2.0.0): + +karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features + +3. Install the feature for the camel-jms-binding quickstart : + +karaf@root> features:install switchyard-quickstart-camel-jms-binding + +4. To submit a jms request, run the quickstart client : +
+``` + mvn exec:java -Pkaraf +``` +
+ +5. Undeploy the quickstart: + +karaf@root> features:uninstall switchyard-quickstart-camel-jms-binding + + + +## Further Reading + +1. [JMS Binding Documentation](https://docs.jboss.org/author/display/SWITCHYARD/JMS) diff --git a/camel-jms-binding/camel-jms-binding.jpg b/quickstarts/camel-jms-binding/camel-jms-binding.jpg similarity index 100% rename from camel-jms-binding/camel-jms-binding.jpg rename to quickstarts/camel-jms-binding/camel-jms-binding.jpg diff --git a/camel-jms-binding/config.cli b/quickstarts/camel-jms-binding/config.cli similarity index 100% rename from camel-jms-binding/config.cli rename to quickstarts/camel-jms-binding/config.cli diff --git a/quickstarts/camel-jms-binding/pom.xml b/quickstarts/camel-jms-binding/pom.xml new file mode 100644 index 000000000..e9622a61a --- /dev/null +++ b/quickstarts/camel-jms-binding/pom.xml @@ -0,0 +1,342 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-jms-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-jms-binding + Quickstart : Camel JMS Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.jms.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + 2.4.1.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-jms + + + org.switchyard.components + switchyard-component-bean + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + org.apache.activemq + activemq-client + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + org.mockito + mockito-all + test + + + org.hamcrest + hamcrest-core + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.camel.jms.binding.JMSClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + true + 8080 + + + + org.hornetq + hornetq-core-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-commons + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-journal + ${version.wildfly.hornetq} + test + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + hornetqmixin.port + 8080 + + + hornetqmixin.http.upgrade.enabled + true + + + + + + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + activemq + + + + + + + diff --git a/camel-jms-binding/src/main/java/org/switchyard/quickstarts/camel/jms/binding/GreetingService.java b/quickstarts/camel-jms-binding/src/main/java/org/switchyard/quickstarts/camel/jms/binding/GreetingService.java similarity index 100% rename from camel-jms-binding/src/main/java/org/switchyard/quickstarts/camel/jms/binding/GreetingService.java rename to quickstarts/camel-jms-binding/src/main/java/org/switchyard/quickstarts/camel/jms/binding/GreetingService.java diff --git a/camel-jms-binding/src/main/java/org/switchyard/quickstarts/camel/jms/binding/GreetingServiceBean.java b/quickstarts/camel-jms-binding/src/main/java/org/switchyard/quickstarts/camel/jms/binding/GreetingServiceBean.java similarity index 100% rename from camel-jms-binding/src/main/java/org/switchyard/quickstarts/camel/jms/binding/GreetingServiceBean.java rename to quickstarts/camel-jms-binding/src/main/java/org/switchyard/quickstarts/camel/jms/binding/GreetingServiceBean.java diff --git a/camel-jms-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-jms-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-jms-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-jms-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-jms-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-jms-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-jms-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-jms-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-jms-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-jms-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-jms-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-jms-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-jms-binding/src/main/resources/OSGI-INF/blueprint/activemq.xml b/quickstarts/camel-jms-binding/src/main/resources/OSGI-INF/blueprint/activemq.xml similarity index 100% rename from camel-jms-binding/src/main/resources/OSGI-INF/blueprint/activemq.xml rename to quickstarts/camel-jms-binding/src/main/resources/OSGI-INF/blueprint/activemq.xml diff --git a/camel-jms-binding/src/test/java/org/switchyard/quickstarts/camel/jms/binding/CamelJMSBindingTest.java b/quickstarts/camel-jms-binding/src/test/java/org/switchyard/quickstarts/camel/jms/binding/CamelJMSBindingTest.java similarity index 100% rename from camel-jms-binding/src/test/java/org/switchyard/quickstarts/camel/jms/binding/CamelJMSBindingTest.java rename to quickstarts/camel-jms-binding/src/test/java/org/switchyard/quickstarts/camel/jms/binding/CamelJMSBindingTest.java diff --git a/camel-jms-binding/src/test/java/org/switchyard/quickstarts/camel/jms/binding/JMSClient.java b/quickstarts/camel-jms-binding/src/test/java/org/switchyard/quickstarts/camel/jms/binding/JMSClient.java similarity index 100% rename from camel-jms-binding/src/test/java/org/switchyard/quickstarts/camel/jms/binding/JMSClient.java rename to quickstarts/camel-jms-binding/src/test/java/org/switchyard/quickstarts/camel/jms/binding/JMSClient.java diff --git a/camel-jms-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-jms-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-jms-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-jms-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-jms-binding/src/test/resources/hornetq-configuration.xml b/quickstarts/camel-jms-binding/src/test/resources/hornetq-configuration.xml similarity index 100% rename from camel-jms-binding/src/test/resources/hornetq-configuration.xml rename to quickstarts/camel-jms-binding/src/test/resources/hornetq-configuration.xml diff --git a/camel-jms-binding/src/test/resources/hornetq-jms.xml b/quickstarts/camel-jms-binding/src/test/resources/hornetq-jms.xml similarity index 100% rename from camel-jms-binding/src/test/resources/hornetq-jms.xml rename to quickstarts/camel-jms-binding/src/test/resources/hornetq-jms.xml diff --git a/camel-jms-binding/src/test/resources/log4j.xml b/quickstarts/camel-jms-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-jms-binding/src/test/resources/log4j.xml rename to quickstarts/camel-jms-binding/src/test/resources/log4j.xml diff --git a/camel-jms-binding/src/test/resources/switchyard-quickstart-camel-jms-binding-hornetq-jms.xml b/quickstarts/camel-jms-binding/src/test/resources/switchyard-quickstart-camel-jms-binding-hornetq-jms.xml similarity index 100% rename from camel-jms-binding/src/test/resources/switchyard-quickstart-camel-jms-binding-hornetq-jms.xml rename to quickstarts/camel-jms-binding/src/test/resources/switchyard-quickstart-camel-jms-binding-hornetq-jms.xml diff --git a/camel-jms-binding/src/test/resources/test.txt b/quickstarts/camel-jms-binding/src/test/resources/test.txt similarity index 100% rename from camel-jms-binding/src/test/resources/test.txt rename to quickstarts/camel-jms-binding/src/test/resources/test.txt diff --git a/camel-jms-binding/unconfig.cli b/quickstarts/camel-jms-binding/unconfig.cli similarity index 100% rename from camel-jms-binding/unconfig.cli rename to quickstarts/camel-jms-binding/unconfig.cli diff --git a/camel-jpa-binding/Readme.md b/quickstarts/camel-jpa-binding/Readme.md similarity index 100% rename from camel-jpa-binding/Readme.md rename to quickstarts/camel-jpa-binding/Readme.md diff --git a/camel-jpa-binding/camel-jpa-binding.jpg b/quickstarts/camel-jpa-binding/camel-jpa-binding.jpg similarity index 100% rename from camel-jpa-binding/camel-jpa-binding.jpg rename to quickstarts/camel-jpa-binding/camel-jpa-binding.jpg diff --git a/quickstarts/camel-jpa-binding/pom.xml b/quickstarts/camel-jpa-binding/pom.xml new file mode 100644 index 000000000..a4e81da81 --- /dev/null +++ b/quickstarts/camel-jpa-binding/pom.xml @@ -0,0 +1,306 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-jpa-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-jpa-binding + Quickstart : Camel JPA Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.jpa.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + java:jboss/datasources/ExampleDS + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-camel-jpa + + + org.switchyard.components + switchyard-component-camel-quartz + + + org.hibernate + hibernate-entitymanager + + + org.switchyard + switchyard-test + test + + + org.hamcrest + hamcrest-core + test + + + com.h2database + h2 + test + + + org.mockito + mockito-all + test + + + org.switchyard.components + switchyard-component-test-mixin-jca + test + + + + ${project.artifactId} + + + true + src/main/resources + + + false + src/main/resources + + **/switchyard.xml + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + resources + process-resources + + resources + + + + ${*} + + false + + + + test-resources + process-test-resources + + testResources + + + + ${*} + + false + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${jpa.persistence.datasource.name} + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + META-INF/persistence.xml + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + karaf + + osgi:service/jboss/datasources/ExampleDS + + + + diff --git a/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/GreetingService.java b/quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/GreetingService.java similarity index 100% rename from camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/GreetingService.java rename to quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/GreetingService.java diff --git a/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/GreetingServiceBean.java b/quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/GreetingServiceBean.java similarity index 100% rename from camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/GreetingServiceBean.java rename to quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/GreetingServiceBean.java diff --git a/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/PeriodicService.java b/quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/PeriodicService.java similarity index 100% rename from camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/PeriodicService.java rename to quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/PeriodicService.java diff --git a/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/PeriodicServiceImpl.java b/quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/PeriodicServiceImpl.java similarity index 100% rename from camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/PeriodicServiceImpl.java rename to quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/PeriodicServiceImpl.java diff --git a/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/StoreService.java b/quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/StoreService.java similarity index 100% rename from camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/StoreService.java rename to quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/StoreService.java diff --git a/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/domain/Greet.java b/quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/domain/Greet.java similarity index 100% rename from camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/domain/Greet.java rename to quickstarts/camel-jpa-binding/src/main/java/org/switchyard/quickstarts/camel/jpa/binding/domain/Greet.java diff --git a/camel-jpa-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-jpa-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-jpa-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-jpa-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-jpa-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-jpa-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-jpa-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-jpa-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-jpa-binding/src/main/resources/META-INF/jboss-deployment-structure.xml b/quickstarts/camel-jpa-binding/src/main/resources/META-INF/jboss-deployment-structure.xml similarity index 100% rename from camel-jpa-binding/src/main/resources/META-INF/jboss-deployment-structure.xml rename to quickstarts/camel-jpa-binding/src/main/resources/META-INF/jboss-deployment-structure.xml diff --git a/camel-jpa-binding/src/main/resources/META-INF/persistence.xml b/quickstarts/camel-jpa-binding/src/main/resources/META-INF/persistence.xml similarity index 100% rename from camel-jpa-binding/src/main/resources/META-INF/persistence.xml rename to quickstarts/camel-jpa-binding/src/main/resources/META-INF/persistence.xml diff --git a/camel-jpa-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-jpa-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-jpa-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-jpa-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-jpa-binding/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/quickstarts/camel-jpa-binding/src/main/resources/OSGI-INF/blueprint/blueprint.xml similarity index 100% rename from camel-jpa-binding/src/main/resources/OSGI-INF/blueprint/blueprint.xml rename to quickstarts/camel-jpa-binding/src/main/resources/OSGI-INF/blueprint/blueprint.xml diff --git a/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingReceiveTest.java b/quickstarts/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingReceiveTest.java similarity index 100% rename from camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingReceiveTest.java rename to quickstarts/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingReceiveTest.java diff --git a/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingStoreTest.java b/quickstarts/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingStoreTest.java similarity index 100% rename from camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingStoreTest.java rename to quickstarts/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingStoreTest.java diff --git a/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingTest.java b/quickstarts/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingTest.java similarity index 100% rename from camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingTest.java rename to quickstarts/camel-jpa-binding/src/test/java/org/switchyard/quickstarts/camel/jpa/binding/CamelJpaBindingTest.java diff --git a/camel-jpa-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-jpa-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-jpa-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-jpa-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-jpa-binding/src/test/resources/log4j.xml b/quickstarts/camel-jpa-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-jpa-binding/src/test/resources/log4j.xml rename to quickstarts/camel-jpa-binding/src/test/resources/log4j.xml diff --git a/camel-mail-binding/Readme.md b/quickstarts/camel-mail-binding/Readme.md similarity index 100% rename from camel-mail-binding/Readme.md rename to quickstarts/camel-mail-binding/Readme.md diff --git a/camel-mail-binding/camel-mail-binding.jpg b/quickstarts/camel-mail-binding/camel-mail-binding.jpg similarity index 100% rename from camel-mail-binding/camel-mail-binding.jpg rename to quickstarts/camel-mail-binding/camel-mail-binding.jpg diff --git a/quickstarts/camel-mail-binding/pom.xml b/quickstarts/camel-mail-binding/pom.xml new file mode 100644 index 000000000..661bcfc4a --- /dev/null +++ b/quickstarts/camel-mail-binding/pom.xml @@ -0,0 +1,235 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-mail-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-mail-binding + Quickstart : Camel Mail Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.mail.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-mail + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.hamcrest + hamcrest-core + test + + + org.jvnet.mock-javamail + mock-javamail + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-mail-binding/src/main/java/org/switchyard/quickstarts/camel/mail/binding/PrintService.java b/quickstarts/camel-mail-binding/src/main/java/org/switchyard/quickstarts/camel/mail/binding/PrintService.java similarity index 100% rename from camel-mail-binding/src/main/java/org/switchyard/quickstarts/camel/mail/binding/PrintService.java rename to quickstarts/camel-mail-binding/src/main/java/org/switchyard/quickstarts/camel/mail/binding/PrintService.java diff --git a/camel-mail-binding/src/main/java/org/switchyard/quickstarts/camel/mail/binding/PrintServiceImpl.java b/quickstarts/camel-mail-binding/src/main/java/org/switchyard/quickstarts/camel/mail/binding/PrintServiceImpl.java similarity index 100% rename from camel-mail-binding/src/main/java/org/switchyard/quickstarts/camel/mail/binding/PrintServiceImpl.java rename to quickstarts/camel-mail-binding/src/main/java/org/switchyard/quickstarts/camel/mail/binding/PrintServiceImpl.java diff --git a/camel-mail-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-mail-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-mail-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-mail-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-mail-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-mail-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-mail-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-mail-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-mail-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-mail-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-mail-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-mail-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-mail-binding/src/test/java/org/switchyard/quickstarts/camel/mail/CamelMailBindingTest.java b/quickstarts/camel-mail-binding/src/test/java/org/switchyard/quickstarts/camel/mail/CamelMailBindingTest.java similarity index 100% rename from camel-mail-binding/src/test/java/org/switchyard/quickstarts/camel/mail/CamelMailBindingTest.java rename to quickstarts/camel-mail-binding/src/test/java/org/switchyard/quickstarts/camel/mail/CamelMailBindingTest.java diff --git a/camel-mail-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-mail-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-mail-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-mail-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-mail-binding/src/test/resources/log4j.xml b/quickstarts/camel-mail-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-mail-binding/src/test/resources/log4j.xml rename to quickstarts/camel-mail-binding/src/test/resources/log4j.xml diff --git a/camel-mqtt-binding/Readme.md b/quickstarts/camel-mqtt-binding/Readme.md similarity index 100% rename from camel-mqtt-binding/Readme.md rename to quickstarts/camel-mqtt-binding/Readme.md diff --git a/camel-mqtt-binding/camel-mqtt-binding.jpg b/quickstarts/camel-mqtt-binding/camel-mqtt-binding.jpg similarity index 100% rename from camel-mqtt-binding/camel-mqtt-binding.jpg rename to quickstarts/camel-mqtt-binding/camel-mqtt-binding.jpg diff --git a/quickstarts/camel-mqtt-binding/pom.xml b/quickstarts/camel-mqtt-binding/pom.xml new file mode 100644 index 000000000..919d4d996 --- /dev/null +++ b/quickstarts/camel-mqtt-binding/pom.xml @@ -0,0 +1,255 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-mqtt-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-mqtt-binding + Quickstart : Camel MQTT Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.mqtt.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + 1.6 + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-mqtt + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.apache.activemq + activemq-broker + test + + + org.apache.activemq + activemq-mqtt + test + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + test + + + org.fusesource.mqtt-client + mqtt-client + ${version.org.fusesource.mqtt-client} + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.camel.mqtt.binding.MQTTClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-mqtt-binding/src/main/java/org/switchyard/quickstarts/camel/mqtt/binding/GreetingService.java b/quickstarts/camel-mqtt-binding/src/main/java/org/switchyard/quickstarts/camel/mqtt/binding/GreetingService.java similarity index 100% rename from camel-mqtt-binding/src/main/java/org/switchyard/quickstarts/camel/mqtt/binding/GreetingService.java rename to quickstarts/camel-mqtt-binding/src/main/java/org/switchyard/quickstarts/camel/mqtt/binding/GreetingService.java diff --git a/camel-mqtt-binding/src/main/java/org/switchyard/quickstarts/camel/mqtt/binding/GreetingServiceBean.java b/quickstarts/camel-mqtt-binding/src/main/java/org/switchyard/quickstarts/camel/mqtt/binding/GreetingServiceBean.java similarity index 100% rename from camel-mqtt-binding/src/main/java/org/switchyard/quickstarts/camel/mqtt/binding/GreetingServiceBean.java rename to quickstarts/camel-mqtt-binding/src/main/java/org/switchyard/quickstarts/camel/mqtt/binding/GreetingServiceBean.java diff --git a/camel-mqtt-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-mqtt-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-mqtt-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-mqtt-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-mqtt-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-mqtt-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-mqtt-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-mqtt-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-mqtt-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-mqtt-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-mqtt-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-mqtt-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-mqtt-binding/src/test/java/org/switchyard/quickstarts/camel/mqtt/binding/CamelMQTTBindingTest.java b/quickstarts/camel-mqtt-binding/src/test/java/org/switchyard/quickstarts/camel/mqtt/binding/CamelMQTTBindingTest.java similarity index 100% rename from camel-mqtt-binding/src/test/java/org/switchyard/quickstarts/camel/mqtt/binding/CamelMQTTBindingTest.java rename to quickstarts/camel-mqtt-binding/src/test/java/org/switchyard/quickstarts/camel/mqtt/binding/CamelMQTTBindingTest.java diff --git a/camel-mqtt-binding/src/test/java/org/switchyard/quickstarts/camel/mqtt/binding/MQTTClient.java b/quickstarts/camel-mqtt-binding/src/test/java/org/switchyard/quickstarts/camel/mqtt/binding/MQTTClient.java similarity index 100% rename from camel-mqtt-binding/src/test/java/org/switchyard/quickstarts/camel/mqtt/binding/MQTTClient.java rename to quickstarts/camel-mqtt-binding/src/test/java/org/switchyard/quickstarts/camel/mqtt/binding/MQTTClient.java diff --git a/camel-mqtt-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-mqtt-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-mqtt-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-mqtt-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-mqtt-binding/src/test/resources/log4j.xml b/quickstarts/camel-mqtt-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-mqtt-binding/src/test/resources/log4j.xml rename to quickstarts/camel-mqtt-binding/src/test/resources/log4j.xml diff --git a/camel-mqtt-binding/src/test/resources/test.txt b/quickstarts/camel-mqtt-binding/src/test/resources/test.txt similarity index 100% rename from camel-mqtt-binding/src/test/resources/test.txt rename to quickstarts/camel-mqtt-binding/src/test/resources/test.txt diff --git a/camel-netty-binding/Readme.md b/quickstarts/camel-netty-binding/Readme.md similarity index 100% rename from camel-netty-binding/Readme.md rename to quickstarts/camel-netty-binding/Readme.md diff --git a/camel-netty-binding/camel-netty-binding.jpg b/quickstarts/camel-netty-binding/camel-netty-binding.jpg similarity index 100% rename from camel-netty-binding/camel-netty-binding.jpg rename to quickstarts/camel-netty-binding/camel-netty-binding.jpg diff --git a/camel-netty-binding/config.cli b/quickstarts/camel-netty-binding/config.cli similarity index 100% rename from camel-netty-binding/config.cli rename to quickstarts/camel-netty-binding/config.cli diff --git a/quickstarts/camel-netty-binding/pom.xml b/quickstarts/camel-netty-binding/pom.xml new file mode 100644 index 000000000..822708ec1 --- /dev/null +++ b/quickstarts/camel-netty-binding/pom.xml @@ -0,0 +1,256 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-netty-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-netty-binding + Quickstart : Camel Netty Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.netty.binding + true + 9999 + org.switchyard.quickstarts.camel.netty.binding.TCPClient + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-netty + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.hamcrest + hamcrest-core + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + ${maven.exec.mainClass} + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + udp + + org.switchyard.quickstarts.camel.netty.binding.UDPClient + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-netty-binding/roles.properties b/quickstarts/camel-netty-binding/roles.properties similarity index 100% rename from camel-netty-binding/roles.properties rename to quickstarts/camel-netty-binding/roles.properties diff --git a/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/DefaultGreetingServiceBean.java b/quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/DefaultGreetingServiceBean.java similarity index 100% rename from camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/DefaultGreetingServiceBean.java rename to quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/DefaultGreetingServiceBean.java diff --git a/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/GreetingService.java b/quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/GreetingService.java similarity index 100% rename from camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/GreetingService.java rename to quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/GreetingService.java diff --git a/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/GreetingServiceBean.java b/quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/GreetingServiceBean.java similarity index 100% rename from camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/GreetingServiceBean.java rename to quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/GreetingServiceBean.java diff --git a/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/SecuredGreetingServiceBean.java b/quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/SecuredGreetingServiceBean.java similarity index 100% rename from camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/SecuredGreetingServiceBean.java rename to quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/SecuredGreetingServiceBean.java diff --git a/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/SslConfigurationFactory.java b/quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/SslConfigurationFactory.java similarity index 100% rename from camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/SslConfigurationFactory.java rename to quickstarts/camel-netty-binding/src/main/java/org/switchyard/quickstarts/camel/netty/binding/SslConfigurationFactory.java diff --git a/camel-netty-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-netty-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-netty-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-netty-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-netty-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-netty-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-netty-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-netty-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-netty-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-netty-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-netty-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-netty-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-netty-binding/src/main/resources/OSGI-INF/blueprint/jaas.xml b/quickstarts/camel-netty-binding/src/main/resources/OSGI-INF/blueprint/jaas.xml similarity index 100% rename from camel-netty-binding/src/main/resources/OSGI-INF/blueprint/jaas.xml rename to quickstarts/camel-netty-binding/src/main/resources/OSGI-INF/blueprint/jaas.xml diff --git a/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/CamelNettyBindingTest.java b/quickstarts/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/CamelNettyBindingTest.java similarity index 100% rename from camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/CamelNettyBindingTest.java rename to quickstarts/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/CamelNettyBindingTest.java diff --git a/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/TCPClient.java b/quickstarts/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/TCPClient.java similarity index 100% rename from camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/TCPClient.java rename to quickstarts/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/TCPClient.java diff --git a/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/TCPUnsecuredClient.java b/quickstarts/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/TCPUnsecuredClient.java similarity index 100% rename from camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/TCPUnsecuredClient.java rename to quickstarts/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/TCPUnsecuredClient.java diff --git a/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/UDPClient.java b/quickstarts/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/UDPClient.java similarity index 100% rename from camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/UDPClient.java rename to quickstarts/camel-netty-binding/src/test/java/org/switchyard/quickstarts/camel/netty/binding/UDPClient.java diff --git a/camel-netty-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-netty-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-netty-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-netty-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-netty-binding/src/test/resources/jaas.conf b/quickstarts/camel-netty-binding/src/test/resources/jaas.conf similarity index 100% rename from camel-netty-binding/src/test/resources/jaas.conf rename to quickstarts/camel-netty-binding/src/test/resources/jaas.conf diff --git a/camel-netty-binding/src/test/resources/log4j.xml b/quickstarts/camel-netty-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-netty-binding/src/test/resources/log4j.xml rename to quickstarts/camel-netty-binding/src/test/resources/log4j.xml diff --git a/camel-netty-binding/unconfig.cli b/quickstarts/camel-netty-binding/unconfig.cli similarity index 100% rename from camel-netty-binding/unconfig.cli rename to quickstarts/camel-netty-binding/unconfig.cli diff --git a/camel-netty-binding/users.jks b/quickstarts/camel-netty-binding/users.jks similarity index 100% rename from camel-netty-binding/users.jks rename to quickstarts/camel-netty-binding/users.jks diff --git a/camel-quartz-binding/Readme.md b/quickstarts/camel-quartz-binding/Readme.md similarity index 100% rename from camel-quartz-binding/Readme.md rename to quickstarts/camel-quartz-binding/Readme.md diff --git a/camel-quartz-binding/camel-quartz-binding.jpg b/quickstarts/camel-quartz-binding/camel-quartz-binding.jpg similarity index 100% rename from camel-quartz-binding/camel-quartz-binding.jpg rename to quickstarts/camel-quartz-binding/camel-quartz-binding.jpg diff --git a/quickstarts/camel-quartz-binding/pom.xml b/quickstarts/camel-quartz-binding/pom.xml new file mode 100644 index 000000000..fe3498869 --- /dev/null +++ b/quickstarts/camel-quartz-binding/pom.xml @@ -0,0 +1,226 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-quartz-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-quartz-binding + Quickstart : Camel Quartz Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.quartz.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-camel-quartz + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.hamcrest + hamcrest-core + test + + + org.hamcrest + hamcrest-library + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-quartz-binding/src/main/java/org/switchyard/quickstarts/camel/quartz/binding/GreetingService.java b/quickstarts/camel-quartz-binding/src/main/java/org/switchyard/quickstarts/camel/quartz/binding/GreetingService.java similarity index 100% rename from camel-quartz-binding/src/main/java/org/switchyard/quickstarts/camel/quartz/binding/GreetingService.java rename to quickstarts/camel-quartz-binding/src/main/java/org/switchyard/quickstarts/camel/quartz/binding/GreetingService.java diff --git a/camel-quartz-binding/src/main/java/org/switchyard/quickstarts/camel/quartz/binding/GreetingServiceBean.java b/quickstarts/camel-quartz-binding/src/main/java/org/switchyard/quickstarts/camel/quartz/binding/GreetingServiceBean.java similarity index 100% rename from camel-quartz-binding/src/main/java/org/switchyard/quickstarts/camel/quartz/binding/GreetingServiceBean.java rename to quickstarts/camel-quartz-binding/src/main/java/org/switchyard/quickstarts/camel/quartz/binding/GreetingServiceBean.java diff --git a/camel-quartz-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-quartz-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-quartz-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-quartz-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-quartz-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-quartz-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-quartz-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-quartz-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-quartz-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-quartz-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-quartz-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-quartz-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-quartz-binding/src/test/java/org/switchyard/quickstarts/camel/quartz/binding/CamelQuartzBindingTest.java b/quickstarts/camel-quartz-binding/src/test/java/org/switchyard/quickstarts/camel/quartz/binding/CamelQuartzBindingTest.java similarity index 100% rename from camel-quartz-binding/src/test/java/org/switchyard/quickstarts/camel/quartz/binding/CamelQuartzBindingTest.java rename to quickstarts/camel-quartz-binding/src/test/java/org/switchyard/quickstarts/camel/quartz/binding/CamelQuartzBindingTest.java diff --git a/camel-quartz-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-quartz-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-quartz-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-quartz-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-quartz-binding/src/test/resources/log4j.xml b/quickstarts/camel-quartz-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-quartz-binding/src/test/resources/log4j.xml rename to quickstarts/camel-quartz-binding/src/test/resources/log4j.xml diff --git a/camel-rss-binding/Readme.md b/quickstarts/camel-rss-binding/Readme.md similarity index 100% rename from camel-rss-binding/Readme.md rename to quickstarts/camel-rss-binding/Readme.md diff --git a/quickstarts/camel-rss-binding/pom.xml b/quickstarts/camel-rss-binding/pom.xml new file mode 100644 index 000000000..dd3b1fcaa --- /dev/null +++ b/quickstarts/camel-rss-binding/pom.xml @@ -0,0 +1,239 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-rss-binding + 2.1.0-SNAPSHOT + SwitchYard Quickstart: camel-rss-binding + Quickstart : Camel RSS Binding + bundle + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.rss.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-rss + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + rome + rome + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + rome.rome:1.0 + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.camel.rss.binding.RSSClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/PrintService.java b/quickstarts/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/PrintService.java similarity index 100% rename from camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/PrintService.java rename to quickstarts/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/PrintService.java diff --git a/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/PrintServiceImpl.java b/quickstarts/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/PrintServiceImpl.java similarity index 100% rename from camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/PrintServiceImpl.java rename to quickstarts/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/PrintServiceImpl.java diff --git a/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/RSSParseService.java b/quickstarts/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/RSSParseService.java similarity index 100% rename from camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/RSSParseService.java rename to quickstarts/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/RSSParseService.java diff --git a/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/RSSParseServiceImpl.java b/quickstarts/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/RSSParseServiceImpl.java similarity index 100% rename from camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/RSSParseServiceImpl.java rename to quickstarts/camel-rss-binding/src/main/java/org/switchyard/quickstarts/camel/rss/binding/RSSParseServiceImpl.java diff --git a/camel-rss-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-rss-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-rss-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-rss-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-rss-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-rss-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-rss-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-rss-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-rss-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-rss-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-rss-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-rss-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-rss-binding/src/main/webapp/WEB-INF/beans.xml b/quickstarts/camel-rss-binding/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from camel-rss-binding/src/main/webapp/WEB-INF/beans.xml rename to quickstarts/camel-rss-binding/src/main/webapp/WEB-INF/beans.xml diff --git a/camel-rss-binding/src/main/webapp/WEB-INF/faces-config.xml b/quickstarts/camel-rss-binding/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from camel-rss-binding/src/main/webapp/WEB-INF/faces-config.xml rename to quickstarts/camel-rss-binding/src/main/webapp/WEB-INF/faces-config.xml diff --git a/camel-rss-binding/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/quickstarts/camel-rss-binding/src/main/webapp/WEB-INF/jboss-deployment-structure.xml similarity index 100% rename from camel-rss-binding/src/main/webapp/WEB-INF/jboss-deployment-structure.xml rename to quickstarts/camel-rss-binding/src/main/webapp/WEB-INF/jboss-deployment-structure.xml diff --git a/camel-rss-binding/src/main/webapp/WEB-INF/jboss-web.xml b/quickstarts/camel-rss-binding/src/main/webapp/WEB-INF/jboss-web.xml similarity index 100% rename from camel-rss-binding/src/main/webapp/WEB-INF/jboss-web.xml rename to quickstarts/camel-rss-binding/src/main/webapp/WEB-INF/jboss-web.xml diff --git a/camel-rss-binding/src/test/java/org/switchyard/quickstarts/camel/rss/CamelRSSPollTest.java b/quickstarts/camel-rss-binding/src/test/java/org/switchyard/quickstarts/camel/rss/CamelRSSPollTest.java similarity index 100% rename from camel-rss-binding/src/test/java/org/switchyard/quickstarts/camel/rss/CamelRSSPollTest.java rename to quickstarts/camel-rss-binding/src/test/java/org/switchyard/quickstarts/camel/rss/CamelRSSPollTest.java diff --git a/camel-rss-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-rss-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-rss-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-rss-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-rss-binding/src/test/resources/META-INF/switchyard.xml b/quickstarts/camel-rss-binding/src/test/resources/META-INF/switchyard.xml similarity index 100% rename from camel-rss-binding/src/test/resources/META-INF/switchyard.xml rename to quickstarts/camel-rss-binding/src/test/resources/META-INF/switchyard.xml diff --git a/camel-rss-binding/src/test/resources/log4j.xml b/quickstarts/camel-rss-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-rss-binding/src/test/resources/log4j.xml rename to quickstarts/camel-rss-binding/src/test/resources/log4j.xml diff --git a/camel-rss-binding/src/test/resources/rss.xml b/quickstarts/camel-rss-binding/src/test/resources/rss.xml similarity index 100% rename from camel-rss-binding/src/test/resources/rss.xml rename to quickstarts/camel-rss-binding/src/test/resources/rss.xml diff --git a/camel-sap-binding/Readme.md b/quickstarts/camel-sap-binding/Readme.md similarity index 100% rename from camel-sap-binding/Readme.md rename to quickstarts/camel-sap-binding/Readme.md diff --git a/camel-sap-binding/Screenshots/ZBOOK_FLIGHT.txt b/quickstarts/camel-sap-binding/Screenshots/ZBOOK_FLIGHT.txt similarity index 100% rename from camel-sap-binding/Screenshots/ZBOOK_FLIGHT.txt rename to quickstarts/camel-sap-binding/Screenshots/ZBOOK_FLIGHT.txt diff --git a/camel-sap-binding/Screenshots/ZCONNECTION_INFO_STRUCTURE.png b/quickstarts/camel-sap-binding/Screenshots/ZCONNECTION_INFO_STRUCTURE.png similarity index 100% rename from camel-sap-binding/Screenshots/ZCONNECTION_INFO_STRUCTURE.png rename to quickstarts/camel-sap-binding/Screenshots/ZCONNECTION_INFO_STRUCTURE.png diff --git a/camel-sap-binding/Screenshots/ZCONNECTION_INFO_TABLE.png b/quickstarts/camel-sap-binding/Screenshots/ZCONNECTION_INFO_TABLE.png similarity index 100% rename from camel-sap-binding/Screenshots/ZCONNECTION_INFO_TABLE.png rename to quickstarts/camel-sap-binding/Screenshots/ZCONNECTION_INFO_TABLE.png diff --git a/quickstarts/camel-sap-binding/pom.xml b/quickstarts/camel-sap-binding/pom.xml new file mode 100644 index 000000000..2487c9992 --- /dev/null +++ b/quickstarts/camel-sap-binding/pom.xml @@ -0,0 +1,237 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-sap-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-sap-binding + Quickstart : Camel SAP Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.sap.binding + 1.6 + 1.6 + true + 9999 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-sap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard.components + switchyard-component-bean + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/AggregateFlightBookingStrategy.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/AggregateFlightBookingStrategy.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/AggregateFlightBookingStrategy.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/AggregateFlightBookingStrategy.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/CreateFlightTripService.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/CreateFlightTripService.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/CreateFlightTripService.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/CreateFlightTripService.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightBookingPromotedService.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightBookingPromotedService.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightBookingPromotedService.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightBookingPromotedService.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightBookingService.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightBookingService.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightBookingService.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightBookingService.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightConnectionInfoService.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightConnectionInfoService.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightConnectionInfoService.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightConnectionInfoService.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightCustomerInfoService.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightCustomerInfoService.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightCustomerInfoService.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/FlightCustomerInfoService.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/GetFlightConnectionDetailService.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/GetFlightConnectionDetailService.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/GetFlightConnectionDetailService.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/GetFlightConnectionDetailService.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/GetFlightConnectionListService.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/GetFlightConnectionListService.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/GetFlightConnectionListService.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/GetFlightConnectionListService.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/PassengerInfoService.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/PassengerInfoService.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/PassengerInfoService.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/PassengerInfoService.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/PassengerInfoServiceBean.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/PassengerInfoServiceBean.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/PassengerInfoServiceBean.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/PassengerInfoServiceBean.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightConnectionInfo.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightConnectionInfo.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightConnectionInfo.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightConnectionInfo.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightCustomerInfo.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightCustomerInfo.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightCustomerInfo.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightCustomerInfo.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightHop.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightHop.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightHop.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightHop.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightTripRequestInfo.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightTripRequestInfo.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightTripRequestInfo.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/FlightTripRequestInfo.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/PassengerInfo.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/PassengerInfo.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/PassengerInfo.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/PassengerInfo.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/PriceInfo.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/PriceInfo.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/PriceInfo.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/PriceInfo.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/SeatAvailibility.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/SeatAvailibility.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/SeatAvailibility.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/bean/SeatAvailibility.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/CreateFlightTripMessageComposer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/CreateFlightTripMessageComposer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/CreateFlightTripMessageComposer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/CreateFlightTripMessageComposer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/FlightCustomerInfoMessageComposer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/FlightCustomerInfoMessageComposer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/FlightCustomerInfoMessageComposer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/FlightCustomerInfoMessageComposer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/GetFlightConnectionDetailMessageComposer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/GetFlightConnectionDetailMessageComposer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/GetFlightConnectionDetailMessageComposer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/GetFlightConnectionDetailMessageComposer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/GetFlightConnectionListMessageComposer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/GetFlightConnectionListMessageComposer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/GetFlightConnectionListMessageComposer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/composer/GetFlightConnectionListMessageComposer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/BookFlightRequest.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/BookFlightRequest.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/BookFlightRequest.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/BookFlightRequest.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/BookFlightResponse.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/BookFlightResponse.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/BookFlightResponse.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/BookFlightResponse.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/ConnectionInfo.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/ConnectionInfo.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/ConnectionInfo.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/ConnectionInfo.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/ConnectionInfoTable.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/ConnectionInfoTable.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/ConnectionInfoTable.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/ConnectionInfoTable.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/DateAdapter.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/DateAdapter.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/DateAdapter.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/DateAdapter.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/FlightInfo.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/FlightInfo.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/FlightInfo.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/jaxb/FlightInfo.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/CamelSAPComponentProducer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/CamelSAPComponentProducer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/CamelSAPComponentProducer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/CamelSAPComponentProducer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/CamelSAPConnectionConfigurationProducer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/CamelSAPConnectionConfigurationProducer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/CamelSAPConnectionConfigurationProducer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/CamelSAPConnectionConfigurationProducer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/ConnectionInfoMetadataProducer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/ConnectionInfoMetadataProducer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/ConnectionInfoMetadataProducer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/ConnectionInfoMetadataProducer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/DestinationMetadataProducer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/DestinationMetadataProducer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/DestinationMetadataProducer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/DestinationMetadataProducer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/FlightInfoMetadataProducer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/FlightInfoMetadataProducer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/FlightInfoMetadataProducer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/FlightInfoMetadataProducer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/FunctionTemplateMetadataProducer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/FunctionTemplateMetadataProducer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/FunctionTemplateMetadataProducer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/FunctionTemplateMetadataProducer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/RepositoryMetadataProducer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/RepositoryMetadataProducer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/RepositoryMetadataProducer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/RepositoryMetadataProducer.java diff --git a/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/ServerMetadataProducer.java b/quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/ServerMetadataProducer.java similarity index 100% rename from camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/ServerMetadataProducer.java rename to quickstarts/camel-sap-binding/src/main/java/org/switchyard/quickstarts/camel/sap/binding/metadata/ServerMetadataProducer.java diff --git a/camel-sap-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-sap-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-sap-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-sap-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-sap-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-sap-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-sap-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-sap-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-sap-binding/src/main/resources/org/switchyard/quickstarts/camel/sap/binding/jaxb/jaxb.index b/quickstarts/camel-sap-binding/src/main/resources/org/switchyard/quickstarts/camel/sap/binding/jaxb/jaxb.index similarity index 100% rename from camel-sap-binding/src/main/resources/org/switchyard/quickstarts/camel/sap/binding/jaxb/jaxb.index rename to quickstarts/camel-sap-binding/src/main/resources/org/switchyard/quickstarts/camel/sap/binding/jaxb/jaxb.index diff --git a/camel-sap-binding/src/main/resources/route-flight-booking.xml b/quickstarts/camel-sap-binding/src/main/resources/route-flight-booking.xml similarity index 100% rename from camel-sap-binding/src/main/resources/route-flight-booking.xml rename to quickstarts/camel-sap-binding/src/main/resources/route-flight-booking.xml diff --git a/camel-sap-binding/src/main/resources/route-flight-connection-info.xml b/quickstarts/camel-sap-binding/src/main/resources/route-flight-connection-info.xml similarity index 100% rename from camel-sap-binding/src/main/resources/route-flight-connection-info.xml rename to quickstarts/camel-sap-binding/src/main/resources/route-flight-connection-info.xml diff --git a/camel-sap-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-sap-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-sap-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-sap-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-saxon/Readme.md b/quickstarts/camel-saxon/Readme.md similarity index 100% rename from camel-saxon/Readme.md rename to quickstarts/camel-saxon/Readme.md diff --git a/camel-saxon/camel-saxon.jpg b/quickstarts/camel-saxon/camel-saxon.jpg similarity index 100% rename from camel-saxon/camel-saxon.jpg rename to quickstarts/camel-saxon/camel-saxon.jpg diff --git a/quickstarts/camel-saxon/pom.xml b/quickstarts/camel-saxon/pom.xml new file mode 100644 index 000000000..9ce8ecf55 --- /dev/null +++ b/quickstarts/camel-saxon/pom.xml @@ -0,0 +1,264 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-saxon + 2.1.0-SNAPSHOT + bundle + org.switchyard.quickstarts:switchyard-camel-saxon + Quickstart : Camel Saxon + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.saxon + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-soap + + + org.apache.camel + camel-saxon + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + org.switchyard.quickstarts.camel.saxon.CamelSaxonClient + test + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/GoodbyeService.java b/quickstarts/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/GoodbyeService.java similarity index 100% rename from camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/GoodbyeService.java rename to quickstarts/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/GoodbyeService.java diff --git a/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/GoodbyeServiceBean.java b/quickstarts/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/GoodbyeServiceBean.java similarity index 100% rename from camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/GoodbyeServiceBean.java rename to quickstarts/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/GoodbyeServiceBean.java diff --git a/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/HelloService.java b/quickstarts/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/HelloService.java similarity index 100% rename from camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/HelloService.java rename to quickstarts/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/HelloService.java diff --git a/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/HelloServiceBean.java b/quickstarts/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/HelloServiceBean.java similarity index 100% rename from camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/HelloServiceBean.java rename to quickstarts/camel-saxon/src/main/java/org/switchyard/quickstarts/camel/saxon/HelloServiceBean.java diff --git a/camel-saxon/src/main/resources/META-INF/beans.xml b/quickstarts/camel-saxon/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-saxon/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-saxon/src/main/resources/META-INF/beans.xml diff --git a/camel-saxon/src/main/resources/META-INF/route.xml b/quickstarts/camel-saxon/src/main/resources/META-INF/route.xml similarity index 100% rename from camel-saxon/src/main/resources/META-INF/route.xml rename to quickstarts/camel-saxon/src/main/resources/META-INF/route.xml diff --git a/camel-saxon/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-saxon/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-saxon/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-saxon/src/main/resources/META-INF/switchyard.xml diff --git a/camel-saxon/src/main/resources/wsdl/GreetingService.wsdl b/quickstarts/camel-saxon/src/main/resources/wsdl/GreetingService.wsdl similarity index 100% rename from camel-saxon/src/main/resources/wsdl/GreetingService.wsdl rename to quickstarts/camel-saxon/src/main/resources/wsdl/GreetingService.wsdl diff --git a/camel-saxon/src/test/java/org/switchyard/quickstarts/camel/saxon/CamelSaxonClient.java b/quickstarts/camel-saxon/src/test/java/org/switchyard/quickstarts/camel/saxon/CamelSaxonClient.java similarity index 100% rename from camel-saxon/src/test/java/org/switchyard/quickstarts/camel/saxon/CamelSaxonClient.java rename to quickstarts/camel-saxon/src/test/java/org/switchyard/quickstarts/camel/saxon/CamelSaxonClient.java diff --git a/camel-saxon/src/test/java/org/switchyard/quickstarts/camel/saxon/CamelServiceTest.java b/quickstarts/camel-saxon/src/test/java/org/switchyard/quickstarts/camel/saxon/CamelServiceTest.java similarity index 100% rename from camel-saxon/src/test/java/org/switchyard/quickstarts/camel/saxon/CamelServiceTest.java rename to quickstarts/camel-saxon/src/test/java/org/switchyard/quickstarts/camel/saxon/CamelServiceTest.java diff --git a/camel-saxon/src/test/resources/META-INF/beans.xml b/quickstarts/camel-saxon/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-saxon/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-saxon/src/test/resources/META-INF/beans.xml diff --git a/camel-service/.gitignore b/quickstarts/camel-service/.gitignore similarity index 100% rename from camel-service/.gitignore rename to quickstarts/camel-service/.gitignore diff --git a/camel-service/Readme.md b/quickstarts/camel-service/Readme.md similarity index 100% rename from camel-service/Readme.md rename to quickstarts/camel-service/Readme.md diff --git a/camel-service/camel-service.jpg b/quickstarts/camel-service/camel-service.jpg similarity index 100% rename from camel-service/camel-service.jpg rename to quickstarts/camel-service/camel-service.jpg diff --git a/quickstarts/camel-service/pom.xml b/quickstarts/camel-service/pom.xml new file mode 100644 index 000000000..6d18a8272 --- /dev/null +++ b/quickstarts/camel-service/pom.xml @@ -0,0 +1,265 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-service + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: camel-service + Quickstart : Camel Service + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.service + true + 9999 + 1.6 + 1.6 + * + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard + switchyard-remote + test + + + org.codehaus.groovy + groovy-all + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-sca + + + org.apache.camel + camel-ognl + + + org.apache.camel + camel-mvel + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + org.switchyard.quickstarts.camel.service.CamelServiceClient + test + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.sca.client.port + 8181 + + + + + + + + + wildfly + + 9990 + + + + diff --git a/camel-service/src/main/java/org/switchyard/quickstarts/camel/service/JavaDSL.java b/quickstarts/camel-service/src/main/java/org/switchyard/quickstarts/camel/service/JavaDSL.java similarity index 100% rename from camel-service/src/main/java/org/switchyard/quickstarts/camel/service/JavaDSL.java rename to quickstarts/camel-service/src/main/java/org/switchyard/quickstarts/camel/service/JavaDSL.java diff --git a/camel-service/src/main/java/org/switchyard/quickstarts/camel/service/JavaDSLBuilder.java b/quickstarts/camel-service/src/main/java/org/switchyard/quickstarts/camel/service/JavaDSLBuilder.java similarity index 100% rename from camel-service/src/main/java/org/switchyard/quickstarts/camel/service/JavaDSLBuilder.java rename to quickstarts/camel-service/src/main/java/org/switchyard/quickstarts/camel/service/JavaDSLBuilder.java diff --git a/camel-service/src/main/resources/META-INF/beans.xml b/quickstarts/camel-service/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-service/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-service/src/main/resources/META-INF/beans.xml diff --git a/camel-service/src/main/resources/META-INF/forge.xml b/quickstarts/camel-service/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-service/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-service/src/main/resources/META-INF/forge.xml diff --git a/camel-service/src/main/resources/META-INF/route.xml b/quickstarts/camel-service/src/main/resources/META-INF/route.xml similarity index 100% rename from camel-service/src/main/resources/META-INF/route.xml rename to quickstarts/camel-service/src/main/resources/META-INF/route.xml diff --git a/camel-service/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-service/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-service/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-service/src/main/resources/META-INF/switchyard.xml diff --git a/camel-service/src/test/java/org/switchyard/quickstarts/camel/service/CamelServiceClient.java b/quickstarts/camel-service/src/test/java/org/switchyard/quickstarts/camel/service/CamelServiceClient.java similarity index 100% rename from camel-service/src/test/java/org/switchyard/quickstarts/camel/service/CamelServiceClient.java rename to quickstarts/camel-service/src/test/java/org/switchyard/quickstarts/camel/service/CamelServiceClient.java diff --git a/camel-service/src/test/java/org/switchyard/quickstarts/camel/service/CamelServiceTest.java b/quickstarts/camel-service/src/test/java/org/switchyard/quickstarts/camel/service/CamelServiceTest.java similarity index 100% rename from camel-service/src/test/java/org/switchyard/quickstarts/camel/service/CamelServiceTest.java rename to quickstarts/camel-service/src/test/java/org/switchyard/quickstarts/camel/service/CamelServiceTest.java diff --git a/camel-service/src/test/resources/META-INF/beans.xml b/quickstarts/camel-service/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-service/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-service/src/test/resources/META-INF/beans.xml diff --git a/camel-service/src/test/resources/log4j.xml b/quickstarts/camel-service/src/test/resources/log4j.xml similarity index 100% rename from camel-service/src/test/resources/log4j.xml rename to quickstarts/camel-service/src/test/resources/log4j.xml diff --git a/camel-soap-proxy/Readme.md b/quickstarts/camel-soap-proxy/Readme.md similarity index 100% rename from camel-soap-proxy/Readme.md rename to quickstarts/camel-soap-proxy/Readme.md diff --git a/camel-soap-proxy/camel-soap-proxy.jpg b/quickstarts/camel-soap-proxy/camel-soap-proxy.jpg similarity index 100% rename from camel-soap-proxy/camel-soap-proxy.jpg rename to quickstarts/camel-soap-proxy/camel-soap-proxy.jpg diff --git a/quickstarts/camel-soap-proxy/pom.xml b/quickstarts/camel-soap-proxy/pom.xml new file mode 100644 index 000000000..1d038575e --- /dev/null +++ b/quickstarts/camel-soap-proxy/pom.xml @@ -0,0 +1,111 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-soap-proxy-parent + 2.1.0-SNAPSHOT + pom + SwitchYard Quickstart: camel-soap-proxy parent + Quickstart : Camel SOAP Proxy Parent + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 9999 + 1.6 + 1.6 + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-reverse + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-reverse-service + ${project.version} + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy + ${project.version} + + + + + reverse + reverse-service + soap-proxy + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/quickstarts/camel-soap-proxy/reverse-service/pom.xml b/quickstarts/camel-soap-proxy/reverse-service/pom.xml new file mode 100644 index 000000000..9520cad56 --- /dev/null +++ b/quickstarts/camel-soap-proxy/reverse-service/pom.xml @@ -0,0 +1,128 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-camel-soap-proxy-reverse-service + war + SwitchYard Quickstart: camel-soap-proxy-reverse-service + Quickstart : Camel SOAP Proxy Reverse Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 1.6 + 1.6 + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-reverse + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + maven-war-plugin + + + false + WEB-INF/jboss-web.xml,WEB-INF/lib/switchyard-camel-soap-proxy-reverse-**.jar + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.war + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.war + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + diff --git a/camel-soap-proxy/reverse-service/src/main/webapp/WEB-INF/jboss-web.xml b/quickstarts/camel-soap-proxy/reverse-service/src/main/webapp/WEB-INF/jboss-web.xml similarity index 100% rename from camel-soap-proxy/reverse-service/src/main/webapp/WEB-INF/jboss-web.xml rename to quickstarts/camel-soap-proxy/reverse-service/src/main/webapp/WEB-INF/jboss-web.xml diff --git a/camel-soap-proxy/reverse-service/src/main/webapp/WEB-INF/web.xml b/quickstarts/camel-soap-proxy/reverse-service/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from camel-soap-proxy/reverse-service/src/main/webapp/WEB-INF/web.xml rename to quickstarts/camel-soap-proxy/reverse-service/src/main/webapp/WEB-INF/web.xml diff --git a/camel-soap-proxy/reverse-service/src/test/resources/META-INF/beans.xml b/quickstarts/camel-soap-proxy/reverse-service/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-soap-proxy/reverse-service/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-soap-proxy/reverse-service/src/test/resources/META-INF/beans.xml diff --git a/quickstarts/camel-soap-proxy/reverse/pom.xml b/quickstarts/camel-soap-proxy/reverse/pom.xml new file mode 100644 index 000000000..08a008c4a --- /dev/null +++ b/quickstarts/camel-soap-proxy/reverse/pom.xml @@ -0,0 +1,112 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-camel-soap-proxy-reverse + bundle + SwitchYard Quickstart: camel-soap-proxy reverse + Quickstart : Camel SOAP Proxy Reverse + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + + org.switchyard.quickstarts.camel.soap.proxy + + + javax.xml.ws.soap, + javax.ws.rs.*;version="[1.1,3)", + org.apache.cxf.*;version="[2,4)", + org.switchyard.quickstarts.camel.soap.proxy + + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + + + org.apache.cxf + cxf-rt-frontend-jaxws + + + + ${project.artifactId} + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${project.name} + ${project.groupId}.${project.artifactId} + ${switchyard.osgi.import} + {maven-resources} + ${switchyard.osgi.dynamic} + <_failok>true + !* + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + diff --git a/camel-soap-proxy/reverse/src/main/java/org/switchyard/quickstarts/camel/soap/proxy/ReverseService.java b/quickstarts/camel-soap-proxy/reverse/src/main/java/org/switchyard/quickstarts/camel/soap/proxy/ReverseService.java similarity index 100% rename from camel-soap-proxy/reverse/src/main/java/org/switchyard/quickstarts/camel/soap/proxy/ReverseService.java rename to quickstarts/camel-soap-proxy/reverse/src/main/java/org/switchyard/quickstarts/camel/soap/proxy/ReverseService.java diff --git a/camel-soap-proxy/reverse/src/main/resources/META-INF/beans.xml b/quickstarts/camel-soap-proxy/reverse/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-soap-proxy/reverse/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-soap-proxy/reverse/src/main/resources/META-INF/beans.xml diff --git a/camel-soap-proxy/reverse/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/quickstarts/camel-soap-proxy/reverse/src/main/resources/OSGI-INF/blueprint/blueprint.xml similarity index 100% rename from camel-soap-proxy/reverse/src/main/resources/OSGI-INF/blueprint/blueprint.xml rename to quickstarts/camel-soap-proxy/reverse/src/main/resources/OSGI-INF/blueprint/blueprint.xml diff --git a/quickstarts/camel-soap-proxy/soap-proxy/pom.xml b/quickstarts/camel-soap-proxy/soap-proxy/pom.xml new file mode 100644 index 000000000..22dbbf5ce --- /dev/null +++ b/quickstarts/camel-soap-proxy/soap-proxy/pom.xml @@ -0,0 +1,208 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-parent + 2.1.0-SNAPSHOT + ../pom.xml + + switchyard-camel-soap-proxy + bundle + SwitchYard Quickstart: camel-soap-proxy + Quickstart : Camel SOAP Proxy + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.soap.proxy + true + 1.6 + 1.6 + + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; + filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-reverse + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.camel.soap.proxy.CamelClient + false + + ${project.build.directory}/test-classes/xml/soap-request.xml + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${project.name} + ${bundle.symbolic.name} + ${switchyard.osgi.import} + {maven-resources}, + META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.dynamic} + <_failok>true + !* + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + org.switchyard.component.soap.standalone.dir + cxf/reverseService + + + + + + + + + diff --git a/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/ReverseService.wsdl b/quickstarts/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/ReverseService.wsdl similarity index 100% rename from camel-soap-proxy/soap-proxy/src/main/resources/META-INF/ReverseService.wsdl rename to quickstarts/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/ReverseService.wsdl diff --git a/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/route.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/route.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/main/resources/META-INF/route.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/route.xml diff --git a/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/main/resources/META-INF/switchyard.xml diff --git a/camel-soap-proxy/soap-proxy/src/test/java/org/switchyard/quickstarts/camel/soap/proxy/CamelClient.java b/quickstarts/camel-soap-proxy/soap-proxy/src/test/java/org/switchyard/quickstarts/camel/soap/proxy/CamelClient.java similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/java/org/switchyard/quickstarts/camel/soap/proxy/CamelClient.java rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/java/org/switchyard/quickstarts/camel/soap/proxy/CamelClient.java diff --git a/camel-soap-proxy/soap-proxy/src/test/java/org/switchyard/quickstarts/camel/soap/proxy/CamelSOAPProxyTest.java b/quickstarts/camel-soap-proxy/soap-proxy/src/test/java/org/switchyard/quickstarts/camel/soap/proxy/CamelSOAPProxyTest.java similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/java/org/switchyard/quickstarts/camel/soap/proxy/CamelSOAPProxyTest.java rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/java/org/switchyard/quickstarts/camel/soap/proxy/CamelSOAPProxyTest.java diff --git a/camel-soap-proxy/soap-proxy/src/test/resources/META-INF/beans.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/META-INF/beans.xml diff --git a/camel-soap-proxy/soap-proxy/src/test/resources/log4j.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/log4j.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/resources/log4j.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/log4j.xml diff --git a/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-fault-request.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-fault-request.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-fault-request.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-fault-request.xml diff --git a/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-fault-response.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-fault-response.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-fault-response.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-fault-response.xml diff --git a/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-proxy-response.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-proxy-response.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-proxy-response.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-proxy-response.xml diff --git a/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-request.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-request.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-request.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-request.xml diff --git a/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-response.xml b/quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-response.xml similarity index 100% rename from camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-response.xml rename to quickstarts/camel-soap-proxy/soap-proxy/src/test/resources/xml/soap-response.xml diff --git a/camel-sql-binding/Readme.md b/quickstarts/camel-sql-binding/Readme.md similarity index 100% rename from camel-sql-binding/Readme.md rename to quickstarts/camel-sql-binding/Readme.md diff --git a/camel-sql-binding/camel-sql-binding.jpg b/quickstarts/camel-sql-binding/camel-sql-binding.jpg similarity index 100% rename from camel-sql-binding/camel-sql-binding.jpg rename to quickstarts/camel-sql-binding/camel-sql-binding.jpg diff --git a/camel-sql-binding/config.cli b/quickstarts/camel-sql-binding/config.cli similarity index 100% rename from camel-sql-binding/config.cli rename to quickstarts/camel-sql-binding/config.cli diff --git a/quickstarts/camel-sql-binding/pom.xml b/quickstarts/camel-sql-binding/pom.xml new file mode 100644 index 000000000..0b3cad1e5 --- /dev/null +++ b/quickstarts/camel-sql-binding/pom.xml @@ -0,0 +1,316 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-camel-sql-binding + 2.1.0-SNAPSHOT + SwitchYard Quickstart: camel-sql-binding + Quickstart : Camel SQL Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.camel.sql.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.168 + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel-sql + + + org.switchyard.components + switchyard-component-camel-quartz + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-naming + test + + + com.h2database + h2 + test + + + org.hamcrest + hamcrest-core + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + db + + + + com.edugility + h2-maven-plugin + 1.0 + false + + ${project.build.directory} + + + + Spawn a new H2 TCP server + package + + spawn + + + + Stop a spawned H2 TCP server + pre-clean + + stop + + + + + + org.codehaus.mojo + sql-maven-plugin + 1.5 + + + com.h2database + h2 + ${version.com.h2database} + + + + org.h2.Driver + jdbc:h2:tcp://localhost/h2db + sa + + + + create + package + + execute + + + CREATE TABLE IF NOT EXISTS greetings ( id INT PRIMARY KEY AUTO_INCREMENT, receiver VARCHAR(255), sender VARCHAR(255) ) + + + + + + + + + wildfly + + 9990 + + + + bundle + diff --git a/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/Greeting.java b/quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/Greeting.java similarity index 100% rename from camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/Greeting.java rename to quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/Greeting.java diff --git a/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingConverter.java b/quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingConverter.java similarity index 100% rename from camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingConverter.java rename to quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingConverter.java diff --git a/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingService.java b/quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingService.java similarity index 100% rename from camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingService.java rename to quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingService.java diff --git a/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingServiceImpl.java b/quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingServiceImpl.java similarity index 100% rename from camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingServiceImpl.java rename to quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/GreetingServiceImpl.java diff --git a/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/PojoIterator.java b/quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/PojoIterator.java similarity index 100% rename from camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/PojoIterator.java rename to quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/PojoIterator.java diff --git a/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/SingleGreetService.java b/quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/SingleGreetService.java similarity index 100% rename from camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/SingleGreetService.java rename to quickstarts/camel-sql-binding/src/main/java/org/switchyard/quickstarts/camel/sql/binding/SingleGreetService.java diff --git a/camel-sql-binding/src/main/resources/META-INF/beans.xml b/quickstarts/camel-sql-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from camel-sql-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/camel-sql-binding/src/main/resources/META-INF/beans.xml diff --git a/camel-sql-binding/src/main/resources/META-INF/forge.xml b/quickstarts/camel-sql-binding/src/main/resources/META-INF/forge.xml similarity index 100% rename from camel-sql-binding/src/main/resources/META-INF/forge.xml rename to quickstarts/camel-sql-binding/src/main/resources/META-INF/forge.xml diff --git a/camel-sql-binding/src/main/resources/META-INF/services/org/apache/camel/TypeConverter b/quickstarts/camel-sql-binding/src/main/resources/META-INF/services/org/apache/camel/TypeConverter similarity index 100% rename from camel-sql-binding/src/main/resources/META-INF/services/org/apache/camel/TypeConverter rename to quickstarts/camel-sql-binding/src/main/resources/META-INF/services/org/apache/camel/TypeConverter diff --git a/camel-sql-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/camel-sql-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from camel-sql-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/camel-sql-binding/src/main/resources/META-INF/switchyard.xml diff --git a/camel-sql-binding/src/main/resources/OSGI-INF/blueprint/datasource-h2.xml b/quickstarts/camel-sql-binding/src/main/resources/OSGI-INF/blueprint/datasource-h2.xml similarity index 100% rename from camel-sql-binding/src/main/resources/OSGI-INF/blueprint/datasource-h2.xml rename to quickstarts/camel-sql-binding/src/main/resources/OSGI-INF/blueprint/datasource-h2.xml diff --git a/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlBindingTest.java b/quickstarts/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlBindingTest.java similarity index 100% rename from camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlBindingTest.java rename to quickstarts/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlBindingTest.java diff --git a/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlRetrieveTest.java b/quickstarts/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlRetrieveTest.java similarity index 100% rename from camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlRetrieveTest.java rename to quickstarts/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlRetrieveTest.java diff --git a/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlStoreTest.java b/quickstarts/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlStoreTest.java similarity index 100% rename from camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlStoreTest.java rename to quickstarts/camel-sql-binding/src/test/java/org/switchyard/quickstarts/camel/sql/CamelSqlStoreTest.java diff --git a/camel-sql-binding/src/test/resources/META-INF/beans.xml b/quickstarts/camel-sql-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from camel-sql-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/camel-sql-binding/src/test/resources/META-INF/beans.xml diff --git a/camel-sql-binding/src/test/resources/log4j.xml b/quickstarts/camel-sql-binding/src/test/resources/log4j.xml similarity index 100% rename from camel-sql-binding/src/test/resources/log4j.xml rename to quickstarts/camel-sql-binding/src/test/resources/log4j.xml diff --git a/camel-sql-binding/unconfig.cli b/quickstarts/camel-sql-binding/unconfig.cli similarity index 100% rename from camel-sql-binding/unconfig.cli rename to quickstarts/camel-sql-binding/unconfig.cli diff --git a/demos/cluster/README.md b/quickstarts/demos/cluster/README.md similarity index 100% rename from demos/cluster/README.md rename to quickstarts/demos/cluster/README.md diff --git a/quickstarts/demos/cluster/client/pom.xml b/quickstarts/demos/cluster/client/pom.xml new file mode 100644 index 000000000..2af12152c --- /dev/null +++ b/quickstarts/demos/cluster/client/pom.xml @@ -0,0 +1,84 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-cluster + 2.1.0-SNAPSHOT + + switchyard-demo-cluster-client + jar + Quickstart Demo: Cluster - Client + Quickstart Demo: Cluster - Client + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + org.switchyard + switchyard-remote + test + + + + ${project.artifactId} + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.demo.cluster.RemoteClient + false + + + + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.sca.client.port + 8181 + + + + + + + + + diff --git a/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java b/quickstarts/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java similarity index 100% rename from demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java rename to quickstarts/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java diff --git a/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java b/quickstarts/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java similarity index 100% rename from demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java rename to quickstarts/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java diff --git a/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java b/quickstarts/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java similarity index 100% rename from demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java rename to quickstarts/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java diff --git a/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java b/quickstarts/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java similarity index 100% rename from demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java rename to quickstarts/demos/cluster/client/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java diff --git a/demos/cluster/client/src/test/java/org/switchyard/quickstarts/demo/cluster/RemoteClient.java b/quickstarts/demos/cluster/client/src/test/java/org/switchyard/quickstarts/demo/cluster/RemoteClient.java similarity index 100% rename from demos/cluster/client/src/test/java/org/switchyard/quickstarts/demo/cluster/RemoteClient.java rename to quickstarts/demos/cluster/client/src/test/java/org/switchyard/quickstarts/demo/cluster/RemoteClient.java diff --git a/quickstarts/demos/cluster/credit/pom.xml b/quickstarts/demos/cluster/credit/pom.xml new file mode 100644 index 000000000..89a3b29ad --- /dev/null +++ b/quickstarts/demos/cluster/credit/pom.xml @@ -0,0 +1,206 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-cluster + 2.1.0-SNAPSHOT + + switchyard-demo-cluster-credit + bundle + Quickstart Demo: Cluster - Credit Service + Quickstart Demo: Cluster - Credit Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.cluster.credit + true + remote + 10999 + 11999 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard.components + switchyard-component-sca + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${wildfly.port.node2} + ${project.build.finalName}.jar + ${deploy.skip} + + + + deploy2 + install + + deploy-only + + + ${wildfly.port.node3} + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${wildfly.port.node2} + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy2 + clean + + undeploy + + + ${wildfly.port.node3} + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + + + deploy + + false + + + + wildfly + + http-remoting + 10990 + 11990 + + + + diff --git a/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java b/quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java similarity index 100% rename from demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java rename to quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java diff --git a/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java b/quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java similarity index 100% rename from demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java rename to quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java diff --git a/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/CreditCheck.java b/quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/CreditCheck.java similarity index 100% rename from demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/CreditCheck.java rename to quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/CreditCheck.java diff --git a/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java b/quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java similarity index 100% rename from demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java rename to quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java diff --git a/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java b/quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java similarity index 100% rename from demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java rename to quickstarts/demos/cluster/credit/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java diff --git a/demos/cluster/credit/src/main/resources/META-INF/beans.xml b/quickstarts/demos/cluster/credit/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/cluster/credit/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/cluster/credit/src/main/resources/META-INF/beans.xml diff --git a/demos/cluster/credit/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/cluster/credit/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/cluster/credit/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/cluster/credit/src/main/resources/META-INF/switchyard.xml diff --git a/demos/cluster/credit/src/main/resources/RulesComponent.drl b/quickstarts/demos/cluster/credit/src/main/resources/RulesComponent.drl similarity index 100% rename from demos/cluster/credit/src/main/resources/RulesComponent.drl rename to quickstarts/demos/cluster/credit/src/main/resources/RulesComponent.drl diff --git a/demos/cluster/credit/src/test/java/org/switchyard/quickstarts/demo/cluster/CreditCheckTest.java b/quickstarts/demos/cluster/credit/src/test/java/org/switchyard/quickstarts/demo/cluster/CreditCheckTest.java similarity index 100% rename from demos/cluster/credit/src/test/java/org/switchyard/quickstarts/demo/cluster/CreditCheckTest.java rename to quickstarts/demos/cluster/credit/src/test/java/org/switchyard/quickstarts/demo/cluster/CreditCheckTest.java diff --git a/demos/cluster/credit/src/test/resources/META-INF/beans.xml b/quickstarts/demos/cluster/credit/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/cluster/credit/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/cluster/credit/src/test/resources/META-INF/beans.xml diff --git a/quickstarts/demos/cluster/dealer/pom.xml b/quickstarts/demos/cluster/dealer/pom.xml new file mode 100644 index 000000000..9ab63e7f6 --- /dev/null +++ b/quickstarts/demos/cluster/dealer/pom.xml @@ -0,0 +1,179 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-cluster + 2.1.0-SNAPSHOT + + switchyard-demo-cluster-dealer + bundle + Quickstart Demo: Cluster - Dealer Service + Quickstart Demo: Cluster - Dealer Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.cluster.dealer + true + 9999 + remote + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + + + deploy + + false + + + + wildfly + + http-remoting + 9990 + + + + diff --git a/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java b/quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java similarity index 100% rename from demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java rename to quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Application.java diff --git a/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java b/quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java similarity index 100% rename from demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java rename to quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Car.java diff --git a/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/CreditCheck.java b/quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/CreditCheck.java similarity index 100% rename from demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/CreditCheck.java rename to quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/CreditCheck.java diff --git a/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java b/quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java similarity index 100% rename from demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java rename to quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Deal.java diff --git a/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Dealer.java b/quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Dealer.java similarity index 100% rename from demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Dealer.java rename to quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Dealer.java diff --git a/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/DealerBean.java b/quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/DealerBean.java similarity index 100% rename from demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/DealerBean.java rename to quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/DealerBean.java diff --git a/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java b/quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java similarity index 100% rename from demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java rename to quickstarts/demos/cluster/dealer/src/main/java/org/switchyard/quickstarts/demo/cluster/Offer.java diff --git a/demos/cluster/dealer/src/main/resources/META-INF/beans.xml b/quickstarts/demos/cluster/dealer/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/cluster/dealer/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/cluster/dealer/src/main/resources/META-INF/beans.xml diff --git a/demos/cluster/dealer/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/cluster/dealer/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/cluster/dealer/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/cluster/dealer/src/main/resources/META-INF/switchyard.xml diff --git a/demos/cluster/dealer/src/test/java/org/switchyard/quickstarts/demo/cluster/DealerTest.java b/quickstarts/demos/cluster/dealer/src/test/java/org/switchyard/quickstarts/demo/cluster/DealerTest.java similarity index 100% rename from demos/cluster/dealer/src/test/java/org/switchyard/quickstarts/demo/cluster/DealerTest.java rename to quickstarts/demos/cluster/dealer/src/test/java/org/switchyard/quickstarts/demo/cluster/DealerTest.java diff --git a/demos/cluster/dealer/src/test/resources/META-INF/beans.xml b/quickstarts/demos/cluster/dealer/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/cluster/dealer/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/cluster/dealer/src/test/resources/META-INF/beans.xml diff --git a/quickstarts/demos/cluster/pom.xml b/quickstarts/demos/cluster/pom.xml new file mode 100644 index 000000000..f0a33a539 --- /dev/null +++ b/quickstarts/demos/cluster/pom.xml @@ -0,0 +1,125 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-cluster + 2.1.0-SNAPSHOT + pom + Quickstart Demo: Cluster + Quickstart Demo: Cluster + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + 1.3.1 + 2.4.0 + 1.0.2.Final + + + client + credit + dealer + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + diff --git a/demos/helpdesk/Readme.md b/quickstarts/demos/helpdesk/Readme.md similarity index 100% rename from demos/helpdesk/Readme.md rename to quickstarts/demos/helpdesk/Readme.md diff --git a/demos/helpdesk/helpdesk.jpg b/quickstarts/demos/helpdesk/helpdesk.jpg similarity index 100% rename from demos/helpdesk/helpdesk.jpg rename to quickstarts/demos/helpdesk/helpdesk.jpg diff --git a/quickstarts/demos/helpdesk/pom.xml b/quickstarts/demos/helpdesk/pom.xml new file mode 100644 index 000000000..789343cc6 --- /dev/null +++ b/quickstarts/demos/helpdesk/pom.xml @@ -0,0 +1,453 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-helpdesk + 2.1.0-SNAPSHOT + war + Quickstart Demo : Help Desk + Quickstart Demo : Help Desk + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.helpdesk + true + 9999 + 1.6 + 1.6 + + javax.el, + javax.faces.webapp, + javax.servlet;version="[3.0.0,4.0.0)", + javax.servlet.http;version="[3.0.0,4.0.0)", + javax.servlet.jsp;version="2.2.0", + javax.servlet.jsp.jstl.core;version="2.2", + javax.servlet.jsp.jstl.fmt;version="2.2", + javax.servlet.jsp.jstl.tlv;version="2.2", + org.apache.taglibs.standard.resources;version="1.1.2", + org.apache.taglibs.standard.tag.common.core;version="1.1.2", + org.apache.taglibs.standard.tag.rt.core;version="1.1.2", + org.apache.taglibs.standard.tei;version="1.1.2", + org.apache.taglibs.standard.tlv;version="1.1.2" + com.sun.el.lang, + com.sun.el.parser, + com.sun.el, + com.sun.el.util, + javax.faces.*, + org.apache.log4j, + org.drools.persistence.info, + org.jbpm.executor.entities, + org.jbpm.persistence.correlation, + org.jbpm.persistence.processinstance, + org.jbpm.process.audit, + org.jbpm.runtime.manager.impl.jpa, + org.jbpm.services.task.audit.impl.model, + org.jbpm.services.task.impl.model, + org.jbpm.services.task.internals.lifecycle, + org.jbpm.services.task.persistence, + org.jbpm.services.task.query, + org.kie.api.task.model, + org.kie.internal.executor.api, + org.kie.internal.task.api.model, + org.w3c.dom, + * + + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.apache.myfaces.core.bundle + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + 6.2.0.CR3 + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + org.jbpm + jbpm-bom + ${version.org.jbpm} + pom + import + + + + + + org.hibernate + hibernate-entitymanager + provided + + + org.switchyard + switchyard-api + provided + + + org.switchyard.components + switchyard-component-bean + provided + + + org.switchyard.components + switchyard-component-bpm + provided + + + org.switchyard.components + switchyard-component-soap + provided + + + + javax.enterprise + cdi-api + provided + + + + org.jboss.spec.javax.annotation + jboss-annotations-api_1.1_spec + provided + + + + org.jboss.spec.javax.faces + jboss-jsf-api_2.1_spec + provided + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + org.apache.httpcomponents + httpclient + test + + + com.h2database + h2 + test + + + org.jbpm + jbpm-executor + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + + + bundle-manifest + process-classes + + manifest + + + + + + war + + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, WEB-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + ${switchyard.osgi.require.bundle} + WEB-INF/classes/META-INF/persistence-osgi.xml + helpdesk + <_wab>src/main/webapp + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + true + + + + maven-war-plugin + + false + + WEB-INF/lib/*.jar, + WEB-INF/classes/META-INF/switchyard.xml, + WEB-INF/classes/META-INF/MANIFEST.MF, + WEB-INF/classes/META-INF/beans.xml, + WEB-INF/classes/OSGI-INF/** + + + + target/classes/META-INF + WEB-INF + + switchyard.xml + + + + target/classes/META-INF + META-INF + + beans.xml + + + + target/classes/OSGI-INF + OSGI-INF + + + + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack-jbpm-orm-files + generate-resources + + unpack + + + + + org.jbpm + jbpm-human-task-audit + jar + + + org.jbpm + jbpm-human-task-jpa + jar + + + org.jbpm + jbpm-persistence-jpa + jar + + + org.jbpm + jbpm-executor + jar + + + org.jbpm + jbpm-kie-services + jar + + + META-INF/*orm.xml + ${project.build.outputDirectory} + true + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.war + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.war + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demos.helpdesk.HelpDeskMain + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDesk.java b/quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDesk.java similarity index 100% rename from demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDesk.java rename to quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDesk.java diff --git a/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskService.java b/quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskService.java similarity index 100% rename from demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskService.java rename to quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskService.java diff --git a/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskUserGroupCallback.java b/quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskUserGroupCallback.java similarity index 100% rename from demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskUserGroupCallback.java rename to quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskUserGroupCallback.java diff --git a/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Ticket.java b/quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Ticket.java similarity index 100% rename from demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Ticket.java rename to quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Ticket.java diff --git a/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketAck.java b/quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketAck.java similarity index 100% rename from demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketAck.java rename to quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketAck.java diff --git a/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketManagementService.java b/quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketManagementService.java similarity index 100% rename from demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketManagementService.java rename to quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketManagementService.java diff --git a/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketManagementServiceBean.java b/quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketManagementServiceBean.java similarity index 100% rename from demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketManagementServiceBean.java rename to quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/TicketManagementServiceBean.java diff --git a/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Transformers.java b/quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Transformers.java similarity index 100% rename from demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Transformers.java rename to quickstarts/demos/helpdesk/src/main/java/org/switchyard/quickstarts/demos/helpdesk/Transformers.java diff --git a/demos/helpdesk/src/main/resources/META-INF/HelpDeskService.bpmn b/quickstarts/demos/helpdesk/src/main/resources/META-INF/HelpDeskService.bpmn similarity index 100% rename from demos/helpdesk/src/main/resources/META-INF/HelpDeskService.bpmn rename to quickstarts/demos/helpdesk/src/main/resources/META-INF/HelpDeskService.bpmn diff --git a/demos/helpdesk/src/main/resources/META-INF/HelpDeskService.wsdl b/quickstarts/demos/helpdesk/src/main/resources/META-INF/HelpDeskService.wsdl similarity index 100% rename from demos/helpdesk/src/main/resources/META-INF/HelpDeskService.wsdl rename to quickstarts/demos/helpdesk/src/main/resources/META-INF/HelpDeskService.wsdl diff --git a/demos/helpdesk/src/main/resources/META-INF/beans.xml b/quickstarts/demos/helpdesk/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/helpdesk/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/helpdesk/src/main/resources/META-INF/beans.xml diff --git a/demos/helpdesk/src/main/resources/META-INF/persistence-osgi.xml b/quickstarts/demos/helpdesk/src/main/resources/META-INF/persistence-osgi.xml similarity index 100% rename from demos/helpdesk/src/main/resources/META-INF/persistence-osgi.xml rename to quickstarts/demos/helpdesk/src/main/resources/META-INF/persistence-osgi.xml diff --git a/demos/helpdesk/src/main/resources/META-INF/persistence.xml b/quickstarts/demos/helpdesk/src/main/resources/META-INF/persistence.xml similarity index 100% rename from demos/helpdesk/src/main/resources/META-INF/persistence.xml rename to quickstarts/demos/helpdesk/src/main/resources/META-INF/persistence.xml diff --git a/demos/helpdesk/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/helpdesk/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/helpdesk/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/helpdesk/src/main/resources/META-INF/switchyard.xml diff --git a/demos/helpdesk/src/main/resources/OSGI-INF/blueprint/datasource.xml b/quickstarts/demos/helpdesk/src/main/resources/OSGI-INF/blueprint/datasource.xml similarity index 100% rename from demos/helpdesk/src/main/resources/OSGI-INF/blueprint/datasource.xml rename to quickstarts/demos/helpdesk/src/main/resources/OSGI-INF/blueprint/datasource.xml diff --git a/demos/helpdesk/src/main/webapp/WEB-INF/beans.xml b/quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from demos/helpdesk/src/main/webapp/WEB-INF/beans.xml rename to quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/beans.xml diff --git a/demos/helpdesk/src/main/webapp/WEB-INF/faces-config.xml b/quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from demos/helpdesk/src/main/webapp/WEB-INF/faces-config.xml rename to quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/faces-config.xml diff --git a/demos/helpdesk/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/jboss-deployment-structure.xml similarity index 100% rename from demos/helpdesk/src/main/webapp/WEB-INF/jboss-deployment-structure.xml rename to quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/jboss-deployment-structure.xml diff --git a/demos/helpdesk/src/main/webapp/WEB-INF/jboss-web.xml b/quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/jboss-web.xml similarity index 100% rename from demos/helpdesk/src/main/webapp/WEB-INF/jboss-web.xml rename to quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/jboss-web.xml diff --git a/demos/helpdesk/src/main/webapp/WEB-INF/jetty-web.xml b/quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/jetty-web.xml similarity index 100% rename from demos/helpdesk/src/main/webapp/WEB-INF/jetty-web.xml rename to quickstarts/demos/helpdesk/src/main/webapp/WEB-INF/jetty-web.xml diff --git a/demos/helpdesk/src/main/webapp/helpdesk.xhtml b/quickstarts/demos/helpdesk/src/main/webapp/helpdesk.xhtml similarity index 100% rename from demos/helpdesk/src/main/webapp/helpdesk.xhtml rename to quickstarts/demos/helpdesk/src/main/webapp/helpdesk.xhtml diff --git a/demos/helpdesk/src/main/webapp/index.html b/quickstarts/demos/helpdesk/src/main/webapp/index.html similarity index 100% rename from demos/helpdesk/src/main/webapp/index.html rename to quickstarts/demos/helpdesk/src/main/webapp/index.html diff --git a/demos/helpdesk/src/test/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskMain.java b/quickstarts/demos/helpdesk/src/test/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskMain.java similarity index 100% rename from demos/helpdesk/src/test/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskMain.java rename to quickstarts/demos/helpdesk/src/test/java/org/switchyard/quickstarts/demos/helpdesk/HelpDeskMain.java diff --git a/demos/helpdesk/src/test/resources/META-INF/beans.xml b/quickstarts/demos/helpdesk/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/helpdesk/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/helpdesk/src/test/resources/META-INF/beans.xml diff --git a/demos/helpdesk/src/test/resources/log4j.xml b/quickstarts/demos/helpdesk/src/test/resources/log4j.xml similarity index 100% rename from demos/helpdesk/src/test/resources/log4j.xml rename to quickstarts/demos/helpdesk/src/test/resources/log4j.xml diff --git a/demos/helpdesk/src/test/resources/xml/soap-request.xml b/quickstarts/demos/helpdesk/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/helpdesk/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/helpdesk/src/test/resources/xml/soap-request.xml diff --git a/demos/library/Readme.md b/quickstarts/demos/library/Readme.md similarity index 100% rename from demos/library/Readme.md rename to quickstarts/demos/library/Readme.md diff --git a/demos/library/library.jpg b/quickstarts/demos/library/library.jpg similarity index 100% rename from demos/library/library.jpg rename to quickstarts/demos/library/library.jpg diff --git a/demos/library/loan-process.jpg b/quickstarts/demos/library/loan-process.jpg similarity index 100% rename from demos/library/loan-process.jpg rename to quickstarts/demos/library/loan-process.jpg diff --git a/quickstarts/demos/library/pom.xml b/quickstarts/demos/library/pom.xml new file mode 100644 index 000000000..70606d71a --- /dev/null +++ b/quickstarts/demos/library/pom.xml @@ -0,0 +1,238 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-library + 2.1.0-SNAPSHOT + bundle + Quickstart Demo : Library + Quickstart Demo : Library + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.library + true + 9999 + 1.6 + 1.6 + * + + org.switchyard,org.switchyard.* + + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bpm + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demos.library.LibraryClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/Library.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/Library.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/Library.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/Library.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/LoanProcess.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/LoanProcess.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/LoanProcess.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/LoanProcess.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/SuggestionRules.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/SuggestionRules.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/SuggestionRules.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/SuggestionRules.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Book.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Book.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Book.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Book.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Loan.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Loan.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Loan.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Loan.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/LoanRequest.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/LoanRequest.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/LoanRequest.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/LoanRequest.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/LoanResponse.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/LoanResponse.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/LoanResponse.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/LoanResponse.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ObjectFactory.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ObjectFactory.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ObjectFactory.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ObjectFactory.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ReturnRequest.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ReturnRequest.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ReturnRequest.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ReturnRequest.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ReturnResponse.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ReturnResponse.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ReturnResponse.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/ReturnResponse.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Suggestion.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Suggestion.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Suggestion.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/Suggestion.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/SuggestionRequest.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/SuggestionRequest.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/SuggestionRequest.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/SuggestionRequest.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/SuggestionResponse.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/SuggestionResponse.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/SuggestionResponse.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/SuggestionResponse.java diff --git a/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/package-info.java b/quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/package-info.java similarity index 100% rename from demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/package-info.java rename to quickstarts/demos/library/src/main/java/org/switchyard/quickstarts/demos/library/types/package-info.java diff --git a/demos/library/src/main/resources/META-INF/LibraryTypes.xsd b/quickstarts/demos/library/src/main/resources/META-INF/LibraryTypes.xsd similarity index 100% rename from demos/library/src/main/resources/META-INF/LibraryTypes.xsd rename to quickstarts/demos/library/src/main/resources/META-INF/LibraryTypes.xsd diff --git a/demos/library/src/main/resources/META-INF/LoanProcess.bpmn b/quickstarts/demos/library/src/main/resources/META-INF/LoanProcess.bpmn similarity index 100% rename from demos/library/src/main/resources/META-INF/LoanProcess.bpmn rename to quickstarts/demos/library/src/main/resources/META-INF/LoanProcess.bpmn diff --git a/demos/library/src/main/resources/META-INF/LoanService.wsdl b/quickstarts/demos/library/src/main/resources/META-INF/LoanService.wsdl similarity index 100% rename from demos/library/src/main/resources/META-INF/LoanService.wsdl rename to quickstarts/demos/library/src/main/resources/META-INF/LoanService.wsdl diff --git a/demos/library/src/main/resources/META-INF/SuggestionRules.drl b/quickstarts/demos/library/src/main/resources/META-INF/SuggestionRules.drl similarity index 100% rename from demos/library/src/main/resources/META-INF/SuggestionRules.drl rename to quickstarts/demos/library/src/main/resources/META-INF/SuggestionRules.drl diff --git a/demos/library/src/main/resources/META-INF/SuggestionService.wsdl b/quickstarts/demos/library/src/main/resources/META-INF/SuggestionService.wsdl similarity index 100% rename from demos/library/src/main/resources/META-INF/SuggestionService.wsdl rename to quickstarts/demos/library/src/main/resources/META-INF/SuggestionService.wsdl diff --git a/demos/library/src/main/resources/META-INF/beans.xml b/quickstarts/demos/library/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/library/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/library/src/main/resources/META-INF/beans.xml diff --git a/demos/library/src/main/resources/META-INF/kmodule.xml b/quickstarts/demos/library/src/main/resources/META-INF/kmodule.xml similarity index 100% rename from demos/library/src/main/resources/META-INF/kmodule.xml rename to quickstarts/demos/library/src/main/resources/META-INF/kmodule.xml diff --git a/demos/library/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/library/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/library/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/library/src/main/resources/META-INF/switchyard.xml diff --git a/demos/library/src/test/java/org/switchyard/quickstarts/demos/library/LibraryClient.java b/quickstarts/demos/library/src/test/java/org/switchyard/quickstarts/demos/library/LibraryClient.java similarity index 100% rename from demos/library/src/test/java/org/switchyard/quickstarts/demos/library/LibraryClient.java rename to quickstarts/demos/library/src/test/java/org/switchyard/quickstarts/demos/library/LibraryClient.java diff --git a/demos/library/src/test/java/org/switchyard/quickstarts/demos/library/WebServiceTest.java b/quickstarts/demos/library/src/test/java/org/switchyard/quickstarts/demos/library/WebServiceTest.java similarity index 100% rename from demos/library/src/test/java/org/switchyard/quickstarts/demos/library/WebServiceTest.java rename to quickstarts/demos/library/src/test/java/org/switchyard/quickstarts/demos/library/WebServiceTest.java diff --git a/demos/library/src/test/resources/META-INF/beans.xml b/quickstarts/demos/library/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/library/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/library/src/test/resources/META-INF/beans.xml diff --git a/demos/library/src/test/resources/log4j.xml b/quickstarts/demos/library/src/test/resources/log4j.xml similarity index 100% rename from demos/library/src/test/resources/log4j.xml rename to quickstarts/demos/library/src/test/resources/log4j.xml diff --git a/quickstarts/demos/multiApp/README.md b/quickstarts/demos/multiApp/README.md new file mode 100644 index 000000000..660a3a341 --- /dev/null +++ b/quickstarts/demos/multiApp/README.md @@ -0,0 +1,70 @@ +# MultiApp Demo Quickstart + +This quickstart provides an example of a multi-project application structure with SwitchYard. The quickstart consists of the following pieces: + +* artifacts : contains XSDs, WSDLs, and Java domain objects which are used by service providers and consumers across application projects +* order-service : provides two services - OrderService and InventoryService +* order-consumer : consumes OrderService through a SOAP/HTTP binding +* web : consumes InventoryService using it's Java service interface + +The MultiApp quickstart can also be used to demonstrate design-time repository integration with SwitchYard. Individual service artifacts in the artifacts project can be uploaded to a service repository (e.g. Guvnor) and exported as a service module for use within projects which consume the service. Additional detail can be found in the SwitchYard Repository Integration wiki article. + +Consult the README.md in each individual project for more info. + +## Running the Example + + +EAP +---------- +1. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy + +4. Use one or both of the consuming application projects: + * Web: Visit . + * JMS: Use 'mvn exec:java' in the order-consumer project to submit a JMS order message via the OrderIntake service. + +5. Check the server console for output from the service. + +6. Undeploy the quickstart: + + mvn clean -Pdeploy + + + +Wildfly +---------- +1. Start Wildfly in standalone mode: + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy -Pwildfly + +4. Use one or both of the consuming application projects: + * Web: Visit . + * JMS: Use 'mvn exec:java -Pwildfly' in the order-consumer project to submit a JMS order message via the OrderIntake service. + +5. Check the server console for output from the service. + +6. Undeploy the quickstart: + + mvn clean -Pdeploy -Pwildfly + + + +## Further Reading + +1. [SwitchYard Repository Integration](https://community.jboss.org/wiki/SwitchYardRepositoryIntegration) diff --git a/demos/multiApp/artifacts/Readme.md b/quickstarts/demos/multiApp/artifacts/Readme.md similarity index 100% rename from demos/multiApp/artifacts/Readme.md rename to quickstarts/demos/multiApp/artifacts/Readme.md diff --git a/quickstarts/demos/multiApp/artifacts/pom.xml b/quickstarts/demos/multiApp/artifacts/pom.xml new file mode 100644 index 000000000..7f70ddd87 --- /dev/null +++ b/quickstarts/demos/multiApp/artifacts/pom.xml @@ -0,0 +1,105 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp + 2.1.0-SNAPSHOT + + switchyard-demo-multiApp-artifacts + jar + Quickstart Demo: Multiple Applications - Service Artifacts + Quickstart Demo: Multiple Applications - Service Artifacts + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + ${project.artifactId} + + + maven-jar-plugin + + + classes + + jar + + package + + classes + + **/*.class + + + + + all + + jar + + package + + + **/* + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + diff --git a/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/InventoryService.java b/quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/InventoryService.java similarity index 100% rename from demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/InventoryService.java rename to quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/InventoryService.java diff --git a/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Item.java b/quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Item.java similarity index 100% rename from demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Item.java rename to quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Item.java diff --git a/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/ItemNotFoundException.java b/quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/ItemNotFoundException.java similarity index 100% rename from demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/ItemNotFoundException.java rename to quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/ItemNotFoundException.java diff --git a/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Order.java b/quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Order.java similarity index 100% rename from demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Order.java rename to quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Order.java diff --git a/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderAck.java b/quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderAck.java similarity index 100% rename from demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderAck.java rename to quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderAck.java diff --git a/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderService.java b/quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderService.java similarity index 100% rename from demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderService.java rename to quickstarts/demos/multiApp/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderService.java diff --git a/demos/multiApp/artifacts/src/main/resources/META-INF/beans.xml b/quickstarts/demos/multiApp/artifacts/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/multiApp/artifacts/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/multiApp/artifacts/src/main/resources/META-INF/beans.xml diff --git a/demos/multiApp/artifacts/src/main/resources/OrderService.wsdl b/quickstarts/demos/multiApp/artifacts/src/main/resources/OrderService.wsdl similarity index 100% rename from demos/multiApp/artifacts/src/main/resources/OrderService.wsdl rename to quickstarts/demos/multiApp/artifacts/src/main/resources/OrderService.wsdl diff --git a/demos/multiApp/artifacts/src/main/resources/orderTypes.xsd b/quickstarts/demos/multiApp/artifacts/src/main/resources/orderTypes.xsd similarity index 100% rename from demos/multiApp/artifacts/src/main/resources/orderTypes.xsd rename to quickstarts/demos/multiApp/artifacts/src/main/resources/orderTypes.xsd diff --git a/demos/multiApp/order-consumer/README.md b/quickstarts/demos/multiApp/order-consumer/README.md similarity index 100% rename from demos/multiApp/order-consumer/README.md rename to quickstarts/demos/multiApp/order-consumer/README.md diff --git a/demos/multiApp/order-consumer/config.cli b/quickstarts/demos/multiApp/order-consumer/config.cli similarity index 100% rename from demos/multiApp/order-consumer/config.cli rename to quickstarts/demos/multiApp/order-consumer/config.cli diff --git a/demos/multiApp/order-consumer/order-consumer.jpg b/quickstarts/demos/multiApp/order-consumer/order-consumer.jpg similarity index 100% rename from demos/multiApp/order-consumer/order-consumer.jpg rename to quickstarts/demos/multiApp/order-consumer/order-consumer.jpg diff --git a/quickstarts/demos/multiApp/order-consumer/pom.xml b/quickstarts/demos/multiApp/order-consumer/pom.xml new file mode 100644 index 000000000..ca39fd691 --- /dev/null +++ b/quickstarts/demos/multiApp/order-consumer/pom.xml @@ -0,0 +1,241 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp + 2.1.0-SNAPSHOT + + switchyard-demo-multiApp-order-consumer + jar + Quickstart Demo: Multiple Applications - Order Consumer + Quickstart Demo: Multiple Applications - Order Consumer + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 2.4.1.Final + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-camel-core + + + org.switchyard.components + switchyard-component-soap + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + junit + junit + test + + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp-artifacts + + + org.switchyard.quickstarts.demos + + switchyard-demo-multiApp-order-service + + + + org.switchyard.quickstarts.demos + + switchyard-demo-multiApp-web + + war + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-jar-plugin + + + + deployment.switchyard-demo-multiApp-artifacts.jar + + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + org.switchyard.quickstarts.demo.multiapp.consumer.OrderIntakeClient + + ${project.build.directory}/test-classes/order.xml + + test + false + + + + + + + wildfly + + true + 8080 + + + + org.hornetq + hornetq-core-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-commons + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-journal + ${version.wildfly.hornetq} + test + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + hornetqmixin.port + 8080 + + + hornetqmixin.http.upgrade.enabled + true + + + + + + + + + diff --git a/demos/multiApp/order-consumer/src/main/resources/META-INF/forge.xml b/quickstarts/demos/multiApp/order-consumer/src/main/resources/META-INF/forge.xml similarity index 100% rename from demos/multiApp/order-consumer/src/main/resources/META-INF/forge.xml rename to quickstarts/demos/multiApp/order-consumer/src/main/resources/META-INF/forge.xml diff --git a/demos/multiApp/order-consumer/src/main/resources/META-INF/route.xml b/quickstarts/demos/multiApp/order-consumer/src/main/resources/META-INF/route.xml similarity index 100% rename from demos/multiApp/order-consumer/src/main/resources/META-INF/route.xml rename to quickstarts/demos/multiApp/order-consumer/src/main/resources/META-INF/route.xml diff --git a/demos/multiApp/order-consumer/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/multiApp/order-consumer/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/multiApp/order-consumer/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/multiApp/order-consumer/src/main/resources/META-INF/switchyard.xml diff --git a/demos/multiApp/order-consumer/src/test/java/org/switchyard/quickstarts/demo/multiapp/consumer/OrderIntakeClient.java b/quickstarts/demos/multiApp/order-consumer/src/test/java/org/switchyard/quickstarts/demo/multiapp/consumer/OrderIntakeClient.java similarity index 100% rename from demos/multiApp/order-consumer/src/test/java/org/switchyard/quickstarts/demo/multiapp/consumer/OrderIntakeClient.java rename to quickstarts/demos/multiApp/order-consumer/src/test/java/org/switchyard/quickstarts/demo/multiapp/consumer/OrderIntakeClient.java diff --git a/demos/multiApp/order-consumer/src/test/resources/META-INF/beans.xml b/quickstarts/demos/multiApp/order-consumer/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/multiApp/order-consumer/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/multiApp/order-consumer/src/test/resources/META-INF/beans.xml diff --git a/demos/multiApp/order-consumer/src/test/resources/order.xml b/quickstarts/demos/multiApp/order-consumer/src/test/resources/order.xml similarity index 100% rename from demos/multiApp/order-consumer/src/test/resources/order.xml rename to quickstarts/demos/multiApp/order-consumer/src/test/resources/order.xml diff --git a/demos/multiApp/order-consumer/src/test/resources/switchyard-quickstart-demo-multi-order-consumer-hornetq-jms.xml b/quickstarts/demos/multiApp/order-consumer/src/test/resources/switchyard-quickstart-demo-multi-order-consumer-hornetq-jms.xml similarity index 100% rename from demos/multiApp/order-consumer/src/test/resources/switchyard-quickstart-demo-multi-order-consumer-hornetq-jms.xml rename to quickstarts/demos/multiApp/order-consumer/src/test/resources/switchyard-quickstart-demo-multi-order-consumer-hornetq-jms.xml diff --git a/demos/multiApp/order-consumer/unconfig.cli b/quickstarts/demos/multiApp/order-consumer/unconfig.cli similarity index 100% rename from demos/multiApp/order-consumer/unconfig.cli rename to quickstarts/demos/multiApp/order-consumer/unconfig.cli diff --git a/demos/multiApp/order-service/Readme.md b/quickstarts/demos/multiApp/order-service/Readme.md similarity index 100% rename from demos/multiApp/order-service/Readme.md rename to quickstarts/demos/multiApp/order-service/Readme.md diff --git a/demos/multiApp/order-service/order-service.jpg b/quickstarts/demos/multiApp/order-service/order-service.jpg similarity index 100% rename from demos/multiApp/order-service/order-service.jpg rename to quickstarts/demos/multiApp/order-service/order-service.jpg diff --git a/quickstarts/demos/multiApp/order-service/pom.xml b/quickstarts/demos/multiApp/order-service/pom.xml new file mode 100644 index 000000000..adbad19fa --- /dev/null +++ b/quickstarts/demos/multiApp/order-service/pom.xml @@ -0,0 +1,142 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp + 2.1.0-SNAPSHOT + + switchyard-demo-multiApp-order-service + jar + Quickstart Demo: Multiple Applications - Order Service + Quickstart Demo: Multiple Applications - Order Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp-artifacts + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + + ${project.artifactId} + + + org.apache.maven.plugins + maven-jar-plugin + + + + deployment.switchyard-demo-multiApp-artifacts.jar + + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + diff --git a/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceBean.java b/quickstarts/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceBean.java similarity index 100% rename from demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceBean.java rename to quickstarts/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceBean.java diff --git a/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceBean.java b/quickstarts/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceBean.java similarity index 100% rename from demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceBean.java rename to quickstarts/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceBean.java diff --git a/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/Transformers.java b/quickstarts/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/Transformers.java similarity index 100% rename from demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/Transformers.java rename to quickstarts/demos/multiApp/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/Transformers.java diff --git a/demos/multiApp/order-service/src/main/resources/META-INF/beans.xml b/quickstarts/demos/multiApp/order-service/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/multiApp/order-service/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/multiApp/order-service/src/main/resources/META-INF/beans.xml diff --git a/demos/multiApp/order-service/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/multiApp/order-service/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/multiApp/order-service/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/multiApp/order-service/src/main/resources/META-INF/switchyard.xml diff --git a/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceTest.java b/quickstarts/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceTest.java similarity index 100% rename from demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceTest.java rename to quickstarts/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceTest.java diff --git a/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceTest.java b/quickstarts/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceTest.java similarity index 100% rename from demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceTest.java rename to quickstarts/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceTest.java diff --git a/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/TypeTransformationTest.java b/quickstarts/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/TypeTransformationTest.java similarity index 100% rename from demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/TypeTransformationTest.java rename to quickstarts/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/TypeTransformationTest.java diff --git a/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/WebServiceTest.java b/quickstarts/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/WebServiceTest.java similarity index 100% rename from demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/WebServiceTest.java rename to quickstarts/demos/multiApp/order-service/src/test/java/org/switchyard/quickstarts/demo/multiapp/service/WebServiceTest.java diff --git a/demos/multiApp/order-service/src/test/resources/META-INF/beans.xml b/quickstarts/demos/multiApp/order-service/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/multiApp/order-service/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/multiApp/order-service/src/test/resources/META-INF/beans.xml diff --git a/demos/multiApp/order-service/src/test/resources/log4j.xml b/quickstarts/demos/multiApp/order-service/src/test/resources/log4j.xml similarity index 100% rename from demos/multiApp/order-service/src/test/resources/log4j.xml rename to quickstarts/demos/multiApp/order-service/src/test/resources/log4j.xml diff --git a/demos/multiApp/order-service/src/test/resources/xml/order.xml b/quickstarts/demos/multiApp/order-service/src/test/resources/xml/order.xml similarity index 100% rename from demos/multiApp/order-service/src/test/resources/xml/order.xml rename to quickstarts/demos/multiApp/order-service/src/test/resources/xml/order.xml diff --git a/demos/multiApp/order-service/src/test/resources/xml/orderAck.xml b/quickstarts/demos/multiApp/order-service/src/test/resources/xml/orderAck.xml similarity index 100% rename from demos/multiApp/order-service/src/test/resources/xml/orderAck.xml rename to quickstarts/demos/multiApp/order-service/src/test/resources/xml/orderAck.xml diff --git a/demos/multiApp/order-service/src/test/resources/xml/soap-request.xml b/quickstarts/demos/multiApp/order-service/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/multiApp/order-service/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/multiApp/order-service/src/test/resources/xml/soap-request.xml diff --git a/demos/multiApp/order-service/src/test/resources/xml/soap-response.xml b/quickstarts/demos/multiApp/order-service/src/test/resources/xml/soap-response.xml similarity index 100% rename from demos/multiApp/order-service/src/test/resources/xml/soap-response.xml rename to quickstarts/demos/multiApp/order-service/src/test/resources/xml/soap-response.xml diff --git a/quickstarts/demos/multiApp/pom.xml b/quickstarts/demos/multiApp/pom.xml new file mode 100644 index 000000000..2f8de8ead --- /dev/null +++ b/quickstarts/demos/multiApp/pom.xml @@ -0,0 +1,157 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-multiApp + 2.1.0-SNAPSHOT + pom + Quickstart Demo: Multiple Applications + Quickstart Demo: Multiple Applications + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 9999 + 1.6 + 1.6 + 1.3.1 + 1.0.2.Final + + + artifacts + order-service + order-consumer + web + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp-artifacts + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp-order-service + ${project.version} + + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp-web + war + ${project.version} + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/demos/multiApp/web/README.md b/quickstarts/demos/multiApp/web/README.md similarity index 100% rename from demos/multiApp/web/README.md rename to quickstarts/demos/multiApp/web/README.md diff --git a/quickstarts/demos/multiApp/web/pom.xml b/quickstarts/demos/multiApp/web/pom.xml new file mode 100644 index 000000000..f3a162cf8 --- /dev/null +++ b/quickstarts/demos/multiApp/web/pom.xml @@ -0,0 +1,152 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp + 2.1.0-SNAPSHOT + + switchyard-demo-multiApp-web + war + Quickstart Demo: Multiple Applications - Web App + Quickstart Demo: Multiple Applications - Web App + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + org.switchyard.quickstarts.demos + switchyard-demo-multiApp-artifacts + + + org.switchyard + switchyard-api + provided + + + org.switchyard.components + switchyard-component-bean + provided + + + + javax.enterprise + cdi-api + provided + + + + org.jboss.spec.javax.annotation + jboss-annotations-api_1.1_spec + provided + + + + org.jboss.spec.javax.faces + jboss-jsf-api_2.1_spec + provided + + + org.switchyard + switchyard-test + test + + + junit + junit + test + + + org.apache.httpcomponents + httpclient + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + ${project.build.directory}/${project.build.finalName}/WEB-INF/switchyard.xml + + + + maven-war-plugin + + + false + + + deployment.switchyard-demo-multiApp-artifacts.jar + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.war + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.war + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + diff --git a/demos/multiApp/web/src/main/java/org/switchyard/quickstarts/demo/multiapp/web/ItemEntry.java b/quickstarts/demos/multiApp/web/src/main/java/org/switchyard/quickstarts/demo/multiapp/web/ItemEntry.java similarity index 100% rename from demos/multiApp/web/src/main/java/org/switchyard/quickstarts/demo/multiapp/web/ItemEntry.java rename to quickstarts/demos/multiApp/web/src/main/java/org/switchyard/quickstarts/demo/multiapp/web/ItemEntry.java diff --git a/demos/multiApp/web/src/main/resources/META-INF/beans.xml b/quickstarts/demos/multiApp/web/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/multiApp/web/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/multiApp/web/src/main/resources/META-INF/beans.xml diff --git a/demos/multiApp/web/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/multiApp/web/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/multiApp/web/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/multiApp/web/src/main/resources/META-INF/switchyard.xml diff --git a/demos/multiApp/web/src/main/webapp/WEB-INF/.faces-config.xml.jsfdia b/quickstarts/demos/multiApp/web/src/main/webapp/WEB-INF/.faces-config.xml.jsfdia similarity index 100% rename from demos/multiApp/web/src/main/webapp/WEB-INF/.faces-config.xml.jsfdia rename to quickstarts/demos/multiApp/web/src/main/webapp/WEB-INF/.faces-config.xml.jsfdia diff --git a/demos/multiApp/web/src/main/webapp/WEB-INF/beans.xml b/quickstarts/demos/multiApp/web/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from demos/multiApp/web/src/main/webapp/WEB-INF/beans.xml rename to quickstarts/demos/multiApp/web/src/main/webapp/WEB-INF/beans.xml diff --git a/demos/multiApp/web/src/main/webapp/WEB-INF/faces-config.xml b/quickstarts/demos/multiApp/web/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from demos/multiApp/web/src/main/webapp/WEB-INF/faces-config.xml rename to quickstarts/demos/multiApp/web/src/main/webapp/WEB-INF/faces-config.xml diff --git a/demos/multiApp/web/src/main/webapp/home.xhtml b/quickstarts/demos/multiApp/web/src/main/webapp/home.xhtml similarity index 100% rename from demos/multiApp/web/src/main/webapp/home.xhtml rename to quickstarts/demos/multiApp/web/src/main/webapp/home.xhtml diff --git a/demos/multiApp/web/src/main/webapp/index.html b/quickstarts/demos/multiApp/web/src/main/webapp/index.html similarity index 100% rename from demos/multiApp/web/src/main/webapp/index.html rename to quickstarts/demos/multiApp/web/src/main/webapp/index.html diff --git a/demos/multiApp/web/src/test/resources/META-INF/beans.xml b/quickstarts/demos/multiApp/web/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/multiApp/web/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/multiApp/web/src/test/resources/META-INF/beans.xml diff --git a/demos/multiApp/web/src/test/resources/log4j.xml b/quickstarts/demos/multiApp/web/src/test/resources/log4j.xml similarity index 100% rename from demos/multiApp/web/src/test/resources/log4j.xml rename to quickstarts/demos/multiApp/web/src/test/resources/log4j.xml diff --git a/demos/multiApp/web/src/test/resources/xml/order.xml b/quickstarts/demos/multiApp/web/src/test/resources/xml/order.xml similarity index 100% rename from demos/multiApp/web/src/test/resources/xml/order.xml rename to quickstarts/demos/multiApp/web/src/test/resources/xml/order.xml diff --git a/demos/multiApp/web/src/test/resources/xml/orderAck.xml b/quickstarts/demos/multiApp/web/src/test/resources/xml/orderAck.xml similarity index 100% rename from demos/multiApp/web/src/test/resources/xml/orderAck.xml rename to quickstarts/demos/multiApp/web/src/test/resources/xml/orderAck.xml diff --git a/demos/multiApp/web/src/test/resources/xml/soap-request.xml b/quickstarts/demos/multiApp/web/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/multiApp/web/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/multiApp/web/src/test/resources/xml/soap-request.xml diff --git a/demos/multiApp/web/src/test/resources/xml/soap-response.xml b/quickstarts/demos/multiApp/web/src/test/resources/xml/soap-response.xml similarity index 100% rename from demos/multiApp/web/src/test/resources/xml/soap-response.xml rename to quickstarts/demos/multiApp/web/src/test/resources/xml/soap-response.xml diff --git a/demos/orders/README.md b/quickstarts/demos/orders/README.md similarity index 100% rename from demos/orders/README.md rename to quickstarts/demos/orders/README.md diff --git a/demos/orders/orders.jpg b/quickstarts/demos/orders/orders.jpg similarity index 100% rename from demos/orders/orders.jpg rename to quickstarts/demos/orders/orders.jpg diff --git a/quickstarts/demos/orders/pom.xml b/quickstarts/demos/orders/pom.xml new file mode 100644 index 000000000..2027a4203 --- /dev/null +++ b/quickstarts/demos/orders/pom.xml @@ -0,0 +1,242 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-orders + 2.1.0-SNAPSHOT + war + Quickstart Demo : Orders + Quickstart Demo : Orders + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 9999 + 1.6 + 1.6 + 1.3.1 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + provided + + + org.switchyard.components + switchyard-component-bean + provided + + + org.switchyard.components + switchyard-component-soap + provided + + + org.switchyard + switchyard-test + provided + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + javax.enterprise + cdi-api + provided + + + + org.jboss.spec.javax.annotation + jboss-annotations-api_1.1_spec + provided + + + + org.jboss.spec.javax.faces + jboss-jsf-api_2.1_spec + provided + + + junit + junit + test + + + org.apache.httpcomponents + httpclient + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + ${project.build.directory}/${project.build.finalName}/WEB-INF/switchyard.xml + + + + + configure + + + + + + maven-war-plugin + + + false + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.war + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.war + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.demos.orders.OrdersClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/InventoryService.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/InventoryService.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/InventoryService.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/InventoryService.java diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/InventoryServiceBean.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/InventoryServiceBean.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/InventoryServiceBean.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/InventoryServiceBean.java diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Item.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Item.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Item.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Item.java diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/ItemNotFoundException.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/ItemNotFoundException.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/ItemNotFoundException.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/ItemNotFoundException.java diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Order.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Order.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Order.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Order.java diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderAck.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderAck.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderAck.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderAck.java diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderService.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderService.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderService.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderService.java diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderServiceBean.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderServiceBean.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderServiceBean.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/OrderServiceBean.java diff --git a/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Transformers.java b/quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Transformers.java similarity index 100% rename from demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Transformers.java rename to quickstarts/demos/orders/src/main/java/org/switchyard/quickstarts/demos/orders/Transformers.java diff --git a/demos/orders/src/main/resources/META-INF/beans.xml b/quickstarts/demos/orders/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/orders/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/orders/src/main/resources/META-INF/beans.xml diff --git a/demos/orders/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/orders/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/orders/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/orders/src/main/resources/META-INF/switchyard.xml diff --git a/demos/orders/src/main/resources/wsdl/OrderService.wsdl b/quickstarts/demos/orders/src/main/resources/wsdl/OrderService.wsdl similarity index 100% rename from demos/orders/src/main/resources/wsdl/OrderService.wsdl rename to quickstarts/demos/orders/src/main/resources/wsdl/OrderService.wsdl diff --git a/demos/orders/src/main/webapp/WEB-INF/.faces-config.xml.jsfdia b/quickstarts/demos/orders/src/main/webapp/WEB-INF/.faces-config.xml.jsfdia similarity index 100% rename from demos/orders/src/main/webapp/WEB-INF/.faces-config.xml.jsfdia rename to quickstarts/demos/orders/src/main/webapp/WEB-INF/.faces-config.xml.jsfdia diff --git a/demos/orders/src/main/webapp/WEB-INF/faces-config.xml b/quickstarts/demos/orders/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from demos/orders/src/main/webapp/WEB-INF/faces-config.xml rename to quickstarts/demos/orders/src/main/webapp/WEB-INF/faces-config.xml diff --git a/demos/orders/src/main/webapp/css/default.css b/quickstarts/demos/orders/src/main/webapp/css/default.css similarity index 100% rename from demos/orders/src/main/webapp/css/default.css rename to quickstarts/demos/orders/src/main/webapp/css/default.css diff --git a/demos/orders/src/main/webapp/home.xhtml b/quickstarts/demos/orders/src/main/webapp/home.xhtml similarity index 100% rename from demos/orders/src/main/webapp/home.xhtml rename to quickstarts/demos/orders/src/main/webapp/home.xhtml diff --git a/demos/orders/src/main/webapp/img/sw.jpg b/quickstarts/demos/orders/src/main/webapp/img/sw.jpg similarity index 100% rename from demos/orders/src/main/webapp/img/sw.jpg rename to quickstarts/demos/orders/src/main/webapp/img/sw.jpg diff --git a/demos/orders/src/main/webapp/index.html b/quickstarts/demos/orders/src/main/webapp/index.html similarity index 100% rename from demos/orders/src/main/webapp/index.html rename to quickstarts/demos/orders/src/main/webapp/index.html diff --git a/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/InventoryServiceTest.java b/quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/InventoryServiceTest.java similarity index 100% rename from demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/InventoryServiceTest.java rename to quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/InventoryServiceTest.java diff --git a/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/OrderServiceTest.java b/quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/OrderServiceTest.java similarity index 100% rename from demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/OrderServiceTest.java rename to quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/OrderServiceTest.java diff --git a/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/OrdersClient.java b/quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/OrdersClient.java similarity index 100% rename from demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/OrdersClient.java rename to quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/OrdersClient.java diff --git a/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/TypeTransformationTest.java b/quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/TypeTransformationTest.java similarity index 100% rename from demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/TypeTransformationTest.java rename to quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/TypeTransformationTest.java diff --git a/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/WebServiceTest.java b/quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/WebServiceTest.java similarity index 100% rename from demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/WebServiceTest.java rename to quickstarts/demos/orders/src/test/java/org/switchyard/quickstarts/demos/orders/WebServiceTest.java diff --git a/demos/orders/src/test/resources/META-INF/beans.xml b/quickstarts/demos/orders/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/orders/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/orders/src/test/resources/META-INF/beans.xml diff --git a/demos/orders/src/test/resources/log4j.xml b/quickstarts/demos/orders/src/test/resources/log4j.xml similarity index 100% rename from demos/orders/src/test/resources/log4j.xml rename to quickstarts/demos/orders/src/test/resources/log4j.xml diff --git a/demos/orders/src/test/resources/xml/order.xml b/quickstarts/demos/orders/src/test/resources/xml/order.xml similarity index 100% rename from demos/orders/src/test/resources/xml/order.xml rename to quickstarts/demos/orders/src/test/resources/xml/order.xml diff --git a/demos/orders/src/test/resources/xml/orderAck.xml b/quickstarts/demos/orders/src/test/resources/xml/orderAck.xml similarity index 100% rename from demos/orders/src/test/resources/xml/orderAck.xml rename to quickstarts/demos/orders/src/test/resources/xml/orderAck.xml diff --git a/demos/orders/src/test/resources/xml/soap-request.xml b/quickstarts/demos/orders/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/orders/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/orders/src/test/resources/xml/soap-request.xml diff --git a/demos/orders/src/test/resources/xml/soap-response.xml b/quickstarts/demos/orders/src/test/resources/xml/soap-response.xml similarity index 100% rename from demos/orders/src/test/resources/xml/soap-response.xml rename to quickstarts/demos/orders/src/test/resources/xml/soap-response.xml diff --git a/quickstarts/demos/policy-security-basic/Readme.md b/quickstarts/demos/policy-security-basic/Readme.md new file mode 100644 index 000000000..046eec08e --- /dev/null +++ b/quickstarts/demos/policy-security-basic/Readme.md @@ -0,0 +1,121 @@ +Introduction +============ +This quickstart demonstrates how policy can be used to control the security characteristics of a +service invocation. The only service in the application is a Bean service called "WorkService". +SSL is used for "confidentiality", and Basic Authentication is used for "clientAuthentication". + + +Running the quickstart +====================== + +EAP +---------- + +1. Create an application user: + + ${AS}/bin/add-user.sh -a --user kermit --password the-frog-1 --group friend + +2. Start EAP in standalone mode: + + ${AS}/bin/standalone.sh + +3. Build and deploy the quickstart + + mvn install -Pdeploy + +4. Execute the test. (See "Options" section below.) + +5. Check the server console for output from the service. + +6. Undeploy the application + + mvn clean -Pdeploy + +Karaf +----- +Instead of steps 1-3,6 above for EAP... + +1. Create a ${KARAF}/quickstarts/demos/policy-security-basic/ directory, and copy connector.jks into it. + +2. Create a ${KARAF}/etc/org.ops4j.pax.web.cfg file, with the following contents: + +org.osgi.service.http.enabled=true +org.osgi.service.http.port=8181 +org.osgi.service.http.secure.enabled=true +org.osgi.service.http.port.secure=8183 +org.ops4j.pax.web.ssl.keystore=quickstarts/demos/policy-security-basic/connector.jks +org.ops4j.pax.web.ssl.keystore.type=JKS +org.ops4j.pax.web.ssl.password=changeit +org.ops4j.pax.web.ssl.keypassword=changeit +org.ops4j.pax.web.ssl.clientauthwanted=false +org.ops4j.pax.web.ssl.clientauthneeded=false + +3. Add this line to ${KARAF}/etc/users.properties: + + kermit = the-frog-1,_g_:friend + _g_\:friend = group,friend + +4. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} +with the version of SwitchYard that you are using (ex. 2.0.0): + +karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features + +5. Install the feature for the bean-service quickstart : + +karaf@root> features:install switchyard-demo-policy-security-basic + +6. When executing the test (as directed below), add the following system property: -Dorg.switchyard.component.soap.client.port=8183 + + +Wildfly +---------- + + +1. Create an application user: + + ${AS}/bin/add-user.sh -a --user kermit --password the-frog-1 --group friend + +2. Start Wildfly in standalone mode : + + ${AS}/bin/standalone.sh + +3. Build and deploy the demo : + + mvn install -Pdeploy -Pwildfly + +4. Execute the test. (See "Options" section below.) + +5. Check the server console for output from the service. + +6. Undeploy the application + + mvn clean -Pdeploy -Pwildfly + +Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. + + + + + +Options +======= + +When running with no options: + + mvn exec:java + +You will be hitting the http (non-SSL) URL, and see this in your log: + + Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: authorization clientAuthentication confidentiality + +When running with this option: + + mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks + +You will be hitting the https (SSL) URL and providing authentication information, and see this in your log: + + :: WorkService :: Received work command => CMD-1398262304944 (caller principal=kermit, in roles? 'friend'=true 'enemy'=false) + + (Because the WorkService is secured, you will see the not-null principal, and true for the expected security role.) + +You can play with the exec.args and only specify one of "confidentiality" or "clientAuthentication". I bet you can guess what will happen... ;) diff --git a/demos/policy-security-basic/config.cli b/quickstarts/demos/policy-security-basic/config.cli similarity index 100% rename from demos/policy-security-basic/config.cli rename to quickstarts/demos/policy-security-basic/config.cli diff --git a/demos/policy-security-basic/config_wildfly.cli b/quickstarts/demos/policy-security-basic/config_wildfly.cli similarity index 100% rename from demos/policy-security-basic/config_wildfly.cli rename to quickstarts/demos/policy-security-basic/config_wildfly.cli diff --git a/demos/policy-security-basic/connector.jks b/quickstarts/demos/policy-security-basic/connector.jks similarity index 100% rename from demos/policy-security-basic/connector.jks rename to quickstarts/demos/policy-security-basic/connector.jks diff --git a/demos/policy-security-basic/policy-security-basic.jpg b/quickstarts/demos/policy-security-basic/policy-security-basic.jpg similarity index 100% rename from demos/policy-security-basic/policy-security-basic.jpg rename to quickstarts/demos/policy-security-basic/policy-security-basic.jpg diff --git a/quickstarts/demos/policy-security-basic/pom.xml b/quickstarts/demos/policy-security-basic/pom.xml new file mode 100644 index 000000000..24a5914a7 --- /dev/null +++ b/quickstarts/demos/policy-security-basic/pom.xml @@ -0,0 +1,253 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-basic + 2.1.0-SNAPSHOT + bundle + Quickstart Demo : Security Policy : Basic Authentication (+SSL) + Quickstart Demo : Security Policy : Basic Authentication (+SSL) + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.policy.security.basic + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + config.cli + unconfig.cli + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.apache.commons + not-yet-commons-ssl + test + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demo.policy.security.basic.WorkServiceMain + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + config_wildfly.cli + unconfig_wildfly.cli + 9990 + + + + diff --git a/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/Transformers.java b/quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/Transformers.java similarity index 100% rename from demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/Transformers.java rename to quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/Transformers.java diff --git a/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/Work.java b/quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/Work.java similarity index 100% rename from demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/Work.java rename to quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/Work.java diff --git a/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkAck.java b/quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkAck.java similarity index 100% rename from demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkAck.java rename to quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkAck.java diff --git a/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkService.java b/quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkService.java similarity index 100% rename from demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkService.java rename to quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkService.java diff --git a/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkServiceBean.java b/quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkServiceBean.java similarity index 100% rename from demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkServiceBean.java rename to quickstarts/demos/policy-security-basic/src/main/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkServiceBean.java diff --git a/demos/policy-security-basic/src/main/resources/META-INF/WorkService.wsdl b/quickstarts/demos/policy-security-basic/src/main/resources/META-INF/WorkService.wsdl similarity index 100% rename from demos/policy-security-basic/src/main/resources/META-INF/WorkService.wsdl rename to quickstarts/demos/policy-security-basic/src/main/resources/META-INF/WorkService.wsdl diff --git a/demos/policy-security-basic/src/main/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-basic/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-basic/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-basic/src/main/resources/META-INF/beans.xml diff --git a/demos/policy-security-basic/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/policy-security-basic/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/policy-security-basic/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/policy-security-basic/src/main/resources/META-INF/switchyard.xml diff --git a/demos/policy-security-basic/src/main/resources/OSGI-INF/blueprint/jaas.xml b/quickstarts/demos/policy-security-basic/src/main/resources/OSGI-INF/blueprint/jaas.xml similarity index 100% rename from demos/policy-security-basic/src/main/resources/OSGI-INF/blueprint/jaas.xml rename to quickstarts/demos/policy-security-basic/src/main/resources/OSGI-INF/blueprint/jaas.xml diff --git a/demos/policy-security-basic/src/test/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkServiceMain.java b/quickstarts/demos/policy-security-basic/src/test/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkServiceMain.java similarity index 100% rename from demos/policy-security-basic/src/test/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkServiceMain.java rename to quickstarts/demos/policy-security-basic/src/test/java/org/switchyard/quickstarts/demo/policy/security/basic/WorkServiceMain.java diff --git a/demos/policy-security-basic/src/test/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-basic/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-basic/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-basic/src/test/resources/META-INF/beans.xml diff --git a/demos/policy-security-basic/src/test/resources/log4j.xml b/quickstarts/demos/policy-security-basic/src/test/resources/log4j.xml similarity index 100% rename from demos/policy-security-basic/src/test/resources/log4j.xml rename to quickstarts/demos/policy-security-basic/src/test/resources/log4j.xml diff --git a/demos/policy-security-basic/src/test/resources/xml/soap-request.xml b/quickstarts/demos/policy-security-basic/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/policy-security-basic/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/policy-security-basic/src/test/resources/xml/soap-request.xml diff --git a/demos/policy-security-basic/unconfig.cli b/quickstarts/demos/policy-security-basic/unconfig.cli similarity index 100% rename from demos/policy-security-basic/unconfig.cli rename to quickstarts/demos/policy-security-basic/unconfig.cli diff --git a/demos/policy-security-basic/unconfig_wildfly.cli b/quickstarts/demos/policy-security-basic/unconfig_wildfly.cli similarity index 100% rename from demos/policy-security-basic/unconfig_wildfly.cli rename to quickstarts/demos/policy-security-basic/unconfig_wildfly.cli diff --git a/quickstarts/demos/policy-security-cert/Readme.md b/quickstarts/demos/policy-security-cert/Readme.md new file mode 100644 index 000000000..5092d81b9 --- /dev/null +++ b/quickstarts/demos/policy-security-cert/Readme.md @@ -0,0 +1,102 @@ +Introduction +============ +This quickstart demonstrates how policy can be used to control the security characteristics of a +service invocation. The only service in the application is a Bean service called "WorkService". +SSL is used for "confidentiality", and Certificate Authentication is used for "clientAuthentication". + + +Running the quickstart +====================== + +1. Start EAP in standalone mode: + + ${AS}/bin/standalone.sh + +2. Build and deploy the quickstart + + mvn install -Pdeploy + +3. Execute the test. (See "Options" section below.) + +4. Check the server console for output from the service. + +5. Undeploy the application + + mvn clean -Pdeploy + +Karaf +----- +Instead of steps 1,2,5 above for EAP... + +1. Create a ${KARAF}/quickstarts/demos/policy-security-cert/ directory, and copy users.jks, roles.properties, and connector.jks into it. + +2. Create a ${KARAF}/etc/org.ops4j.pax.web.cfg file, with the following contents: + +org.osgi.service.http.enabled=true +org.osgi.service.http.port=8181 +org.osgi.service.http.secure.enabled=true +org.osgi.service.http.port.secure=8183 +org.ops4j.pax.web.ssl.keystore=quickstarts/demos/policy-security-cert/connector.jks +org.ops4j.pax.web.ssl.keystore.type=JKS +org.ops4j.pax.web.ssl.password=changeit +org.ops4j.pax.web.ssl.keypassword=changeit +org.ops4j.pax.web.ssl.clientauthwanted=false +org.ops4j.pax.web.ssl.clientauthneeded=false + +3. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} +with the version of SwitchYard that you are using (ex. 2.0.0): + +karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features + +4. Install the feature for the bean-service quickstart : + +karaf@root> features:install switchyard-demo-policy-security-cert + +5. When executing the test (as directed below in the "Options" section), add the following system property: -Dorg.switchyard.component.soap.client.port=8183 + + +Wildfly +---------- + + +1. Start Wildfly in standalone mode : + + ${AS}/bin/standalone.sh + +2. Build and deploy the demo : + + mvn install -Pdeploy -Pwildfly + +3. Execute the test. (See "Options" section below.) + +4. Check the server console for output from the service. + +5. Undeploy the application + + mvn clean -Pdeploy -Pwildfly + +Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. + + +Options +======= + +When running with no options: + + mvn exec:java + +You will be hitting the http (non-SSL) URL, and see this in your log: + + Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: authorization clientAuthentication confidentiality + +When running with this option: + + mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks + +You will be hitting the https (SSL) URL and providing authentication information, and see this in your log: + + :: WorkService :: Received work command => CMD-1398262622127 (caller principal=UserPrincipal@640268438[name=kermit], in roles? 'friend'=true 'enemy'=false) + + (Because the WorkService is secured, you will see the not-null principal, and true for the expected security role.) + +You can play with the exec.args and only specify one of "confidentiality" or "clientAuthentication". I bet you can guess what will happen... ;) diff --git a/demos/policy-security-cert/config.cli b/quickstarts/demos/policy-security-cert/config.cli similarity index 100% rename from demos/policy-security-cert/config.cli rename to quickstarts/demos/policy-security-cert/config.cli diff --git a/demos/policy-security-cert/config_wildfly.cli b/quickstarts/demos/policy-security-cert/config_wildfly.cli similarity index 100% rename from demos/policy-security-cert/config_wildfly.cli rename to quickstarts/demos/policy-security-cert/config_wildfly.cli diff --git a/demos/policy-security-cert/connector.jks b/quickstarts/demos/policy-security-cert/connector.jks similarity index 100% rename from demos/policy-security-cert/connector.jks rename to quickstarts/demos/policy-security-cert/connector.jks diff --git a/demos/policy-security-cert/policy-security-cert.jpg b/quickstarts/demos/policy-security-cert/policy-security-cert.jpg similarity index 100% rename from demos/policy-security-cert/policy-security-cert.jpg rename to quickstarts/demos/policy-security-cert/policy-security-cert.jpg diff --git a/quickstarts/demos/policy-security-cert/pom.xml b/quickstarts/demos/policy-security-cert/pom.xml new file mode 100644 index 000000000..6ef7b8eae --- /dev/null +++ b/quickstarts/demos/policy-security-cert/pom.xml @@ -0,0 +1,253 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-cert + 2.1.0-SNAPSHOT + bundle + Quickstart Demo : Security Policy : Certificate Authentication (+SSL) + Quickstart Demo : Security Policy : Certificate Authentication (+SSL) + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.policy.security.cert + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + config.cli + unconfig.cli + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.apache.commons + not-yet-commons-ssl + test + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demo.policy.security.cert.WorkServiceMain + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + config_wildfly.cli + unconfig_wildfly.cli + + + + diff --git a/demos/policy-security-cert/roles.properties b/quickstarts/demos/policy-security-cert/roles.properties similarity index 100% rename from demos/policy-security-cert/roles.properties rename to quickstarts/demos/policy-security-cert/roles.properties diff --git a/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/Transformers.java b/quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/Transformers.java similarity index 100% rename from demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/Transformers.java rename to quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/Transformers.java diff --git a/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/Work.java b/quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/Work.java similarity index 100% rename from demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/Work.java rename to quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/Work.java diff --git a/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkAck.java b/quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkAck.java similarity index 100% rename from demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkAck.java rename to quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkAck.java diff --git a/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkService.java b/quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkService.java similarity index 100% rename from demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkService.java rename to quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkService.java diff --git a/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkServiceBean.java b/quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkServiceBean.java similarity index 100% rename from demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkServiceBean.java rename to quickstarts/demos/policy-security-cert/src/main/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkServiceBean.java diff --git a/demos/policy-security-cert/src/main/resources/META-INF/WorkService.wsdl b/quickstarts/demos/policy-security-cert/src/main/resources/META-INF/WorkService.wsdl similarity index 100% rename from demos/policy-security-cert/src/main/resources/META-INF/WorkService.wsdl rename to quickstarts/demos/policy-security-cert/src/main/resources/META-INF/WorkService.wsdl diff --git a/demos/policy-security-cert/src/main/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-cert/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-cert/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-cert/src/main/resources/META-INF/beans.xml diff --git a/demos/policy-security-cert/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/policy-security-cert/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/policy-security-cert/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/policy-security-cert/src/main/resources/META-INF/switchyard.xml diff --git a/demos/policy-security-cert/src/main/resources/OSGI-INF/blueprint/jaas.xml b/quickstarts/demos/policy-security-cert/src/main/resources/OSGI-INF/blueprint/jaas.xml similarity index 100% rename from demos/policy-security-cert/src/main/resources/OSGI-INF/blueprint/jaas.xml rename to quickstarts/demos/policy-security-cert/src/main/resources/OSGI-INF/blueprint/jaas.xml diff --git a/demos/policy-security-cert/src/test/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkServiceMain.java b/quickstarts/demos/policy-security-cert/src/test/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkServiceMain.java similarity index 100% rename from demos/policy-security-cert/src/test/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkServiceMain.java rename to quickstarts/demos/policy-security-cert/src/test/java/org/switchyard/quickstarts/demo/policy/security/cert/WorkServiceMain.java diff --git a/demos/policy-security-cert/src/test/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-cert/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-cert/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-cert/src/test/resources/META-INF/beans.xml diff --git a/demos/policy-security-cert/src/test/resources/log4j.xml b/quickstarts/demos/policy-security-cert/src/test/resources/log4j.xml similarity index 100% rename from demos/policy-security-cert/src/test/resources/log4j.xml rename to quickstarts/demos/policy-security-cert/src/test/resources/log4j.xml diff --git a/demos/policy-security-cert/src/test/resources/xml/BinarySecurityToken.xml b/quickstarts/demos/policy-security-cert/src/test/resources/xml/BinarySecurityToken.xml similarity index 100% rename from demos/policy-security-cert/src/test/resources/xml/BinarySecurityToken.xml rename to quickstarts/demos/policy-security-cert/src/test/resources/xml/BinarySecurityToken.xml diff --git a/demos/policy-security-cert/src/test/resources/xml/soap-request.xml b/quickstarts/demos/policy-security-cert/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/policy-security-cert/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/policy-security-cert/src/test/resources/xml/soap-request.xml diff --git a/demos/policy-security-cert/unconfig.cli b/quickstarts/demos/policy-security-cert/unconfig.cli similarity index 100% rename from demos/policy-security-cert/unconfig.cli rename to quickstarts/demos/policy-security-cert/unconfig.cli diff --git a/demos/policy-security-cert/unconfig_wildfly.cli b/quickstarts/demos/policy-security-cert/unconfig_wildfly.cli similarity index 100% rename from demos/policy-security-cert/unconfig_wildfly.cli rename to quickstarts/demos/policy-security-cert/unconfig_wildfly.cli diff --git a/demos/policy-security-cert/users.jks b/quickstarts/demos/policy-security-cert/users.jks similarity index 100% rename from demos/policy-security-cert/users.jks rename to quickstarts/demos/policy-security-cert/users.jks diff --git a/quickstarts/demos/policy-security-saml/Readme.md b/quickstarts/demos/policy-security-saml/Readme.md new file mode 100644 index 000000000..6ea78f792 --- /dev/null +++ b/quickstarts/demos/policy-security-saml/Readme.md @@ -0,0 +1,76 @@ +Introduction +============ +This quickstart demonstrates how policy can be used to control the security characteristics of a +service invocation. The only service in the application is a Bean service called "WorkService". +SSL is used for "confidentiality", and SAML Assertion is used for "clientAuthentication". + + +Running the quickstart +====================== + +EAP +---------- +1. Start JBoss EAP in standalone mode: + + ${AS}/bin/standalone.sh + +2. Build and deploy the quickstart + + mvn install -Pdeploy + +3. Execute the test. (See "Options" section below.) + +4. Check the server console for output from the service. + +5. Undeploy the application + + mvn clean -Pdeploy + + + +Wildfly +---------- + + +1. Start Wildfly in standalone mode : + + ${AS}/bin/standalone.sh + +2. Build and deploy the demo : + + mvn install -Pdeploy -Pwildfly + +3. Execute the test. (See "Options" section below.) + +4. Check the server console for output from the service. + +5. Undeploy the application + + mvn clean -Pdeploy -Pwildfly + +Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. + + + +Options +======= + +When running with no options: + + mvn exec:java + +You will be hitting the http (non-SSL) URL, and see this in your log: + + Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: clientAuthentication confidentiality + +When running with this option: + + mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks + +You will be hitting the https (SSL) URL and providing authentication information, and see this in your log: + + :: WorkService :: Received work command => CMD-1398967051060 (caller principal=UserPrincipal@1045975928[name=admin]) + + (Because the WorkService is secured, you will see the not-null principal.) + +You can play with the exec.args and only specify one of "confidentiality" or "clientAuthentication". I bet you can guess what will happen... ;) diff --git a/demos/policy-security-saml/config.cli b/quickstarts/demos/policy-security-saml/config.cli similarity index 100% rename from demos/policy-security-saml/config.cli rename to quickstarts/demos/policy-security-saml/config.cli diff --git a/demos/policy-security-saml/config_wildfly.cli b/quickstarts/demos/policy-security-saml/config_wildfly.cli similarity index 100% rename from demos/policy-security-saml/config_wildfly.cli rename to quickstarts/demos/policy-security-saml/config_wildfly.cli diff --git a/demos/policy-security-saml/connector.jks b/quickstarts/demos/policy-security-saml/connector.jks similarity index 100% rename from demos/policy-security-saml/connector.jks rename to quickstarts/demos/policy-security-saml/connector.jks diff --git a/demos/policy-security-saml/picketlink-sts.war b/quickstarts/demos/policy-security-saml/picketlink-sts.war similarity index 100% rename from demos/policy-security-saml/picketlink-sts.war rename to quickstarts/demos/policy-security-saml/picketlink-sts.war diff --git a/demos/policy-security-saml/picketlink-sts/META-INF/jboss-deployment-structure.xml b/quickstarts/demos/policy-security-saml/picketlink-sts/META-INF/jboss-deployment-structure.xml similarity index 100% rename from demos/policy-security-saml/picketlink-sts/META-INF/jboss-deployment-structure.xml rename to quickstarts/demos/policy-security-saml/picketlink-sts/META-INF/jboss-deployment-structure.xml diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/org/picketlink/identity/federation/app/sts/PicketLinkSTService.class b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/org/picketlink/identity/federation/app/sts/PicketLinkSTService.class similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/classes/org/picketlink/identity/federation/app/sts/PicketLinkSTService.class rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/org/picketlink/identity/federation/app/sts/PicketLinkSTService.class diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/picketlink-sts.xml b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/picketlink-sts.xml similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/classes/picketlink-sts.xml rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/picketlink-sts.xml diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/roles.properties b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/roles.properties similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/classes/roles.properties rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/roles.properties diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/sts_keystore.jks b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/sts_keystore.jks similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/classes/sts_keystore.jks rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/sts_keystore.jks diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/users.properties b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/users.properties similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/classes/users.properties rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/classes/users.properties diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/jboss-web.xml b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/jboss-web.xml similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/jboss-web.xml rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/jboss-web.xml diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/jboss-wsse-server.xml b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/jboss-wsse-server.xml similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/jboss-wsse-server.xml rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/jboss-wsse-server.xml diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/web.xml b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/web.xml similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/web.xml rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/web.xml diff --git a/demos/policy-security-saml/picketlink-sts/WEB-INF/wsdl/PicketLinkSTS.wsdl b/quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/wsdl/PicketLinkSTS.wsdl similarity index 100% rename from demos/policy-security-saml/picketlink-sts/WEB-INF/wsdl/PicketLinkSTS.wsdl rename to quickstarts/demos/policy-security-saml/picketlink-sts/WEB-INF/wsdl/PicketLinkSTS.wsdl diff --git a/demos/policy-security-saml/policy-security-saml.jpg b/quickstarts/demos/policy-security-saml/policy-security-saml.jpg similarity index 100% rename from demos/policy-security-saml/policy-security-saml.jpg rename to quickstarts/demos/policy-security-saml/policy-security-saml.jpg diff --git a/quickstarts/demos/policy-security-saml/pom.xml b/quickstarts/demos/policy-security-saml/pom.xml new file mode 100644 index 000000000..5cfbfc250 --- /dev/null +++ b/quickstarts/demos/policy-security-saml/pom.xml @@ -0,0 +1,280 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-saml + 2.1.0-SNAPSHOT + bundle + Quickstart Demo : Security Policy : SAML Assertion (+SSL) + Quickstart Demo : Security Policy : SAML Assertion (+SSL) + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.policy.security.saml + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + config.cli + unconfig.cli + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.wildfly + wildfly-picketlink + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.apache.commons + not-yet-commons-ssl + test + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + deploy-picketlink + install + + deploy-only + + + ../picketlink-sts.war + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy-picketlink + clean + + undeploy + + + + + + + + ../picketlink-sts.war + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demo.policy.security.saml.WorkServiceMain + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + config_wildfly.cli + unconfig_wildfly.cli + + + + diff --git a/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/Transformers.java b/quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/Transformers.java similarity index 100% rename from demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/Transformers.java rename to quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/Transformers.java diff --git a/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/Work.java b/quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/Work.java similarity index 100% rename from demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/Work.java rename to quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/Work.java diff --git a/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkAck.java b/quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkAck.java similarity index 100% rename from demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkAck.java rename to quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkAck.java diff --git a/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkService.java b/quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkService.java similarity index 100% rename from demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkService.java rename to quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkService.java diff --git a/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkServiceBean.java b/quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkServiceBean.java similarity index 100% rename from demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkServiceBean.java rename to quickstarts/demos/policy-security-saml/src/main/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkServiceBean.java diff --git a/demos/policy-security-saml/src/main/resources/META-INF/WorkService.wsdl b/quickstarts/demos/policy-security-saml/src/main/resources/META-INF/WorkService.wsdl similarity index 100% rename from demos/policy-security-saml/src/main/resources/META-INF/WorkService.wsdl rename to quickstarts/demos/policy-security-saml/src/main/resources/META-INF/WorkService.wsdl diff --git a/demos/policy-security-saml/src/main/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-saml/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-saml/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-saml/src/main/resources/META-INF/beans.xml diff --git a/demos/policy-security-saml/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/policy-security-saml/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/policy-security-saml/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/policy-security-saml/src/main/resources/META-INF/switchyard.xml diff --git a/demos/policy-security-saml/src/main/resources/OSGI-INF/blueprint/jaas.xml b/quickstarts/demos/policy-security-saml/src/main/resources/OSGI-INF/blueprint/jaas.xml similarity index 100% rename from demos/policy-security-saml/src/main/resources/OSGI-INF/blueprint/jaas.xml rename to quickstarts/demos/policy-security-saml/src/main/resources/OSGI-INF/blueprint/jaas.xml diff --git a/demos/policy-security-saml/src/test/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkServiceMain.java b/quickstarts/demos/policy-security-saml/src/test/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkServiceMain.java similarity index 100% rename from demos/policy-security-saml/src/test/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkServiceMain.java rename to quickstarts/demos/policy-security-saml/src/test/java/org/switchyard/quickstarts/demo/policy/security/saml/WorkServiceMain.java diff --git a/demos/policy-security-saml/src/test/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-saml/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-saml/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-saml/src/test/resources/META-INF/beans.xml diff --git a/demos/policy-security-saml/src/test/resources/log4j.xml b/quickstarts/demos/policy-security-saml/src/test/resources/log4j.xml similarity index 100% rename from demos/policy-security-saml/src/test/resources/log4j.xml rename to quickstarts/demos/policy-security-saml/src/test/resources/log4j.xml diff --git a/demos/policy-security-saml/src/test/resources/xml/soap-request.xml b/quickstarts/demos/policy-security-saml/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/policy-security-saml/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/policy-security-saml/src/test/resources/xml/soap-request.xml diff --git a/demos/policy-security-saml/sts-client.properties b/quickstarts/demos/policy-security-saml/sts-client.properties similarity index 100% rename from demos/policy-security-saml/sts-client.properties rename to quickstarts/demos/policy-security-saml/sts-client.properties diff --git a/demos/policy-security-saml/unconfig.cli b/quickstarts/demos/policy-security-saml/unconfig.cli similarity index 100% rename from demos/policy-security-saml/unconfig.cli rename to quickstarts/demos/policy-security-saml/unconfig.cli diff --git a/demos/policy-security-saml/unconfig_wildfly.cli b/quickstarts/demos/policy-security-saml/unconfig_wildfly.cli similarity index 100% rename from demos/policy-security-saml/unconfig_wildfly.cli rename to quickstarts/demos/policy-security-saml/unconfig_wildfly.cli diff --git a/quickstarts/demos/policy-security-wss-signencrypt/Readme.md b/quickstarts/demos/policy-security-wss-signencrypt/Readme.md new file mode 100644 index 000000000..8bc7046e2 --- /dev/null +++ b/quickstarts/demos/policy-security-wss-signencrypt/Readme.md @@ -0,0 +1,93 @@ +Introduction +============ +This quickstart demonstrates how policy can be used to control the security characteristics of a +service invocation. The only service in the application is a Bean service called "WorkService". +SSL and/or WS-Security encryption can be used for "confidentiality", and WS-Security is used to verify the Signature and Encryption +of the SOAP message. + + +Running the quickstart +====================== + + +EAP +---------- + +1. Start JBoss EAP in standalone mode: + + ${AS}/bin/standalone.sh + +2. Build and deploy the quickstart + + mvn install -Pdeploy + +3. Execute the test. (See "Options" section below.) + +4. Check the server console for output from the service. + +5. Undeploy the application + + mvn clean -Pdeploy + + +Wildfly +---------- + + +1. Start Wildfly in standalone mode : + + ${AS}/bin/standalone.sh + +2. Build and deploy the demo : + + mvn install -Pdeploy -Pwildfly + +3. Execute the test. (See "Options" section below.) + +4. Check the server console for output from the service. + +5. Undeploy the application + + mvn clean -Pdeploy -Pwildfly + +Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. + + + +Options +======= + +When running with no options: + + mvn exec:java + +You will be hitting the http (non-SSL) URL while NOT providing signed and encrypted information, and see this in your log: + +``` +[org.apache.cxf.phase.PhaseInterceptorChain] (http-/127.0.0.1:8080-1) Interceptor for +{urn:switchyard-quickstart-demo:policy-security-wss-signencrypt:0.1.0}WorkService#{urn:switchyard-quickstart-demo:policy-security-wss-signencrypt:0.1.0}doWork has thrown +exception, unwinding now: org.apache.cxf.ws.policy.PolicyException: These policy alternatives can not be satisfied: +{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}X509Token: The received token does not match the token inclusion requirement +{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}SignedParts: {http://schemas.xmlsoap.org/soap/envelope/}Body not SIGNED +{http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702}EncryptedParts: {http://schemas.xmlsoap.org/soap/envelope/}Body not ENCRYPTED +``` + +When running with this option: + + mvn exec:java -Dexec.args="confidentiality signencrypt" -Djavax.net.ssl.trustStore=connector.jks + +You will be hitting the https (SSL) URL while providing signed and encrypted information, and see this in your log: + + :: WorkService :: Received work command => CMD-86 + +When running with this option: + + mvn exec:java -Dexec.args="signencrypt" + +You will be hitting the http (non-SSL) URL while providing signed and encrypted information, and see this in your log: + + :: WorkService :: Received work command => CMD-86 + +Wait - why did this work? Even though SSL was not used, the content of the message is encrypted, thus the confidentiality policy is still being fulfilled. + +Success! diff --git a/demos/policy-security-wss-signencrypt/config.cli b/quickstarts/demos/policy-security-wss-signencrypt/config.cli similarity index 100% rename from demos/policy-security-wss-signencrypt/config.cli rename to quickstarts/demos/policy-security-wss-signencrypt/config.cli diff --git a/demos/policy-security-wss-signencrypt/config_wildfly.cli b/quickstarts/demos/policy-security-wss-signencrypt/config_wildfly.cli similarity index 100% rename from demos/policy-security-wss-signencrypt/config_wildfly.cli rename to quickstarts/demos/policy-security-wss-signencrypt/config_wildfly.cli diff --git a/demos/policy-security-wss-signencrypt/connector.jks b/quickstarts/demos/policy-security-wss-signencrypt/connector.jks similarity index 100% rename from demos/policy-security-wss-signencrypt/connector.jks rename to quickstarts/demos/policy-security-wss-signencrypt/connector.jks diff --git a/quickstarts/demos/policy-security-wss-signencrypt/pom.xml b/quickstarts/demos/policy-security-wss-signencrypt/pom.xml new file mode 100644 index 000000000..e3c1eb9be --- /dev/null +++ b/quickstarts/demos/policy-security-wss-signencrypt/pom.xml @@ -0,0 +1,258 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-wss-signencrypt + 2.1.0-SNAPSHOT + bundle + Quickstart Demo : Security Policy : WSS Signature+Encryption (+SSL) + Quickstart Demo : Security Policy : WSS Signature+Encryption (+SSL) + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.policy.security.wss.signencrypt + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + config.cli + unconfig.cli + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.apache.commons + not-yet-commons-ssl + test + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.apache.ws.security + wss4j + provided + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demo.policy.security.wss.signencrypt.WorkServiceMain + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + config_wildfly.cli + unconfig_wildfly.cli + + + + diff --git a/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/Transformers.java b/quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/Transformers.java similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/Transformers.java rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/Transformers.java diff --git a/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/Work.java b/quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/Work.java similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/Work.java rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/Work.java diff --git a/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkAck.java b/quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkAck.java similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkAck.java rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkAck.java diff --git a/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkService.java b/quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkService.java similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkService.java rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkService.java diff --git a/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceBean.java b/quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceBean.java similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceBean.java rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceBean.java diff --git a/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceCallbackHandler.java b/quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceCallbackHandler.java similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceCallbackHandler.java rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceCallbackHandler.java diff --git a/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/WorkService.wsdl b/quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/WorkService.wsdl similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/resources/META-INF/WorkService.wsdl rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/WorkService.wsdl diff --git a/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/beans.xml diff --git a/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/bob.jks b/quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/bob.jks similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/resources/META-INF/bob.jks rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/bob.jks diff --git a/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/bob.properties b/quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/bob.properties similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/resources/META-INF/bob.properties rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/bob.properties diff --git a/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/jaxws-endpoint-config.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/jaxws-endpoint-config.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/resources/META-INF/jaxws-endpoint-config.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/jaxws-endpoint-config.xml diff --git a/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/jboss-webservices.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/jboss-webservices.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/resources/META-INF/jboss-webservices.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/jboss-webservices.xml diff --git a/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/META-INF/switchyard.xml diff --git a/demos/policy-security-wss-signencrypt/src/main/resources/OSGI-INF/blueprint/jaas.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/OSGI-INF/blueprint/jaas.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/main/resources/OSGI-INF/blueprint/jaas.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/main/resources/OSGI-INF/blueprint/jaas.xml diff --git a/demos/policy-security-wss-signencrypt/src/test/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceMain.java b/quickstarts/demos/policy-security-wss-signencrypt/src/test/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceMain.java similarity index 100% rename from demos/policy-security-wss-signencrypt/src/test/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceMain.java rename to quickstarts/demos/policy-security-wss-signencrypt/src/test/java/org/switchyard/quickstarts/demo/policy/security/wss/signencrypt/WorkServiceMain.java diff --git a/demos/policy-security-wss-signencrypt/src/test/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/test/resources/META-INF/beans.xml diff --git a/demos/policy-security-wss-signencrypt/src/test/resources/log4j.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/test/resources/log4j.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/test/resources/log4j.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/test/resources/log4j.xml diff --git a/demos/policy-security-wss-signencrypt/src/test/resources/xml/insecure-request.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/test/resources/xml/insecure-request.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/test/resources/xml/insecure-request.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/test/resources/xml/insecure-request.xml diff --git a/demos/policy-security-wss-signencrypt/src/test/resources/xml/secure-request.xml b/quickstarts/demos/policy-security-wss-signencrypt/src/test/resources/xml/secure-request.xml similarity index 100% rename from demos/policy-security-wss-signencrypt/src/test/resources/xml/secure-request.xml rename to quickstarts/demos/policy-security-wss-signencrypt/src/test/resources/xml/secure-request.xml diff --git a/demos/policy-security-wss-signencrypt/unconfig.cli b/quickstarts/demos/policy-security-wss-signencrypt/unconfig.cli similarity index 100% rename from demos/policy-security-wss-signencrypt/unconfig.cli rename to quickstarts/demos/policy-security-wss-signencrypt/unconfig.cli diff --git a/demos/policy-security-wss-signencrypt/unconfig_wildfly.cli b/quickstarts/demos/policy-security-wss-signencrypt/unconfig_wildfly.cli similarity index 100% rename from demos/policy-security-wss-signencrypt/unconfig_wildfly.cli rename to quickstarts/demos/policy-security-wss-signencrypt/unconfig_wildfly.cli diff --git a/quickstarts/demos/policy-security-wss-username/Readme.md b/quickstarts/demos/policy-security-wss-username/Readme.md new file mode 100644 index 000000000..445422f8e --- /dev/null +++ b/quickstarts/demos/policy-security-wss-username/Readme.md @@ -0,0 +1,91 @@ +Introduction +============ +This quickstart demonstrates how policy can be used to control the security characteristics of a +service invocation. The only service in the application is a Bean service called "WorkService". +SSL is used for "confidentiality", and WS-Security UsernameToken is used for "clientAuthentication". + + +Running the quickstart +====================== + + +EAP +---------- + +1. Create an application user: + + ${AS}/bin/add-user.sh -a --user kermit --password the-frog-1 --group friend + +2. Start JBoss EAP in standalone mode: + + ${AS}/bin/standalone.sh + +3. Build and deploy the quickstart + + mvn install -Pdeploy + +4. Execute the test. (See "Options" section below.) + +5. Check the server console for output from the service. + +6. Undeploy the application + + mvn clean -Pdeploy + + +Wildfly +---------- + + +1. Create an application user: + + ${AS}/bin/add-user.sh -a --user kermit --password the-frog-1 --group friend + +2. Start Wildfly in standalone mode : + + ${AS}/bin/standalone.sh + +3. Build and deploy the demo : + + mvn install -Pdeploy -Pwildfly + +4. Execute the test. (See "Options" section below.) + +5. Check the server console for output from the service. + +6. Undeploy the application + + mvn clean -Pdeploy -Pwildfly + +Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. + +Options +======= + +When running with no options: + + mvn exec:java + +You will be hitting the http (non-SSL) URL without providing authentication information, and see this in your log: + + Caused by: org.apache.ws.security.WSSecurityException: Failed Authentication : Subject has not been created + +When running with this option: + + mvn exec:java -Dexec.args="clientAuthentication" + +You will be hitting the http (non-SSL) URL while providing authentication information, and see this in your log: + + Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: confidentiality + +When running with this option: + + mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks + +You will be hitting the https (SSL) URL while providing authentication information, and see this in your log: + + :: WorkService :: Received work command => CMD-1398262803294 (caller principal=kermit, in roles? 'friend'=true 'enemy'=false) + + (Because the WorkService is secured, you will see the not-null principal, and true for the expected security role.) + +Success! diff --git a/demos/policy-security-wss-username/config.cli b/quickstarts/demos/policy-security-wss-username/config.cli similarity index 100% rename from demos/policy-security-wss-username/config.cli rename to quickstarts/demos/policy-security-wss-username/config.cli diff --git a/demos/policy-security-wss-username/config_wildfly.cli b/quickstarts/demos/policy-security-wss-username/config_wildfly.cli similarity index 100% rename from demos/policy-security-wss-username/config_wildfly.cli rename to quickstarts/demos/policy-security-wss-username/config_wildfly.cli diff --git a/demos/policy-security-wss-username/connector.jks b/quickstarts/demos/policy-security-wss-username/connector.jks similarity index 100% rename from demos/policy-security-wss-username/connector.jks rename to quickstarts/demos/policy-security-wss-username/connector.jks diff --git a/quickstarts/demos/policy-security-wss-username/pom.xml b/quickstarts/demos/policy-security-wss-username/pom.xml new file mode 100644 index 000000000..4d1d850eb --- /dev/null +++ b/quickstarts/demos/policy-security-wss-username/pom.xml @@ -0,0 +1,232 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-wss-username + 2.1.0-SNAPSHOT + bundle + Quickstart Demo : Security Policy : WSS Username (+SSL) + Quickstart Demo : Security Policy : WSS Username (+SSL) + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.policy.security.wss.username + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.apache.karaf.jaas.config,org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + config.cli + unconfig.cli + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.apache.commons + not-yet-commons-ssl + test + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demo.policy.security.wss.username.WorkServiceMain + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + config_wildfly.cli + unconfig_wildfly.cli + + + + diff --git a/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/Transformers.java b/quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/Transformers.java similarity index 100% rename from demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/Transformers.java rename to quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/Transformers.java diff --git a/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/Work.java b/quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/Work.java similarity index 100% rename from demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/Work.java rename to quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/Work.java diff --git a/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkAck.java b/quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkAck.java similarity index 100% rename from demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkAck.java rename to quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkAck.java diff --git a/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkService.java b/quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkService.java similarity index 100% rename from demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkService.java rename to quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkService.java diff --git a/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkServiceBean.java b/quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkServiceBean.java similarity index 100% rename from demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkServiceBean.java rename to quickstarts/demos/policy-security-wss-username/src/main/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkServiceBean.java diff --git a/demos/policy-security-wss-username/src/main/resources/META-INF/WorkService.wsdl b/quickstarts/demos/policy-security-wss-username/src/main/resources/META-INF/WorkService.wsdl similarity index 100% rename from demos/policy-security-wss-username/src/main/resources/META-INF/WorkService.wsdl rename to quickstarts/demos/policy-security-wss-username/src/main/resources/META-INF/WorkService.wsdl diff --git a/demos/policy-security-wss-username/src/main/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-wss-username/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-wss-username/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-wss-username/src/main/resources/META-INF/beans.xml diff --git a/demos/policy-security-wss-username/src/main/resources/META-INF/jaxws-endpoint-config.xml b/quickstarts/demos/policy-security-wss-username/src/main/resources/META-INF/jaxws-endpoint-config.xml similarity index 100% rename from demos/policy-security-wss-username/src/main/resources/META-INF/jaxws-endpoint-config.xml rename to quickstarts/demos/policy-security-wss-username/src/main/resources/META-INF/jaxws-endpoint-config.xml diff --git a/demos/policy-security-wss-username/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/policy-security-wss-username/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/policy-security-wss-username/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/policy-security-wss-username/src/main/resources/META-INF/switchyard.xml diff --git a/demos/policy-security-wss-username/src/main/resources/OSGI-INF/blueprint/jaas.xml b/quickstarts/demos/policy-security-wss-username/src/main/resources/OSGI-INF/blueprint/jaas.xml similarity index 100% rename from demos/policy-security-wss-username/src/main/resources/OSGI-INF/blueprint/jaas.xml rename to quickstarts/demos/policy-security-wss-username/src/main/resources/OSGI-INF/blueprint/jaas.xml diff --git a/demos/policy-security-wss-username/src/main/resources/WEB-INF/jboss-web.xml b/quickstarts/demos/policy-security-wss-username/src/main/resources/WEB-INF/jboss-web.xml similarity index 100% rename from demos/policy-security-wss-username/src/main/resources/WEB-INF/jboss-web.xml rename to quickstarts/demos/policy-security-wss-username/src/main/resources/WEB-INF/jboss-web.xml diff --git a/demos/policy-security-wss-username/src/test/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkServiceMain.java b/quickstarts/demos/policy-security-wss-username/src/test/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkServiceMain.java similarity index 100% rename from demos/policy-security-wss-username/src/test/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkServiceMain.java rename to quickstarts/demos/policy-security-wss-username/src/test/java/org/switchyard/quickstarts/demo/policy/security/wss/username/WorkServiceMain.java diff --git a/demos/policy-security-wss-username/src/test/resources/META-INF/beans.xml b/quickstarts/demos/policy-security-wss-username/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-security-wss-username/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/policy-security-wss-username/src/test/resources/META-INF/beans.xml diff --git a/demos/policy-security-wss-username/src/test/resources/log4j.xml b/quickstarts/demos/policy-security-wss-username/src/test/resources/log4j.xml similarity index 100% rename from demos/policy-security-wss-username/src/test/resources/log4j.xml rename to quickstarts/demos/policy-security-wss-username/src/test/resources/log4j.xml diff --git a/demos/policy-security-wss-username/src/test/resources/xml/soap-request.xml b/quickstarts/demos/policy-security-wss-username/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/policy-security-wss-username/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/policy-security-wss-username/src/test/resources/xml/soap-request.xml diff --git a/demos/policy-security-wss-username/unconfig.cli b/quickstarts/demos/policy-security-wss-username/unconfig.cli similarity index 100% rename from demos/policy-security-wss-username/unconfig.cli rename to quickstarts/demos/policy-security-wss-username/unconfig.cli diff --git a/demos/policy-security-wss-username/unconfig_wildfly.cli b/quickstarts/demos/policy-security-wss-username/unconfig_wildfly.cli similarity index 100% rename from demos/policy-security-wss-username/unconfig_wildfly.cli rename to quickstarts/demos/policy-security-wss-username/unconfig_wildfly.cli diff --git a/quickstarts/demos/policy-transaction/Readme.md b/quickstarts/demos/policy-transaction/Readme.md new file mode 100644 index 000000000..1b347f98a --- /dev/null +++ b/quickstarts/demos/policy-transaction/Readme.md @@ -0,0 +1,209 @@ +Introduction +============ +This quickstart demonstrates how policy can be used to control the transactional characteristics +of a service invocation. This application contains 4 Bean services, called "WorkService", +"TaskAService", "TaskBService" and "TaskCService. The WorkService accepts commands and dispatch +to other 3 services. +TaskAService expects the global transaction to be propagated, and accepts the "rollback.A" command +to set rollback only flag on that global transaction. +TaskBService requires local transaction, so it suspends the propagated transaction and create new +one. It accepts the "rollback.B" command to set rollback only flang on its local transaction. +TaskCService requires no managed transaction, so it suspends the propagated transaction and run +without managed transaction - i.e. this service never has a transaction to rollback, although it +accepts "rollback.C" command. It simply prints the message saying no transaction when it gets that +command. + +![Policy Transaction Quickstart](https://github.com/jboss-switchyard/quickstarts/raw/master/demos/policy-transaction/policy-transaction.jpg) + + +Running the quickstart +====================== + +EAP +---------- + +1. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy + +4. Execute HornetQClient + + mvn exec:java + +5. Check the server console for output from the service. With the default + configuration of the quickstart, you should see the output below in the + AS server.log. + +6. Undeploy the application + + mvn clean -Pdeploy + + +Wildfly +---------- +1. Start Wildfly in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy,wildfly + +4. Execute HornetQClient + + mvn exec:java -Pwildfly + +5. Check the server console for output from the service. With the default + configuration of the quickstart, you should see the output below in the + AS server.log. + +6. Undeploy the application + + mvn clean -Pdeploy,wildfly + + +Karaf +---------- +1. Start the Karaf server : + + ${KARAF_HOME}/bin/karaf + +2. Add the features URL for the respective version of SwitchYard. Replace {SWITCHYARD-VERSION} +with the version of SwitchYard that you are using (ex. 2.0.0): + +karaf@root> features:addurl mvn:org.switchyard.karaf/switchyard/{SWITCHYARD-VERSION}/xml/features + +3. Install the feature for the policy-transaction demo : + +karaf@root> features:install switchyard-demo-policy-transaction + +4. Execute JMSClient + + mvn exec:java -Dexec.args="activemq" + +5. Check the server console for output from the service. With the default + configuration of the quickstart, you should see the output below in the + karaf console. + +6. Undeploy the demo: + +karaf@root> features:uninstall switchyard-demo-policy-transaction + + +CONSOLE +---------- +``` +:: WorkService :: Received command => rollback.A +:: TaskAService :: Received command => rollback.A +:: TaskAService :: Marked transaction to rollback! +:: TaskBService :: Received command => rollback.A +:: TaskCService :: Received command => rollback.A +:: TaskCService :: No active transaction +:: WorkService :: transaction is marked as rollback only +:: WorkService :: Received command => rollback.A +:: TaskAService :: Received command => rollback.A +:: TaskAService :: Marked transaction to rollback! +:: TaskBService :: Received command => rollback.A +:: TaskCService :: Received command => rollback.A +:: TaskCService :: No active transaction +:: WorkService :: transaction is marked as rollback only +:: WorkService :: Received command => rollback.A +:: TaskAService :: Received command => rollback.A +:: TaskAService :: Marked transaction to rollback! +:: TaskBService :: Received command => rollback.A +:: TaskCService :: Received command => rollback.A +:: TaskCService :: No active transaction +:: WorkService :: transaction is marked as rollback only +:: WorkService :: Received command => rollback.A +:: TaskAService :: Received command => rollback.A +:: TaskAService :: Rollbacks completed - will be committed +:: TaskBService :: Received command => rollback.A +:: TaskCService :: Received command => rollback.A +:: TaskCService :: No active transaction +:: WorkService :: transaction will be committed +``` + +Scenarios +========= +You can test any of these transaction policy scenarios using this quickstart: + +1) Global transaction propagated to the bean service. This is the default + configuration of the quickstart and requires the TaskAServiceBean to be + annotated with @Requires(transaction=TransactionPolicy.PROPAGATES_TRANSACTION) + and messages to be sent to the policyQSTransacted queue. + +2) Policy violation - transaction required to be propagated, but no transaction + provided by the gateway. To exercise this scenario, send a message to the + policyQSNonTransacted queue with TransactionPolicy.PROPAGATES_TRANSACTION + on the bean service. + +3) Suspend incoming transaction. Change the WorkServiceBean transaction + annotation type to TransactionPolicy.SUSPENDS_TRANSACTION and send a + message to the policyQSTransacted queue with the command "rollback.A". Check + the output and note that the rollback does not impact the transaction used + to receive the JMS message. + +4) A variety of Transaction implementation policy. Each of TaskAService, + TaskBService and TaskCService has different implementation policy. + You can see those behavior with passing combination of the "rollback.A", + "rollback.B" and "rollback.C". TaskAService accepts "rollback.A" and + set rollback only flag on global transaction, so the receiving from JMS + queue will be retried. TaskBService accepts "rollback.B" and set rollback + only flag on local transaction, but it doesn't impact the transaction used + to receive the JMS message. TaskCService accepts "rollback.C", but it doesn't + have any transaction to rollback, just print a message. + + +Options +======= +The maven exec goal in this quickstart accepts the following options: + + mvn exec:java -D exec.args="[command] [queueName]" + +Running "mvn exec:java" with no options is equivalent to: + + mvn exec:java -Dexec.args="rollback policyQSTransacted" + +If the value for 'command' contains the string "rollback", then the bean service +will attempt to rollback an existing transaction. + +The value for 'queueName' should be "policyQSTransacted" or +"policyQSNonTransacted". + +Notes +======= + +o Due to an issue with shutdown processing, server shutdown may take + more than 2 minutes when this quickstart is deployed. To avoid this + problem, undeploy the application before shutting down the server. + +Running a functional test +========================= + +Since this quickstart requires Java EE environment, the functional test +"JmsBindingTest" does not run by default. You need to execute it manually +by following steps. + +1. Build the quickstart: + + mvn clean package + +2. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +3. Execute the test: + + mvn test -DskipTests=false diff --git a/demos/policy-transaction/config.cli b/quickstarts/demos/policy-transaction/config.cli similarity index 100% rename from demos/policy-transaction/config.cli rename to quickstarts/demos/policy-transaction/config.cli diff --git a/demos/policy-transaction/policy-transaction.jpg b/quickstarts/demos/policy-transaction/policy-transaction.jpg similarity index 100% rename from demos/policy-transaction/policy-transaction.jpg rename to quickstarts/demos/policy-transaction/policy-transaction.jpg diff --git a/quickstarts/demos/policy-transaction/pom.xml b/quickstarts/demos/policy-transaction/pom.xml new file mode 100644 index 000000000..7a6364786 --- /dev/null +++ b/quickstarts/demos/policy-transaction/pom.xml @@ -0,0 +1,370 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-policy-transaction + 2.1.0-SNAPSHOT + bundle + Quickstart Demo : Transaction Policy + Quickstart Demo : Transaction Policy + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.demo.policy.transaction + true + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + 2.4.1.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-camel-jms + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + com.h2database + h2 + test + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + org.switchyard + switchyard-test + test + + + org.switchyard.quickstarts + switchyard-quickstart-testutil + test + + + org.jboss.as + jboss-as-arquillian-container-remote + test + + + org.jboss.as + jboss-as-cli + test + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + org.mockito + mockito-all + test + + + org.hamcrest + hamcrest-core + test + + + org.apache.activemq + activemq-client + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + META-INF/persistence.xml + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demo.policy.transaction.JMSClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${skipTests} + + config.cli + unconfig.cli + guest + guestp.1 + ${project.build.directory}/${project.build.finalName}.jar + + + + + + + + deploy + + false + + + + wildfly + + 9990 + true + 8080 + + + + org.hornetq + hornetq-core-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-commons + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-journal + ${version.wildfly.hornetq} + test + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + hornetqmixin.port + 8080 + + + hornetqmixin.http.upgrade.enabled + true + + + + + + + + + diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/StoreService.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/StoreService.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/StoreService.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/StoreService.java diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskAService.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskAService.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskAService.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskAService.java diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskAServiceBean.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskAServiceBean.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskAServiceBean.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskAServiceBean.java diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskBService.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskBService.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskBService.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskBService.java diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskBServiceBean.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskBServiceBean.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskBServiceBean.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskBServiceBean.java diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskCService.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskCService.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskCService.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskCService.java diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskCServiceBean.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskCServiceBean.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskCServiceBean.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/TaskCServiceBean.java diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/WorkService.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/WorkService.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/WorkService.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/WorkService.java diff --git a/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/WorkServiceBean.java b/quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/WorkServiceBean.java similarity index 100% rename from demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/WorkServiceBean.java rename to quickstarts/demos/policy-transaction/src/main/java/org/switchyard/quickstarts/demo/policy/transaction/WorkServiceBean.java diff --git a/demos/policy-transaction/src/main/resources/META-INF/beans.xml b/quickstarts/demos/policy-transaction/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-transaction/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/policy-transaction/src/main/resources/META-INF/beans.xml diff --git a/demos/policy-transaction/src/main/resources/META-INF/forge.xml b/quickstarts/demos/policy-transaction/src/main/resources/META-INF/forge.xml similarity index 100% rename from demos/policy-transaction/src/main/resources/META-INF/forge.xml rename to quickstarts/demos/policy-transaction/src/main/resources/META-INF/forge.xml diff --git a/demos/policy-transaction/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/policy-transaction/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/policy-transaction/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/policy-transaction/src/main/resources/META-INF/switchyard.xml diff --git a/demos/policy-transaction/src/main/resources/OSGI-INF/blueprint/activemq-xa.xml b/quickstarts/demos/policy-transaction/src/main/resources/OSGI-INF/blueprint/activemq-xa.xml similarity index 100% rename from demos/policy-transaction/src/main/resources/OSGI-INF/blueprint/activemq-xa.xml rename to quickstarts/demos/policy-transaction/src/main/resources/OSGI-INF/blueprint/activemq-xa.xml diff --git a/demos/policy-transaction/src/main/resources/test.txt b/quickstarts/demos/policy-transaction/src/main/resources/test.txt similarity index 100% rename from demos/policy-transaction/src/main/resources/test.txt rename to quickstarts/demos/policy-transaction/src/main/resources/test.txt diff --git a/demos/policy-transaction/src/test/java/org/switchyard/quickstarts/demo/policy/transaction/JMSClient.java b/quickstarts/demos/policy-transaction/src/test/java/org/switchyard/quickstarts/demo/policy/transaction/JMSClient.java similarity index 100% rename from demos/policy-transaction/src/test/java/org/switchyard/quickstarts/demo/policy/transaction/JMSClient.java rename to quickstarts/demos/policy-transaction/src/test/java/org/switchyard/quickstarts/demo/policy/transaction/JMSClient.java diff --git a/demos/policy-transaction/src/test/java/org/switchyard/quickstarts/demo/policy/transaction/JmsBindingTest.java b/quickstarts/demos/policy-transaction/src/test/java/org/switchyard/quickstarts/demo/policy/transaction/JmsBindingTest.java similarity index 100% rename from demos/policy-transaction/src/test/java/org/switchyard/quickstarts/demo/policy/transaction/JmsBindingTest.java rename to quickstarts/demos/policy-transaction/src/test/java/org/switchyard/quickstarts/demo/policy/transaction/JmsBindingTest.java diff --git a/demos/policy-transaction/src/test/resources/META-INF/beans.xml b/quickstarts/demos/policy-transaction/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/policy-transaction/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/policy-transaction/src/test/resources/META-INF/beans.xml diff --git a/demos/policy-transaction/src/test/resources/arquillian.xml b/quickstarts/demos/policy-transaction/src/test/resources/arquillian.xml similarity index 100% rename from demos/policy-transaction/src/test/resources/arquillian.xml rename to quickstarts/demos/policy-transaction/src/test/resources/arquillian.xml diff --git a/demos/policy-transaction/src/test/resources/log4j.xml b/quickstarts/demos/policy-transaction/src/test/resources/log4j.xml similarity index 100% rename from demos/policy-transaction/src/test/resources/log4j.xml rename to quickstarts/demos/policy-transaction/src/test/resources/log4j.xml diff --git a/demos/policy-transaction/unconfig.cli b/quickstarts/demos/policy-transaction/unconfig.cli similarity index 100% rename from demos/policy-transaction/unconfig.cli rename to quickstarts/demos/policy-transaction/unconfig.cli diff --git a/quickstarts/demos/security-propagation/Readme.md b/quickstarts/demos/security-propagation/Readme.md new file mode 100644 index 000000000..6024ea44b --- /dev/null +++ b/quickstarts/demos/security-propagation/Readme.md @@ -0,0 +1,111 @@ +Introduction +============ +This quickstart builds on the policy-security-basic quickstart. There is still a Bean service +called "WorkService" which is protected by security policy (SSL is used for "confidentiality", +and Basic Authentication is used for "clientAuthentication"). However this quickstart differs +in that it calls another Bean service called "BackEndService" which is also protected by +security policy, but there is no need for re-authentication, since the current security +context is propagated from one service to the next. Furthermore, an EJB which itself is +protected via annotations is also called, and the security context is propagated there too. + + +Running the quickstart +====================== + +EAP +---------- + +1. Create an application user: + + ${AS}/bin/add-user.sh -a --user kermit --password the-frog-1 --group friend + +2. Start JBoss AS in standalone mode: + + ${AS}/bin/standalone.sh + +3. Build and deploy the ejb, then the basic application + + cd ejb; mvn install -Pdeploy + cd ../basic; mvn install -Pdeploy + +4. Execute the test. (See "Options" section below.) + +5. Check the server console for output from the service. + +6. Undeploy the application, then the ejb + + mvn clean -Pdeploy + cd ../ejb; mvn clean -Pdeploy + + +Wildfly +---------- + + +1. Create an application user: + + ${AS}/bin/add-user.sh -a --user kermit --password the-frog-1 --group friend + +2. Edit the standalone.xml placed on ${WILDFLY_HOME}/standalone/configuration + + Remove the default-security-domain tag inside of the ejb3 domain + + + + + + + ... +- + + + + +3. Start Wildfly in standalone mode : + + ${AS}/bin/standalone.sh + +4. Build and deploy the demo : + + cd ejb; mvn install -Pdeploy -Pwildfly + cd ../basic; mvn install -Pdeploy -Pwildfly + +5. Execute the test. (See "Options" section below.) + +6. Check the server console for output from the service. + +7. Undeploy the application, then the ejb + + mvn clean -Pdeploy -Pwildfly + cd ../ejb; mvn clean -Pdeploy -Pwildfly + +Warning --> Wildfly 8.0.0 When the application is undeployed, it is required to restart the server to get all the undeployment changes done. + + + +Options +======= + +When running with no options: + + mvn exec:java + +You will be hitting the http (non-SSL) URL, and see this in your log: + + Caused by: org.switchyard.exception.SwitchYardException: Required policies have not been provided: authorization clientAuthentication confidentiality + +When running with this option: + + mvn exec:java -Dexec.args="confidentiality clientAuthentication" -Djavax.net.ssl.trustStore=connector.jks + +You will be hitting the https (SSL) URL and providing authentication information, and see this in your log: + + :: WorkService :: Received work command => CMD-1401308184129 (caller principal=kermit, in roles? 'friend'=true 'enemy'=false) + :: BackEndService :: process => CMD-1401308184129 (caller principal=kermit, in roles? 'friend'=true 'enemy'=false) + :: WorkService :: returned from BackEndService => Processed by BackEndService: CMD-1401308184129 + :: TestEJBBean :: process => CMD-1401308184129 (caller principal=[roles=[friend],principal=kermit], in roles? 'friend'=true 'enemy'=false) + :: WorkService :: returned from TestEJBBean => Processed by TestEJBBean: CMD-1401308184129 + + (Because the WorkService, BackEndService and TestEBJBean are secured, you will see the not-null principal, and true for the expected security role.) + +You can play with the exec.args and only specify one of "confidentiality" or "clientAuthentication". I bet you can guess what will happen... ;) diff --git a/demos/security-propagation/basic/config.cli b/quickstarts/demos/security-propagation/basic/config.cli similarity index 100% rename from demos/security-propagation/basic/config.cli rename to quickstarts/demos/security-propagation/basic/config.cli diff --git a/demos/security-propagation/basic/config_wildfly.cli b/quickstarts/demos/security-propagation/basic/config_wildfly.cli similarity index 100% rename from demos/security-propagation/basic/config_wildfly.cli rename to quickstarts/demos/security-propagation/basic/config_wildfly.cli diff --git a/demos/security-propagation/basic/connector.jks b/quickstarts/demos/security-propagation/basic/connector.jks similarity index 100% rename from demos/security-propagation/basic/connector.jks rename to quickstarts/demos/security-propagation/basic/connector.jks diff --git a/quickstarts/demos/security-propagation/basic/pom.xml b/quickstarts/demos/security-propagation/basic/pom.xml new file mode 100644 index 000000000..bc65adc49 --- /dev/null +++ b/quickstarts/demos/security-propagation/basic/pom.xml @@ -0,0 +1,166 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-security-propagation + 2.1.0-SNAPSHOT + + switchyard-demo-security-propagation-basic + Quickstart Demo : Security Propagation : Basic Authentication (+SSL) to Bean + EJB + Quickstart Demo : Security Propagation : Basic Authentication (+SSL) to Bean + EJB + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 9999 + 1.6 + 1.6 + 1.0.2.Final + config.cli + unconfig.cli + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.apache.commons + not-yet-commons-ssl + test + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.quickstarts.demos + switchyard-demo-security-propagation-ejb + + + org.jboss.spec.javax.ejb + jboss-ejb-api_3.1_spec + provided + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.demo.security.propagation.basic.WorkServiceMain + false + + + + + + + deploy + + false + + + + wildfly + + 9990 + config_wildfly.cli + unconfig_wildfly.cli + + + + diff --git a/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/BackEndService.java b/quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/BackEndService.java similarity index 100% rename from demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/BackEndService.java rename to quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/BackEndService.java diff --git a/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/BackEndServiceBean.java b/quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/BackEndServiceBean.java similarity index 100% rename from demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/BackEndServiceBean.java rename to quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/BackEndServiceBean.java diff --git a/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/Transformers.java b/quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/Transformers.java similarity index 100% rename from demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/Transformers.java rename to quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/Transformers.java diff --git a/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/Work.java b/quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/Work.java similarity index 100% rename from demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/Work.java rename to quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/Work.java diff --git a/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkAck.java b/quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkAck.java similarity index 100% rename from demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkAck.java rename to quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkAck.java diff --git a/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkService.java b/quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkService.java similarity index 100% rename from demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkService.java rename to quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkService.java diff --git a/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkServiceBean.java b/quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkServiceBean.java similarity index 100% rename from demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkServiceBean.java rename to quickstarts/demos/security-propagation/basic/src/main/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkServiceBean.java diff --git a/demos/security-propagation/basic/src/main/resources/META-INF/WorkService.wsdl b/quickstarts/demos/security-propagation/basic/src/main/resources/META-INF/WorkService.wsdl similarity index 100% rename from demos/security-propagation/basic/src/main/resources/META-INF/WorkService.wsdl rename to quickstarts/demos/security-propagation/basic/src/main/resources/META-INF/WorkService.wsdl diff --git a/demos/security-propagation/basic/src/main/resources/META-INF/beans.xml b/quickstarts/demos/security-propagation/basic/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/security-propagation/basic/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/security-propagation/basic/src/main/resources/META-INF/beans.xml diff --git a/demos/security-propagation/basic/src/main/resources/META-INF/jboss-deployment-structure.xml b/quickstarts/demos/security-propagation/basic/src/main/resources/META-INF/jboss-deployment-structure.xml similarity index 100% rename from demos/security-propagation/basic/src/main/resources/META-INF/jboss-deployment-structure.xml rename to quickstarts/demos/security-propagation/basic/src/main/resources/META-INF/jboss-deployment-structure.xml diff --git a/demos/security-propagation/basic/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/security-propagation/basic/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/security-propagation/basic/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/security-propagation/basic/src/main/resources/META-INF/switchyard.xml diff --git a/demos/security-propagation/basic/src/test/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkServiceMain.java b/quickstarts/demos/security-propagation/basic/src/test/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkServiceMain.java similarity index 100% rename from demos/security-propagation/basic/src/test/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkServiceMain.java rename to quickstarts/demos/security-propagation/basic/src/test/java/org/switchyard/quickstarts/demo/security/propagation/basic/WorkServiceMain.java diff --git a/demos/security-propagation/basic/src/test/resources/META-INF/beans.xml b/quickstarts/demos/security-propagation/basic/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/security-propagation/basic/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/security-propagation/basic/src/test/resources/META-INF/beans.xml diff --git a/demos/security-propagation/basic/src/test/resources/log4j.xml b/quickstarts/demos/security-propagation/basic/src/test/resources/log4j.xml similarity index 100% rename from demos/security-propagation/basic/src/test/resources/log4j.xml rename to quickstarts/demos/security-propagation/basic/src/test/resources/log4j.xml diff --git a/demos/security-propagation/basic/src/test/resources/xml/soap-request.xml b/quickstarts/demos/security-propagation/basic/src/test/resources/xml/soap-request.xml similarity index 100% rename from demos/security-propagation/basic/src/test/resources/xml/soap-request.xml rename to quickstarts/demos/security-propagation/basic/src/test/resources/xml/soap-request.xml diff --git a/demos/security-propagation/basic/unconfig.cli b/quickstarts/demos/security-propagation/basic/unconfig.cli similarity index 100% rename from demos/security-propagation/basic/unconfig.cli rename to quickstarts/demos/security-propagation/basic/unconfig.cli diff --git a/demos/security-propagation/basic/unconfig_wildfly.cli b/quickstarts/demos/security-propagation/basic/unconfig_wildfly.cli similarity index 100% rename from demos/security-propagation/basic/unconfig_wildfly.cli rename to quickstarts/demos/security-propagation/basic/unconfig_wildfly.cli diff --git a/quickstarts/demos/security-propagation/ejb/pom.xml b/quickstarts/demos/security-propagation/ejb/pom.xml new file mode 100644 index 000000000..b5e4821e2 --- /dev/null +++ b/quickstarts/demos/security-propagation/ejb/pom.xml @@ -0,0 +1,115 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-security-propagation + 2.1.0-SNAPSHOT + + switchyard-demo-security-propagation-ejb + ejb + Quickstart Demo : Security Propagation : EJB + Quickstart Demo : Security Propagation : EJB + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 9999 + 1.6 + 1.6 + 1.0.2.Final + + + + javax.enterprise + cdi-api + provided + + + org.jboss.spec.javax.ejb + jboss-ejb-api_3.1_spec + provided + + + org.jboss.ejb3 + jboss-ejb3-ext-api + provided + + + log4j + log4j + + + + ${project.artifactId} + + + maven-ejb-plugin + + 3.1 + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBBean.java b/quickstarts/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBBean.java similarity index 100% rename from demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBBean.java rename to quickstarts/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBBean.java diff --git a/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBBeanLocal.java b/quickstarts/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBBeanLocal.java similarity index 100% rename from demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBBeanLocal.java rename to quickstarts/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBBeanLocal.java diff --git a/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBQualifier.java b/quickstarts/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBQualifier.java similarity index 100% rename from demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBQualifier.java rename to quickstarts/demos/security-propagation/ejb/src/main/java/org/switchyard/quickstarts/demo/security/propagation/ejb/TestEJBQualifier.java diff --git a/demos/security-propagation/ejb/src/main/resources/META-INF/beans.xml b/quickstarts/demos/security-propagation/ejb/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/security-propagation/ejb/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/security-propagation/ejb/src/main/resources/META-INF/beans.xml diff --git a/demos/security-propagation/ejb/src/test/resources/META-INF/beans.xml b/quickstarts/demos/security-propagation/ejb/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/security-propagation/ejb/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/security-propagation/ejb/src/test/resources/META-INF/beans.xml diff --git a/demos/security-propagation/ejb/src/test/resources/log4j.xml b/quickstarts/demos/security-propagation/ejb/src/test/resources/log4j.xml similarity index 100% rename from demos/security-propagation/ejb/src/test/resources/log4j.xml rename to quickstarts/demos/security-propagation/ejb/src/test/resources/log4j.xml diff --git a/quickstarts/demos/security-propagation/pom.xml b/quickstarts/demos/security-propagation/pom.xml new file mode 100644 index 000000000..9066d94c0 --- /dev/null +++ b/quickstarts/demos/security-propagation/pom.xml @@ -0,0 +1,158 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-security-propagation + 2.1.0-SNAPSHOT + pom + Quickstart Demo: Security Propagation + Quickstart Demo: Security Propagation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + true + 9999 + 1.3.1 + 1.0.2.Final + + + ejb + basic + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + org.switchyard.quickstarts.demos + switchyard-demo-security-propagation-ejb + ${project.version} + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + + maven-clean-plugin + + + + ${project.build.directory} + + + + + + + + + wildfly + + 9990 + + + + diff --git a/demos/transaction-propagation/README.md b/quickstarts/demos/transaction-propagation/README.md similarity index 100% rename from demos/transaction-propagation/README.md rename to quickstarts/demos/transaction-propagation/README.md diff --git a/quickstarts/demos/transaction-propagation/client/pom.xml b/quickstarts/demos/transaction-propagation/client/pom.xml new file mode 100644 index 000000000..ecdc77546 --- /dev/null +++ b/quickstarts/demos/transaction-propagation/client/pom.xml @@ -0,0 +1,67 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-transaction-propagation + 2.1.0-SNAPSHOT + + switchyard-demo-transaction-propagation-client + jar + Quickstart Demo: Remote Transaction Propagation - Client + Quickstart Demo: Remote Transaction Propagation - Client + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + + + + org.switchyard + switchyard-remote + test + + + + ${project.artifactId} + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.demo.txpropagation.RemoteClient + false + + + + + diff --git a/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java b/quickstarts/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java similarity index 100% rename from demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java rename to quickstarts/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java diff --git a/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java b/quickstarts/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java similarity index 100% rename from demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java rename to quickstarts/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java diff --git a/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java b/quickstarts/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java similarity index 100% rename from demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java rename to quickstarts/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java diff --git a/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java b/quickstarts/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java similarity index 100% rename from demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java rename to quickstarts/demos/transaction-propagation/client/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java diff --git a/demos/transaction-propagation/client/src/test/java/org/switchyard/quickstarts/demo/txpropagation/RemoteClient.java b/quickstarts/demos/transaction-propagation/client/src/test/java/org/switchyard/quickstarts/demo/txpropagation/RemoteClient.java similarity index 100% rename from demos/transaction-propagation/client/src/test/java/org/switchyard/quickstarts/demo/txpropagation/RemoteClient.java rename to quickstarts/demos/transaction-propagation/client/src/test/java/org/switchyard/quickstarts/demo/txpropagation/RemoteClient.java diff --git a/demos/transaction-propagation/credit/config.cli b/quickstarts/demos/transaction-propagation/credit/config.cli similarity index 100% rename from demos/transaction-propagation/credit/config.cli rename to quickstarts/demos/transaction-propagation/credit/config.cli diff --git a/quickstarts/demos/transaction-propagation/credit/pom.xml b/quickstarts/demos/transaction-propagation/credit/pom.xml new file mode 100644 index 000000000..ccf40c9d0 --- /dev/null +++ b/quickstarts/demos/transaction-propagation/credit/pom.xml @@ -0,0 +1,205 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-transaction-propagation + 2.1.0-SNAPSHOT + + switchyard-demo-transaction-propagation-credit + Quickstart Demo: Remote Transaction Propagation - Credit Service + Quickstart Demo: Remote Transaction Propagation - Credit Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + 1.3.168 + remote + 10999 + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-jca + test + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard.components + switchyard-component-camel-jpa + + + org.hibernate + hibernate-core + + + org.hibernate + hibernate-entitymanager + + + org.switchyard.components + switchyard-component-bean + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + de.juplo + hibernate4-maven-plugin + 1.0.3 + + + com.h2database + h2 + ${version.com.h2database} + + + + + create + install + + export + + + + + org.h2.Driver + org.hibernate.dialect.H2Dialect + jdbc:h2:tcp://localhost/h2db/credit + sa + sa + ${deploy.skip} + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + + + deploy + + false + + + + wildfly + + http-remoting + 10990 + + + + diff --git a/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java b/quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java similarity index 100% rename from demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java rename to quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java diff --git a/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/ApplicationLogger.java b/quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/ApplicationLogger.java similarity index 100% rename from demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/ApplicationLogger.java rename to quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/ApplicationLogger.java diff --git a/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java b/quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java similarity index 100% rename from demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java rename to quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java diff --git a/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckService.java b/quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckService.java similarity index 100% rename from demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckService.java rename to quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckService.java diff --git a/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckServiceBean.java b/quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckServiceBean.java similarity index 100% rename from demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckServiceBean.java rename to quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckServiceBean.java diff --git a/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java b/quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java similarity index 100% rename from demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java rename to quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java diff --git a/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java b/quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java similarity index 100% rename from demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java rename to quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java diff --git a/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/RuleService.java b/quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/RuleService.java similarity index 100% rename from demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/RuleService.java rename to quickstarts/demos/transaction-propagation/credit/src/main/java/org/switchyard/quickstarts/demo/txpropagation/RuleService.java diff --git a/demos/transaction-propagation/credit/src/main/resources/META-INF/beans.xml b/quickstarts/demos/transaction-propagation/credit/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/transaction-propagation/credit/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/transaction-propagation/credit/src/main/resources/META-INF/beans.xml diff --git a/demos/transaction-propagation/credit/src/main/resources/META-INF/h2-xa-ds.xml b/quickstarts/demos/transaction-propagation/credit/src/main/resources/META-INF/h2-xa-ds.xml similarity index 100% rename from demos/transaction-propagation/credit/src/main/resources/META-INF/h2-xa-ds.xml rename to quickstarts/demos/transaction-propagation/credit/src/main/resources/META-INF/h2-xa-ds.xml diff --git a/demos/transaction-propagation/credit/src/main/resources/META-INF/persistence.xml b/quickstarts/demos/transaction-propagation/credit/src/main/resources/META-INF/persistence.xml similarity index 100% rename from demos/transaction-propagation/credit/src/main/resources/META-INF/persistence.xml rename to quickstarts/demos/transaction-propagation/credit/src/main/resources/META-INF/persistence.xml diff --git a/demos/transaction-propagation/credit/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/transaction-propagation/credit/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/transaction-propagation/credit/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/transaction-propagation/credit/src/main/resources/META-INF/switchyard.xml diff --git a/demos/transaction-propagation/credit/src/main/resources/RulesComponent.drl b/quickstarts/demos/transaction-propagation/credit/src/main/resources/RulesComponent.drl similarity index 100% rename from demos/transaction-propagation/credit/src/main/resources/RulesComponent.drl rename to quickstarts/demos/transaction-propagation/credit/src/main/resources/RulesComponent.drl diff --git a/demos/transaction-propagation/credit/src/test/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckTest.java b/quickstarts/demos/transaction-propagation/credit/src/test/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckTest.java similarity index 100% rename from demos/transaction-propagation/credit/src/test/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckTest.java rename to quickstarts/demos/transaction-propagation/credit/src/test/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckTest.java diff --git a/demos/transaction-propagation/credit/src/test/resources/META-INF/beans.xml b/quickstarts/demos/transaction-propagation/credit/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/transaction-propagation/credit/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/transaction-propagation/credit/src/test/resources/META-INF/beans.xml diff --git a/demos/transaction-propagation/credit/unconfig.cli b/quickstarts/demos/transaction-propagation/credit/unconfig.cli similarity index 100% rename from demos/transaction-propagation/credit/unconfig.cli rename to quickstarts/demos/transaction-propagation/credit/unconfig.cli diff --git a/demos/transaction-propagation/dealer/config.cli b/quickstarts/demos/transaction-propagation/dealer/config.cli similarity index 100% rename from demos/transaction-propagation/dealer/config.cli rename to quickstarts/demos/transaction-propagation/dealer/config.cli diff --git a/quickstarts/demos/transaction-propagation/dealer/pom.xml b/quickstarts/demos/transaction-propagation/dealer/pom.xml new file mode 100644 index 000000000..f59dea116 --- /dev/null +++ b/quickstarts/demos/transaction-propagation/dealer/pom.xml @@ -0,0 +1,202 @@ + + + + 4.0.0 + + org.switchyard.quickstarts.demos + switchyard-demo-transaction-propagation + 2.1.0-SNAPSHOT + + switchyard-demo-transaction-propagation-dealer + Quickstart Demo: Remote Transaction Propagation - Dealer Service + Quickstart Demo: Remote Transaction Propagation - Dealer Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + 1.3.168 + 9999 + remote + true + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard.components + switchyard-component-camel-jpa + + + org.hibernate + hibernate-core + + + org.hibernate + hibernate-entitymanager + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-jca + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + de.juplo + hibernate4-maven-plugin + 1.0.3 + + + com.h2database + h2 + ${version.com.h2database} + + + + + create + install + + export + + + + + org.h2.Driver + org.hibernate.dialect.H2Dialect + jdbc:h2:tcp://localhost/h2db/dealer + sa + sa + ${deploy.skip} + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + + + deploy + + false + + + + wildfly + + http-remoting + 9990 + + + + diff --git a/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java b/quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java similarity index 100% rename from demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java rename to quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Application.java diff --git a/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java b/quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java similarity index 100% rename from demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java rename to quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Car.java diff --git a/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckService.java b/quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckService.java similarity index 100% rename from demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckService.java rename to quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/CreditCheckService.java diff --git a/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java b/quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java similarity index 100% rename from demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java rename to quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Deal.java diff --git a/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/DealLogger.java b/quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/DealLogger.java similarity index 100% rename from demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/DealLogger.java rename to quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/DealLogger.java diff --git a/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Dealer.java b/quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Dealer.java similarity index 100% rename from demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Dealer.java rename to quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Dealer.java diff --git a/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/DealerBean.java b/quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/DealerBean.java similarity index 100% rename from demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/DealerBean.java rename to quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/DealerBean.java diff --git a/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java b/quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java similarity index 100% rename from demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java rename to quickstarts/demos/transaction-propagation/dealer/src/main/java/org/switchyard/quickstarts/demo/txpropagation/Offer.java diff --git a/demos/transaction-propagation/dealer/src/main/resources/META-INF/beans.xml b/quickstarts/demos/transaction-propagation/dealer/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/transaction-propagation/dealer/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/transaction-propagation/dealer/src/main/resources/META-INF/beans.xml diff --git a/demos/transaction-propagation/dealer/src/main/resources/META-INF/h2-xa-ds.xml b/quickstarts/demos/transaction-propagation/dealer/src/main/resources/META-INF/h2-xa-ds.xml similarity index 100% rename from demos/transaction-propagation/dealer/src/main/resources/META-INF/h2-xa-ds.xml rename to quickstarts/demos/transaction-propagation/dealer/src/main/resources/META-INF/h2-xa-ds.xml diff --git a/demos/transaction-propagation/dealer/src/main/resources/META-INF/persistence.xml b/quickstarts/demos/transaction-propagation/dealer/src/main/resources/META-INF/persistence.xml similarity index 100% rename from demos/transaction-propagation/dealer/src/main/resources/META-INF/persistence.xml rename to quickstarts/demos/transaction-propagation/dealer/src/main/resources/META-INF/persistence.xml diff --git a/demos/transaction-propagation/dealer/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/transaction-propagation/dealer/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/transaction-propagation/dealer/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/transaction-propagation/dealer/src/main/resources/META-INF/switchyard.xml diff --git a/demos/transaction-propagation/dealer/src/test/java/org/switchyard/quickstarts/demo/txpropagation/DealerTest.java b/quickstarts/demos/transaction-propagation/dealer/src/test/java/org/switchyard/quickstarts/demo/txpropagation/DealerTest.java similarity index 100% rename from demos/transaction-propagation/dealer/src/test/java/org/switchyard/quickstarts/demo/txpropagation/DealerTest.java rename to quickstarts/demos/transaction-propagation/dealer/src/test/java/org/switchyard/quickstarts/demo/txpropagation/DealerTest.java diff --git a/demos/transaction-propagation/dealer/src/test/resources/META-INF/beans.xml b/quickstarts/demos/transaction-propagation/dealer/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/transaction-propagation/dealer/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/transaction-propagation/dealer/src/test/resources/META-INF/beans.xml diff --git a/demos/transaction-propagation/dealer/unconfig.cli b/quickstarts/demos/transaction-propagation/dealer/unconfig.cli similarity index 100% rename from demos/transaction-propagation/dealer/unconfig.cli rename to quickstarts/demos/transaction-propagation/dealer/unconfig.cli diff --git a/quickstarts/demos/transaction-propagation/pom.xml b/quickstarts/demos/transaction-propagation/pom.xml new file mode 100644 index 000000000..c94c54c76 --- /dev/null +++ b/quickstarts/demos/transaction-propagation/pom.xml @@ -0,0 +1,179 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-transaction-propagation + 2.1.0-SNAPSHOT + pom + Quickstart Demo: Remote Transaction Propagation + Quickstart Demo: Remote Transaction Propagation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.6 + 1.6 + true + 9999 + 1.3.1 + 1.0.2.Final + + + client + credit + dealer + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + + com.edugility + h2-maven-plugin + 1.0 + false + + ${project.build.directory} + + + + Spawn a new H2 TCP server + install + + spawn + + + + Stop a spawned H2 TCP server + pre-clean + + stop + + + + + + maven-clean-plugin + + + + ${project.build.directory} + + + + + + + + + wildfly + + 9990 + + + + diff --git a/quickstarts/demos/webapp-deploy/pom.xml b/quickstarts/demos/webapp-deploy/pom.xml new file mode 100644 index 000000000..871924189 --- /dev/null +++ b/quickstarts/demos/webapp-deploy/pom.xml @@ -0,0 +1,121 @@ + + + + 4.0.0 + org.switchyard.quickstarts.demos + switchyard-demo-webapp-deploy + 2.1.0-SNAPSHOT + war + Quickstart Demo : JEE Webapp Deployment + Quickstart Demo : JEE Webapp Deployment + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 1.3.1 + 1.6 + 1.6 + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-deploy-webapp + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.jboss.weld.servlet + weld-servlet-core + + + org.switchyard + switchyard-test + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + diff --git a/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/Order.java b/quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/Order.java similarity index 100% rename from demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/Order.java rename to quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/Order.java diff --git a/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderAck.java b/quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderAck.java similarity index 100% rename from demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderAck.java rename to quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderAck.java diff --git a/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderService.java b/quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderService.java similarity index 100% rename from demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderService.java rename to quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderService.java diff --git a/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderServiceBean.java b/quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderServiceBean.java similarity index 100% rename from demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderServiceBean.java rename to quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/OrderServiceBean.java diff --git a/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/Transformers.java b/quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/Transformers.java similarity index 100% rename from demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/Transformers.java rename to quickstarts/demos/webapp-deploy/src/main/java/org/switchyard/quickstarts/demos/orders/Transformers.java diff --git a/demos/webapp-deploy/src/main/resources/META-INF/beans.xml b/quickstarts/demos/webapp-deploy/src/main/resources/META-INF/beans.xml similarity index 100% rename from demos/webapp-deploy/src/main/resources/META-INF/beans.xml rename to quickstarts/demos/webapp-deploy/src/main/resources/META-INF/beans.xml diff --git a/demos/webapp-deploy/src/main/resources/META-INF/switchyard.xml b/quickstarts/demos/webapp-deploy/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from demos/webapp-deploy/src/main/resources/META-INF/switchyard.xml rename to quickstarts/demos/webapp-deploy/src/main/resources/META-INF/switchyard.xml diff --git a/demos/webapp-deploy/src/main/resources/wsdl/OrderService.wsdl b/quickstarts/demos/webapp-deploy/src/main/resources/wsdl/OrderService.wsdl similarity index 100% rename from demos/webapp-deploy/src/main/resources/wsdl/OrderService.wsdl rename to quickstarts/demos/webapp-deploy/src/main/resources/wsdl/OrderService.wsdl diff --git a/demos/webapp-deploy/src/main/webapp/META-INF/context.xml b/quickstarts/demos/webapp-deploy/src/main/webapp/META-INF/context.xml similarity index 100% rename from demos/webapp-deploy/src/main/webapp/META-INF/context.xml rename to quickstarts/demos/webapp-deploy/src/main/webapp/META-INF/context.xml diff --git a/demos/webapp-deploy/src/main/webapp/WEB-INF/web.xml b/quickstarts/demos/webapp-deploy/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from demos/webapp-deploy/src/main/webapp/WEB-INF/web.xml rename to quickstarts/demos/webapp-deploy/src/main/webapp/WEB-INF/web.xml diff --git a/demos/webapp-deploy/src/test/resources/META-INF/beans.xml b/quickstarts/demos/webapp-deploy/src/test/resources/META-INF/beans.xml similarity index 100% rename from demos/webapp-deploy/src/test/resources/META-INF/beans.xml rename to quickstarts/demos/webapp-deploy/src/test/resources/META-INF/beans.xml diff --git a/quickstarts/ear-deployment/README.md b/quickstarts/ear-deployment/README.md new file mode 100644 index 000000000..83117e172 --- /dev/null +++ b/quickstarts/ear-deployment/README.md @@ -0,0 +1,66 @@ +# EAR Deployment Quickstart + +This quickstart provides an example packaging multiple SwitchYard applications, associated libraries, and a JMS destination inside an EAR archive. The quickstart consists of the following pieces: + +* artifacts : contains XSDs, WSDLs, and Java domain objects which are used by service providers and consumers across application projects +* order-service : provides two services - OrderService and InventoryService +* order-consumer : consumes OrderService through a SOAP/HTTP binding +* ear-assembly : packages all of the above into an EAR archive + + +## Deploying the EAR + +Preqrequisites +============== +Maven + + +Running the quickstart +====================== + + +EAP +---------- +1. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the EAR + + mvn install -Pdeploy + +4. Test the application + + mvn exec:java + +5. Undeploy the EAR + + mvn clean -Pdeploy + + +Wildfly +---------- +1. Start Wildfly in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the EAR + + mvn install -Pdeploy -Pwildfly + +4. Test the application + + mvn exec:java -Pwildfly + +5. Undeploy the EAR + + mvn clean -Pdeploy -Pwildfly + diff --git a/quickstarts/ear-deployment/artifacts/pom.xml b/quickstarts/ear-deployment/artifacts/pom.xml new file mode 100644 index 000000000..c41cc9f4f --- /dev/null +++ b/quickstarts/ear-deployment/artifacts/pom.xml @@ -0,0 +1,55 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-ear-deployment + 2.1.0-SNAPSHOT + + switchyard-ear-deployment-artifacts + jar + SwitchYard Quickstart: ear-deployment - artifacts + Quickstart : EAR Deployment - Service Artifacts + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + ${project.artifactId} + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + diff --git a/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/InventoryService.java b/quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/InventoryService.java similarity index 100% rename from ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/InventoryService.java rename to quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/InventoryService.java diff --git a/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Item.java b/quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Item.java similarity index 100% rename from ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Item.java rename to quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Item.java diff --git a/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/ItemNotFoundException.java b/quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/ItemNotFoundException.java similarity index 100% rename from ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/ItemNotFoundException.java rename to quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/ItemNotFoundException.java diff --git a/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Order.java b/quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Order.java similarity index 100% rename from ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Order.java rename to quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/Order.java diff --git a/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderAck.java b/quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderAck.java similarity index 100% rename from ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderAck.java rename to quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderAck.java diff --git a/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderService.java b/quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderService.java similarity index 100% rename from ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderService.java rename to quickstarts/ear-deployment/artifacts/src/main/java/org/switchyard/quickstarts/demo/multiapp/OrderService.java diff --git a/ear-deployment/artifacts/src/main/resources/META-INF/beans.xml b/quickstarts/ear-deployment/artifacts/src/main/resources/META-INF/beans.xml similarity index 100% rename from ear-deployment/artifacts/src/main/resources/META-INF/beans.xml rename to quickstarts/ear-deployment/artifacts/src/main/resources/META-INF/beans.xml diff --git a/ear-deployment/artifacts/src/main/resources/OrderService.wsdl b/quickstarts/ear-deployment/artifacts/src/main/resources/OrderService.wsdl similarity index 100% rename from ear-deployment/artifacts/src/main/resources/OrderService.wsdl rename to quickstarts/ear-deployment/artifacts/src/main/resources/OrderService.wsdl diff --git a/ear-deployment/artifacts/src/main/resources/orderTypes.xsd b/quickstarts/ear-deployment/artifacts/src/main/resources/orderTypes.xsd similarity index 100% rename from ear-deployment/artifacts/src/main/resources/orderTypes.xsd rename to quickstarts/ear-deployment/artifacts/src/main/resources/orderTypes.xsd diff --git a/quickstarts/ear-deployment/ear-assembly/pom.xml b/quickstarts/ear-deployment/ear-assembly/pom.xml new file mode 100644 index 000000000..5d523dc72 --- /dev/null +++ b/quickstarts/ear-deployment/ear-assembly/pom.xml @@ -0,0 +1,117 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-ear-deployment + 2.1.0-SNAPSHOT + + switchyard-ear-deployment-ear-assembly + ear + SwitchYard Quickstart: ear-deployment - ear-assembly + Quickstart : EAR Deployment - Application Assembly + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + org.switchyard.quickstarts + switchyard-ear-deployment-artifacts + + + org.switchyard.quickstarts + switchyard-ear-deployment-order-consumer + + + org.switchyard.quickstarts + switchyard-ear-deployment-order-service + + + + ${project.parent.artifactId} + + + maven-ear-plugin + 2.8 + + true + 5 + + + org.switchyard.quickstarts + switchyard-ear-deployment-artifacts + lib + + + org.switchyard.quickstarts + switchyard-ear-deployment-order-consumer + true + + + org.switchyard.quickstarts + switchyard-ear-deployment-order-service + true + + + + switchyard-ear-*, + lib/*, + META-INF/* + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + diff --git a/ear-deployment/ear-assembly/src/main/application/META-INF/application.xml b/quickstarts/ear-deployment/ear-assembly/src/main/application/META-INF/application.xml similarity index 100% rename from ear-deployment/ear-assembly/src/main/application/META-INF/application.xml rename to quickstarts/ear-deployment/ear-assembly/src/main/application/META-INF/application.xml diff --git a/ear-deployment/ear-assembly/src/main/application/META-INF/consumer-hornetq-jms.xml b/quickstarts/ear-deployment/ear-assembly/src/main/application/META-INF/consumer-hornetq-jms.xml similarity index 100% rename from ear-deployment/ear-assembly/src/main/application/META-INF/consumer-hornetq-jms.xml rename to quickstarts/ear-deployment/ear-assembly/src/main/application/META-INF/consumer-hornetq-jms.xml diff --git a/quickstarts/ear-deployment/order-consumer/pom.xml b/quickstarts/ear-deployment/order-consumer/pom.xml new file mode 100644 index 000000000..7aae3ce00 --- /dev/null +++ b/quickstarts/ear-deployment/order-consumer/pom.xml @@ -0,0 +1,198 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-ear-deployment + 2.1.0-SNAPSHOT + + switchyard-ear-deployment-order-consumer + SwitchYard Quickstart: ear-deployment - order-consumer + Quickstart : EAR Deployment - Order Consumer + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + 2.4.1.Final + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.quickstarts + switchyard-ear-deployment-artifacts + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + junit + junit + test + + + org.switchyard.components + switchyard-component-camel-jms + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-sca + + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + org.switchyard.quickstarts.eardeploy.OrderIntakeClient + test + false + + ${project.build.directory}/test-classes/order.xml + + + + + + + + wildfly + + true + 8080 + + + + org.hornetq + hornetq-core-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-commons + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-journal + ${version.wildfly.hornetq} + test + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + hornetqmixin.port + 8080 + + + hornetqmixin.http.upgrade.enabled + true + + + + + + + + + diff --git a/ear-deployment/order-consumer/src/main/resources/META-INF/beans.xml b/quickstarts/ear-deployment/order-consumer/src/main/resources/META-INF/beans.xml similarity index 100% rename from ear-deployment/order-consumer/src/main/resources/META-INF/beans.xml rename to quickstarts/ear-deployment/order-consumer/src/main/resources/META-INF/beans.xml diff --git a/ear-deployment/order-consumer/src/main/resources/META-INF/route.xml b/quickstarts/ear-deployment/order-consumer/src/main/resources/META-INF/route.xml similarity index 100% rename from ear-deployment/order-consumer/src/main/resources/META-INF/route.xml rename to quickstarts/ear-deployment/order-consumer/src/main/resources/META-INF/route.xml diff --git a/ear-deployment/order-consumer/src/main/resources/META-INF/switchyard.xml b/quickstarts/ear-deployment/order-consumer/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from ear-deployment/order-consumer/src/main/resources/META-INF/switchyard.xml rename to quickstarts/ear-deployment/order-consumer/src/main/resources/META-INF/switchyard.xml diff --git a/ear-deployment/order-consumer/src/test/java/org/switchyard/quickstarts/eardeploy/OrderIntakeClient.java b/quickstarts/ear-deployment/order-consumer/src/test/java/org/switchyard/quickstarts/eardeploy/OrderIntakeClient.java similarity index 100% rename from ear-deployment/order-consumer/src/test/java/org/switchyard/quickstarts/eardeploy/OrderIntakeClient.java rename to quickstarts/ear-deployment/order-consumer/src/test/java/org/switchyard/quickstarts/eardeploy/OrderIntakeClient.java diff --git a/ear-deployment/order-consumer/src/test/resources/META-INF/beans.xml b/quickstarts/ear-deployment/order-consumer/src/test/resources/META-INF/beans.xml similarity index 100% rename from ear-deployment/order-consumer/src/test/resources/META-INF/beans.xml rename to quickstarts/ear-deployment/order-consumer/src/test/resources/META-INF/beans.xml diff --git a/ear-deployment/order-consumer/src/test/resources/order.xml b/quickstarts/ear-deployment/order-consumer/src/test/resources/order.xml similarity index 100% rename from ear-deployment/order-consumer/src/test/resources/order.xml rename to quickstarts/ear-deployment/order-consumer/src/test/resources/order.xml diff --git a/quickstarts/ear-deployment/order-service/pom.xml b/quickstarts/ear-deployment/order-service/pom.xml new file mode 100644 index 000000000..07af71a5a --- /dev/null +++ b/quickstarts/ear-deployment/order-service/pom.xml @@ -0,0 +1,116 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-ear-deployment + 2.1.0-SNAPSHOT + + switchyard-ear-deployment-order-service + SwitchYard Quickstart: ear-deployment - order-service + Quickstart : EAR Deployment - Order Service + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.quickstarts + switchyard-ear-deployment-artifacts + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + + dummy + true + + + + + diff --git a/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceBean.java b/quickstarts/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceBean.java similarity index 100% rename from ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceBean.java rename to quickstarts/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/InventoryServiceBean.java diff --git a/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceBean.java b/quickstarts/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceBean.java similarity index 100% rename from ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceBean.java rename to quickstarts/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/OrderServiceBean.java diff --git a/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/Transformers.java b/quickstarts/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/Transformers.java similarity index 100% rename from ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/Transformers.java rename to quickstarts/ear-deployment/order-service/src/main/java/org/switchyard/quickstarts/demo/multiapp/service/Transformers.java diff --git a/ear-deployment/order-service/src/main/resources/META-INF/beans.xml b/quickstarts/ear-deployment/order-service/src/main/resources/META-INF/beans.xml similarity index 100% rename from ear-deployment/order-service/src/main/resources/META-INF/beans.xml rename to quickstarts/ear-deployment/order-service/src/main/resources/META-INF/beans.xml diff --git a/ear-deployment/order-service/src/main/resources/META-INF/switchyard.xml b/quickstarts/ear-deployment/order-service/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from ear-deployment/order-service/src/main/resources/META-INF/switchyard.xml rename to quickstarts/ear-deployment/order-service/src/main/resources/META-INF/switchyard.xml diff --git a/ear-deployment/order-service/src/test/resources/META-INF/beans.xml b/quickstarts/ear-deployment/order-service/src/test/resources/META-INF/beans.xml similarity index 100% rename from ear-deployment/order-service/src/test/resources/META-INF/beans.xml rename to quickstarts/ear-deployment/order-service/src/test/resources/META-INF/beans.xml diff --git a/ear-deployment/order-service/src/test/resources/log4j.xml b/quickstarts/ear-deployment/order-service/src/test/resources/log4j.xml similarity index 100% rename from ear-deployment/order-service/src/test/resources/log4j.xml rename to quickstarts/ear-deployment/order-service/src/test/resources/log4j.xml diff --git a/quickstarts/ear-deployment/pom.xml b/quickstarts/ear-deployment/pom.xml new file mode 100644 index 000000000..42d97dc8d --- /dev/null +++ b/quickstarts/ear-deployment/pom.xml @@ -0,0 +1,158 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-ear-deployment + 2.1.0-SNAPSHOT + pom + SwitchYard Quickstart: ear-deployment + Quickstart : EAR Deployment + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + 9999 + 1.6 + 1.6 + 1.3.1 + 2.4.0 + 1.0.2.Final + + + artifacts + order-service + order-consumer + ear-assembly + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + org.switchyard.quickstarts + switchyard-ear-deployment-artifacts + ${project.version} + + + org.switchyard.quickstarts + switchyard-ear-deployment-order-consumer + ${project.version} + + + org.switchyard.quickstarts + switchyard-ear-deployment-order-service + ${project.version} + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + false + + true + + + + org.codehaus.mojo + exec-maven-plugin + false + + dummy + true + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + + + + diff --git a/http-binding/Readme.md b/quickstarts/http-binding/Readme.md similarity index 100% rename from http-binding/Readme.md rename to quickstarts/http-binding/Readme.md diff --git a/http-binding/http-binding.jpg b/quickstarts/http-binding/http-binding.jpg similarity index 100% rename from http-binding/http-binding.jpg rename to quickstarts/http-binding/http-binding.jpg diff --git a/quickstarts/http-binding/pom.xml b/quickstarts/http-binding/pom.xml new file mode 100644 index 000000000..70066b153 --- /dev/null +++ b/quickstarts/http-binding/pom.xml @@ -0,0 +1,263 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-http-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: http-binding + Quickstart : HTTP Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.http.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-http + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.http.binding.HttpBindingClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.http.client.port + 8181 + + + + + + + + + wildfly + + 9990 + + + + diff --git a/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/CustomComposer.java b/quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/CustomComposer.java similarity index 100% rename from http-binding/src/main/java/org/switchyard/quickstarts/http/binding/CustomComposer.java rename to quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/CustomComposer.java diff --git a/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteErrorService.java b/quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteErrorService.java similarity index 100% rename from http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteErrorService.java rename to quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteErrorService.java diff --git a/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteErrorServiceImpl.java b/quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteErrorServiceImpl.java similarity index 100% rename from http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteErrorServiceImpl.java rename to quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteErrorServiceImpl.java diff --git a/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteService.java b/quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteService.java similarity index 100% rename from http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteService.java rename to quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteService.java diff --git a/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteServiceImpl.java b/quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteServiceImpl.java similarity index 100% rename from http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteServiceImpl.java rename to quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/QuoteServiceImpl.java diff --git a/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/SymbolService.java b/quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/SymbolService.java similarity index 100% rename from http-binding/src/main/java/org/switchyard/quickstarts/http/binding/SymbolService.java rename to quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/SymbolService.java diff --git a/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/SymbolServiceImpl.java b/quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/SymbolServiceImpl.java similarity index 100% rename from http-binding/src/main/java/org/switchyard/quickstarts/http/binding/SymbolServiceImpl.java rename to quickstarts/http-binding/src/main/java/org/switchyard/quickstarts/http/binding/SymbolServiceImpl.java diff --git a/http-binding/src/main/resources/META-INF/beans.xml b/quickstarts/http-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from http-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/http-binding/src/main/resources/META-INF/beans.xml diff --git a/http-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/http-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from http-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/http-binding/src/main/resources/META-INF/switchyard.xml diff --git a/http-binding/src/test/java/org/switchyard/quickstarts/http/binding/HttpBindingClient.java b/quickstarts/http-binding/src/test/java/org/switchyard/quickstarts/http/binding/HttpBindingClient.java similarity index 100% rename from http-binding/src/test/java/org/switchyard/quickstarts/http/binding/HttpBindingClient.java rename to quickstarts/http-binding/src/test/java/org/switchyard/quickstarts/http/binding/HttpBindingClient.java diff --git a/http-binding/src/test/java/org/switchyard/quickstarts/http/binding/HttpBindingTest.java b/quickstarts/http-binding/src/test/java/org/switchyard/quickstarts/http/binding/HttpBindingTest.java similarity index 100% rename from http-binding/src/test/java/org/switchyard/quickstarts/http/binding/HttpBindingTest.java rename to quickstarts/http-binding/src/test/java/org/switchyard/quickstarts/http/binding/HttpBindingTest.java diff --git a/http-binding/src/test/resources/META-INF/beans.xml b/quickstarts/http-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from http-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/http-binding/src/test/resources/META-INF/beans.xml diff --git a/http-binding/src/test/resources/log4j.xml b/quickstarts/http-binding/src/test/resources/log4j.xml similarity index 100% rename from http-binding/src/test/resources/log4j.xml rename to quickstarts/http-binding/src/test/resources/log4j.xml diff --git a/jca-inflow-activemq/Readme.md b/quickstarts/jca-inflow-activemq/Readme.md similarity index 100% rename from jca-inflow-activemq/Readme.md rename to quickstarts/jca-inflow-activemq/Readme.md diff --git a/jca-inflow-activemq/config.cli b/quickstarts/jca-inflow-activemq/config.cli similarity index 100% rename from jca-inflow-activemq/config.cli rename to quickstarts/jca-inflow-activemq/config.cli diff --git a/jca-inflow-activemq/jca-inflow-activemq.jpg b/quickstarts/jca-inflow-activemq/jca-inflow-activemq.jpg similarity index 100% rename from jca-inflow-activemq/jca-inflow-activemq.jpg rename to quickstarts/jca-inflow-activemq/jca-inflow-activemq.jpg diff --git a/quickstarts/jca-inflow-activemq/pom.xml b/quickstarts/jca-inflow-activemq/pom.xml new file mode 100644 index 000000000..af4820048 --- /dev/null +++ b/quickstarts/jca-inflow-activemq/pom.xml @@ -0,0 +1,275 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-jca-inflow-activemq + 2.1.0-SNAPSHOT + SwitchYard Quickstart: jca-inflow-activemq + Quickstart : JCA Inflow Binding for ActiveMQ + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + true + true + 9999 + 1.6 + 1.6 + 1.3.1 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-jca + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-activemq + test + + + org.apache.activemq + activemq-rar + rar + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + test + + + org.jboss.as + jboss-as-arquillian-container-remote + test + + + org.switchyard.quickstarts + switchyard-quickstart-testutil + test + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy-activemq + install + + deploy-artifact + + + org.apache.activemq + activemq-rar + activemq-ra.rar + + + + + + ${deploy-rar.skip} + + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy-activemq + clean + + undeploy + + + activemq-ra.rar + + + + + + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.jca.inflow.ActiveMQClient + + Skippy + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${skipTests} + + config.cli + unconfig.cli + ${project.build.directory}/${project.build.finalName}.jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + deploy-rar + + false + + + + wildfly + + 9990 + + + + diff --git a/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingGateway.java b/quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingGateway.java similarity index 100% rename from jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingGateway.java rename to quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingGateway.java diff --git a/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingService.java b/quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingService.java similarity index 100% rename from jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingService.java rename to quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingService.java diff --git a/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingServiceBean.java b/quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingServiceBean.java similarity index 100% rename from jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingServiceBean.java rename to quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingServiceBean.java diff --git a/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/ObjectFactory.java b/quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/ObjectFactory.java similarity index 100% rename from jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/ObjectFactory.java rename to quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/ObjectFactory.java diff --git a/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/Person.java b/quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/Person.java similarity index 100% rename from jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/Person.java rename to quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/Person.java diff --git a/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/package-info.java b/quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/package-info.java similarity index 100% rename from jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/package-info.java rename to quickstarts/jca-inflow-activemq/src/main/java/org/switchyard/quickstarts/jca/inflow/package-info.java diff --git a/jca-inflow-activemq/src/main/resources/META-INF/beans.xml b/quickstarts/jca-inflow-activemq/src/main/resources/META-INF/beans.xml similarity index 100% rename from jca-inflow-activemq/src/main/resources/META-INF/beans.xml rename to quickstarts/jca-inflow-activemq/src/main/resources/META-INF/beans.xml diff --git a/jca-inflow-activemq/src/main/resources/META-INF/forge.xml b/quickstarts/jca-inflow-activemq/src/main/resources/META-INF/forge.xml similarity index 100% rename from jca-inflow-activemq/src/main/resources/META-INF/forge.xml rename to quickstarts/jca-inflow-activemq/src/main/resources/META-INF/forge.xml diff --git a/jca-inflow-activemq/src/main/resources/META-INF/jboss-deployment-structure.xml b/quickstarts/jca-inflow-activemq/src/main/resources/META-INF/jboss-deployment-structure.xml similarity index 100% rename from jca-inflow-activemq/src/main/resources/META-INF/jboss-deployment-structure.xml rename to quickstarts/jca-inflow-activemq/src/main/resources/META-INF/jboss-deployment-structure.xml diff --git a/jca-inflow-activemq/src/main/resources/META-INF/switchyard.xml b/quickstarts/jca-inflow-activemq/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from jca-inflow-activemq/src/main/resources/META-INF/switchyard.xml rename to quickstarts/jca-inflow-activemq/src/main/resources/META-INF/switchyard.xml diff --git a/jca-inflow-activemq/src/test/java/org/switchyard/quickstarts/jca/inflow/ActiveMQClient.java b/quickstarts/jca-inflow-activemq/src/test/java/org/switchyard/quickstarts/jca/inflow/ActiveMQClient.java similarity index 100% rename from jca-inflow-activemq/src/test/java/org/switchyard/quickstarts/jca/inflow/ActiveMQClient.java rename to quickstarts/jca-inflow-activemq/src/test/java/org/switchyard/quickstarts/jca/inflow/ActiveMQClient.java diff --git a/jca-inflow-activemq/src/test/java/org/switchyard/quickstarts/jca/inflow/JCAInflowBindingTest.java b/quickstarts/jca-inflow-activemq/src/test/java/org/switchyard/quickstarts/jca/inflow/JCAInflowBindingTest.java similarity index 100% rename from jca-inflow-activemq/src/test/java/org/switchyard/quickstarts/jca/inflow/JCAInflowBindingTest.java rename to quickstarts/jca-inflow-activemq/src/test/java/org/switchyard/quickstarts/jca/inflow/JCAInflowBindingTest.java diff --git a/jca-inflow-activemq/src/test/resources/META-INF/beans.xml b/quickstarts/jca-inflow-activemq/src/test/resources/META-INF/beans.xml similarity index 100% rename from jca-inflow-activemq/src/test/resources/META-INF/beans.xml rename to quickstarts/jca-inflow-activemq/src/test/resources/META-INF/beans.xml diff --git a/jca-inflow-activemq/src/test/resources/arquillian.xml b/quickstarts/jca-inflow-activemq/src/test/resources/arquillian.xml similarity index 100% rename from jca-inflow-activemq/src/test/resources/arquillian.xml rename to quickstarts/jca-inflow-activemq/src/test/resources/arquillian.xml diff --git a/jca-inflow-activemq/src/test/resources/log4j.xml b/quickstarts/jca-inflow-activemq/src/test/resources/log4j.xml similarity index 100% rename from jca-inflow-activemq/src/test/resources/log4j.xml rename to quickstarts/jca-inflow-activemq/src/test/resources/log4j.xml diff --git a/jca-inflow-activemq/unconfig.cli b/quickstarts/jca-inflow-activemq/unconfig.cli similarity index 100% rename from jca-inflow-activemq/unconfig.cli rename to quickstarts/jca-inflow-activemq/unconfig.cli diff --git a/quickstarts/jca-inflow-hornetq/Readme.md b/quickstarts/jca-inflow-hornetq/Readme.md new file mode 100644 index 000000000..fec985219 --- /dev/null +++ b/quickstarts/jca-inflow-hornetq/Readme.md @@ -0,0 +1,99 @@ +Introduction +============ +This quickstart demonstrates the usage of the JCA Component and it's service +binding feature, by binding to a HornetQ Queue. When a message arrives in this +queue the service will be invoked. This quickstart is using XPath dynamic +operation selector which determines the service operation to be invoked by +reading message content. If you pass the name and language parameters at step 7 +like following: + + mvn exec:java -Dexec.args="Fernando spanish" + +then operation selector choose the spanish operation so you would get a spanish greeting like this: + + Hola Fernando :-) + + +EAP +---------- +1. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy + +4. Execute HornetQClient + + mvn exec:java + +5. Check the server console for output from the service. + +6. Undeploy the quickstart: + + mvn clean -Pdeploy + + +Wildfly +---------- +1. Start Wildfly in standalone-full mode: + + ${AS}/bin/standalone.sh -server-config standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy -Pwildfly + +4. Execute HornetQClient + + mvn exec:java -Pwildfly + +5. Check the server console for output from the service. + +6. Undeploy the quickstart: + + mvn clean -Pdeploy -Pwildfly + + +Karaf +---------- +No Karaf feature is present for this quickstart. + + +Expected Results +================ +``` +21:51:08,132 INFO [stdout] (Thread-1 (HornetQ-client-global-threads-1584009536)) Hello there Skippy :-) +``` + +Running a functional test +========================= + +Since this quickstart requires Java EE environment, the functional test +"JCAInflowBindingTest" does not run by default. You need to execute it manually +by following steps. + +1. Build the quickstart: + + mvn clean package + +2. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +3. Execute the test: + + mvn test -DskipTests=false + +## Further Reading + +1. [HornetQ Bindings Documentation](https://docs.jboss.org/author/display/SWITCHYARD/JCA) diff --git a/jca-inflow-hornetq/config.cli b/quickstarts/jca-inflow-hornetq/config.cli similarity index 100% rename from jca-inflow-hornetq/config.cli rename to quickstarts/jca-inflow-hornetq/config.cli diff --git a/jca-inflow-hornetq/jca-inflow-hornetq.jpg b/quickstarts/jca-inflow-hornetq/jca-inflow-hornetq.jpg similarity index 100% rename from jca-inflow-hornetq/jca-inflow-hornetq.jpg rename to quickstarts/jca-inflow-hornetq/jca-inflow-hornetq.jpg diff --git a/quickstarts/jca-inflow-hornetq/pom.xml b/quickstarts/jca-inflow-hornetq/pom.xml new file mode 100644 index 000000000..e130c1cd1 --- /dev/null +++ b/quickstarts/jca-inflow-hornetq/pom.xml @@ -0,0 +1,302 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-jca-inflow-hornetq + 2.1.0-SNAPSHOT + SwitchYard Quickstart: jca-inflow-hornetq + Quickstart : JCA Inflow Binding for HornetQ + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + true + 9999 + 1.6 + 1.6 + 1.3.1 + 1.0.2.Final + 2.4.1.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-jca + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + test + + + org.jboss.as + jboss-as-arquillian-container-remote + test + + + org.switchyard.quickstarts + switchyard-quickstart-testutil + test + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.jca.inflow.HornetQClient + + Skippy + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${skipTests} + + config.cli + unconfig.cli + guest + guestp.1 + ${project.build.directory}/${project.build.finalName}.jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + true + 8080 + + + + org.hornetq + hornetq-core-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-commons + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-journal + ${version.wildfly.hornetq} + test + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + hornetqmixin.port + 8080 + + + hornetqmixin.http.upgrade.enabled + true + + + + + + + + + diff --git a/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingGateway.java b/quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingGateway.java similarity index 100% rename from jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingGateway.java rename to quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingGateway.java diff --git a/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingService.java b/quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingService.java similarity index 100% rename from jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingService.java rename to quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingService.java diff --git a/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingServiceBean.java b/quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingServiceBean.java similarity index 100% rename from jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingServiceBean.java rename to quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/GreetingServiceBean.java diff --git a/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/ObjectFactory.java b/quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/ObjectFactory.java similarity index 100% rename from jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/ObjectFactory.java rename to quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/ObjectFactory.java diff --git a/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/Person.java b/quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/Person.java similarity index 100% rename from jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/Person.java rename to quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/Person.java diff --git a/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/package-info.java b/quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/package-info.java similarity index 100% rename from jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/package-info.java rename to quickstarts/jca-inflow-hornetq/src/main/java/org/switchyard/quickstarts/jca/inflow/package-info.java diff --git a/jca-inflow-hornetq/src/main/resources/META-INF/beans.xml b/quickstarts/jca-inflow-hornetq/src/main/resources/META-INF/beans.xml similarity index 100% rename from jca-inflow-hornetq/src/main/resources/META-INF/beans.xml rename to quickstarts/jca-inflow-hornetq/src/main/resources/META-INF/beans.xml diff --git a/jca-inflow-hornetq/src/main/resources/META-INF/forge.xml b/quickstarts/jca-inflow-hornetq/src/main/resources/META-INF/forge.xml similarity index 100% rename from jca-inflow-hornetq/src/main/resources/META-INF/forge.xml rename to quickstarts/jca-inflow-hornetq/src/main/resources/META-INF/forge.xml diff --git a/jca-inflow-hornetq/src/main/resources/META-INF/switchyard.xml b/quickstarts/jca-inflow-hornetq/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from jca-inflow-hornetq/src/main/resources/META-INF/switchyard.xml rename to quickstarts/jca-inflow-hornetq/src/main/resources/META-INF/switchyard.xml diff --git a/jca-inflow-hornetq/src/test/java/org/switchyard/quickstarts/jca/inflow/HornetQClient.java b/quickstarts/jca-inflow-hornetq/src/test/java/org/switchyard/quickstarts/jca/inflow/HornetQClient.java similarity index 100% rename from jca-inflow-hornetq/src/test/java/org/switchyard/quickstarts/jca/inflow/HornetQClient.java rename to quickstarts/jca-inflow-hornetq/src/test/java/org/switchyard/quickstarts/jca/inflow/HornetQClient.java diff --git a/jca-inflow-hornetq/src/test/java/org/switchyard/quickstarts/jca/inflow/JCAInflowBindingTest.java b/quickstarts/jca-inflow-hornetq/src/test/java/org/switchyard/quickstarts/jca/inflow/JCAInflowBindingTest.java similarity index 100% rename from jca-inflow-hornetq/src/test/java/org/switchyard/quickstarts/jca/inflow/JCAInflowBindingTest.java rename to quickstarts/jca-inflow-hornetq/src/test/java/org/switchyard/quickstarts/jca/inflow/JCAInflowBindingTest.java diff --git a/jca-inflow-hornetq/src/test/resources/META-INF/beans.xml b/quickstarts/jca-inflow-hornetq/src/test/resources/META-INF/beans.xml similarity index 100% rename from jca-inflow-hornetq/src/test/resources/META-INF/beans.xml rename to quickstarts/jca-inflow-hornetq/src/test/resources/META-INF/beans.xml diff --git a/jca-inflow-hornetq/src/test/resources/arquillian.xml b/quickstarts/jca-inflow-hornetq/src/test/resources/arquillian.xml similarity index 100% rename from jca-inflow-hornetq/src/test/resources/arquillian.xml rename to quickstarts/jca-inflow-hornetq/src/test/resources/arquillian.xml diff --git a/jca-inflow-hornetq/unconfig.cli b/quickstarts/jca-inflow-hornetq/unconfig.cli similarity index 100% rename from jca-inflow-hornetq/unconfig.cli rename to quickstarts/jca-inflow-hornetq/unconfig.cli diff --git a/jca-outbound-activemq/Readme.md b/quickstarts/jca-outbound-activemq/Readme.md similarity index 100% rename from jca-outbound-activemq/Readme.md rename to quickstarts/jca-outbound-activemq/Readme.md diff --git a/jca-outbound-activemq/config.cli b/quickstarts/jca-outbound-activemq/config.cli similarity index 100% rename from jca-outbound-activemq/config.cli rename to quickstarts/jca-outbound-activemq/config.cli diff --git a/jca-outbound-activemq/jca-outbound-activemq.jpg b/quickstarts/jca-outbound-activemq/jca-outbound-activemq.jpg similarity index 100% rename from jca-outbound-activemq/jca-outbound-activemq.jpg rename to quickstarts/jca-outbound-activemq/jca-outbound-activemq.jpg diff --git a/quickstarts/jca-outbound-activemq/pom.xml b/quickstarts/jca-outbound-activemq/pom.xml new file mode 100644 index 000000000..23f27f049 --- /dev/null +++ b/quickstarts/jca-outbound-activemq/pom.xml @@ -0,0 +1,263 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-jca-outbound-activemq + 2.1.0-SNAPSHOT + SwitchYard Quickstart: jca-outbound-activemq + Quickstart : JCA Outbound Binding for ActiveMQ + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + true + true + 9999 + 1.6 + 1.6 + 1.3.1 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-jca + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-activemq + test + + + org.apache.activemq + activemq-rar + rar + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + + + org.apache.activemq + activemq-client + + + org.jboss.as + jboss-as-arquillian-container-remote + test + + + org.switchyard.quickstarts + switchyard-quickstart-testutil + test + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy-activemq + install + + deploy-artifact + + + org.apache.activemq + activemq-rar + activemq-ra.rar + + + + + + ${deploy-rar.skip} + + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy-activemq + clean + + undeploy + + + activemq-ra.rar + + + + + + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.jca.outbound.ActiveMQClient + + BREAD + PIZZA + JAM + POTATO + MILK + JAM + TOYODA RUV4 2008 SILVER + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${skipTests} + + config.cli + unconfig.cli + ${project.build.directory}/${project.build.finalName}.jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + deploy-rar + + false + + + + wildfly + + 9990 + + + + diff --git a/jca-outbound-activemq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderService.java b/quickstarts/jca-outbound-activemq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderService.java similarity index 100% rename from jca-outbound-activemq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderService.java rename to quickstarts/jca-outbound-activemq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderService.java diff --git a/jca-outbound-activemq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderServiceBean.java b/quickstarts/jca-outbound-activemq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderServiceBean.java similarity index 100% rename from jca-outbound-activemq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderServiceBean.java rename to quickstarts/jca-outbound-activemq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderServiceBean.java diff --git a/jca-outbound-activemq/src/main/resources/META-INF/beans.xml b/quickstarts/jca-outbound-activemq/src/main/resources/META-INF/beans.xml similarity index 100% rename from jca-outbound-activemq/src/main/resources/META-INF/beans.xml rename to quickstarts/jca-outbound-activemq/src/main/resources/META-INF/beans.xml diff --git a/jca-outbound-activemq/src/main/resources/META-INF/forge.xml b/quickstarts/jca-outbound-activemq/src/main/resources/META-INF/forge.xml similarity index 100% rename from jca-outbound-activemq/src/main/resources/META-INF/forge.xml rename to quickstarts/jca-outbound-activemq/src/main/resources/META-INF/forge.xml diff --git a/jca-outbound-activemq/src/main/resources/META-INF/jboss-deployment-structure.xml b/quickstarts/jca-outbound-activemq/src/main/resources/META-INF/jboss-deployment-structure.xml similarity index 100% rename from jca-outbound-activemq/src/main/resources/META-INF/jboss-deployment-structure.xml rename to quickstarts/jca-outbound-activemq/src/main/resources/META-INF/jboss-deployment-structure.xml diff --git a/jca-outbound-activemq/src/main/resources/META-INF/switchyard.xml b/quickstarts/jca-outbound-activemq/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from jca-outbound-activemq/src/main/resources/META-INF/switchyard.xml rename to quickstarts/jca-outbound-activemq/src/main/resources/META-INF/switchyard.xml diff --git a/jca-outbound-activemq/src/test/java/org/switchyard/quickstarts/jca/outbound/ActiveMQClient.java b/quickstarts/jca-outbound-activemq/src/test/java/org/switchyard/quickstarts/jca/outbound/ActiveMQClient.java similarity index 100% rename from jca-outbound-activemq/src/test/java/org/switchyard/quickstarts/jca/outbound/ActiveMQClient.java rename to quickstarts/jca-outbound-activemq/src/test/java/org/switchyard/quickstarts/jca/outbound/ActiveMQClient.java diff --git a/jca-outbound-activemq/src/test/java/org/switchyard/quickstarts/jca/outbound/JCAOutboundBindingTest.java b/quickstarts/jca-outbound-activemq/src/test/java/org/switchyard/quickstarts/jca/outbound/JCAOutboundBindingTest.java similarity index 100% rename from jca-outbound-activemq/src/test/java/org/switchyard/quickstarts/jca/outbound/JCAOutboundBindingTest.java rename to quickstarts/jca-outbound-activemq/src/test/java/org/switchyard/quickstarts/jca/outbound/JCAOutboundBindingTest.java diff --git a/jca-outbound-activemq/src/test/resources/META-INF/beans.xml b/quickstarts/jca-outbound-activemq/src/test/resources/META-INF/beans.xml similarity index 100% rename from jca-outbound-activemq/src/test/resources/META-INF/beans.xml rename to quickstarts/jca-outbound-activemq/src/test/resources/META-INF/beans.xml diff --git a/jca-outbound-activemq/src/test/resources/arquillian.xml b/quickstarts/jca-outbound-activemq/src/test/resources/arquillian.xml similarity index 100% rename from jca-outbound-activemq/src/test/resources/arquillian.xml rename to quickstarts/jca-outbound-activemq/src/test/resources/arquillian.xml diff --git a/jca-outbound-activemq/unconfig.cli b/quickstarts/jca-outbound-activemq/unconfig.cli similarity index 100% rename from jca-outbound-activemq/unconfig.cli rename to quickstarts/jca-outbound-activemq/unconfig.cli diff --git a/quickstarts/jca-outbound-hornetq/Readme.md b/quickstarts/jca-outbound-hornetq/Readme.md new file mode 100644 index 000000000..c85e84cbd --- /dev/null +++ b/quickstarts/jca-outbound-hornetq/Readme.md @@ -0,0 +1,106 @@ +Introduction +============ +This quickstart demonstrates the usage of the JCA Component and it's reference binding feature, +by binding to a HornetQ Queue. When service is invoked the message will be sent to the queue. +This quickstart also has a service binding to a HornetQ Queue. When you send a message into +OrderService queue, corresponding OrderServiceBean#process() will be called. And then +OrderServiceBean will forward it to the ShippingQueue or FillingStockQueue through the reference bindings. + + +EAP +---------- +1. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy + +4. Execute HornetQClient + + mvn exec:java + +5. Check the output from the client. + +6. Undeploy the quickstart: + + mvn clean -Pdeploy + + +Wildfly +---------- +1. Start Wildfly in standalone-full mode: + + ${AS}/bin/standalone.sh -server-config standalone-full.xml + +2. Create an application user: + + ${AS}/bin/add-user.sh -a --user guest --password guestp.1 --group guest + +3. Build and deploy the quickstart + + mvn install -Pdeploy -Pwildfly + +4. Execute HornetQClient + + mvn exec:java -Pwildfly + +5. Check the output from the client. + +6. Undeploy the quickstart: + + mvn clean -Pdeploy -Pwildfly + + +Karaf +---------- +No Karaf feature is present for this quickstart. + + + +Expected Results +================ +``` +[INFO] --- exec-maven-plugin:1.2:java (default-cli) @ switchyard-quickstart-jca-outbound-hornetq --- +* * * SHIPPING ORDERS * * * + - JAM + - MILK + - BREAD + - JAM + +* * * PENDING ORDERS (FILLING STOCK) * * * + - PIZZA + - POTATO + - TOYODA RUV4 2008 SILVER +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +``` + +Running a functional test +========================= + +Since this quickstart requires Java EE environment, the functional test +"JCAOutboundBindingTest" does not run by default. You need to execute it manually +by following steps. + +1. Build the quickstart: + + mvn clean package + +2. Start EAP in standalone-full mode: + + ${AS}/bin/standalone.sh --server-config=standalone-full.xml + +3. Execute the test: + + mvn test -DskipTests=false + +## Further Reading + +1. [JCA Bindings Documentation](https://docs.jboss.org/author/display/SWITCHYARD/JCA) diff --git a/jca-outbound-hornetq/config.cli b/quickstarts/jca-outbound-hornetq/config.cli similarity index 100% rename from jca-outbound-hornetq/config.cli rename to quickstarts/jca-outbound-hornetq/config.cli diff --git a/jca-outbound-hornetq/jca-outbound-hornetq.jpg b/quickstarts/jca-outbound-hornetq/jca-outbound-hornetq.jpg similarity index 100% rename from jca-outbound-hornetq/jca-outbound-hornetq.jpg rename to quickstarts/jca-outbound-hornetq/jca-outbound-hornetq.jpg diff --git a/quickstarts/jca-outbound-hornetq/pom.xml b/quickstarts/jca-outbound-hornetq/pom.xml new file mode 100644 index 000000000..8c047474c --- /dev/null +++ b/quickstarts/jca-outbound-hornetq/pom.xml @@ -0,0 +1,286 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-jca-outbound-hornetq + 2.1.0-SNAPSHOT + SwitchYard Quickstart: jca-outbound-hornetq + Quickstart : JCA Outbound Binding for HornetQ + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + true + true + 9999 + 1.6 + 1.6 + 1.0.2.Final + 2.4.1.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-jca + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + test + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + test + + + org.jboss.as + jboss-as-arquillian-container-remote + test + + + org.switchyard.quickstarts + switchyard-quickstart-testutil + test + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + + + + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.jca.outbound.HornetQClient + + BREAD + PIZZA + JAM + POTATO + MILK + JAM + TOYODA RUV4 2008 SILVER + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${skipTests} + + config.cli + unconfig.cli + guest + guestp.1 + ${project.build.directory}/${project.build.finalName}.jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + wildfly + + 9990 + true + 8080 + + + + org.hornetq + hornetq-core-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-client + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-jms-server + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-commons + ${version.wildfly.hornetq} + test + + + org.hornetq + hornetq-journal + ${version.wildfly.hornetq} + test + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + hornetqmixin.port + 8080 + + + hornetqmixin.http.upgrade.enabled + true + + + + + + + + + diff --git a/jca-outbound-hornetq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderService.java b/quickstarts/jca-outbound-hornetq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderService.java similarity index 100% rename from jca-outbound-hornetq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderService.java rename to quickstarts/jca-outbound-hornetq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderService.java diff --git a/jca-outbound-hornetq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderServiceBean.java b/quickstarts/jca-outbound-hornetq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderServiceBean.java similarity index 100% rename from jca-outbound-hornetq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderServiceBean.java rename to quickstarts/jca-outbound-hornetq/src/main/java/org/switchyard/quickstarts/jca/outbound/OrderServiceBean.java diff --git a/jca-outbound-hornetq/src/main/resources/META-INF/beans.xml b/quickstarts/jca-outbound-hornetq/src/main/resources/META-INF/beans.xml similarity index 100% rename from jca-outbound-hornetq/src/main/resources/META-INF/beans.xml rename to quickstarts/jca-outbound-hornetq/src/main/resources/META-INF/beans.xml diff --git a/jca-outbound-hornetq/src/main/resources/META-INF/forge.xml b/quickstarts/jca-outbound-hornetq/src/main/resources/META-INF/forge.xml similarity index 100% rename from jca-outbound-hornetq/src/main/resources/META-INF/forge.xml rename to quickstarts/jca-outbound-hornetq/src/main/resources/META-INF/forge.xml diff --git a/jca-outbound-hornetq/src/main/resources/META-INF/switchyard.xml b/quickstarts/jca-outbound-hornetq/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from jca-outbound-hornetq/src/main/resources/META-INF/switchyard.xml rename to quickstarts/jca-outbound-hornetq/src/main/resources/META-INF/switchyard.xml diff --git a/jca-outbound-hornetq/src/test/java/org/switchyard/quickstarts/jca/outbound/HornetQClient.java b/quickstarts/jca-outbound-hornetq/src/test/java/org/switchyard/quickstarts/jca/outbound/HornetQClient.java similarity index 100% rename from jca-outbound-hornetq/src/test/java/org/switchyard/quickstarts/jca/outbound/HornetQClient.java rename to quickstarts/jca-outbound-hornetq/src/test/java/org/switchyard/quickstarts/jca/outbound/HornetQClient.java diff --git a/jca-outbound-hornetq/src/test/java/org/switchyard/quickstarts/jca/outbound/JCAOutboundBindingTest.java b/quickstarts/jca-outbound-hornetq/src/test/java/org/switchyard/quickstarts/jca/outbound/JCAOutboundBindingTest.java similarity index 100% rename from jca-outbound-hornetq/src/test/java/org/switchyard/quickstarts/jca/outbound/JCAOutboundBindingTest.java rename to quickstarts/jca-outbound-hornetq/src/test/java/org/switchyard/quickstarts/jca/outbound/JCAOutboundBindingTest.java diff --git a/jca-outbound-hornetq/src/test/resources/META-INF/beans.xml b/quickstarts/jca-outbound-hornetq/src/test/resources/META-INF/beans.xml similarity index 100% rename from jca-outbound-hornetq/src/test/resources/META-INF/beans.xml rename to quickstarts/jca-outbound-hornetq/src/test/resources/META-INF/beans.xml diff --git a/jca-outbound-hornetq/src/test/resources/arquillian.xml b/quickstarts/jca-outbound-hornetq/src/test/resources/arquillian.xml similarity index 100% rename from jca-outbound-hornetq/src/test/resources/arquillian.xml rename to quickstarts/jca-outbound-hornetq/src/test/resources/arquillian.xml diff --git a/jca-outbound-hornetq/unconfig.cli b/quickstarts/jca-outbound-hornetq/unconfig.cli similarity index 100% rename from jca-outbound-hornetq/unconfig.cli rename to quickstarts/jca-outbound-hornetq/unconfig.cli diff --git a/quickstarts/pom.xml b/quickstarts/pom.xml new file mode 100644 index 000000000..a32767650 --- /dev/null +++ b/quickstarts/pom.xml @@ -0,0 +1,146 @@ + + + + 4.0.0 + + org.switchyard + switchyard-parent + 2.1.0-SNAPSHOT + .. + + org.switchyard.quickstarts + switchyard-quickstart-parent + pom + SwitchYard Quickstart: quickstarts + Quickstarts repository for SwitchYard + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + https://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + 1.6 + 1.6 + + + testutil + bean-service + bpel-jms-binding + bpel-loan-approval + bpel-say-hello + bpel-simple-correlation + bpel-xts-subordinate-wsba + bpel-xts-wsat + bpm-service + camel-atom-binding + camel-file-binding + camel-cxf-binding + camel-jaxb + camel-hl7 + camel-amqp-binding + camel-ftp-binding + camel-jms-binding + camel-netty-binding + camel-quartz-binding + camel-rss-binding + camel-jpa-binding + camel-sql-binding + camel-mail-binding + camel-mqtt-binding + camel-sap-binding + camel-service + camel-soap-proxy + camel-bus-cdi + camel-bindy + camel-saxon + ear-deployment + http-binding + remote-invoker + rest-binding + rules-camel-cbr + rules-interview + rules-interview-container + rules-interview-dtable + soap-addressing + soap-attachment + soap-binding-rpc + soap-mtom + jca-inflow-hornetq + jca-outbound-hornetq + jca-inflow-activemq + jca-outbound-activemq + transform-dozer + transform-jaxb + transform-json + transform-smooks + transform-xslt + validate-xml + demos/helpdesk + demos/library + demos/orders + demos/webapp-deploy + demos/multiApp + demos/policy-security-basic + demos/policy-security-cert + demos/policy-security-saml + demos/policy-security-wss-signencrypt + demos/policy-security-wss-username + demos/policy-transaction + demos/cluster + demos/security-propagation + demos/transaction-propagation + + + + + + + assembly + + + + assembly + + + + diff --git a/remote-invoker/Readme.md b/quickstarts/remote-invoker/Readme.md similarity index 100% rename from remote-invoker/Readme.md rename to quickstarts/remote-invoker/Readme.md diff --git a/quickstarts/remote-invoker/pom.xml b/quickstarts/remote-invoker/pom.xml new file mode 100644 index 000000000..af71a1a98 --- /dev/null +++ b/quickstarts/remote-invoker/pom.xml @@ -0,0 +1,264 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-remote-invoker + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: remote-invoker + Quickstart : Remote Invoker + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.remote.invoker + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard.components + switchyard-component-sca + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.remoteinvoker.RemoteClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.sca.client.port + 8181 + + + + + + + + + wildfly + + 9990 + + + + diff --git a/remote-invoker/remote-invoker.jpg b/quickstarts/remote-invoker/remote-invoker.jpg similarity index 100% rename from remote-invoker/remote-invoker.jpg rename to quickstarts/remote-invoker/remote-invoker.jpg diff --git a/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Application.java b/quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Application.java similarity index 100% rename from remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Application.java rename to quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Application.java diff --git a/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Car.java b/quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Car.java similarity index 100% rename from remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Car.java rename to quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Car.java diff --git a/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/CreditCheck.java b/quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/CreditCheck.java similarity index 100% rename from remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/CreditCheck.java rename to quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/CreditCheck.java diff --git a/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Deal.java b/quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Deal.java similarity index 100% rename from remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Deal.java rename to quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Deal.java diff --git a/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Dealer.java b/quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Dealer.java similarity index 100% rename from remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Dealer.java rename to quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Dealer.java diff --git a/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/DealerBean.java b/quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/DealerBean.java similarity index 100% rename from remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/DealerBean.java rename to quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/DealerBean.java diff --git a/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Offer.java b/quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Offer.java similarity index 100% rename from remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Offer.java rename to quickstarts/remote-invoker/src/main/java/org/switchyard/quickstarts/remoteinvoker/Offer.java diff --git a/remote-invoker/src/main/resources/META-INF/beans.xml b/quickstarts/remote-invoker/src/main/resources/META-INF/beans.xml similarity index 100% rename from remote-invoker/src/main/resources/META-INF/beans.xml rename to quickstarts/remote-invoker/src/main/resources/META-INF/beans.xml diff --git a/remote-invoker/src/main/resources/META-INF/switchyard.xml b/quickstarts/remote-invoker/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from remote-invoker/src/main/resources/META-INF/switchyard.xml rename to quickstarts/remote-invoker/src/main/resources/META-INF/switchyard.xml diff --git a/remote-invoker/src/main/resources/RulesComponent.drl b/quickstarts/remote-invoker/src/main/resources/RulesComponent.drl similarity index 100% rename from remote-invoker/src/main/resources/RulesComponent.drl rename to quickstarts/remote-invoker/src/main/resources/RulesComponent.drl diff --git a/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/CreditCheckTest.java b/quickstarts/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/CreditCheckTest.java similarity index 100% rename from remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/CreditCheckTest.java rename to quickstarts/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/CreditCheckTest.java diff --git a/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/DealerTest.java b/quickstarts/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/DealerTest.java similarity index 100% rename from remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/DealerTest.java rename to quickstarts/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/DealerTest.java diff --git a/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/RemoteClient.java b/quickstarts/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/RemoteClient.java similarity index 100% rename from remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/RemoteClient.java rename to quickstarts/remote-invoker/src/test/java/org/switchyard/quickstarts/remoteinvoker/RemoteClient.java diff --git a/remote-invoker/src/test/resources/META-INF/beans.xml b/quickstarts/remote-invoker/src/test/resources/META-INF/beans.xml similarity index 100% rename from remote-invoker/src/test/resources/META-INF/beans.xml rename to quickstarts/remote-invoker/src/test/resources/META-INF/beans.xml diff --git a/rest-binding/Readme.md b/quickstarts/rest-binding/Readme.md similarity index 100% rename from rest-binding/Readme.md rename to quickstarts/rest-binding/Readme.md diff --git a/quickstarts/rest-binding/pom.xml b/quickstarts/rest-binding/pom.xml new file mode 100644 index 000000000..c538eb731 --- /dev/null +++ b/quickstarts/rest-binding/pom.xml @@ -0,0 +1,280 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-rest-binding + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: rest-binding + Quickstart : RESTEasy Binding + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.rest.binding + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-resteasy + + + org.jboss.as + jboss-as-jaxrs + + + org.jboss.resteasy + resteasy-jaxrs + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-netty + test + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + java + test + org.switchyard.quickstarts.rest.binding.RESTEasyBindingClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.resteasy.client.port + 8181 + + + + + + + + + wildfly + + 9990 + + + + diff --git a/rest-binding/rest-binding.jpg b/quickstarts/rest-binding/rest-binding.jpg similarity index 100% rename from rest-binding/rest-binding.jpg rename to quickstarts/rest-binding/rest-binding.jpg diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ApiError.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ApiError.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ApiError.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ApiError.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/CustomComposer.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/CustomComposer.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/CustomComposer.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/CustomComposer.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Item.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Item.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Item.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Item.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ItemNotFoundException.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ItemNotFoundException.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ItemNotFoundException.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ItemNotFoundException.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ItemNotFoundExceptionMapper.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ItemNotFoundExceptionMapper.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ItemNotFoundExceptionMapper.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/ItemNotFoundExceptionMapper.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/MyClientErrorInterceptor.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/MyClientErrorInterceptor.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/MyClientErrorInterceptor.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/MyClientErrorInterceptor.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/MyClientExecutionInterceptor.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/MyClientExecutionInterceptor.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/MyClientExecutionInterceptor.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/MyClientExecutionInterceptor.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Order.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Order.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Order.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Order.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderItem.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderItem.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderItem.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderItem.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderResource.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderResource.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderResource.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderResource.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderService.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderService.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderService.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderService.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderServiceImpl.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderServiceImpl.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderServiceImpl.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/OrderServiceImpl.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/TestResource.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/TestResource.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/TestResource.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/TestResource.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Transformers.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Transformers.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Transformers.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Transformers.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Warehouse.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Warehouse.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Warehouse.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/Warehouse.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseRef.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseRef.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseRef.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseRef.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseResource.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseResource.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseResource.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseResource.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseResourceRef.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseResourceRef.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseResourceRef.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseResourceRef.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseService.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseService.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseService.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseService.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseServiceImpl.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseServiceImpl.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseServiceImpl.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WarehouseServiceImpl.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WrongRequestArgsException.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WrongRequestArgsException.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WrongRequestArgsException.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WrongRequestArgsException.java diff --git a/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WrongRequestArgsExceptionMapper.java b/quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WrongRequestArgsExceptionMapper.java similarity index 100% rename from rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WrongRequestArgsExceptionMapper.java rename to quickstarts/rest-binding/src/main/java/org/switchyard/quickstarts/rest/binding/WrongRequestArgsExceptionMapper.java diff --git a/rest-binding/src/main/resources/META-INF/beans.xml b/quickstarts/rest-binding/src/main/resources/META-INF/beans.xml similarity index 100% rename from rest-binding/src/main/resources/META-INF/beans.xml rename to quickstarts/rest-binding/src/main/resources/META-INF/beans.xml diff --git a/rest-binding/src/main/resources/META-INF/switchyard.xml b/quickstarts/rest-binding/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from rest-binding/src/main/resources/META-INF/switchyard.xml rename to quickstarts/rest-binding/src/main/resources/META-INF/switchyard.xml diff --git a/rest-binding/src/test/java/org/switchyard/quickstarts/rest/binding/RESTEasyBindingClient.java b/quickstarts/rest-binding/src/test/java/org/switchyard/quickstarts/rest/binding/RESTEasyBindingClient.java similarity index 100% rename from rest-binding/src/test/java/org/switchyard/quickstarts/rest/binding/RESTEasyBindingClient.java rename to quickstarts/rest-binding/src/test/java/org/switchyard/quickstarts/rest/binding/RESTEasyBindingClient.java diff --git a/rest-binding/src/test/java/org/switchyard/quickstarts/rest/binding/RESTEasyBindingTest.java b/quickstarts/rest-binding/src/test/java/org/switchyard/quickstarts/rest/binding/RESTEasyBindingTest.java similarity index 100% rename from rest-binding/src/test/java/org/switchyard/quickstarts/rest/binding/RESTEasyBindingTest.java rename to quickstarts/rest-binding/src/test/java/org/switchyard/quickstarts/rest/binding/RESTEasyBindingTest.java diff --git a/rest-binding/src/test/resources/META-INF/beans.xml b/quickstarts/rest-binding/src/test/resources/META-INF/beans.xml similarity index 100% rename from rest-binding/src/test/resources/META-INF/beans.xml rename to quickstarts/rest-binding/src/test/resources/META-INF/beans.xml diff --git a/rest-binding/src/test/resources/META-INF/services/org.switchyard.component.resteasy.resource.ResourcePublisher b/quickstarts/rest-binding/src/test/resources/META-INF/services/org.switchyard.component.resteasy.resource.ResourcePublisher similarity index 100% rename from rest-binding/src/test/resources/META-INF/services/org.switchyard.component.resteasy.resource.ResourcePublisher rename to quickstarts/rest-binding/src/test/resources/META-INF/services/org.switchyard.component.resteasy.resource.ResourcePublisher diff --git a/rest-binding/src/test/resources/log4j.xml b/quickstarts/rest-binding/src/test/resources/log4j.xml similarity index 100% rename from rest-binding/src/test/resources/log4j.xml rename to quickstarts/rest-binding/src/test/resources/log4j.xml diff --git a/rules-camel-cbr/Readme.md b/quickstarts/rules-camel-cbr/Readme.md similarity index 100% rename from rules-camel-cbr/Readme.md rename to quickstarts/rules-camel-cbr/Readme.md diff --git a/quickstarts/rules-camel-cbr/pom.xml b/quickstarts/rules-camel-cbr/pom.xml new file mode 100644 index 000000000..f493a0806 --- /dev/null +++ b/quickstarts/rules-camel-cbr/pom.xml @@ -0,0 +1,268 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-rules-camel-cbr + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: rules-camel-cbr + Quickstart : Rules+Camel Content-Based Router + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.rules.camel.cbr + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.rules.camel.cbr.RulesCamelCBRClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.sca.client.port + 8181 + + + + + + + + + wildfly + + 9990 + + + + diff --git a/rules-camel-cbr/rules-camel-cbr.jpg b/quickstarts/rules-camel-cbr/rules-camel-cbr.jpg similarity index 100% rename from rules-camel-cbr/rules-camel-cbr.jpg rename to quickstarts/rules-camel-cbr/rules-camel-cbr.jpg diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/BlueService.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/BlueService.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/BlueService.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/BlueService.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/BlueServiceBean.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/BlueServiceBean.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/BlueServiceBean.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/BlueServiceBean.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/Box.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/Box.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/Box.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/Box.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/DestinationService.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/DestinationService.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/DestinationService.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/DestinationService.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/GreenService.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/GreenService.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/GreenService.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/GreenService.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/GreenServiceBean.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/GreenServiceBean.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/GreenServiceBean.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/GreenServiceBean.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RedService.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RedService.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RedService.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RedService.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RedServiceBean.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RedServiceBean.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RedServiceBean.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RedServiceBean.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RoutingService.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RoutingService.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RoutingService.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/RoutingService.java diff --git a/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/Widget.java b/quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/Widget.java similarity index 100% rename from rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/Widget.java rename to quickstarts/rules-camel-cbr/src/main/java/org/switchyard/quickstarts/rules/camel/cbr/Widget.java diff --git a/rules-camel-cbr/src/main/resources/META-INF/DestinationServiceRules.drl b/quickstarts/rules-camel-cbr/src/main/resources/META-INF/DestinationServiceRules.drl similarity index 100% rename from rules-camel-cbr/src/main/resources/META-INF/DestinationServiceRules.drl rename to quickstarts/rules-camel-cbr/src/main/resources/META-INF/DestinationServiceRules.drl diff --git a/rules-camel-cbr/src/main/resources/META-INF/beans.xml b/quickstarts/rules-camel-cbr/src/main/resources/META-INF/beans.xml similarity index 100% rename from rules-camel-cbr/src/main/resources/META-INF/beans.xml rename to quickstarts/rules-camel-cbr/src/main/resources/META-INF/beans.xml diff --git a/rules-camel-cbr/src/main/resources/META-INF/forge.xml b/quickstarts/rules-camel-cbr/src/main/resources/META-INF/forge.xml similarity index 100% rename from rules-camel-cbr/src/main/resources/META-INF/forge.xml rename to quickstarts/rules-camel-cbr/src/main/resources/META-INF/forge.xml diff --git a/rules-camel-cbr/src/main/resources/META-INF/route.xml b/quickstarts/rules-camel-cbr/src/main/resources/META-INF/route.xml similarity index 100% rename from rules-camel-cbr/src/main/resources/META-INF/route.xml rename to quickstarts/rules-camel-cbr/src/main/resources/META-INF/route.xml diff --git a/rules-camel-cbr/src/main/resources/META-INF/switchyard.xml b/quickstarts/rules-camel-cbr/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from rules-camel-cbr/src/main/resources/META-INF/switchyard.xml rename to quickstarts/rules-camel-cbr/src/main/resources/META-INF/switchyard.xml diff --git a/rules-camel-cbr/src/test/java/org/switchyard/quickstarts/rules/camel/cbr/RulesCamelCBRClient.java b/quickstarts/rules-camel-cbr/src/test/java/org/switchyard/quickstarts/rules/camel/cbr/RulesCamelCBRClient.java similarity index 100% rename from rules-camel-cbr/src/test/java/org/switchyard/quickstarts/rules/camel/cbr/RulesCamelCBRClient.java rename to quickstarts/rules-camel-cbr/src/test/java/org/switchyard/quickstarts/rules/camel/cbr/RulesCamelCBRClient.java diff --git a/rules-camel-cbr/src/test/java/org/switchyard/quickstarts/rules/camel/cbr/RulesCamelCBRTest.java b/quickstarts/rules-camel-cbr/src/test/java/org/switchyard/quickstarts/rules/camel/cbr/RulesCamelCBRTest.java similarity index 100% rename from rules-camel-cbr/src/test/java/org/switchyard/quickstarts/rules/camel/cbr/RulesCamelCBRTest.java rename to quickstarts/rules-camel-cbr/src/test/java/org/switchyard/quickstarts/rules/camel/cbr/RulesCamelCBRTest.java diff --git a/rules-camel-cbr/src/test/resources/META-INF/beans.xml b/quickstarts/rules-camel-cbr/src/test/resources/META-INF/beans.xml similarity index 100% rename from rules-camel-cbr/src/test/resources/META-INF/beans.xml rename to quickstarts/rules-camel-cbr/src/test/resources/META-INF/beans.xml diff --git a/rules-camel-cbr/src/test/resources/log4j.xml b/quickstarts/rules-camel-cbr/src/test/resources/log4j.xml similarity index 100% rename from rules-camel-cbr/src/test/resources/log4j.xml rename to quickstarts/rules-camel-cbr/src/test/resources/log4j.xml diff --git a/rules-interview-container/Readme.md b/quickstarts/rules-interview-container/Readme.md similarity index 100% rename from rules-interview-container/Readme.md rename to quickstarts/rules-interview-container/Readme.md diff --git a/quickstarts/rules-interview-container/pom.xml b/quickstarts/rules-interview-container/pom.xml new file mode 100644 index 000000000..95bbed2ee --- /dev/null +++ b/quickstarts/rules-interview-container/pom.xml @@ -0,0 +1,265 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-rules-interview-container + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: rules-interview-container + Quickstart : Rules Interview (Container) + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.rules.interview.container + true + 9999 + 1.6 + 1.6 + 1.3.1 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard.components + switchyard-component-soap + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.rules.interview.RulesInterviewClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/rules-interview-container/rules-interview-container.jpg b/quickstarts/rules-interview-container/rules-interview-container.jpg similarity index 100% rename from rules-interview-container/rules-interview-container.jpg rename to quickstarts/rules-interview-container/rules-interview-container.jpg diff --git a/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java b/quickstarts/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java similarity index 100% rename from rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java rename to quickstarts/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java diff --git a/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java b/quickstarts/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java similarity index 100% rename from rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java rename to quickstarts/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java diff --git a/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java b/quickstarts/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java similarity index 100% rename from rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java rename to quickstarts/rules-interview-container/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java diff --git a/rules-interview-container/src/main/resources/META-INF/Interview.wsdl b/quickstarts/rules-interview-container/src/main/resources/META-INF/Interview.wsdl similarity index 100% rename from rules-interview-container/src/main/resources/META-INF/Interview.wsdl rename to quickstarts/rules-interview-container/src/main/resources/META-INF/Interview.wsdl diff --git a/rules-interview-container/src/main/resources/META-INF/beans.xml b/quickstarts/rules-interview-container/src/main/resources/META-INF/beans.xml similarity index 100% rename from rules-interview-container/src/main/resources/META-INF/beans.xml rename to quickstarts/rules-interview-container/src/main/resources/META-INF/beans.xml diff --git a/rules-interview-container/src/main/resources/META-INF/forge.xml b/quickstarts/rules-interview-container/src/main/resources/META-INF/forge.xml similarity index 100% rename from rules-interview-container/src/main/resources/META-INF/forge.xml rename to quickstarts/rules-interview-container/src/main/resources/META-INF/forge.xml diff --git a/rules-interview-container/src/main/resources/META-INF/kmodule.xml b/quickstarts/rules-interview-container/src/main/resources/META-INF/kmodule.xml similarity index 100% rename from rules-interview-container/src/main/resources/META-INF/kmodule.xml rename to quickstarts/rules-interview-container/src/main/resources/META-INF/kmodule.xml diff --git a/rules-interview-container/src/main/resources/META-INF/switchyard.xml b/quickstarts/rules-interview-container/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from rules-interview-container/src/main/resources/META-INF/switchyard.xml rename to quickstarts/rules-interview-container/src/main/resources/META-INF/switchyard.xml diff --git a/rules-interview-container/src/main/resources/org/switchyard/quickstarts/rules/interview/Interview.drl b/quickstarts/rules-interview-container/src/main/resources/org/switchyard/quickstarts/rules/interview/Interview.drl similarity index 100% rename from rules-interview-container/src/main/resources/org/switchyard/quickstarts/rules/interview/Interview.drl rename to quickstarts/rules-interview-container/src/main/resources/org/switchyard/quickstarts/rules/interview/Interview.drl diff --git a/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java b/quickstarts/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java similarity index 100% rename from rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java rename to quickstarts/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java diff --git a/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java b/quickstarts/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java similarity index 100% rename from rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java rename to quickstarts/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java diff --git a/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java b/quickstarts/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java similarity index 100% rename from rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java rename to quickstarts/rules-interview-container/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java diff --git a/rules-interview-container/src/test/resources/META-INF/beans.xml b/quickstarts/rules-interview-container/src/test/resources/META-INF/beans.xml similarity index 100% rename from rules-interview-container/src/test/resources/META-INF/beans.xml rename to quickstarts/rules-interview-container/src/test/resources/META-INF/beans.xml diff --git a/rules-interview-container/src/test/resources/xml/soap-request-fail.xml b/quickstarts/rules-interview-container/src/test/resources/xml/soap-request-fail.xml similarity index 100% rename from rules-interview-container/src/test/resources/xml/soap-request-fail.xml rename to quickstarts/rules-interview-container/src/test/resources/xml/soap-request-fail.xml diff --git a/rules-interview-container/src/test/resources/xml/soap-request-pass.xml b/quickstarts/rules-interview-container/src/test/resources/xml/soap-request-pass.xml similarity index 100% rename from rules-interview-container/src/test/resources/xml/soap-request-pass.xml rename to quickstarts/rules-interview-container/src/test/resources/xml/soap-request-pass.xml diff --git a/rules-interview-container/src/test/resources/xml/soap-response-fail.xml b/quickstarts/rules-interview-container/src/test/resources/xml/soap-response-fail.xml similarity index 100% rename from rules-interview-container/src/test/resources/xml/soap-response-fail.xml rename to quickstarts/rules-interview-container/src/test/resources/xml/soap-response-fail.xml diff --git a/rules-interview-container/src/test/resources/xml/soap-response-pass.xml b/quickstarts/rules-interview-container/src/test/resources/xml/soap-response-pass.xml similarity index 100% rename from rules-interview-container/src/test/resources/xml/soap-response-pass.xml rename to quickstarts/rules-interview-container/src/test/resources/xml/soap-response-pass.xml diff --git a/rules-interview-dtable/Readme.md b/quickstarts/rules-interview-dtable/Readme.md similarity index 100% rename from rules-interview-dtable/Readme.md rename to quickstarts/rules-interview-dtable/Readme.md diff --git a/quickstarts/rules-interview-dtable/pom.xml b/quickstarts/rules-interview-dtable/pom.xml new file mode 100644 index 000000000..edf01cbf6 --- /dev/null +++ b/quickstarts/rules-interview-dtable/pom.xml @@ -0,0 +1,265 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-rules-interview-dtable + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: rules-interview-dtable + Quickstart : Rules Interview (Decision Table) + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.rules.interview.dtable + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard.components + switchyard-component-soap + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.rules.interview.RulesInterviewClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/rules-interview-dtable/rules-interview-dtable.jpg b/quickstarts/rules-interview-dtable/rules-interview-dtable.jpg similarity index 100% rename from rules-interview-dtable/rules-interview-dtable.jpg rename to quickstarts/rules-interview-dtable/rules-interview-dtable.jpg diff --git a/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java b/quickstarts/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java similarity index 100% rename from rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java rename to quickstarts/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java diff --git a/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java b/quickstarts/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java similarity index 100% rename from rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java rename to quickstarts/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java diff --git a/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java b/quickstarts/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java similarity index 100% rename from rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java rename to quickstarts/rules-interview-dtable/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java diff --git a/rules-interview-dtable/src/main/resources/META-INF/Interview.wsdl b/quickstarts/rules-interview-dtable/src/main/resources/META-INF/Interview.wsdl similarity index 100% rename from rules-interview-dtable/src/main/resources/META-INF/Interview.wsdl rename to quickstarts/rules-interview-dtable/src/main/resources/META-INF/Interview.wsdl diff --git a/rules-interview-dtable/src/main/resources/META-INF/Interview.xls b/quickstarts/rules-interview-dtable/src/main/resources/META-INF/Interview.xls similarity index 100% rename from rules-interview-dtable/src/main/resources/META-INF/Interview.xls rename to quickstarts/rules-interview-dtable/src/main/resources/META-INF/Interview.xls diff --git a/rules-interview-dtable/src/main/resources/META-INF/beans.xml b/quickstarts/rules-interview-dtable/src/main/resources/META-INF/beans.xml similarity index 100% rename from rules-interview-dtable/src/main/resources/META-INF/beans.xml rename to quickstarts/rules-interview-dtable/src/main/resources/META-INF/beans.xml diff --git a/rules-interview-dtable/src/main/resources/META-INF/forge.xml b/quickstarts/rules-interview-dtable/src/main/resources/META-INF/forge.xml similarity index 100% rename from rules-interview-dtable/src/main/resources/META-INF/forge.xml rename to quickstarts/rules-interview-dtable/src/main/resources/META-INF/forge.xml diff --git a/rules-interview-dtable/src/main/resources/META-INF/switchyard.xml b/quickstarts/rules-interview-dtable/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from rules-interview-dtable/src/main/resources/META-INF/switchyard.xml rename to quickstarts/rules-interview-dtable/src/main/resources/META-INF/switchyard.xml diff --git a/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java b/quickstarts/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java similarity index 100% rename from rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java rename to quickstarts/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java diff --git a/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java b/quickstarts/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java similarity index 100% rename from rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java rename to quickstarts/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java diff --git a/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java b/quickstarts/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java similarity index 100% rename from rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java rename to quickstarts/rules-interview-dtable/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java diff --git a/rules-interview-dtable/src/test/resources/META-INF/beans.xml b/quickstarts/rules-interview-dtable/src/test/resources/META-INF/beans.xml similarity index 100% rename from rules-interview-dtable/src/test/resources/META-INF/beans.xml rename to quickstarts/rules-interview-dtable/src/test/resources/META-INF/beans.xml diff --git a/rules-interview-dtable/src/test/resources/xml/soap-request-fail.xml b/quickstarts/rules-interview-dtable/src/test/resources/xml/soap-request-fail.xml similarity index 100% rename from rules-interview-dtable/src/test/resources/xml/soap-request-fail.xml rename to quickstarts/rules-interview-dtable/src/test/resources/xml/soap-request-fail.xml diff --git a/rules-interview-dtable/src/test/resources/xml/soap-request-pass.xml b/quickstarts/rules-interview-dtable/src/test/resources/xml/soap-request-pass.xml similarity index 100% rename from rules-interview-dtable/src/test/resources/xml/soap-request-pass.xml rename to quickstarts/rules-interview-dtable/src/test/resources/xml/soap-request-pass.xml diff --git a/rules-interview-dtable/src/test/resources/xml/soap-response-fail.xml b/quickstarts/rules-interview-dtable/src/test/resources/xml/soap-response-fail.xml similarity index 100% rename from rules-interview-dtable/src/test/resources/xml/soap-response-fail.xml rename to quickstarts/rules-interview-dtable/src/test/resources/xml/soap-response-fail.xml diff --git a/rules-interview-dtable/src/test/resources/xml/soap-response-pass.xml b/quickstarts/rules-interview-dtable/src/test/resources/xml/soap-response-pass.xml similarity index 100% rename from rules-interview-dtable/src/test/resources/xml/soap-response-pass.xml rename to quickstarts/rules-interview-dtable/src/test/resources/xml/soap-response-pass.xml diff --git a/rules-interview/Readme.md b/quickstarts/rules-interview/Readme.md similarity index 100% rename from rules-interview/Readme.md rename to quickstarts/rules-interview/Readme.md diff --git a/quickstarts/rules-interview/pom.xml b/quickstarts/rules-interview/pom.xml new file mode 100644 index 000000000..e58215a91 --- /dev/null +++ b/quickstarts/rules-interview/pom.xml @@ -0,0 +1,279 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-rules-interview + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: rules-interview + Quickstart : Rules Interview + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + jboss-public-repository + JBoss Public Maven Repository + http://repository.jboss.org/nexus/content/groups/public + + + + + jboss-public-repository + JBoss Public Maven Repository + http://repository.jboss.org/nexus/content/groups/public + + + + + ${project.groupId}.switchyard.rules.interview + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard.components + switchyard-component-soap + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.rules.interview.RulesInterviewClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/rules-interview/rules-interview.jpg b/quickstarts/rules-interview/rules-interview.jpg similarity index 100% rename from rules-interview/rules-interview.jpg rename to quickstarts/rules-interview/rules-interview.jpg diff --git a/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java b/quickstarts/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java similarity index 100% rename from rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java rename to quickstarts/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Applicant.java diff --git a/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java b/quickstarts/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java similarity index 100% rename from rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java rename to quickstarts/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Interview.java diff --git a/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java b/quickstarts/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java similarity index 100% rename from rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java rename to quickstarts/rules-interview/src/main/java/org/switchyard/quickstarts/rules/interview/Transformers.java diff --git a/rules-interview/src/main/resources/META-INF/Interview.drl b/quickstarts/rules-interview/src/main/resources/META-INF/Interview.drl similarity index 100% rename from rules-interview/src/main/resources/META-INF/Interview.drl rename to quickstarts/rules-interview/src/main/resources/META-INF/Interview.drl diff --git a/rules-interview/src/main/resources/META-INF/Interview.wsdl b/quickstarts/rules-interview/src/main/resources/META-INF/Interview.wsdl similarity index 100% rename from rules-interview/src/main/resources/META-INF/Interview.wsdl rename to quickstarts/rules-interview/src/main/resources/META-INF/Interview.wsdl diff --git a/rules-interview/src/main/resources/META-INF/beans.xml b/quickstarts/rules-interview/src/main/resources/META-INF/beans.xml similarity index 100% rename from rules-interview/src/main/resources/META-INF/beans.xml rename to quickstarts/rules-interview/src/main/resources/META-INF/beans.xml diff --git a/rules-interview/src/main/resources/META-INF/forge.xml b/quickstarts/rules-interview/src/main/resources/META-INF/forge.xml similarity index 100% rename from rules-interview/src/main/resources/META-INF/forge.xml rename to quickstarts/rules-interview/src/main/resources/META-INF/forge.xml diff --git a/rules-interview/src/main/resources/META-INF/switchyard.xml b/quickstarts/rules-interview/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from rules-interview/src/main/resources/META-INF/switchyard.xml rename to quickstarts/rules-interview/src/main/resources/META-INF/switchyard.xml diff --git a/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java b/quickstarts/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java similarity index 100% rename from rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java rename to quickstarts/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewClient.java diff --git a/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java b/quickstarts/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java similarity index 100% rename from rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java rename to quickstarts/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/RulesInterviewTest.java diff --git a/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java b/quickstarts/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java similarity index 100% rename from rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java rename to quickstarts/rules-interview/src/test/java/org/switchyard/quickstarts/rules/interview/WebServiceTest.java diff --git a/rules-interview/src/test/resources/META-INF/beans.xml b/quickstarts/rules-interview/src/test/resources/META-INF/beans.xml similarity index 100% rename from rules-interview/src/test/resources/META-INF/beans.xml rename to quickstarts/rules-interview/src/test/resources/META-INF/beans.xml diff --git a/rules-interview/src/test/resources/xml/soap-request-fail.xml b/quickstarts/rules-interview/src/test/resources/xml/soap-request-fail.xml similarity index 100% rename from rules-interview/src/test/resources/xml/soap-request-fail.xml rename to quickstarts/rules-interview/src/test/resources/xml/soap-request-fail.xml diff --git a/rules-interview/src/test/resources/xml/soap-request-pass.xml b/quickstarts/rules-interview/src/test/resources/xml/soap-request-pass.xml similarity index 100% rename from rules-interview/src/test/resources/xml/soap-request-pass.xml rename to quickstarts/rules-interview/src/test/resources/xml/soap-request-pass.xml diff --git a/rules-interview/src/test/resources/xml/soap-response-fail.xml b/quickstarts/rules-interview/src/test/resources/xml/soap-response-fail.xml similarity index 100% rename from rules-interview/src/test/resources/xml/soap-response-fail.xml rename to quickstarts/rules-interview/src/test/resources/xml/soap-response-fail.xml diff --git a/rules-interview/src/test/resources/xml/soap-response-pass.xml b/quickstarts/rules-interview/src/test/resources/xml/soap-response-pass.xml similarity index 100% rename from rules-interview/src/test/resources/xml/soap-response-pass.xml rename to quickstarts/rules-interview/src/test/resources/xml/soap-response-pass.xml diff --git a/settings.xml b/quickstarts/settings.xml similarity index 100% rename from settings.xml rename to quickstarts/settings.xml diff --git a/soap-addressing/Readme.md b/quickstarts/soap-addressing/Readme.md similarity index 100% rename from soap-addressing/Readme.md rename to quickstarts/soap-addressing/Readme.md diff --git a/quickstarts/soap-addressing/pom.xml b/quickstarts/soap-addressing/pom.xml new file mode 100644 index 000000000..469c80f3d --- /dev/null +++ b/quickstarts/soap-addressing/pom.xml @@ -0,0 +1,261 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-soap-addressing + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: soap-addressing + Quickstart : SOAP with WS-Addressing + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.soap.addressing + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-camel-file + + + org.switchyard.components + switchyard-component-http + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.soap.addressing.SoapAddressingClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/soap-addressing/soap-addressing.jpg b/quickstarts/soap-addressing/soap-addressing.jpg similarity index 100% rename from soap-addressing/soap-addressing.jpg rename to quickstarts/soap-addressing/soap-addressing.jpg diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ClientProcessor.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ClientProcessor.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ClientProcessor.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ClientProcessor.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ItemNotAvailable.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ItemNotAvailable.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ItemNotAvailable.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ItemNotAvailable.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/Order.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/Order.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/Order.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/Order.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderProcessor.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderProcessor.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderProcessor.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderProcessor.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderReplyProcessor.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderReplyProcessor.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderReplyProcessor.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderReplyProcessor.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderResponse.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderResponse.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderResponse.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/OrderResponse.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ServiceTransformers.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ServiceTransformers.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ServiceTransformers.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/ServiceTransformers.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/UnknownItem.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/UnknownItem.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/UnknownItem.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/UnknownItem.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/UnknownItemBean.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/UnknownItemBean.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/UnknownItemBean.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/UnknownItemBean.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/WarehouseProcessor.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/WarehouseProcessor.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/WarehouseProcessor.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/WarehouseProcessor.java diff --git a/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/WarehouseService.java b/quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/WarehouseService.java similarity index 100% rename from soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/WarehouseService.java rename to quickstarts/soap-addressing/src/main/java/org/switchyard/quickstarts/soap/addressing/WarehouseService.java diff --git a/soap-addressing/src/main/resources/META-INF/beans.xml b/quickstarts/soap-addressing/src/main/resources/META-INF/beans.xml similarity index 100% rename from soap-addressing/src/main/resources/META-INF/beans.xml rename to quickstarts/soap-addressing/src/main/resources/META-INF/beans.xml diff --git a/soap-addressing/src/main/resources/META-INF/switchyard.xml b/quickstarts/soap-addressing/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from soap-addressing/src/main/resources/META-INF/switchyard.xml rename to quickstarts/soap-addressing/src/main/resources/META-INF/switchyard.xml diff --git a/soap-addressing/src/main/resources/OrderService.wsdl b/quickstarts/soap-addressing/src/main/resources/OrderService.wsdl similarity index 100% rename from soap-addressing/src/main/resources/OrderService.wsdl rename to quickstarts/soap-addressing/src/main/resources/OrderService.wsdl diff --git a/soap-addressing/src/main/resources/ResponseService.wsdl b/quickstarts/soap-addressing/src/main/resources/ResponseService.wsdl similarity index 100% rename from soap-addressing/src/main/resources/ResponseService.wsdl rename to quickstarts/soap-addressing/src/main/resources/ResponseService.wsdl diff --git a/soap-addressing/src/main/resources/WarehouseService.wsdl b/quickstarts/soap-addressing/src/main/resources/WarehouseService.wsdl similarity index 100% rename from soap-addressing/src/main/resources/WarehouseService.wsdl rename to quickstarts/soap-addressing/src/main/resources/WarehouseService.wsdl diff --git a/soap-addressing/src/main/resources/client-route.xml b/quickstarts/soap-addressing/src/main/resources/client-route.xml similarity index 100% rename from soap-addressing/src/main/resources/client-route.xml rename to quickstarts/soap-addressing/src/main/resources/client-route.xml diff --git a/soap-addressing/src/main/resources/fault-route.xml b/quickstarts/soap-addressing/src/main/resources/fault-route.xml similarity index 100% rename from soap-addressing/src/main/resources/fault-route.xml rename to quickstarts/soap-addressing/src/main/resources/fault-route.xml diff --git a/soap-addressing/src/main/resources/route.xml b/quickstarts/soap-addressing/src/main/resources/route.xml similarity index 100% rename from soap-addressing/src/main/resources/route.xml rename to quickstarts/soap-addressing/src/main/resources/route.xml diff --git a/soap-addressing/src/main/resources/route2.xml b/quickstarts/soap-addressing/src/main/resources/route2.xml similarity index 100% rename from soap-addressing/src/main/resources/route2.xml rename to quickstarts/soap-addressing/src/main/resources/route2.xml diff --git a/soap-addressing/src/test/java/org/switchyard/quickstarts/soap/addressing/SoapAddressingClient.java b/quickstarts/soap-addressing/src/test/java/org/switchyard/quickstarts/soap/addressing/SoapAddressingClient.java similarity index 100% rename from soap-addressing/src/test/java/org/switchyard/quickstarts/soap/addressing/SoapAddressingClient.java rename to quickstarts/soap-addressing/src/test/java/org/switchyard/quickstarts/soap/addressing/SoapAddressingClient.java diff --git a/soap-addressing/src/test/java/org/switchyard/quickstarts/soap/addressing/SoapAddressingTest.java b/quickstarts/soap-addressing/src/test/java/org/switchyard/quickstarts/soap/addressing/SoapAddressingTest.java similarity index 100% rename from soap-addressing/src/test/java/org/switchyard/quickstarts/soap/addressing/SoapAddressingTest.java rename to quickstarts/soap-addressing/src/test/java/org/switchyard/quickstarts/soap/addressing/SoapAddressingTest.java diff --git a/soap-addressing/src/test/resources/META-INF/beans.xml b/quickstarts/soap-addressing/src/test/resources/META-INF/beans.xml similarity index 100% rename from soap-addressing/src/test/resources/META-INF/beans.xml rename to quickstarts/soap-addressing/src/test/resources/META-INF/beans.xml diff --git a/soap-addressing/src/test/resources/log4j.xml b/quickstarts/soap-addressing/src/test/resources/log4j.xml similarity index 100% rename from soap-addressing/src/test/resources/log4j.xml rename to quickstarts/soap-addressing/src/test/resources/log4j.xml diff --git a/soap-addressing/src/test/resources/xml/soap-addressing-missing.xml b/quickstarts/soap-addressing/src/test/resources/xml/soap-addressing-missing.xml similarity index 100% rename from soap-addressing/src/test/resources/xml/soap-addressing-missing.xml rename to quickstarts/soap-addressing/src/test/resources/xml/soap-addressing-missing.xml diff --git a/soap-addressing/src/test/resources/xml/soap-fault-request.xml b/quickstarts/soap-addressing/src/test/resources/xml/soap-fault-request.xml similarity index 100% rename from soap-addressing/src/test/resources/xml/soap-fault-request.xml rename to quickstarts/soap-addressing/src/test/resources/xml/soap-fault-request.xml diff --git a/soap-addressing/src/test/resources/xml/soap-fault-response.xml b/quickstarts/soap-addressing/src/test/resources/xml/soap-fault-response.xml similarity index 100% rename from soap-addressing/src/test/resources/xml/soap-fault-response.xml rename to quickstarts/soap-addressing/src/test/resources/xml/soap-fault-response.xml diff --git a/soap-addressing/src/test/resources/xml/soap-request-faultto.xml b/quickstarts/soap-addressing/src/test/resources/xml/soap-request-faultto.xml similarity index 100% rename from soap-addressing/src/test/resources/xml/soap-request-faultto.xml rename to quickstarts/soap-addressing/src/test/resources/xml/soap-request-faultto.xml diff --git a/soap-addressing/src/test/resources/xml/soap-request-replyto.xml b/quickstarts/soap-addressing/src/test/resources/xml/soap-request-replyto.xml similarity index 100% rename from soap-addressing/src/test/resources/xml/soap-request-replyto.xml rename to quickstarts/soap-addressing/src/test/resources/xml/soap-request-replyto.xml diff --git a/soap-addressing/src/test/resources/xml/soap-request.xml b/quickstarts/soap-addressing/src/test/resources/xml/soap-request.xml similarity index 100% rename from soap-addressing/src/test/resources/xml/soap-request.xml rename to quickstarts/soap-addressing/src/test/resources/xml/soap-request.xml diff --git a/soap-attachment/Readme.md b/quickstarts/soap-attachment/Readme.md similarity index 100% rename from soap-attachment/Readme.md rename to quickstarts/soap-attachment/Readme.md diff --git a/quickstarts/soap-attachment/pom.xml b/quickstarts/soap-attachment/pom.xml new file mode 100644 index 000000000..5de00ab91 --- /dev/null +++ b/quickstarts/soap-attachment/pom.xml @@ -0,0 +1,236 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-soap-attachment + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: soap-attachment + Quickstart : SOAP with Attachments + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.soap.attachment + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.soap.attachment.SoapAttachmentClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/soap-attachment/soap-attachment.jpg b/quickstarts/soap-attachment/soap-attachment.jpg similarity index 100% rename from soap-attachment/soap-attachment.jpg rename to quickstarts/soap-attachment/soap-attachment.jpg diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/CustomProcessor.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/CustomProcessor.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/CustomProcessor.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/CustomProcessor.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/EchoService.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/EchoService.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/EchoService.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/EchoService.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/EchoServiceBean.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/EchoServiceBean.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/EchoServiceBean.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/EchoServiceBean.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageRequest.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageRequest.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageRequest.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageRequest.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageResponse.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageResponse.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageResponse.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageResponse.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageService.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageService.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageService.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageService.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageServiceImpl.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageServiceImpl.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageServiceImpl.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ImageServiceImpl.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalCustomProcessor.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalCustomProcessor.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalCustomProcessor.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalCustomProcessor.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalEchoService.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalEchoService.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalEchoService.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalEchoService.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalEchoServiceBean.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalEchoServiceBean.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalEchoServiceBean.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/InternalEchoServiceBean.java diff --git a/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ServiceTransformers.java b/quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ServiceTransformers.java similarity index 100% rename from soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ServiceTransformers.java rename to quickstarts/soap-attachment/src/main/java/org/switchyard/quickstarts/soap/attachment/ServiceTransformers.java diff --git a/soap-attachment/src/main/resources/ImageService-External.wsdl b/quickstarts/soap-attachment/src/main/resources/ImageService-External.wsdl similarity index 100% rename from soap-attachment/src/main/resources/ImageService-External.wsdl rename to quickstarts/soap-attachment/src/main/resources/ImageService-External.wsdl diff --git a/soap-attachment/src/main/resources/ImageService.wsdl b/quickstarts/soap-attachment/src/main/resources/ImageService.wsdl similarity index 100% rename from soap-attachment/src/main/resources/ImageService.wsdl rename to quickstarts/soap-attachment/src/main/resources/ImageService.wsdl diff --git a/soap-attachment/src/main/resources/META-INF/beans.xml b/quickstarts/soap-attachment/src/main/resources/META-INF/beans.xml similarity index 100% rename from soap-attachment/src/main/resources/META-INF/beans.xml rename to quickstarts/soap-attachment/src/main/resources/META-INF/beans.xml diff --git a/soap-attachment/src/main/resources/META-INF/filter.xml b/quickstarts/soap-attachment/src/main/resources/META-INF/filter.xml similarity index 100% rename from soap-attachment/src/main/resources/META-INF/filter.xml rename to quickstarts/soap-attachment/src/main/resources/META-INF/filter.xml diff --git a/soap-attachment/src/main/resources/META-INF/route.xml b/quickstarts/soap-attachment/src/main/resources/META-INF/route.xml similarity index 100% rename from soap-attachment/src/main/resources/META-INF/route.xml rename to quickstarts/soap-attachment/src/main/resources/META-INF/route.xml diff --git a/soap-attachment/src/main/resources/META-INF/switchyard.xml b/quickstarts/soap-attachment/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from soap-attachment/src/main/resources/META-INF/switchyard.xml rename to quickstarts/soap-attachment/src/main/resources/META-INF/switchyard.xml diff --git a/soap-attachment/src/main/resources/switchyard.png b/quickstarts/soap-attachment/src/main/resources/switchyard.png similarity index 100% rename from soap-attachment/src/main/resources/switchyard.png rename to quickstarts/soap-attachment/src/main/resources/switchyard.png diff --git a/soap-attachment/src/test/java/org/switchyard/quickstarts/soap/attachment/SoapAttachmentClient.java b/quickstarts/soap-attachment/src/test/java/org/switchyard/quickstarts/soap/attachment/SoapAttachmentClient.java similarity index 100% rename from soap-attachment/src/test/java/org/switchyard/quickstarts/soap/attachment/SoapAttachmentClient.java rename to quickstarts/soap-attachment/src/test/java/org/switchyard/quickstarts/soap/attachment/SoapAttachmentClient.java diff --git a/soap-attachment/src/test/java/org/switchyard/quickstarts/soap/attachment/SoapAttachmentTest.java b/quickstarts/soap-attachment/src/test/java/org/switchyard/quickstarts/soap/attachment/SoapAttachmentTest.java similarity index 100% rename from soap-attachment/src/test/java/org/switchyard/quickstarts/soap/attachment/SoapAttachmentTest.java rename to quickstarts/soap-attachment/src/test/java/org/switchyard/quickstarts/soap/attachment/SoapAttachmentTest.java diff --git a/soap-attachment/src/test/resources/META-INF/beans.xml b/quickstarts/soap-attachment/src/test/resources/META-INF/beans.xml similarity index 100% rename from soap-attachment/src/test/resources/META-INF/beans.xml rename to quickstarts/soap-attachment/src/test/resources/META-INF/beans.xml diff --git a/soap-attachment/src/test/resources/log4j.xml b/quickstarts/soap-attachment/src/test/resources/log4j.xml similarity index 100% rename from soap-attachment/src/test/resources/log4j.xml rename to quickstarts/soap-attachment/src/test/resources/log4j.xml diff --git a/soap-attachment/src/test/resources/xml/soap-request.xml b/quickstarts/soap-attachment/src/test/resources/xml/soap-request.xml similarity index 100% rename from soap-attachment/src/test/resources/xml/soap-request.xml rename to quickstarts/soap-attachment/src/test/resources/xml/soap-request.xml diff --git a/soap-attachment/src/test/resources/xml/soap-response.xml b/quickstarts/soap-attachment/src/test/resources/xml/soap-response.xml similarity index 100% rename from soap-attachment/src/test/resources/xml/soap-response.xml rename to quickstarts/soap-attachment/src/test/resources/xml/soap-response.xml diff --git a/soap-binding-rpc/Readme.md b/quickstarts/soap-binding-rpc/Readme.md similarity index 100% rename from soap-binding-rpc/Readme.md rename to quickstarts/soap-binding-rpc/Readme.md diff --git a/quickstarts/soap-binding-rpc/pom.xml b/quickstarts/soap-binding-rpc/pom.xml new file mode 100644 index 000000000..9b9bfbcf1 --- /dev/null +++ b/quickstarts/soap-binding-rpc/pom.xml @@ -0,0 +1,257 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-soap-binding-rpc + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: soap-binding-rpc + Quickstart : SOAP Binding RPC/Lit + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.soap.binding.rpc + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.soap.binding.rpc.SoapBindingClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/soap-binding-rpc/soap-binding-rpc.jpg b/quickstarts/soap-binding-rpc/soap-binding-rpc.jpg similarity index 100% rename from soap-binding-rpc/soap-binding-rpc.jpg rename to quickstarts/soap-binding-rpc/soap-binding-rpc.jpg diff --git a/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/CustomComposer.java b/quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/CustomComposer.java similarity index 100% rename from soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/CustomComposer.java rename to quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/CustomComposer.java diff --git a/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/HelloWorldService.java b/quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/HelloWorldService.java similarity index 100% rename from soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/HelloWorldService.java rename to quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/HelloWorldService.java diff --git a/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/HelloWorldServiceBean.java b/quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/HelloWorldServiceBean.java similarity index 100% rename from soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/HelloWorldServiceBean.java rename to quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/HelloWorldServiceBean.java diff --git a/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/SayHello.java b/quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/SayHello.java similarity index 100% rename from soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/SayHello.java rename to quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/SayHello.java diff --git a/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/SayHelloExternal.java b/quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/SayHelloExternal.java similarity index 100% rename from soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/SayHelloExternal.java rename to quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/SayHelloExternal.java diff --git a/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/ServiceTransformers.java b/quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/ServiceTransformers.java similarity index 100% rename from soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/ServiceTransformers.java rename to quickstarts/soap-binding-rpc/src/main/java/org/switchyard/quickstarts/soap/binding/rpc/ServiceTransformers.java diff --git a/soap-binding-rpc/src/main/resources/HelloWorldWS-External.wsdl b/quickstarts/soap-binding-rpc/src/main/resources/HelloWorldWS-External.wsdl similarity index 100% rename from soap-binding-rpc/src/main/resources/HelloWorldWS-External.wsdl rename to quickstarts/soap-binding-rpc/src/main/resources/HelloWorldWS-External.wsdl diff --git a/soap-binding-rpc/src/main/resources/HelloWorldWS.wsdl b/quickstarts/soap-binding-rpc/src/main/resources/HelloWorldWS.wsdl similarity index 100% rename from soap-binding-rpc/src/main/resources/HelloWorldWS.wsdl rename to quickstarts/soap-binding-rpc/src/main/resources/HelloWorldWS.wsdl diff --git a/soap-binding-rpc/src/main/resources/META-INF/beans.xml b/quickstarts/soap-binding-rpc/src/main/resources/META-INF/beans.xml similarity index 100% rename from soap-binding-rpc/src/main/resources/META-INF/beans.xml rename to quickstarts/soap-binding-rpc/src/main/resources/META-INF/beans.xml diff --git a/soap-binding-rpc/src/main/resources/META-INF/route.xml b/quickstarts/soap-binding-rpc/src/main/resources/META-INF/route.xml similarity index 100% rename from soap-binding-rpc/src/main/resources/META-INF/route.xml rename to quickstarts/soap-binding-rpc/src/main/resources/META-INF/route.xml diff --git a/soap-binding-rpc/src/main/resources/META-INF/switchyard.xml b/quickstarts/soap-binding-rpc/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from soap-binding-rpc/src/main/resources/META-INF/switchyard.xml rename to quickstarts/soap-binding-rpc/src/main/resources/META-INF/switchyard.xml diff --git a/soap-binding-rpc/src/test/java/org/switchyard/quickstarts/soap/binding/rpc/SoapBindingClient.java b/quickstarts/soap-binding-rpc/src/test/java/org/switchyard/quickstarts/soap/binding/rpc/SoapBindingClient.java similarity index 100% rename from soap-binding-rpc/src/test/java/org/switchyard/quickstarts/soap/binding/rpc/SoapBindingClient.java rename to quickstarts/soap-binding-rpc/src/test/java/org/switchyard/quickstarts/soap/binding/rpc/SoapBindingClient.java diff --git a/soap-binding-rpc/src/test/java/org/switchyard/quickstarts/soap/binding/rpc/SoapBindingTest.java b/quickstarts/soap-binding-rpc/src/test/java/org/switchyard/quickstarts/soap/binding/rpc/SoapBindingTest.java similarity index 100% rename from soap-binding-rpc/src/test/java/org/switchyard/quickstarts/soap/binding/rpc/SoapBindingTest.java rename to quickstarts/soap-binding-rpc/src/test/java/org/switchyard/quickstarts/soap/binding/rpc/SoapBindingTest.java diff --git a/soap-binding-rpc/src/test/resources/META-INF/beans.xml b/quickstarts/soap-binding-rpc/src/test/resources/META-INF/beans.xml similarity index 100% rename from soap-binding-rpc/src/test/resources/META-INF/beans.xml rename to quickstarts/soap-binding-rpc/src/test/resources/META-INF/beans.xml diff --git a/soap-binding-rpc/src/test/resources/log4j.xml b/quickstarts/soap-binding-rpc/src/test/resources/log4j.xml similarity index 100% rename from soap-binding-rpc/src/test/resources/log4j.xml rename to quickstarts/soap-binding-rpc/src/test/resources/log4j.xml diff --git a/soap-binding-rpc/src/test/resources/xml/soap-request-500.xml b/quickstarts/soap-binding-rpc/src/test/resources/xml/soap-request-500.xml similarity index 100% rename from soap-binding-rpc/src/test/resources/xml/soap-request-500.xml rename to quickstarts/soap-binding-rpc/src/test/resources/xml/soap-request-500.xml diff --git a/soap-binding-rpc/src/test/resources/xml/soap-request.xml b/quickstarts/soap-binding-rpc/src/test/resources/xml/soap-request.xml similarity index 100% rename from soap-binding-rpc/src/test/resources/xml/soap-request.xml rename to quickstarts/soap-binding-rpc/src/test/resources/xml/soap-request.xml diff --git a/soap-binding-rpc/src/test/resources/xml/soap-response.xml b/quickstarts/soap-binding-rpc/src/test/resources/xml/soap-response.xml similarity index 100% rename from soap-binding-rpc/src/test/resources/xml/soap-response.xml rename to quickstarts/soap-binding-rpc/src/test/resources/xml/soap-response.xml diff --git a/soap-mtom/Readme.md b/quickstarts/soap-mtom/Readme.md similarity index 100% rename from soap-mtom/Readme.md rename to quickstarts/soap-mtom/Readme.md diff --git a/quickstarts/soap-mtom/pom.xml b/quickstarts/soap-mtom/pom.xml new file mode 100644 index 000000000..50a95ba23 --- /dev/null +++ b/quickstarts/soap-mtom/pom.xml @@ -0,0 +1,253 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-soap-mtom + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: soap-mtom + Quickstart : SOAP with MTOM + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.soap.mtom + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.soap.mtom.SoapMtomClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/soap-mtom/soap-mtom.jpg b/quickstarts/soap-mtom/soap-mtom.jpg similarity index 100% rename from soap-mtom/soap-mtom.jpg rename to quickstarts/soap-mtom/soap-mtom.jpg diff --git a/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ExternalCustomProcessor.java b/quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ExternalCustomProcessor.java similarity index 100% rename from soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ExternalCustomProcessor.java rename to quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ExternalCustomProcessor.java diff --git a/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ImageService.java b/quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ImageService.java similarity index 100% rename from soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ImageService.java rename to quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ImageService.java diff --git a/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ImageServiceService.java b/quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ImageServiceService.java similarity index 100% rename from soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ImageServiceService.java rename to quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ImageServiceService.java diff --git a/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/InternalCustomProcessor.java b/quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/InternalCustomProcessor.java similarity index 100% rename from soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/InternalCustomProcessor.java rename to quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/InternalCustomProcessor.java diff --git a/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/InternalResponseProcessor.java b/quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/InternalResponseProcessor.java similarity index 100% rename from soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/InternalResponseProcessor.java rename to quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/InternalResponseProcessor.java diff --git a/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ServiceTransformers.java b/quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ServiceTransformers.java similarity index 100% rename from soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ServiceTransformers.java rename to quickstarts/soap-mtom/src/main/java/org/switchyard/quickstarts/soap/mtom/ServiceTransformers.java diff --git a/soap-mtom/src/main/resources/ImageService-External.wsdl b/quickstarts/soap-mtom/src/main/resources/ImageService-External.wsdl similarity index 100% rename from soap-mtom/src/main/resources/ImageService-External.wsdl rename to quickstarts/soap-mtom/src/main/resources/ImageService-External.wsdl diff --git a/soap-mtom/src/main/resources/ImageService.wsdl b/quickstarts/soap-mtom/src/main/resources/ImageService.wsdl similarity index 100% rename from soap-mtom/src/main/resources/ImageService.wsdl rename to quickstarts/soap-mtom/src/main/resources/ImageService.wsdl diff --git a/soap-mtom/src/main/resources/META-INF/beans.xml b/quickstarts/soap-mtom/src/main/resources/META-INF/beans.xml similarity index 100% rename from soap-mtom/src/main/resources/META-INF/beans.xml rename to quickstarts/soap-mtom/src/main/resources/META-INF/beans.xml diff --git a/soap-mtom/src/main/resources/META-INF/filter.xml b/quickstarts/soap-mtom/src/main/resources/META-INF/filter.xml similarity index 100% rename from soap-mtom/src/main/resources/META-INF/filter.xml rename to quickstarts/soap-mtom/src/main/resources/META-INF/filter.xml diff --git a/soap-mtom/src/main/resources/META-INF/route.xml b/quickstarts/soap-mtom/src/main/resources/META-INF/route.xml similarity index 100% rename from soap-mtom/src/main/resources/META-INF/route.xml rename to quickstarts/soap-mtom/src/main/resources/META-INF/route.xml diff --git a/soap-mtom/src/main/resources/META-INF/switchyard.xml b/quickstarts/soap-mtom/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from soap-mtom/src/main/resources/META-INF/switchyard.xml rename to quickstarts/soap-mtom/src/main/resources/META-INF/switchyard.xml diff --git a/soap-mtom/src/main/resources/switchyard.jpeg b/quickstarts/soap-mtom/src/main/resources/switchyard.jpeg similarity index 100% rename from soap-mtom/src/main/resources/switchyard.jpeg rename to quickstarts/soap-mtom/src/main/resources/switchyard.jpeg diff --git a/soap-mtom/src/main/resources/switchyard_icon.jpeg b/quickstarts/soap-mtom/src/main/resources/switchyard_icon.jpeg similarity index 100% rename from soap-mtom/src/main/resources/switchyard_icon.jpeg rename to quickstarts/soap-mtom/src/main/resources/switchyard_icon.jpeg diff --git a/soap-mtom/src/test/java/org/switchyard/quickstarts/soap/mtom/SoapMtomClient.java b/quickstarts/soap-mtom/src/test/java/org/switchyard/quickstarts/soap/mtom/SoapMtomClient.java similarity index 100% rename from soap-mtom/src/test/java/org/switchyard/quickstarts/soap/mtom/SoapMtomClient.java rename to quickstarts/soap-mtom/src/test/java/org/switchyard/quickstarts/soap/mtom/SoapMtomClient.java diff --git a/soap-mtom/src/test/java/org/switchyard/quickstarts/soap/mtom/SoapMtomTest.java b/quickstarts/soap-mtom/src/test/java/org/switchyard/quickstarts/soap/mtom/SoapMtomTest.java similarity index 100% rename from soap-mtom/src/test/java/org/switchyard/quickstarts/soap/mtom/SoapMtomTest.java rename to quickstarts/soap-mtom/src/test/java/org/switchyard/quickstarts/soap/mtom/SoapMtomTest.java diff --git a/soap-mtom/src/test/resources/META-INF/beans.xml b/quickstarts/soap-mtom/src/test/resources/META-INF/beans.xml similarity index 100% rename from soap-mtom/src/test/resources/META-INF/beans.xml rename to quickstarts/soap-mtom/src/test/resources/META-INF/beans.xml diff --git a/soap-mtom/src/test/resources/log4j.xml b/quickstarts/soap-mtom/src/test/resources/log4j.xml similarity index 100% rename from soap-mtom/src/test/resources/log4j.xml rename to quickstarts/soap-mtom/src/test/resources/log4j.xml diff --git a/soap-mtom/src/test/resources/xml/soap-request.xml b/quickstarts/soap-mtom/src/test/resources/xml/soap-request.xml similarity index 100% rename from soap-mtom/src/test/resources/xml/soap-request.xml rename to quickstarts/soap-mtom/src/test/resources/xml/soap-request.xml diff --git a/soap-mtom/src/test/resources/xml/soap-response.xml b/quickstarts/soap-mtom/src/test/resources/xml/soap-response.xml similarity index 100% rename from soap-mtom/src/test/resources/xml/soap-response.xml rename to quickstarts/soap-mtom/src/test/resources/xml/soap-response.xml diff --git a/quickstarts/testutil/pom.xml b/quickstarts/testutil/pom.xml new file mode 100644 index 000000000..417195014 --- /dev/null +++ b/quickstarts/testutil/pom.xml @@ -0,0 +1,80 @@ + + + + 4.0.0 + + org.switchyard.quickstarts + switchyard-quickstart-parent + 2.1.0-SNAPSHOT + .. + + org.switchyard.quickstarts + switchyard-quickstart-testutil + jar + SwitchYard Quickstart: testutil + Testutil for SwitchYard Quickstarts + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + https://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + never + + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + 1.6 + 1.6 + + + + org.jboss.as + jboss-as-cli + + + org.jboss.as + jboss-as-protocol + + + org.jboss.logging + jboss-logging + + + + diff --git a/testutil/src/main/java/org/switchyard/quickstarts/testutil/JBossCliUtil.java b/quickstarts/testutil/src/main/java/org/switchyard/quickstarts/testutil/JBossCliUtil.java similarity index 100% rename from testutil/src/main/java/org/switchyard/quickstarts/testutil/JBossCliUtil.java rename to quickstarts/testutil/src/main/java/org/switchyard/quickstarts/testutil/JBossCliUtil.java diff --git a/transform-dozer/Readme.md b/quickstarts/transform-dozer/Readme.md similarity index 100% rename from transform-dozer/Readme.md rename to quickstarts/transform-dozer/Readme.md diff --git a/quickstarts/transform-dozer/pom.xml b/quickstarts/transform-dozer/pom.xml new file mode 100644 index 000000000..4ba87c77d --- /dev/null +++ b/quickstarts/transform-dozer/pom.xml @@ -0,0 +1,273 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-transform-dozer + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: transform-dozer + Quickstart : Dozer Transformation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.transform.dozer + 1.6 + 1.6 + true + 9999 + + org.dozer.util, + * + + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard + switchyard-validate + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.transform.dozer.DozerTransformationClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.sca.client.port + 8181 + + + + + + + + + wildfly + + 9990 + + + + diff --git a/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/Order.java b/quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/Order.java similarity index 100% rename from transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/Order.java rename to quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/Order.java diff --git a/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/OrderAck.java b/quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/OrderAck.java similarity index 100% rename from transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/OrderAck.java rename to quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/OrderAck.java diff --git a/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/OrderService.java b/quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/OrderService.java similarity index 100% rename from transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/OrderService.java rename to quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/OrderService.java diff --git a/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderDomain.java b/quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderDomain.java similarity index 100% rename from transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderDomain.java rename to quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderDomain.java diff --git a/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderService.java b/quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderService.java similarity index 100% rename from transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderService.java rename to quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderService.java diff --git a/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderServiceBean.java b/quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderServiceBean.java similarity index 100% rename from transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderServiceBean.java rename to quickstarts/transform-dozer/src/main/java/org/switchyard/quickstarts/transform/dozer/domain/OrderServiceBean.java diff --git a/transform-dozer/src/main/resources/META-INF/beans.xml b/quickstarts/transform-dozer/src/main/resources/META-INF/beans.xml similarity index 100% rename from transform-dozer/src/main/resources/META-INF/beans.xml rename to quickstarts/transform-dozer/src/main/resources/META-INF/beans.xml diff --git a/transform-dozer/src/main/resources/META-INF/switchyard.xml b/quickstarts/transform-dozer/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from transform-dozer/src/main/resources/META-INF/switchyard.xml rename to quickstarts/transform-dozer/src/main/resources/META-INF/switchyard.xml diff --git a/transform-dozer/src/main/resources/mapping-order.xml b/quickstarts/transform-dozer/src/main/resources/mapping-order.xml similarity index 100% rename from transform-dozer/src/main/resources/mapping-order.xml rename to quickstarts/transform-dozer/src/main/resources/mapping-order.xml diff --git a/transform-dozer/src/test/java/org/switchyard/quickstarts/transform/dozer/DozerTransformationClient.java b/quickstarts/transform-dozer/src/test/java/org/switchyard/quickstarts/transform/dozer/DozerTransformationClient.java similarity index 100% rename from transform-dozer/src/test/java/org/switchyard/quickstarts/transform/dozer/DozerTransformationClient.java rename to quickstarts/transform-dozer/src/test/java/org/switchyard/quickstarts/transform/dozer/DozerTransformationClient.java diff --git a/transform-dozer/src/test/java/org/switchyard/quickstarts/transform/dozer/DozerTransformationTest.java b/quickstarts/transform-dozer/src/test/java/org/switchyard/quickstarts/transform/dozer/DozerTransformationTest.java similarity index 100% rename from transform-dozer/src/test/java/org/switchyard/quickstarts/transform/dozer/DozerTransformationTest.java rename to quickstarts/transform-dozer/src/test/java/org/switchyard/quickstarts/transform/dozer/DozerTransformationTest.java diff --git a/transform-dozer/src/test/resources/META-INF/beans.xml b/quickstarts/transform-dozer/src/test/resources/META-INF/beans.xml similarity index 100% rename from transform-dozer/src/test/resources/META-INF/beans.xml rename to quickstarts/transform-dozer/src/test/resources/META-INF/beans.xml diff --git a/transform-dozer/src/test/resources/json/order.json b/quickstarts/transform-dozer/src/test/resources/json/order.json similarity index 100% rename from transform-dozer/src/test/resources/json/order.json rename to quickstarts/transform-dozer/src/test/resources/json/order.json diff --git a/transform-dozer/src/test/resources/json/orderAck.json b/quickstarts/transform-dozer/src/test/resources/json/orderAck.json similarity index 100% rename from transform-dozer/src/test/resources/json/orderAck.json rename to quickstarts/transform-dozer/src/test/resources/json/orderAck.json diff --git a/transform-dozer/src/test/resources/log4j.xml b/quickstarts/transform-dozer/src/test/resources/log4j.xml similarity index 100% rename from transform-dozer/src/test/resources/log4j.xml rename to quickstarts/transform-dozer/src/test/resources/log4j.xml diff --git a/transform-dozer/transform-dozer.png b/quickstarts/transform-dozer/transform-dozer.png similarity index 100% rename from transform-dozer/transform-dozer.png rename to quickstarts/transform-dozer/transform-dozer.png diff --git a/transform-jaxb/Readme.md b/quickstarts/transform-jaxb/Readme.md similarity index 100% rename from transform-jaxb/Readme.md rename to quickstarts/transform-jaxb/Readme.md diff --git a/quickstarts/transform-jaxb/pom.xml b/quickstarts/transform-jaxb/pom.xml new file mode 100644 index 000000000..f5f68757c --- /dev/null +++ b/quickstarts/transform-jaxb/pom.xml @@ -0,0 +1,262 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-transform-jaxb + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: transform-jaxb + Quickstart : JAXB Transformation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.transform.jaxb + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + org.apache.httpcomponents + httpclient + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.transform.jaxb.JAXBClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/transform-jaxb/src/main/java/META-INF/MANIFEST.MF b/quickstarts/transform-jaxb/src/main/java/META-INF/MANIFEST.MF similarity index 100% rename from transform-jaxb/src/main/java/META-INF/MANIFEST.MF rename to quickstarts/transform-jaxb/src/main/java/META-INF/MANIFEST.MF diff --git a/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/ObjectFactory.java b/quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/ObjectFactory.java similarity index 100% rename from transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/ObjectFactory.java rename to quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/ObjectFactory.java diff --git a/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/Order.java b/quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/Order.java similarity index 100% rename from transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/Order.java rename to quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/Order.java diff --git a/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderAck.java b/quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderAck.java similarity index 100% rename from transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderAck.java rename to quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderAck.java diff --git a/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderService.java b/quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderService.java similarity index 100% rename from transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderService.java rename to quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderService.java diff --git a/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderServiceBean.java b/quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderServiceBean.java similarity index 100% rename from transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderServiceBean.java rename to quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/OrderServiceBean.java diff --git a/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/package-info.java b/quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/package-info.java similarity index 100% rename from transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/package-info.java rename to quickstarts/transform-jaxb/src/main/java/org/switchyard/quickstarts/transform/jaxb/package-info.java diff --git a/transform-jaxb/src/main/resources/META-INF/beans.xml b/quickstarts/transform-jaxb/src/main/resources/META-INF/beans.xml similarity index 100% rename from transform-jaxb/src/main/resources/META-INF/beans.xml rename to quickstarts/transform-jaxb/src/main/resources/META-INF/beans.xml diff --git a/transform-jaxb/src/main/resources/META-INF/switchyard.xml b/quickstarts/transform-jaxb/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from transform-jaxb/src/main/resources/META-INF/switchyard.xml rename to quickstarts/transform-jaxb/src/main/resources/META-INF/switchyard.xml diff --git a/transform-jaxb/src/main/resources/wsdl/OrderService.wsdl b/quickstarts/transform-jaxb/src/main/resources/wsdl/OrderService.wsdl similarity index 100% rename from transform-jaxb/src/main/resources/wsdl/OrderService.wsdl rename to quickstarts/transform-jaxb/src/main/resources/wsdl/OrderService.wsdl diff --git a/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/JAXBClient.java b/quickstarts/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/JAXBClient.java similarity index 100% rename from transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/JAXBClient.java rename to quickstarts/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/JAXBClient.java diff --git a/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/JaxbTransformationTest.java b/quickstarts/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/JaxbTransformationTest.java similarity index 100% rename from transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/JaxbTransformationTest.java rename to quickstarts/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/JaxbTransformationTest.java diff --git a/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/WebServiceTest.java b/quickstarts/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/WebServiceTest.java similarity index 100% rename from transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/WebServiceTest.java rename to quickstarts/transform-jaxb/src/test/java/org/switchyard/quickstarts/transform/jaxb/WebServiceTest.java diff --git a/transform-jaxb/src/test/resources/META-INF/beans.xml b/quickstarts/transform-jaxb/src/test/resources/META-INF/beans.xml similarity index 100% rename from transform-jaxb/src/test/resources/META-INF/beans.xml rename to quickstarts/transform-jaxb/src/test/resources/META-INF/beans.xml diff --git a/transform-jaxb/src/test/resources/log4j.xml b/quickstarts/transform-jaxb/src/test/resources/log4j.xml similarity index 100% rename from transform-jaxb/src/test/resources/log4j.xml rename to quickstarts/transform-jaxb/src/test/resources/log4j.xml diff --git a/transform-jaxb/src/test/resources/xml/order.xml b/quickstarts/transform-jaxb/src/test/resources/xml/order.xml similarity index 100% rename from transform-jaxb/src/test/resources/xml/order.xml rename to quickstarts/transform-jaxb/src/test/resources/xml/order.xml diff --git a/transform-jaxb/src/test/resources/xml/orderAck.xml b/quickstarts/transform-jaxb/src/test/resources/xml/orderAck.xml similarity index 100% rename from transform-jaxb/src/test/resources/xml/orderAck.xml rename to quickstarts/transform-jaxb/src/test/resources/xml/orderAck.xml diff --git a/transform-jaxb/src/test/resources/xml/soap-request.xml b/quickstarts/transform-jaxb/src/test/resources/xml/soap-request.xml similarity index 100% rename from transform-jaxb/src/test/resources/xml/soap-request.xml rename to quickstarts/transform-jaxb/src/test/resources/xml/soap-request.xml diff --git a/transform-jaxb/src/test/resources/xml/soap-response.xml b/quickstarts/transform-jaxb/src/test/resources/xml/soap-response.xml similarity index 100% rename from transform-jaxb/src/test/resources/xml/soap-response.xml rename to quickstarts/transform-jaxb/src/test/resources/xml/soap-response.xml diff --git a/transform-jaxb/transform-jaxb.jpg b/quickstarts/transform-jaxb/transform-jaxb.jpg similarity index 100% rename from transform-jaxb/transform-jaxb.jpg rename to quickstarts/transform-jaxb/transform-jaxb.jpg diff --git a/transform-json/Readme.md b/quickstarts/transform-json/Readme.md similarity index 100% rename from transform-json/Readme.md rename to quickstarts/transform-json/Readme.md diff --git a/quickstarts/transform-json/pom.xml b/quickstarts/transform-json/pom.xml new file mode 100644 index 000000000..d003926b2 --- /dev/null +++ b/quickstarts/transform-json/pom.xml @@ -0,0 +1,270 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-transform-json + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: transform-json + Quickstart : JSON Transformation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.transform.json + 1.6 + 1.6 + true + 9999 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard + switchyard-validate + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.transform.json.JsonTransformationClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.sca.client.port + 8181 + + + + + + + + + wildfly + + 9990 + + + + diff --git a/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/Order.java b/quickstarts/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/Order.java similarity index 100% rename from transform-json/src/main/java/org/switchyard/quickstarts/transform/json/Order.java rename to quickstarts/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/Order.java diff --git a/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderAck.java b/quickstarts/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderAck.java similarity index 100% rename from transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderAck.java rename to quickstarts/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderAck.java diff --git a/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderService.java b/quickstarts/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderService.java similarity index 100% rename from transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderService.java rename to quickstarts/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderService.java diff --git a/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderServiceBean.java b/quickstarts/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderServiceBean.java similarity index 100% rename from transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderServiceBean.java rename to quickstarts/transform-json/src/main/java/org/switchyard/quickstarts/transform/json/OrderServiceBean.java diff --git a/transform-json/src/main/resources/META-INF/beans.xml b/quickstarts/transform-json/src/main/resources/META-INF/beans.xml similarity index 100% rename from transform-json/src/main/resources/META-INF/beans.xml rename to quickstarts/transform-json/src/main/resources/META-INF/beans.xml diff --git a/transform-json/src/main/resources/META-INF/switchyard.xml b/quickstarts/transform-json/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from transform-json/src/main/resources/META-INF/switchyard.xml rename to quickstarts/transform-json/src/main/resources/META-INF/switchyard.xml diff --git a/transform-json/src/test/java/org/switchyard/quickstarts/transform/json/JsonTransformationClient.java b/quickstarts/transform-json/src/test/java/org/switchyard/quickstarts/transform/json/JsonTransformationClient.java similarity index 100% rename from transform-json/src/test/java/org/switchyard/quickstarts/transform/json/JsonTransformationClient.java rename to quickstarts/transform-json/src/test/java/org/switchyard/quickstarts/transform/json/JsonTransformationClient.java diff --git a/transform-json/src/test/java/org/switchyard/quickstarts/transform/json/JsonTransformationTest.java b/quickstarts/transform-json/src/test/java/org/switchyard/quickstarts/transform/json/JsonTransformationTest.java similarity index 100% rename from transform-json/src/test/java/org/switchyard/quickstarts/transform/json/JsonTransformationTest.java rename to quickstarts/transform-json/src/test/java/org/switchyard/quickstarts/transform/json/JsonTransformationTest.java diff --git a/transform-json/src/test/resources/META-INF/beans.xml b/quickstarts/transform-json/src/test/resources/META-INF/beans.xml similarity index 100% rename from transform-json/src/test/resources/META-INF/beans.xml rename to quickstarts/transform-json/src/test/resources/META-INF/beans.xml diff --git a/transform-json/src/test/resources/json/order.json b/quickstarts/transform-json/src/test/resources/json/order.json similarity index 100% rename from transform-json/src/test/resources/json/order.json rename to quickstarts/transform-json/src/test/resources/json/order.json diff --git a/transform-json/src/test/resources/json/orderAck.json b/quickstarts/transform-json/src/test/resources/json/orderAck.json similarity index 100% rename from transform-json/src/test/resources/json/orderAck.json rename to quickstarts/transform-json/src/test/resources/json/orderAck.json diff --git a/transform-json/src/test/resources/log4j.xml b/quickstarts/transform-json/src/test/resources/log4j.xml similarity index 100% rename from transform-json/src/test/resources/log4j.xml rename to quickstarts/transform-json/src/test/resources/log4j.xml diff --git a/transform-json/transform-json.jpg b/quickstarts/transform-json/transform-json.jpg similarity index 100% rename from transform-json/transform-json.jpg rename to quickstarts/transform-json/transform-json.jpg diff --git a/transform-smooks/Readme.md b/quickstarts/transform-smooks/Readme.md similarity index 100% rename from transform-smooks/Readme.md rename to quickstarts/transform-smooks/Readme.md diff --git a/quickstarts/transform-smooks/pom.xml b/quickstarts/transform-smooks/pom.xml new file mode 100644 index 000000000..314348d01 --- /dev/null +++ b/quickstarts/transform-smooks/pom.xml @@ -0,0 +1,271 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-transform-smooks + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: transform-smooks + Quickstart : Smooks Transformation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.transform.smooks + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-transform + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard.components + switchyard-component-test-mixin-smooks + test + + + junit + junit + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + org.switchyard.transform.config.model.TransformSwitchYardScanner + + + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.transform.smooks.ServiceTransformationClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/Order.java b/quickstarts/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/Order.java similarity index 100% rename from transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/Order.java rename to quickstarts/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/Order.java diff --git a/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderAck.java b/quickstarts/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderAck.java similarity index 100% rename from transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderAck.java rename to quickstarts/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderAck.java diff --git a/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderService.java b/quickstarts/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderService.java similarity index 100% rename from transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderService.java rename to quickstarts/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderService.java diff --git a/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderServiceBean.java b/quickstarts/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderServiceBean.java similarity index 100% rename from transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderServiceBean.java rename to quickstarts/transform-smooks/src/main/java/org/switchyard/quickstarts/transform/smooks/OrderServiceBean.java diff --git a/transform-smooks/src/main/resources/META-INF/beans.xml b/quickstarts/transform-smooks/src/main/resources/META-INF/beans.xml similarity index 100% rename from transform-smooks/src/main/resources/META-INF/beans.xml rename to quickstarts/transform-smooks/src/main/resources/META-INF/beans.xml diff --git a/transform-smooks/src/main/resources/META-INF/switchyard.xml b/quickstarts/transform-smooks/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from transform-smooks/src/main/resources/META-INF/switchyard.xml rename to quickstarts/transform-smooks/src/main/resources/META-INF/switchyard.xml diff --git a/transform-smooks/src/main/resources/smooks/OrderAck_XML.xml b/quickstarts/transform-smooks/src/main/resources/smooks/OrderAck_XML.xml similarity index 100% rename from transform-smooks/src/main/resources/smooks/OrderAck_XML.xml rename to quickstarts/transform-smooks/src/main/resources/smooks/OrderAck_XML.xml diff --git a/transform-smooks/src/main/resources/smooks/Order_XML.xml b/quickstarts/transform-smooks/src/main/resources/smooks/Order_XML.xml similarity index 100% rename from transform-smooks/src/main/resources/smooks/Order_XML.xml rename to quickstarts/transform-smooks/src/main/resources/smooks/Order_XML.xml diff --git a/transform-smooks/src/main/resources/wsdl/OrderService.wsdl b/quickstarts/transform-smooks/src/main/resources/wsdl/OrderService.wsdl similarity index 100% rename from transform-smooks/src/main/resources/wsdl/OrderService.wsdl rename to quickstarts/transform-smooks/src/main/resources/wsdl/OrderService.wsdl diff --git a/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/ServiceTransformationClient.java b/quickstarts/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/ServiceTransformationClient.java similarity index 100% rename from transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/ServiceTransformationClient.java rename to quickstarts/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/ServiceTransformationClient.java diff --git a/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/ServiceTransformationTest.java b/quickstarts/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/ServiceTransformationTest.java similarity index 100% rename from transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/ServiceTransformationTest.java rename to quickstarts/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/ServiceTransformationTest.java diff --git a/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/SmooksTransformationTest.java b/quickstarts/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/SmooksTransformationTest.java similarity index 100% rename from transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/SmooksTransformationTest.java rename to quickstarts/transform-smooks/src/test/java/org/switchyard/quickstarts/transform/smooks/SmooksTransformationTest.java diff --git a/transform-smooks/src/test/resources/META-INF/beans.xml b/quickstarts/transform-smooks/src/test/resources/META-INF/beans.xml similarity index 100% rename from transform-smooks/src/test/resources/META-INF/beans.xml rename to quickstarts/transform-smooks/src/test/resources/META-INF/beans.xml diff --git a/transform-smooks/src/test/resources/log4j.xml b/quickstarts/transform-smooks/src/test/resources/log4j.xml similarity index 100% rename from transform-smooks/src/test/resources/log4j.xml rename to quickstarts/transform-smooks/src/test/resources/log4j.xml diff --git a/transform-smooks/src/test/resources/xml/order.xml b/quickstarts/transform-smooks/src/test/resources/xml/order.xml similarity index 100% rename from transform-smooks/src/test/resources/xml/order.xml rename to quickstarts/transform-smooks/src/test/resources/xml/order.xml diff --git a/transform-smooks/src/test/resources/xml/orderAck.xml b/quickstarts/transform-smooks/src/test/resources/xml/orderAck.xml similarity index 100% rename from transform-smooks/src/test/resources/xml/orderAck.xml rename to quickstarts/transform-smooks/src/test/resources/xml/orderAck.xml diff --git a/transform-smooks/src/test/resources/xml/soap-request.xml b/quickstarts/transform-smooks/src/test/resources/xml/soap-request.xml similarity index 100% rename from transform-smooks/src/test/resources/xml/soap-request.xml rename to quickstarts/transform-smooks/src/test/resources/xml/soap-request.xml diff --git a/transform-smooks/src/test/resources/xml/soap-response.xml b/quickstarts/transform-smooks/src/test/resources/xml/soap-response.xml similarity index 100% rename from transform-smooks/src/test/resources/xml/soap-response.xml rename to quickstarts/transform-smooks/src/test/resources/xml/soap-response.xml diff --git a/transform-smooks/transform-smooks.jpg b/quickstarts/transform-smooks/transform-smooks.jpg similarity index 100% rename from transform-smooks/transform-smooks.jpg rename to quickstarts/transform-smooks/transform-smooks.jpg diff --git a/transform-xslt/Readme.md b/quickstarts/transform-xslt/Readme.md similarity index 100% rename from transform-xslt/Readme.md rename to quickstarts/transform-xslt/Readme.md diff --git a/quickstarts/transform-xslt/pom.xml b/quickstarts/transform-xslt/pom.xml new file mode 100644 index 000000000..209e1fc94 --- /dev/null +++ b/quickstarts/transform-xslt/pom.xml @@ -0,0 +1,262 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-transform-xslt + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: transform-xslt + Quickstart : XSLT Transformation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.transform.xslt + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + org.apache.httpcomponents + httpclient + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.transform.xslt.XSLTClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/transform-xslt/src/main/java/org/switchyard/quickstarts/transform/xslt/OrderService.java b/quickstarts/transform-xslt/src/main/java/org/switchyard/quickstarts/transform/xslt/OrderService.java similarity index 100% rename from transform-xslt/src/main/java/org/switchyard/quickstarts/transform/xslt/OrderService.java rename to quickstarts/transform-xslt/src/main/java/org/switchyard/quickstarts/transform/xslt/OrderService.java diff --git a/transform-xslt/src/main/java/org/switchyard/quickstarts/transform/xslt/OrderServiceBean.java b/quickstarts/transform-xslt/src/main/java/org/switchyard/quickstarts/transform/xslt/OrderServiceBean.java similarity index 100% rename from transform-xslt/src/main/java/org/switchyard/quickstarts/transform/xslt/OrderServiceBean.java rename to quickstarts/transform-xslt/src/main/java/org/switchyard/quickstarts/transform/xslt/OrderServiceBean.java diff --git a/transform-xslt/src/main/resources/META-INF/beans.xml b/quickstarts/transform-xslt/src/main/resources/META-INF/beans.xml similarity index 100% rename from transform-xslt/src/main/resources/META-INF/beans.xml rename to quickstarts/transform-xslt/src/main/resources/META-INF/beans.xml diff --git a/transform-xslt/src/main/resources/META-INF/switchyard.xml b/quickstarts/transform-xslt/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from transform-xslt/src/main/resources/META-INF/switchyard.xml rename to quickstarts/transform-xslt/src/main/resources/META-INF/switchyard.xml diff --git a/transform-xslt/src/main/resources/wsdl/OrderService.wsdl b/quickstarts/transform-xslt/src/main/resources/wsdl/OrderService.wsdl similarity index 100% rename from transform-xslt/src/main/resources/wsdl/OrderService.wsdl rename to quickstarts/transform-xslt/src/main/resources/wsdl/OrderService.wsdl diff --git a/transform-xslt/src/main/resources/xslt/order.xslt b/quickstarts/transform-xslt/src/main/resources/xslt/order.xslt similarity index 100% rename from transform-xslt/src/main/resources/xslt/order.xslt rename to quickstarts/transform-xslt/src/main/resources/xslt/order.xslt diff --git a/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/WebServiceTest.java b/quickstarts/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/WebServiceTest.java similarity index 100% rename from transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/WebServiceTest.java rename to quickstarts/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/WebServiceTest.java diff --git a/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/XSLTClient.java b/quickstarts/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/XSLTClient.java similarity index 100% rename from transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/XSLTClient.java rename to quickstarts/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/XSLTClient.java diff --git a/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/XsltTransformationTest.java b/quickstarts/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/XsltTransformationTest.java similarity index 100% rename from transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/XsltTransformationTest.java rename to quickstarts/transform-xslt/src/test/java/org/switchyard/quickstarts/transform/xslt/XsltTransformationTest.java diff --git a/transform-xslt/src/test/resources/META-INF/beans.xml b/quickstarts/transform-xslt/src/test/resources/META-INF/beans.xml similarity index 100% rename from transform-xslt/src/test/resources/META-INF/beans.xml rename to quickstarts/transform-xslt/src/test/resources/META-INF/beans.xml diff --git a/transform-xslt/src/test/resources/xml/order.xml b/quickstarts/transform-xslt/src/test/resources/xml/order.xml similarity index 100% rename from transform-xslt/src/test/resources/xml/order.xml rename to quickstarts/transform-xslt/src/test/resources/xml/order.xml diff --git a/transform-xslt/src/test/resources/xml/orderAck.xml b/quickstarts/transform-xslt/src/test/resources/xml/orderAck.xml similarity index 100% rename from transform-xslt/src/test/resources/xml/orderAck.xml rename to quickstarts/transform-xslt/src/test/resources/xml/orderAck.xml diff --git a/transform-xslt/src/test/resources/xml/soap-request.xml b/quickstarts/transform-xslt/src/test/resources/xml/soap-request.xml similarity index 100% rename from transform-xslt/src/test/resources/xml/soap-request.xml rename to quickstarts/transform-xslt/src/test/resources/xml/soap-request.xml diff --git a/transform-xslt/src/test/resources/xml/soap-response.xml b/quickstarts/transform-xslt/src/test/resources/xml/soap-response.xml similarity index 100% rename from transform-xslt/src/test/resources/xml/soap-response.xml rename to quickstarts/transform-xslt/src/test/resources/xml/soap-response.xml diff --git a/transform-xslt/transform-xslt.jpg b/quickstarts/transform-xslt/transform-xslt.jpg similarity index 100% rename from transform-xslt/transform-xslt.jpg rename to quickstarts/transform-xslt/transform-xslt.jpg diff --git a/validate-xml/Readme.md b/quickstarts/validate-xml/Readme.md similarity index 100% rename from validate-xml/Readme.md rename to quickstarts/validate-xml/Readme.md diff --git a/quickstarts/validate-xml/pom.xml b/quickstarts/validate-xml/pom.xml new file mode 100644 index 000000000..4ae3c0f57 --- /dev/null +++ b/quickstarts/validate-xml/pom.xml @@ -0,0 +1,262 @@ + + + + 4.0.0 + org.switchyard.quickstarts + switchyard-validate-xml + 2.1.0-SNAPSHOT + bundle + SwitchYard Quickstart: validate-xml + Quickstart : XML Message Validation + http://switchyard.org + + JBoss by Red Hat + http://jboss.org + + + + SwitchYard committers + + + + scm:git:https://github.com/jboss-switchyard/quickstarts.git + scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git + http://github.com/jboss-switchyard/quickstarts + + + + Apache License, Version 2.0 + repo + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + ${project.groupId}.switchyard.validate.xml + true + 9999 + 1.6 + 1.6 + * + + org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", + org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", + osgi.extender; filter:="(osgi.extender=pax.cdi)" + + + org.switchyard,org.switchyard.* + + 1.3.1 + 2.4.0 + 1.0.2.Final + + + + + org.switchyard + switchyard-bom + ${project.version} + import + pom + + + + + + org.switchyard + switchyard-api + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard + switchyard-test + test + + + org.switchyard.components + switchyard-component-test-mixin-cdi + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + junit + junit + test + + + org.apache.httpcomponents + httpclient + test + + + + ${project.artifactId} + + + org.switchyard + switchyard-plugin + ${project.version} + + + + configure + + + + + + org.apache.felix + maven-bundle-plugin + ${version.felix.maven} + true + + false + + ${bundle.symbolic.name} + ${switchyard.osgi.dynamic} + !* + ${switchyard.osgi.import} + {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml + ${switchyard.osgi.require.capability} + + + + ${project.artifactId} + ${project.groupId} + ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${version.enforcer.maven} + + + enforce-versions + + enforce + + clean + + + + 1.7 + + + + + + + + org.wildfly.plugins + wildfly-maven-plugin + ${version.wildfly.maven} + + + deploy + install + + deploy-only + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + undeploy + clean + + undeploy + + + ${project.build.finalName}.jar + ${deploy.skip} + + + + + + org.codehaus.mojo + exec-maven-plugin + + test + org.switchyard.quickstarts.validate.xml.ValidationClient + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.1 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + deploy + + false + + + + karaf + + + + org.codehaus.mojo + exec-maven-plugin + + + + org.switchyard.component.soap.client.port + 8181/cxf + + + + + + + + + wildfly + + 9990 + + + + diff --git a/validate-xml/src/main/java/org/switchyard/quickstarts/validate/xml/OrderService.java b/quickstarts/validate-xml/src/main/java/org/switchyard/quickstarts/validate/xml/OrderService.java similarity index 100% rename from validate-xml/src/main/java/org/switchyard/quickstarts/validate/xml/OrderService.java rename to quickstarts/validate-xml/src/main/java/org/switchyard/quickstarts/validate/xml/OrderService.java diff --git a/validate-xml/src/main/java/org/switchyard/quickstarts/validate/xml/OrderServiceBean.java b/quickstarts/validate-xml/src/main/java/org/switchyard/quickstarts/validate/xml/OrderServiceBean.java similarity index 100% rename from validate-xml/src/main/java/org/switchyard/quickstarts/validate/xml/OrderServiceBean.java rename to quickstarts/validate-xml/src/main/java/org/switchyard/quickstarts/validate/xml/OrderServiceBean.java diff --git a/validate-xml/src/main/resources/META-INF/beans.xml b/quickstarts/validate-xml/src/main/resources/META-INF/beans.xml similarity index 100% rename from validate-xml/src/main/resources/META-INF/beans.xml rename to quickstarts/validate-xml/src/main/resources/META-INF/beans.xml diff --git a/validate-xml/src/main/resources/META-INF/switchyard.xml b/quickstarts/validate-xml/src/main/resources/META-INF/switchyard.xml similarity index 100% rename from validate-xml/src/main/resources/META-INF/switchyard.xml rename to quickstarts/validate-xml/src/main/resources/META-INF/switchyard.xml diff --git a/validate-xml/src/main/resources/wsdl/OrderService.wsdl b/quickstarts/validate-xml/src/main/resources/wsdl/OrderService.wsdl similarity index 100% rename from validate-xml/src/main/resources/wsdl/OrderService.wsdl rename to quickstarts/validate-xml/src/main/resources/wsdl/OrderService.wsdl diff --git a/validate-xml/src/main/resources/xsd/catalog.xml b/quickstarts/validate-xml/src/main/resources/xsd/catalog.xml similarity index 100% rename from validate-xml/src/main/resources/xsd/catalog.xml rename to quickstarts/validate-xml/src/main/resources/xsd/catalog.xml diff --git a/validate-xml/src/main/resources/xsd/orders-base.xsd b/quickstarts/validate-xml/src/main/resources/xsd/orders-base.xsd similarity index 100% rename from validate-xml/src/main/resources/xsd/orders-base.xsd rename to quickstarts/validate-xml/src/main/resources/xsd/orders-base.xsd diff --git a/validate-xml/src/main/resources/xsd/orders.xsd b/quickstarts/validate-xml/src/main/resources/xsd/orders.xsd similarity index 100% rename from validate-xml/src/main/resources/xsd/orders.xsd rename to quickstarts/validate-xml/src/main/resources/xsd/orders.xsd diff --git a/validate-xml/src/main/resources/xslt/order.xslt b/quickstarts/validate-xml/src/main/resources/xslt/order.xslt similarity index 100% rename from validate-xml/src/main/resources/xslt/order.xslt rename to quickstarts/validate-xml/src/main/resources/xslt/order.xslt diff --git a/validate-xml/src/test/java/org/switchyard/quickstarts/validate/xml/ValidationClient.java b/quickstarts/validate-xml/src/test/java/org/switchyard/quickstarts/validate/xml/ValidationClient.java similarity index 100% rename from validate-xml/src/test/java/org/switchyard/quickstarts/validate/xml/ValidationClient.java rename to quickstarts/validate-xml/src/test/java/org/switchyard/quickstarts/validate/xml/ValidationClient.java diff --git a/validate-xml/src/test/java/org/switchyard/quickstarts/validate/xml/WebServiceTest.java b/quickstarts/validate-xml/src/test/java/org/switchyard/quickstarts/validate/xml/WebServiceTest.java similarity index 100% rename from validate-xml/src/test/java/org/switchyard/quickstarts/validate/xml/WebServiceTest.java rename to quickstarts/validate-xml/src/test/java/org/switchyard/quickstarts/validate/xml/WebServiceTest.java diff --git a/validate-xml/src/test/resources/META-INF/beans.xml b/quickstarts/validate-xml/src/test/resources/META-INF/beans.xml similarity index 100% rename from validate-xml/src/test/resources/META-INF/beans.xml rename to quickstarts/validate-xml/src/test/resources/META-INF/beans.xml diff --git a/validate-xml/src/test/resources/xml/soap-request-with-invalid-element.xml b/quickstarts/validate-xml/src/test/resources/xml/soap-request-with-invalid-element.xml similarity index 100% rename from validate-xml/src/test/resources/xml/soap-request-with-invalid-element.xml rename to quickstarts/validate-xml/src/test/resources/xml/soap-request-with-invalid-element.xml diff --git a/validate-xml/src/test/resources/xml/soap-request.xml b/quickstarts/validate-xml/src/test/resources/xml/soap-request.xml similarity index 100% rename from validate-xml/src/test/resources/xml/soap-request.xml rename to quickstarts/validate-xml/src/test/resources/xml/soap-request.xml diff --git a/validate-xml/src/test/resources/xml/soap-response-validation-failed.xml b/quickstarts/validate-xml/src/test/resources/xml/soap-response-validation-failed.xml similarity index 100% rename from validate-xml/src/test/resources/xml/soap-response-validation-failed.xml rename to quickstarts/validate-xml/src/test/resources/xml/soap-response-validation-failed.xml diff --git a/validate-xml/src/test/resources/xml/soap-response.xml b/quickstarts/validate-xml/src/test/resources/xml/soap-response.xml similarity index 100% rename from validate-xml/src/test/resources/xml/soap-response.xml rename to quickstarts/validate-xml/src/test/resources/xml/soap-response.xml diff --git a/validate-xml/validate-xml.jpg b/quickstarts/validate-xml/validate-xml.jpg similarity index 100% rename from validate-xml/validate-xml.jpg rename to quickstarts/validate-xml/validate-xml.jpg diff --git a/release/.gitignore b/release/.gitignore new file mode 100644 index 000000000..61adfd6ac --- /dev/null +++ b/release/.gitignore @@ -0,0 +1,13 @@ +.project +.classpath +.settings/ +target/ +.checkstyle +*.iml +*.ipr +*.iws +.DS_Store +transaction.log +.fbExcludeFilterFile +.factorypath +.idea diff --git a/release/README.md b/release/README.md new file mode 100644 index 000000000..e3d776983 --- /dev/null +++ b/release/README.md @@ -0,0 +1,16 @@ +# SwitchYard Release Distributions + +This repository houses the build scripts for the SwitchYard Release Distributions. To build, just +clone this repository and run "mvn clean package" in the clone root directory, or in the root +folder of the base JBoss Application Server version on which you would like to run SwitchYard. + +These scripts create JBoss Application server zip files with SwitchYard pre-installed and ready-to-go. +The zip files are also available (pre-built) in the +[JBoss Nexus Maven Repository](https://repository.jboss.org/nexus/content/groups/public/) +(groupId [org.switchyard](https://repository.jboss.org/nexus/content/groups/public/org/switchyard/), +artifactIds [switchyard-release-as6](https://repository.jboss.org/nexus/content/groups/public/org/switchyard/switchyard-release-as6) +and [switchyard-release-as7](https://repository.jboss.org/nexus/content/groups/public/org/switchyard/switchyard-release-as7)), +which means you can skip the build step and go straight to running SwitchYard. + +The assembly definition for both release distributions assumes that the quickstarts repository has been checked out and exists in the same directory as your release checkout (i.e. quickstarts and release share the same parent directory). The build will still work if this directory is not present, but the quickstarts will not be included in the built distributions. + diff --git a/release/admin/rhq/pom.xml b/release/admin/rhq/pom.xml new file mode 100644 index 000000000..70a4f3d7a --- /dev/null +++ b/release/admin/rhq/pom.xml @@ -0,0 +1,118 @@ + + + + 4.0.0 + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../../pom.xml + + switchyard-rhq-plugin + jar + SwitchYard: RHQ Plugin + SwitchYard RHQ Plugin + + + org.rhq + rhq-enterprise-comm + provided + + + org.rhq + rhq-jboss-as-7-plugin + provided + + + mc4j + org-mc4j-ems + provided + + + org.rhq + rhq-core-domain + provided + + + org.rhq + rhq-core-plugin-api + provided + + + org.rhq + rhq-core-native-system + provided + + + org.rhq + rhq-core-plugin-container + test + + + org.hibernate + hibernate-core + provided + + + commons-logging + commons-logging + provided + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-mapper-asl + + + + + + maven-dependency-plugin + + + copy-deps + process-resources + + copy + + + + + org.rhq + rhq-enterprise-comm + ${version.org.rhq} + + + org.rhq + rhq-jmx-plugin + ${version.org.rhq} + + + mc4j + org-mc4j-ems + ${version.mc4j} + + + ${project.build.outputDirectory}/lib + + + + + + + diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ApplicationDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ApplicationDiscoveryComponent.java new file mode 100644 index 000000000..5d4c9f3ff --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ApplicationDiscoveryComponent.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.Application; + +/** + * SwitchYard Application Discovery Component + */ +public class ApplicationDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ApplicationDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final SwitchYardResourceComponent parent = context.getParentResourceComponent(); + + final Map applications = parent.getApplications(); + + if (applications != null) { + for (Application application : applications.values()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + final QName name = application.getName(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), name.toString(), + name.getLocalPart(), + name.getNamespaceURI(), null, + pluginConfig, null); + + discoveredResources.add(resource); + + if (LOG.isDebugEnabled()) { + LOG.debug("Discovered SwitchYard Application " + application); + } + } + } + + return discoveredResources; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ApplicationResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ApplicationResourceComponent.java new file mode 100644 index 000000000..f61ef60be --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ApplicationResourceComponent.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.Collections; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Application; +import org.switchyard.rhq.plugin.model.ComponentService; +import org.switchyard.rhq.plugin.model.ComponentServiceMetrics; +import org.switchyard.rhq.plugin.model.Reference; +import org.switchyard.rhq.plugin.model.ReferenceMetrics; +import org.switchyard.rhq.plugin.model.Service; +import org.switchyard.rhq.plugin.model.ServiceMetrics; + +/** + * SwitchYard Application Resource Component + */ +public class ApplicationResourceComponent extends BaseSwitchYardResourceComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ApplicationResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final Application application = getApplication(); + return (application == null ? AvailabilityType.DOWN : AvailabilityType.UP); + } + + public Map getServices() { + final Application application = getApplication(); + if (application == null) { + return Collections.emptyMap(); + } else { + return application.getServices(); + } + } + + public Map getReferences() { + final Application application = getApplication(); + if (application == null) { + return Collections.emptyMap(); + } else { + return application.getReferences(); + } + } + + public Map getComponentServices() { + final Application application = getApplication(); + if (application == null) { + return Collections.emptyMap(); + } else { + return application.getComponentServices(); + } + } + + public Application getApplication() { + final String applicationKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getApplication(applicationKey); + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } + + public Map getServiceMetrics() { + final String applicationKey = getResourceContext().getResourceKey(); + final Map> serviceMetricsMap = getResourceContext().getParentResourceComponent().getServiceMetrics(); + return serviceMetricsMap.get(applicationKey); + } + + public Map getReferenceMetrics() { + final String applicationKey = getResourceContext().getResourceKey(); + final Map> referenceMetricsMap = getResourceContext().getParentResourceComponent().getReferenceMetrics(); + return referenceMetricsMap.get(applicationKey); + } + + public Map getComponentServiceMetrics() { + final String applicationKey = getResourceContext().getResourceKey(); + final Map> componentServiceMetricsMap = getResourceContext().getParentResourceComponent().getComponentServiceMetrics(); + return componentServiceMetricsMap.get(applicationKey); + } + + public void clearApplications() { + getResourceContext().getParentResourceComponent().clearApplications(); + } + + public void clearServiceMetrics() { + getResourceContext().getParentResourceComponent().clearServiceMetrics(); + } + + public void clearReferenceMetrics() { + getResourceContext().getParentResourceComponent().clearReferenceMetrics(); + } + + public void clearComponentServiceMetrics() { + getResourceContext().getParentResourceComponent().clearComponentServiceMetrics(); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/BaseSwitchYardResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/BaseSwitchYardResourceComponent.java new file mode 100644 index 000000000..7677af5eb --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/BaseSwitchYardResourceComponent.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_AVERAGE_PROCESSING_TIME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_FAULT_COUNT; +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_MAX_PROCESSING_TIME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_MIN_PROCESSING_TIME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_SUCCESS_COUNT; +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_TOTAL_COUNT; +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_TOTAL_PROCESSING_TIME; + +import org.apache.commons.logging.Log; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.inventory.InvalidPluginConfigurationException; +import org.rhq.core.pluginapi.inventory.ResourceComponent; +import org.rhq.core.pluginapi.inventory.ResourceContext; +import org.switchyard.rhq.plugin.model.Metrics; + +/** + * Base SwitchYard Component + */ +abstract class BaseSwitchYardResourceComponent> implements ResourceComponent { + /** + * The current resource context. + */ + private ResourceContext resourceContext; + + @Override + public void start(ResourceContext context) + throws InvalidPluginConfigurationException, Exception { + this.resourceContext = context; + } + + protected ResourceContext getResourceContext() { + return resourceContext; + } + + @Override + public void stop() { + return; + } + + protected abstract Log getLog(); + + protected MeasurementDataNumeric getCommonMetric(final MeasurementScheduleRequest request, final Metrics metrics) { + final String name = request.getName(); + if (METRIC_SUCCESS_COUNT.equals(name)) { + return new MeasurementDataNumeric(request, Double.valueOf(metrics.getSuccessCount())); + } else if (METRIC_FAULT_COUNT.equals(name)) { + return new MeasurementDataNumeric(request, Double.valueOf(metrics.getFaultCount())); + } else if (METRIC_TOTAL_COUNT.equals(name)) { + return new MeasurementDataNumeric(request, Double.valueOf(metrics.getTotalCount())); + } else if (METRIC_TOTAL_PROCESSING_TIME.equals(name)) { + return new MeasurementDataNumeric(request, Double.valueOf(metrics.getTotalTime())); + } else if (METRIC_AVERAGE_PROCESSING_TIME.equals(name)) { + return new MeasurementDataNumeric(request, Double.valueOf(metrics.getAverageTime())); + } else if (METRIC_MIN_PROCESSING_TIME.equals(name)) { + return new MeasurementDataNumeric(request, Double.valueOf(metrics.getMinTime())); + } else if (METRIC_MAX_PROCESSING_TIME.equals(name)) { + return new MeasurementDataNumeric(request, Double.valueOf(metrics.getMaxTime())); + } else { + return null; + } + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentReferenceDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentReferenceDiscoveryComponent.java new file mode 100644 index 000000000..e1276ae92 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentReferenceDiscoveryComponent.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.ComponentReference; + +/** + * SwitchYard Component Reference Discovery Component + */ +public class ComponentReferenceDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ComponentReferenceDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ComponentServiceResourceComponent parent = context.getParentResourceComponent(); + + final Map references = parent.getReferences(); + + if (references != null) { + for (ComponentReference reference : references.values()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + final QName name = reference.getName(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), name.toString(), + name.getLocalPart(), + name.getNamespaceURI(), null, + pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Component Reference " + reference); + } + } + + return discoveredResources; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentReferenceResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentReferenceResourceComponent.java new file mode 100644 index 000000000..270b39036 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentReferenceResourceComponent.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Application; +import org.switchyard.rhq.plugin.model.ComponentReference; +import org.switchyard.rhq.plugin.model.ComponentReferenceMetrics; +import org.switchyard.rhq.plugin.model.ComponentService; + +/** + * SwitchYard Component Reference Resource Component + */ +public class ComponentReferenceResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ComponentReferenceResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final ComponentReference componentReference = getComponentReference(); + return (componentReference == null) ? AvailabilityType.DOWN : AvailabilityType.UP; + } + + public ComponentReference getComponentReference() { + final String referenceKey = getResourceContext().getResourceKey(); + return getComponentService().getReferences().get(referenceKey); + } + + public ComponentService getComponentService() { + return getResourceContext().getParentResourceComponent().getComponentService(); + } + + public Application getApplication() { + return getResourceContext().getParentResourceComponent().getApplication(); + } + + private ComponentReferenceMetrics getComponentReferenceMetrics() { + final String componentReferenceKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getComponentReferenceMetrics().get(componentReferenceKey); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final ComponentReferenceMetrics metrics = getComponentReferenceMetrics(); + if (metrics != null) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Component Reference measurement " + request.getName()); + } + } + } + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceDiscoveryComponent.java new file mode 100644 index 000000000..8787f7854 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceDiscoveryComponent.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.ComponentService; + +/** + * SwitchYard Component Service Discovery Component + */ +public class ComponentServiceDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ComponentServiceDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ApplicationResourceComponent parent = context.getParentResourceComponent(); + + final Map componentServices = parent.getComponentServices(); + + for (ComponentService componentService : componentServices.values()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + final QName name = componentService.getName(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), name.toString(), + name.getLocalPart(), + name.getNamespaceURI(), null, + pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Component Service " + componentService); + } + + return discoveredResources; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceOperationDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceOperationDiscoveryComponent.java new file mode 100644 index 000000000..6344a71a8 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceOperationDiscoveryComponent.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.ComponentService; +import org.switchyard.rhq.plugin.model.OperationMetrics; + +/** + * SwitchYard Component Service Operation Discovery Component + */ +public class ComponentServiceOperationDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ComponentServiceOperationDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ComponentServiceResourceComponent parent = context.getParentResourceComponent(); + final ComponentService service = parent.getComponentService() ; + if (service != null) + { + Map metrics = parent.getOperationMetrics(); + final QName serviceName = service.getName(); + + for (String operationName : metrics.keySet()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), operationName, operationName, + serviceName.getNamespaceURI(), null, pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Component Service Operation " + operationName); + } + } + + return discoveredResources; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceOperationResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceOperationResourceComponent.java new file mode 100644 index 000000000..440fec011 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceOperationResourceComponent.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.OperationMetrics; + +/** + * SwitchYard Component Service Operation Resource Component + */ +public class ComponentServiceOperationResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ComponentServiceOperationResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final OperationMetrics metrics = getOperationMetrics(); + return (metrics == null) ? AvailabilityType.DOWN : AvailabilityType.UP; + } + + public OperationMetrics getOperationMetrics() { + final String operationKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getOperationMetrics().get(operationKey); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final OperationMetrics metrics = getOperationMetrics(); + if (metrics != null) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Component Service Operation measurement " + request.getName()); + } + } + } + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceResourceComponent.java new file mode 100644 index 000000000..8fbbf1375 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ComponentServiceResourceComponent.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_RESET; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.core.pluginapi.operation.OperationFacet; +import org.rhq.core.pluginapi.operation.OperationResult; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Application; +import org.switchyard.rhq.plugin.model.ComponentReference; +import org.switchyard.rhq.plugin.model.ComponentReferenceMetrics; +import org.switchyard.rhq.plugin.model.ComponentService; +import org.switchyard.rhq.plugin.model.ComponentServiceMetrics; +import org.switchyard.rhq.plugin.model.OperationMetrics; +import org.switchyard.rhq.plugin.operations.ResetComponentServiceMetrics; + +/** + * SwitchYard Component Service Resource Component + */ +public class ComponentServiceResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet, OperationFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ComponentServiceResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final ComponentService componentService = getComponentService(); + return (componentService == null) ? AvailabilityType.DOWN : AvailabilityType.UP; + } + + public Map getReferences() { + final ComponentService componentService = getComponentService(); + if (componentService == null) { + return Collections.emptyMap(); + } else { + return componentService.getReferences(); + } + } + + public ComponentService getComponentService() { + final String componentServiceKey = getResourceContext().getResourceKey(); + return getApplication().getComponentServices().get(componentServiceKey); + } + + public Application getApplication() { + return getResourceContext().getParentResourceComponent().getApplication(); + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } + + private ComponentServiceMetrics getComponentServiceMetrics() { + final String componentServiceKey = getResourceContext().getResourceKey(); + final Map componentServiceMetrics = getResourceContext().getParentResourceComponent().getComponentServiceMetrics(); + return (componentServiceMetrics != null) ? componentServiceMetrics.get(componentServiceKey) : null; + } + + public Map getOperationMetrics() { + final ComponentServiceMetrics componentServiceMetrics = getComponentServiceMetrics(); + if (componentServiceMetrics != null) { + return componentServiceMetrics.getOperationMetrics(); + } else { + return Collections.emptyMap(); + } + } + + public Map getComponentReferenceMetrics() { + final ComponentServiceMetrics componentServiceMetrics = getComponentServiceMetrics(); + if (componentServiceMetrics != null) { + return componentServiceMetrics.getComponentReferenceMetrics(); + } else { + return Collections.emptyMap(); + } + } + + public void clearComponentServiceMetrics() { + getResourceContext().getParentResourceComponent().clearComponentServiceMetrics(); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final ComponentServiceMetrics metrics = getComponentServiceMetrics(); + if (metrics != null) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Component Service measurement " + request.getName()); + } + } + } + } + + @Override + public OperationResult invokeOperation(final String name, final Configuration parameters) throws InterruptedException, Exception { + if (OPERATION_RESET.equals(name)) { + final ComponentService componentService = getComponentService(); + final Application application = getApplication(); + if ((componentService != null) && (application != null)) { + final String componentServiceName = componentService.getName().toString(); + final String applicationName = application.getName().toString(); + execute(new ResetComponentServiceMetrics(applicationName, componentServiceName), Void.class); + clearComponentServiceMetrics(); + } + } else if (LOG.isDebugEnabled()) { + LOG.warn("Unknown Component Service operation " + name); + } + return null; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceBindingDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceBindingDiscoveryComponent.java new file mode 100644 index 000000000..b0187404c --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceBindingDiscoveryComponent.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.Gateway; + +/** + * SwitchYard Reference Binding Discovery Component + */ +public class ReferenceBindingDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ReferenceBindingDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ReferenceResourceComponent parent = context.getParentResourceComponent(); + + final Map gateways = parent.getGateways(); + + if (gateways != null) { + for (Gateway gateway : gateways.values()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + final QName name = gateway.getName(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), name.toString(), + name.getLocalPart(), + name.getNamespaceURI(), null, + pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Reference Binding " + gateway); + } + } + + return discoveredResources; + } +} \ No newline at end of file diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceBindingResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceBindingResourceComponent.java new file mode 100644 index 000000000..0f977d3ce --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceBindingResourceComponent.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_STATE; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_START; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_STOP; + +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementDataTrait; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.core.pluginapi.operation.OperationFacet; +import org.rhq.core.pluginapi.operation.OperationResult; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Application; +import org.switchyard.rhq.plugin.model.Gateway; +import org.switchyard.rhq.plugin.model.GatewayMetrics; +import org.switchyard.rhq.plugin.model.Reference; +import org.switchyard.rhq.plugin.operations.StartGateway; +import org.switchyard.rhq.plugin.operations.StopGateway; + +/** + * SwitchYard Reference Binding Resource Component + */ +public class ReferenceBindingResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet, OperationFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ReferenceBindingResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final Gateway gateway = getGateway(); + return (gateway == null) ? AvailabilityType.DOWN : AvailabilityType.UP; + } + + public Gateway getGateway() { + final String gatewayKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getGateways().get(gatewayKey); + } + + public Reference getReference() { + return getResourceContext().getParentResourceComponent().getReference(); + } + + public Application getApplication() { + return getResourceContext().getParentResourceComponent().getApplication(); + } + + public GatewayMetrics getGatewayMetrics() { + final String operationKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getGatewayMetrics().get(operationKey); + } + + public void clearApplications() { + getResourceContext().getParentResourceComponent().clearApplications(); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final GatewayMetrics metrics = getGatewayMetrics(); + final Gateway gateway = getGateway(); + if ((metrics != null) && (gateway != null)) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else { + final String name = request.getName(); + if (METRIC_STATE.equals(name)) { + report.addData(new MeasurementDataTrait(request, gateway.getState())); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Reference Binding measurement " + request.getName()); + } + } + } + } + } + + @Override + public OperationResult invokeOperation(final String name, final Configuration parameters) throws InterruptedException, Exception { + if (OPERATION_START.equals(name)) { + final String bindingKey = getResourceContext().getResourceKey(); + final Reference reference = getReference(); + if (reference != null) { + final Application application = getApplication(); + if (application != null) { + final String referenceName = reference.getName().toString(); + final String applicationName = application.getName().toString(); + execute(new StartGateway(applicationName, referenceName, bindingKey, "reference"), Void.class); + clearApplications(); + } + } + } else if (OPERATION_STOP.equals(name)) { + final String bindingKey = getResourceContext().getResourceKey(); + final Reference reference = getReference(); + if (reference != null) { + final Application application = getApplication(); + if (application != null) { + final String referenceName = reference.getName().toString(); + final String applicationName = application.getName().toString(); + execute(new StopGateway(applicationName, referenceName, bindingKey, "reference"), Void.class); + clearApplications(); + } + } + } else if (LOG.isDebugEnabled()) { + LOG.warn("Unknown Reference Binding operation " + name); + } + return null; + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceDiscoveryComponent.java new file mode 100644 index 000000000..414144248 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceDiscoveryComponent.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.Reference; + +/** + * SwitchYard Reference Discovery Component + */ +public class ReferenceDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ReferenceDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ApplicationResourceComponent parent = context.getParentResourceComponent(); + + final Map references = parent.getReferences(); + + for (Reference reference : references.values()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + final QName name = reference.getName(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), name.toString(), + name.getLocalPart(), + name.getNamespaceURI(), null, + pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Reference " + reference); + } + + return discoveredResources; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceOperationDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceOperationDiscoveryComponent.java new file mode 100644 index 000000000..dc0cdfba7 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceOperationDiscoveryComponent.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.OperationMetrics; +import org.switchyard.rhq.plugin.model.Reference; + +/** + * SwitchYard Reference Operation Discovery Component + */ +public class ReferenceOperationDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ReferenceOperationDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ReferenceResourceComponent parent = context.getParentResourceComponent(); + final Reference reference = parent.getReference() ; + if (reference != null) + { + Map metrics = parent.getOperationMetrics(); + final QName referenceName = reference.getName(); + + for (String operationName : metrics.keySet()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), operationName, operationName, + referenceName.getNamespaceURI(), null, pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Reference Operation " + operationName); + } + } + + return discoveredResources; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceOperationResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceOperationResourceComponent.java new file mode 100644 index 000000000..51b69d737 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceOperationResourceComponent.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.OperationMetrics; + +/** + * SwitchYard Reference Operation Resource Component + */ +public class ReferenceOperationResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ReferenceOperationResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final OperationMetrics metrics = getOperationMetrics(); + return (metrics == null) ? AvailabilityType.DOWN : AvailabilityType.UP; + } + + public OperationMetrics getOperationMetrics() { + final String operationKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getOperationMetrics().get(operationKey); + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final OperationMetrics metrics = getOperationMetrics(); + if (metrics != null) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Reference Operation measurement " + request.getName()); + } + } + } + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceResourceComponent.java new file mode 100644 index 000000000..e9e1e3ffc --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ReferenceResourceComponent.java @@ -0,0 +1,145 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_RESET; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.core.pluginapi.operation.OperationFacet; +import org.rhq.core.pluginapi.operation.OperationResult; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Application; +import org.switchyard.rhq.plugin.model.Gateway; +import org.switchyard.rhq.plugin.model.GatewayMetrics; +import org.switchyard.rhq.plugin.model.OperationMetrics; +import org.switchyard.rhq.plugin.model.Reference; +import org.switchyard.rhq.plugin.model.ReferenceMetrics; +import org.switchyard.rhq.plugin.operations.ResetReferenceMetrics; + +/** + * SwitchYard Reference Resource Component + */ +public class ReferenceResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet, OperationFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ReferenceResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final Reference reference = getReference(); + return (reference != null) ? AvailabilityType.UP : AvailabilityType.DOWN; + } + + public Map getGateways() { + final Reference reference = getReference(); + if (reference == null) { + return Collections.emptyMap(); + } else { + return reference.getGateways(); + } + } + + public Reference getReference() { + final String referenceKey = getResourceContext().getResourceKey(); + return getApplication().getReferences().get(referenceKey); + } + + public Application getApplication() { + return getResourceContext().getParentResourceComponent().getApplication(); + } + + public ReferenceMetrics getReferenceMetrics() { + final String operationKey = getResourceContext().getResourceKey(); + final Map referenceMetrics = getResourceContext().getParentResourceComponent().getReferenceMetrics(); + return (referenceMetrics != null) ? referenceMetrics.get(operationKey) : null; + } + + public Map getOperationMetrics() { + final ReferenceMetrics referenceMetrics = getReferenceMetrics(); + if (referenceMetrics != null) { + return referenceMetrics.getOperationMetrics(); + } else { + return Collections.emptyMap(); + } + } + + public Map getGatewayMetrics() { + final ReferenceMetrics serviceMetrics = getReferenceMetrics(); + if (serviceMetrics != null) { + return serviceMetrics.getGatewayMetrics(); + } else { + return Collections.emptyMap(); + } + } + + public void clearReferenceMetrics() { + getResourceContext().getParentResourceComponent().clearReferenceMetrics(); + } + + public void clearApplications() { + getResourceContext().getParentResourceComponent().clearApplications(); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final ReferenceMetrics metrics = getReferenceMetrics(); + if (metrics != null) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Reference measurement " + request.getName()); + } + } + } + } + + @Override + public OperationResult invokeOperation(final String name, final Configuration parameters) throws InterruptedException, Exception { + if (OPERATION_RESET.equals(name)) { + final Reference reference = getReference(); + final Application application = getApplication(); + if ((reference != null) && (application != null)) { + final String referenceName = reference.getName().toString(); + final String applicationName = application.getName().toString(); + execute(new ResetReferenceMetrics(applicationName, referenceName), Void.class); + clearReferenceMetrics(); + } + } else if (LOG.isDebugEnabled()) { + LOG.warn("Unknown Referencs operation " + name); + } + return null; + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceBindingDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceBindingDiscoveryComponent.java new file mode 100644 index 000000000..bc03cb5c1 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceBindingDiscoveryComponent.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.Gateway; + +/** + * SwitchYard Service Binding Discovery Component + */ +public class ServiceBindingDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ServiceBindingDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ServiceResourceComponent parent = context.getParentResourceComponent(); + + final Map gateways = parent.getGateways(); + + if (gateways != null) { + for (Gateway gateway : gateways.values()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + final QName name = gateway.getName(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), name.toString(), + name.getLocalPart(), + name.getNamespaceURI(), null, + pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Service Binding " + gateway); + } + } + + return discoveredResources; + } +} \ No newline at end of file diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceBindingResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceBindingResourceComponent.java new file mode 100644 index 000000000..0dcc64043 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceBindingResourceComponent.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_STATE; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_START; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_STOP; + +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementDataTrait; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.core.pluginapi.operation.OperationFacet; +import org.rhq.core.pluginapi.operation.OperationResult; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Application; +import org.switchyard.rhq.plugin.model.Gateway; +import org.switchyard.rhq.plugin.model.GatewayMetrics; +import org.switchyard.rhq.plugin.model.Service; +import org.switchyard.rhq.plugin.operations.StartGateway; +import org.switchyard.rhq.plugin.operations.StopGateway; + +/** + * SwitchYard Service Binding Resource Component + */ +public class ServiceBindingResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet, OperationFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ServiceBindingResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final Gateway gateway = getGateway(); + return (gateway == null) ? AvailabilityType.DOWN : AvailabilityType.UP; + } + + public Gateway getGateway() { + final String gatewayKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getGateways().get(gatewayKey); + } + + public Service getService() { + return getResourceContext().getParentResourceComponent().getService(); + } + + public Application getApplication() { + return getResourceContext().getParentResourceComponent().getApplication(); + } + + public GatewayMetrics getGatewayMetrics() { + final String operationKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getGatewayMetrics().get(operationKey); + } + + public void clearApplications() { + getResourceContext().getParentResourceComponent().clearApplications(); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final GatewayMetrics metrics = getGatewayMetrics(); + final Gateway gateway = getGateway(); + if ((metrics != null) && (gateway != null)) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else { + final String name = request.getName(); + if (METRIC_STATE.equals(name)) { + report.addData(new MeasurementDataTrait(request, gateway.getState())); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Service Binding measurement " + request.getName()); + } + } + } + } + } + + @Override + public OperationResult invokeOperation(final String name, final Configuration parameters) throws InterruptedException, Exception { + if (OPERATION_START.equals(name)) { + final String bindingKey = getResourceContext().getResourceKey(); + final Service service = getService(); + if (service != null) { + final Application application = getApplication(); + if (application != null) { + final String serviceName = service.getName().toString(); + final String applicationName = application.getName().toString(); + execute(new StartGateway(applicationName, serviceName, bindingKey, "service"), Void.class); + clearApplications(); + } + } + } else if (OPERATION_STOP.equals(name)) { + final String bindingKey = getResourceContext().getResourceKey(); + final Service service = getService(); + if (service != null) { + final Application application = getApplication(); + if (application != null) { + final String serviceName = service.getName().toString(); + final String applicationName = application.getName().toString(); + execute(new StopGateway(applicationName, serviceName, bindingKey, "service"), Void.class); + clearApplications(); + } + } + } else if (LOG.isDebugEnabled()) { + LOG.warn("Unknown Service Binding operation " + name); + } + return null; + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceDiscoveryComponent.java new file mode 100644 index 000000000..66debd9e7 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceDiscoveryComponent.java @@ -0,0 +1,72 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.Service; + +/** + * SwitchYard Service Discovery Component + */ +public class ServiceDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ServiceDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ApplicationResourceComponent parent = context.getParentResourceComponent(); + + final Map services = parent.getServices(); + + for (Service service : services.values()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + final QName name = service.getName(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), name.toString(), + name.getLocalPart(), + name.getNamespaceURI(), null, + pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Service " + service); + } + + return discoveredResources; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceOperationDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceOperationDiscoveryComponent.java new file mode 100644 index 000000000..b98a114e8 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceOperationDiscoveryComponent.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.switchyard.rhq.plugin.model.OperationMetrics; +import org.switchyard.rhq.plugin.model.Service; + +/** + * SwitchYard Service Operation Discovery Component + */ +public class ServiceOperationDiscoveryComponent implements ResourceDiscoveryComponent { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ServiceOperationDiscoveryComponent.class); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext context) { + + final HashSet discoveredResources = new HashSet(); + + final ServiceResourceComponent parent = context.getParentResourceComponent(); + final Service service = parent.getService() ; + if (service != null) + { + Map metrics = parent.getOperationMetrics(); + final QName serviceName = service.getName(); + + for (String operationName : metrics.keySet()) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), operationName, operationName, + serviceName.getNamespaceURI(), null, pluginConfig, null); + + discoveredResources.add(resource); + + LOG.debug("Discovered SwitchYard Service Operation " + operationName); + } + } + + return discoveredResources; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceOperationResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceOperationResourceComponent.java new file mode 100644 index 000000000..157c9c1b3 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceOperationResourceComponent.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.OperationMetrics; + +/** + * SwitchYard Service Operation Resource Component + */ +public class ServiceOperationResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ServiceOperationResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final OperationMetrics metrics = getOperationMetrics(); + return (metrics == null) ? AvailabilityType.DOWN : AvailabilityType.UP; + } + + public OperationMetrics getOperationMetrics() { + final String operationKey = getResourceContext().getResourceKey(); + return getResourceContext().getParentResourceComponent().getOperationMetrics().get(operationKey); + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final OperationMetrics metrics = getOperationMetrics(); + if (metrics != null) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Service Operation measurement " + request.getName()); + } + } + } + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceResourceComponent.java new file mode 100644 index 000000000..6e3c2e454 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/ServiceResourceComponent.java @@ -0,0 +1,180 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_MAX_REQUESTS; +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_THROTTLING_ENABLED; +import static org.switchyard.rhq.plugin.SwitchYardConstants.METRIC_TIME_PERIOD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_PARAMETER_ENABLED; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_PARAMETER_MAX_REQUESTS; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_RESET; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_SET_THROTTLING; + +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.configuration.PropertySimple; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementDataTrait; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.core.pluginapi.operation.OperationFacet; +import org.rhq.core.pluginapi.operation.OperationResult; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Application; +import org.switchyard.rhq.plugin.model.Gateway; +import org.switchyard.rhq.plugin.model.GatewayMetrics; +import org.switchyard.rhq.plugin.model.OperationMetrics; +import org.switchyard.rhq.plugin.model.Service; +import org.switchyard.rhq.plugin.model.ServiceMetrics; +import org.switchyard.rhq.plugin.model.Throttling; +import org.switchyard.rhq.plugin.operations.ResetServiceMetrics; +import org.switchyard.rhq.plugin.operations.UpdateThrottling; + +/** + * SwitchYard Service Resource Component + */ +public class ServiceResourceComponent extends BaseSwitchYardResourceComponent implements MeasurementFacet, OperationFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(ServiceResourceComponent.class); + + protected Log getLog() { + return LOG; + } + + @Override + public AvailabilityType getAvailability() { + final Service service = getService(); + return (service == null ? AvailabilityType.DOWN : AvailabilityType.UP); + } + + public Map getGateways() { + final Service service = getService(); + if (service == null) { + return Collections.emptyMap(); + } else { + return service.getGateways(); + } + } + + public Service getService() { + final String serviceKey = getResourceContext().getResourceKey(); + return getApplication().getServices().get(serviceKey); + } + + public Application getApplication() { + return getResourceContext().getParentResourceComponent().getApplication(); + } + + public void clearServiceMetrics() { + getResourceContext().getParentResourceComponent().clearServiceMetrics(); + } + + private ServiceMetrics getServiceMetrics() { + final String serviceKey = getResourceContext().getResourceKey(); + final Map serviceMetrics = getResourceContext().getParentResourceComponent().getServiceMetrics(); + return (serviceMetrics != null) ? serviceMetrics.get(serviceKey) : null; + } + + public Map getOperationMetrics() { + final ServiceMetrics serviceMetrics = getServiceMetrics(); + if (serviceMetrics != null) { + return serviceMetrics.getOperationMetrics(); + } else { + return Collections.emptyMap(); + } + } + + public Map getGatewayMetrics() { + final ServiceMetrics serviceMetrics = getServiceMetrics(); + if (serviceMetrics != null) { + return serviceMetrics.getGatewayMetrics(); + } else { + return Collections.emptyMap(); + } + } + + public void clearApplications() { + getResourceContext().getParentResourceComponent().clearApplications(); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final ServiceMetrics metrics = getServiceMetrics(); + final Service service = getService(); + if ((metrics != null) && (service != null)) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else { + final String name = request.getName(); + final Throttling throttling = service.getThrottling(); + if (METRIC_THROTTLING_ENABLED.equals(name)) { + report.addData(new MeasurementDataTrait(request, Boolean.toString(throttling.isEnabled()))); + } else if (METRIC_TIME_PERIOD.equals(name)) { + report.addData(new MeasurementDataTrait(request, Long.toString(throttling.getTimePeriod()))); + } else if (METRIC_MAX_REQUESTS.equals(name)) { + report.addData(new MeasurementDataTrait(request, Integer.toString(throttling.getMaxRequests()))); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect Service measurement " + request.getName()); + } + } + } + } + } + + @Override + public OperationResult invokeOperation(final String name, final Configuration parameters) throws InterruptedException, Exception { + if (OPERATION_RESET.equals(name)) { + final Service service = getService(); + final Application application = getApplication(); + if ((service != null) && (application != null)) { + final String serviceName = service.getName().toString(); + final String applicationName = application.getName().toString(); + execute(new ResetServiceMetrics(applicationName, serviceName), Void.class); + clearServiceMetrics(); + } + } else if (OPERATION_SET_THROTTLING.equals(name)) { + final PropertySimple enabled = (PropertySimple) parameters.get(OPERATION_PARAMETER_ENABLED); + final PropertySimple maxRequests = (PropertySimple) parameters.get(OPERATION_PARAMETER_MAX_REQUESTS); + final Service service = getService(); + final Application application = getApplication(); + if ((service != null) && (application != null)) { + final String serviceName = service.getName().toString(); + final String applicationName = application.getName().toString(); + execute(new UpdateThrottling(applicationName, serviceName, + (enabled != null ? enabled.getBooleanValue() : null), + (maxRequests != null ? maxRequests.getIntegerValue() : null)), + Void.class); + clearApplications(); + } + } else if (LOG.isDebugEnabled()) { + LOG.warn("Unknown Service operation " + name); + } + return null; + } + + public T execute(final Operation operation, Class clazz) { + return getResourceContext().getParentResourceComponent().execute(operation, clazz); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardConstants.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardConstants.java new file mode 100644 index 000000000..8457a3bae --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardConstants.java @@ -0,0 +1,193 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import org.rhq.modules.plugins.jbossas7.json.Address; + +/** + * SwitchYard Constants + */ +public class SwitchYardConstants { + /** + * The SwitchYard subsystem address. + */ + public static final Address ADDRESS_SWITCHYARD = new Address("subsystem=switchyard"); + + /** + * The invocation outcome flag. + */ + public static final String INVOCATION_OUTCOME = "outcome"; + /** + * The invocation result. + */ + public static final String INVOCATION_RESULT = "result"; + /** + * The failure description value. + */ + public static final String INVOCATION_FAILURE_DESCRIPTION = "failure-description"; + /** + * The successful outcome value. + */ + public static final String OUTCOME_SUCCESS = "success"; + + + /** + * The get-version operation + */ + public static final String DMR_GET_VERSION = "get-version"; + /** + * The read-application operation + */ + public static final String DMR_READ_APPLICATION = "read-application"; + /** + * The read-service operation + */ + public static final String DMR_READ_SERVICE = "read-service"; + /** + * The read-reference operation + */ + public static final String DMR_READ_REFERENCE = "read-reference"; + /** + * The show-metrics operation + */ + public static final String DMR_SHOW_METRICS = "show-metrics"; + /** + * The reset-metrics operation + */ + public static final String DMR_RESET_METRICS = "reset-metrics"; + /** + * The start-gateway operation + */ + public static final String DMR_START_GATEWAY = "start-gateway"; + /** + * The stop-gateway operation + */ + public static final String DMR_STOP_GATEWAY = "stop-gateway"; + /** + * The update-throttling operation + */ + public static final String DMR_UPDATE_THROTTLING = "update-throttling"; + + + /** + * The name parameter + */ + public static final String PARAM_NAME = "name"; + /** + * The type parameter + */ + public static final String PARAM_TYPE = "type"; + /** + * The application-name parameter + */ + public static final String PARAM_APPLICATION_NAME = "application-name"; + /** + * The service-name parameter + */ + public static final String PARAM_SERVICE_NAME = "service-name"; + /** + * The reference-name parameter + */ + public static final String PARAM_REFERENCE_NAME = "reference-name"; + /** + * The throttling parameter + */ + public static final String PARAM_THROTTLING = "throttling"; + + + /** + * The reset operation + */ + public static final String OPERATION_RESET = "reset"; + /** + * The start operation + */ + public static final String OPERATION_START = "start"; + /** + * The stop operation + */ + public static final String OPERATION_STOP = "stop"; + /** + * The setThrottling operation + */ + public static final Object OPERATION_SET_THROTTLING = "setThrottling"; + /** + * The enabled parameter + */ + public static final String OPERATION_PARAMETER_ENABLED = "enabled"; + /** + * The maxRequests parameter + */ + public static final String OPERATION_PARAMETER_MAX_REQUESTS = "maxRequests"; + + + /** + * The SwitchYard component key. + */ + public static final String KEY_SWITCH_YARD = "SwitchYardSubsystem"; + /** + * The SwitchYard component description. + */ + public static final String DESCRIPTION_SWITCH_YARD = "Container for SwitchYard Applications"; + /** + * The SwitchYard component name. + */ + public static final String NAME_SWITCH_YARD = "SwitchYard"; + + + /** + * The success count metric + */ + public static final String METRIC_SUCCESS_COUNT = "SuccessCount"; + /** + * The fault count metric + */ + public static final String METRIC_FAULT_COUNT = "FaultCount"; + /** + * The total count metric + */ + public static final String METRIC_TOTAL_COUNT = "TotalCount"; + /** + * The total processing time metric + */ + public static final String METRIC_TOTAL_PROCESSING_TIME = "TotalProcessingTime"; + /** + * The average processing time metric + */ + public static final String METRIC_AVERAGE_PROCESSING_TIME = "AverageProcessingTime"; + /** + * The minimum processing time metric + */ + public static final String METRIC_MIN_PROCESSING_TIME = "MinProcessingTime"; + /** + * The maximum processing time metric + */ + public static final String METRIC_MAX_PROCESSING_TIME = "MaxProcessingTime"; + /** + * The throttling enabled metric + */ + public static final String METRIC_THROTTLING_ENABLED = "throttlingEnabled"; + /** + * The throttling time period metric + */ + public static final String METRIC_TIME_PERIOD = "TimePeriod"; + /** + * The throttling max requests metric + */ + public static final String METRIC_MAX_REQUESTS = "MaxRequests"; + /** + * The state metric + */ + public static final String METRIC_STATE = "State"; +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardDiscoveryComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardDiscoveryComponent.java new file mode 100644 index 000000000..2af0f9000 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardDiscoveryComponent.java @@ -0,0 +1,131 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.DESCRIPTION_SWITCH_YARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.KEY_SWITCH_YARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.NAME_SWITCH_YARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.INVOCATION_FAILURE_DESCRIPTION; +import static org.switchyard.rhq.plugin.SwitchYardConstants.INVOCATION_OUTCOME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.INVOCATION_RESULT; +import static org.switchyard.rhq.plugin.SwitchYardConstants.OUTCOME_SUCCESS; + +import java.util.HashSet; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.map.ObjectMapper; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; +import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext; +import org.rhq.modules.plugins.jbossas7.ASConnection; +import org.rhq.modules.plugins.jbossas7.BaseComponent; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.GetVersionResult; +import org.switchyard.rhq.plugin.operations.GetVersion; + +/** + * SwitchYard Discovery Component + */ +public class SwitchYardDiscoveryComponent implements ResourceDiscoveryComponent> { + /** + * The logger instance. + */ + private static final Log LOG = LogFactory.getLog(SwitchYardDiscoveryComponent.class); + + /** + * The JSON object mapper + */ + private static final ObjectMapper mapper = new ObjectMapper(); + + /** + * Discover existing resources. + * + * @param context + * The context for the current discovery component. + * @return The discovered resources. + */ + @Override + public Set discoverResources(final ResourceDiscoveryContext> context) { + + final HashSet discoveredResources = new HashSet(); + + final GetVersionResult result = execute(context.getParentResourceComponent(), new GetVersion(), GetVersionResult.class); + + if (result != null) { + final Configuration pluginConfig = context.getDefaultPluginConfiguration(); + + final DiscoveredResourceDetails resource = new DiscoveredResourceDetails( + context.getResourceType(), KEY_SWITCH_YARD, + NAME_SWITCH_YARD, result.getVersion(), + DESCRIPTION_SWITCH_YARD, pluginConfig, null); + + discoveredResources.add(resource); + + if (LOG.isDebugEnabled()) { + LOG.debug("Discovered SwitchYard subsystem for " + context.getPluginContainerName()); + } + } + + return discoveredResources; + } + + public static T execute(final BaseComponent server, + final Operation operation, final Class clazz) { + + final ASConnection asConnection = server.getASConnection(); + + final JsonNode jsonNode = asConnection.executeRaw(operation); + + if (jsonNode == null) { + if (LOG.isDebugEnabled()) { + LOG.debug("Receiver null response to operation " + operation); + } + return null; + } + + final JsonNode outcome = jsonNode.findValue(INVOCATION_OUTCOME); + if ((outcome == null) || !OUTCOME_SUCCESS.equals(outcome.asText())) { + if (LOG.isDebugEnabled()) { + final JsonNode failureDescription = jsonNode.findValue(INVOCATION_FAILURE_DESCRIPTION); + if (failureDescription != null) { + LOG.debug("Invocation failed for operation " + operation + ": " + failureDescription.asText()); + } else { + LOG.debug("Invocation failed for operation " + operation); + } + } + return null; + } + + final JsonNode result = jsonNode.findValue(INVOCATION_RESULT); + if (result == null) { + return null; + } + + final T response; + try { + response = mapper.readValue(result,clazz); + } catch (final Exception ex) { + if (LOG.isDebugEnabled()) { + LOG.debug("Failure during deserialisation of operation " + operation, ex); + } + return null; + } + + return response; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardResourceComponent.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardResourceComponent.java new file mode 100644 index 000000000..9c28ae7db --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/SwitchYardResourceComponent.java @@ -0,0 +1,294 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.rhq.core.domain.configuration.Configuration; +import org.rhq.core.domain.measurement.AvailabilityType; +import org.rhq.core.domain.measurement.MeasurementDataNumeric; +import org.rhq.core.domain.measurement.MeasurementReport; +import org.rhq.core.domain.measurement.MeasurementScheduleRequest; +import org.rhq.core.pluginapi.measurement.MeasurementFacet; +import org.rhq.core.pluginapi.operation.OperationFacet; +import org.rhq.core.pluginapi.operation.OperationResult; +import org.rhq.modules.plugins.jbossas7.BaseServerComponent; +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Application; +import org.switchyard.rhq.plugin.model.ComponentServiceMetrics; +import org.switchyard.rhq.plugin.model.ModelUtil; +import org.switchyard.rhq.plugin.model.ReferenceMetrics; +import org.switchyard.rhq.plugin.model.ServiceMetrics; +import org.switchyard.rhq.plugin.model.SwitchYardMetrics; +import org.switchyard.rhq.plugin.operations.ReadApplication; +import org.switchyard.rhq.plugin.operations.ReadComponentServiceMetrics; +import org.switchyard.rhq.plugin.operations.ReadReferenceMetrics; +import org.switchyard.rhq.plugin.operations.ReadServiceMetrics; +import org.switchyard.rhq.plugin.operations.ReadSwitchYardMetrics; +import org.switchyard.rhq.plugin.operations.ResetMetrics; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.OPERATION_RESET; +/** + * SwitchYard Component + */ +public class SwitchYardResourceComponent extends BaseSwitchYardResourceComponent> implements MeasurementFacet, OperationFacet { + /** + * The logger instance. + */ + private static Log LOG = LogFactory.getLog(SwitchYardResourceComponent.class); + + // TODO, make configurable + private static long REFRESH = 30*1000; + + /** + * The current application map + */ + private AtomicReference> applications = new AtomicReference>(); + /** + * The timestamp of the last application refresh. + */ + private AtomicLong applicationTimestamp = new AtomicLong(); + + /** + * The global metrics + */ + private AtomicReference switchYardMetrics = new AtomicReference(); + /** + * The timestamp of the last global metric refresh. + */ + private AtomicLong switchYardMetricsTimestamp = new AtomicLong(); + + /** + * The service metrics + */ + private AtomicReference>> serviceMetrics = new AtomicReference>>(); + /** + * The timestamp of the last service metric refresh. + */ + private AtomicLong serviceMetricsTimestamp = new AtomicLong(); + + /** + * The reference metrics + */ + private AtomicReference>> referenceMetrics = new AtomicReference>>(); + /** + * The timestamp of the last reference metric refresh. + */ + private AtomicLong referenceMetricsTimestamp = new AtomicLong(); + + /** + * The component service metrics + */ + private AtomicReference>> componentServiceMetrics = new AtomicReference>>(); + /** + * The timestamp of the last component service metric refresh. + */ + private AtomicLong componentServiceMetricsTimestamp = new AtomicLong(); + + + @Override + public AvailabilityType getAvailability() { + final SwitchYardMetrics metrics = getSwitchYardMetrics(); + return (metrics == null) ? AvailabilityType.DOWN : AvailabilityType.UP; + } + + protected Log getLog() { + return LOG; + } + + public T execute(final Operation operation, Class clazz) { + return SwitchYardDiscoveryComponent.execute(getResourceContext() + .getParentResourceComponent(), operation, clazz); + } + + public Map getApplications() { + return getApplicationMap(); + } + + public Application getApplication(final String name) { + return getApplicationMap().get(name); + } + + public SwitchYardMetrics getSwitchYardMetrics() { + return getCachedSwitchYardMetrics(); + } + + public Map> getServiceMetrics() { + return getCachedServiceMetrics(); + } + + public Map> getReferenceMetrics() { + return getCachedReferenceMetrics(); + } + + public Map> getComponentServiceMetrics() { + return getCachedComponentServiceMetrics(); + } + + public void clearApplications() { + applicationTimestamp.set(0); + } + + public void clearServiceMetrics() { + serviceMetricsTimestamp.set(0); + } + + public void clearReferenceMetrics() { + referenceMetricsTimestamp.set(0); + } + + public void clearComponentServiceMetrics() { + componentServiceMetricsTimestamp.set(0); + } + + private Map getApplicationMap() { + Map applicationMap = applications.get(); + long now = System.currentTimeMillis(); + if (now - applicationTimestamp.get() > REFRESH) { + synchronized(this) { + if (now - applicationTimestamp.get() > REFRESH) { + applicationMap = ModelUtil.createNamedResourceMap(loadApplications()); + applications.set(applicationMap); + applicationTimestamp.set(System.currentTimeMillis()); + } + } + applicationMap = applications.get(); + } + return applicationMap; + } + + private SwitchYardMetrics getCachedSwitchYardMetrics() { + SwitchYardMetrics metrics = switchYardMetrics.get(); + long now = System.currentTimeMillis(); + if (now - switchYardMetricsTimestamp.get() > REFRESH) { + synchronized(this) { + if (now - switchYardMetricsTimestamp.get() > REFRESH) { + metrics = loadSwitchYardMetrics(); + if (metrics != null) { + switchYardMetrics.set(metrics); + switchYardMetricsTimestamp.set(System.currentTimeMillis()); + } + } + } + metrics = switchYardMetrics.get(); + } + return metrics; + } + + private Map> getCachedServiceMetrics() { + Map> serviceMetricsMap = serviceMetrics.get(); + long now = System.currentTimeMillis(); + if (now - serviceMetricsTimestamp.get() > REFRESH) { + synchronized(this) { + if (now - serviceMetricsTimestamp.get() > REFRESH) { + serviceMetricsMap = ModelUtil.createApplicationNamedMetricMap(loadServiceMetrics()); + serviceMetrics.set(serviceMetricsMap); + serviceMetricsTimestamp.set(System.currentTimeMillis()); + } + } + serviceMetricsMap = serviceMetrics.get(); + } + return serviceMetricsMap; + } + + private Map> getCachedReferenceMetrics() { + Map> referenceMetricsMap = referenceMetrics.get(); + long now = System.currentTimeMillis(); + if (now - referenceMetricsTimestamp.get() > REFRESH) { + synchronized(this) { + if (now - referenceMetricsTimestamp.get() > REFRESH) { + referenceMetricsMap = ModelUtil.createApplicationNamedMetricMap(loadReferenceMetrics()); + referenceMetrics.set(referenceMetricsMap); + referenceMetricsTimestamp.set(System.currentTimeMillis()); + } + } + referenceMetricsMap = referenceMetrics.get(); + } + return referenceMetricsMap; + } + + private Map> getCachedComponentServiceMetrics() { + Map> componentServiceMetricsMap = componentServiceMetrics.get(); + long now = System.currentTimeMillis(); + if (now - componentServiceMetricsTimestamp.get() > REFRESH) { + synchronized(this) { + if (now - componentServiceMetricsTimestamp.get() > REFRESH) { + componentServiceMetricsMap = ModelUtil.createApplicationNamedMetricMap(loadComponentServiceMetrics()); + componentServiceMetrics.set(componentServiceMetricsMap); + componentServiceMetricsTimestamp.set(System.currentTimeMillis()); + } + } + componentServiceMetricsMap = componentServiceMetrics.get(); + } + return componentServiceMetricsMap; + } + + private Application[] loadApplications() { + final Application[] applications = execute(new ReadApplication(), Application[].class); + return (applications == null ? new Application[0] : applications); + } + + private SwitchYardMetrics loadSwitchYardMetrics() { + final SwitchYardMetrics[] metrics = execute(new ReadSwitchYardMetrics(), SwitchYardMetrics[].class); + return (metrics == null ? null : metrics[0]); + } + + private ServiceMetrics[] loadServiceMetrics() { + final ServiceMetrics[] serviceMetrics = execute(new ReadServiceMetrics(), ServiceMetrics[].class); + return (serviceMetrics == null ? new ServiceMetrics[0] : serviceMetrics); + } + + private ReferenceMetrics[] loadReferenceMetrics() { + final ReferenceMetrics[] referenceMetrics = execute(new ReadReferenceMetrics(), ReferenceMetrics[].class); + return (referenceMetrics == null ? new ReferenceMetrics[0] : referenceMetrics); + } + + private ComponentServiceMetrics[] loadComponentServiceMetrics() { + final ComponentServiceMetrics[] componentServiceMetrics = execute(new ReadComponentServiceMetrics(), ComponentServiceMetrics[].class); + return (componentServiceMetrics == null ? new ComponentServiceMetrics[0] : componentServiceMetrics); + } + + @Override + public void getValues(final MeasurementReport report, final Set requests) throws Exception { + final SwitchYardMetrics metrics = getSwitchYardMetrics(); + if (metrics != null) { + for (MeasurementScheduleRequest request: requests) { + final MeasurementDataNumeric measurementData = getCommonMetric(request, metrics); + if (measurementData != null) { + report.addData(measurementData); + } else if (LOG.isDebugEnabled()) { + LOG.debug("Unable to collect SwitchYard measurement " + request.getName()); + } + } + } + } + + @Override + public OperationResult invokeOperation(final String name, final Configuration parameters) throws InterruptedException, Exception { + if (OPERATION_RESET.equals(name)) { + execute(new ResetMetrics(), Void.class); + clearServiceMetrics(); + clearReferenceMetrics(); + clearComponentServiceMetrics(); + } else if (LOG.isDebugEnabled()) { + LOG.warn("Unknown SwitchYard operation " + name); + } + return null; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Application.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Application.java new file mode 100644 index 000000000..bd7d5e748 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Application.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Application + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class Application implements NamedResource { + private final QName name; + private final Map services; + private final Map references; + private final Map componentServices; + + @JsonCreator + public Application(@JsonProperty("name") QName name, + @JsonProperty("services") Service[] services, + @JsonProperty("references") Reference[] references, + @JsonProperty("componentServices") ComponentService[] componentServices) { + this.name = name; + this.services = ModelUtil.createNamedResourceMap(services); + this.references = ModelUtil.createNamedResourceMap(references); + this.componentServices = ModelUtil.createNamedResourceMap(componentServices); + } + + public QName getName() { + return name; + } + + public Map getServices() { + return services; + } + + public Map getReferences() { + return references; + } + + public Map getComponentServices() { + return componentServices; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ApplicationNamedMetric.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ApplicationNamedMetric.java new file mode 100644 index 000000000..d1440fcba --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ApplicationNamedMetric.java @@ -0,0 +1,20 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + + + +public interface ApplicationNamedMetric extends NamedMetric { + public String getApplication() ; +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentReference.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentReference.java new file mode 100644 index 000000000..91ccc4068 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentReference.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Component Reference + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class ComponentReference implements NamedResource { + private final QName name; + private final String interfaceName; + + @JsonCreator + public ComponentReference(@JsonProperty("name") QName name, + @JsonProperty("interface") String interfaceName) { + this.name = name; + this.interfaceName = interfaceName; + } + + public QName getName() { + return name; + } + + public String getInterfaceName() { + return interfaceName; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentReferenceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentReferenceMetrics.java new file mode 100644 index 000000000..50542bd4f --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentReferenceMetrics.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Component Reference Metrics + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class ComponentReferenceMetrics extends Metrics implements NamedMetric { + private final String name; + + @JsonCreator + public ComponentReferenceMetrics(@JsonProperty("name") String name, + @JsonProperty("successCount") int successCount, + @JsonProperty("faultCount") int faultCount, + @JsonProperty("totalCount") int totalCount, + @JsonProperty("averageTime") double averageTime, + @JsonProperty("minTime") long minTime, + @JsonProperty("maxTime") long maxTime, + @JsonProperty("totalTime") long totalTime) { + super(successCount, faultCount, totalCount, averageTime, minTime, maxTime, totalTime); + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentService.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentService.java new file mode 100644 index 000000000..fe415d224 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentService.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Component Service + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class ComponentService implements NamedResource { + private final QName name; + private final String interfaceName; + private final String implementationType; + private final String implementationConfiguration; + private final Map references; + + @JsonCreator + public ComponentService(@JsonProperty("name") QName name, + @JsonProperty("interface") String interfaceName, + @JsonProperty("implementation") String implementationType, + @JsonProperty("implementationConfiguration") String implementationConfiguration, + @JsonProperty("references") ComponentReference[] references) { + this.name = name; + this.interfaceName = interfaceName; + this.implementationConfiguration = implementationConfiguration; + this.implementationType = implementationType; + this.references = ModelUtil.createNamedResourceMap(references); + } + + public QName getName() { + return name; + } + + public String getInterfaceName() { + return interfaceName; + } + + public String getImplementationType() { + return implementationType; + } + + public String getImplementationConfiguration() { + return implementationConfiguration; + } + + public Map getReferences() { + return references; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentServiceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentServiceMetrics.java new file mode 100644 index 000000000..df7167f81 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ComponentServiceMetrics.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import java.util.Map; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Component Service Metrics + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class ComponentServiceMetrics extends Metrics implements ApplicationNamedMetric { + private final String name; + private final String application; + private final Map operationMetrics; + private final Map componentReferenceMetrics; + + @JsonCreator + public ComponentServiceMetrics(@JsonProperty("name") String name, + @JsonProperty("application") String application, + @JsonProperty("successCount") int successCount, + @JsonProperty("faultCount") int faultCount, + @JsonProperty("totalCount") int totalCount, + @JsonProperty("averageTime") double averageTime, + @JsonProperty("minTime") long minTime, + @JsonProperty("maxTime") long maxTime, + @JsonProperty("totalTime") long totalTime, + @JsonProperty("operations") OperationMetrics[] operations, + @JsonProperty("references") ComponentReferenceMetrics[] references) { + super(successCount, faultCount, totalCount, averageTime, minTime, maxTime, totalTime); + this.name = name; + this.application = application; + this.operationMetrics = ModelUtil.createNamedMetricMap(operations); + this.componentReferenceMetrics = ModelUtil.createNamedMetricMap(references); + } + + public String getName() { + return name; + } + + public String getApplication() { + return application; + } + + public Map getOperationMetrics() { + return operationMetrics; + } + + public Map getComponentReferenceMetrics() { + return componentReferenceMetrics; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Gateway.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Gateway.java new file mode 100644 index 000000000..6e66274e4 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Gateway.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Gateway (Binding) + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class Gateway implements NamedResource { + private final QName name; + private final String type; + private final String configuration; + private final String state; + + @JsonCreator + public Gateway( + @JsonProperty("name") QName name, + @JsonProperty("type") final String type, + @JsonProperty("configuration") String configuration, + @JsonProperty("state") String state) { + this.name = name; + this.type = type; + this.configuration = configuration; + this.state = state; + } + + public QName getName() { + return name; + } + + public String getType() { + return type; + } + + public String getConfiguration() { + return configuration; + } + + public String getState() { + return state; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/GatewayMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/GatewayMetrics.java new file mode 100644 index 000000000..22de7da66 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/GatewayMetrics.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Gateway(Binding) Metrics + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class GatewayMetrics extends Metrics implements NamedMetric { + private final String name; + + @JsonCreator + public GatewayMetrics(@JsonProperty("name") String name, + @JsonProperty("successCount") int successCount, + @JsonProperty("faultCount") int faultCount, + @JsonProperty("totalCount") int totalCount, + @JsonProperty("averageTime") double averageTime, + @JsonProperty("minTime") long minTime, + @JsonProperty("maxTime") long maxTime, + @JsonProperty("totalTime") long totalTime) { + super(successCount, faultCount, totalCount, averageTime, minTime, maxTime, totalTime); + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/GetVersionResult.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/GetVersionResult.java new file mode 100644 index 000000000..bdbc83a7d --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/GetVersionResult.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + + +/** + * Result Object for Get Version + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class GetVersionResult { + private final String version; + + @JsonCreator + public GetVersionResult(@JsonProperty("version") final String version) { + this.version = version; + } + + public String getVersion() { + return version; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Metrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Metrics.java new file mode 100644 index 000000000..705243088 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Metrics.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + + +/** + * Metrics + */ +public class Metrics { + private final int successCount; + private final int faultCount; + private final int totalCount; + private final double averageTime; + private final long minTime; + private final long maxTime; + private final long totalTime; + + public Metrics(final int successCount, final int faultCount, final int totalCount, + final double averageTime, final long minTime, final long maxTime, + final long totalTime) { + this.successCount = successCount; + this.faultCount = faultCount; + this.totalCount = totalCount; + this.averageTime = averageTime; + this.minTime = minTime; + this.maxTime = maxTime; + this.totalTime = totalTime; + } + + public int getSuccessCount() { + return successCount; + } + + public int getFaultCount() { + return faultCount; + } + + public int getTotalCount() { + return totalCount; + } + + public double getAverageTime() { + return averageTime; + } + + public long getMinTime() { + return minTime; + } + + public long getMaxTime() { + return maxTime; + } + + public long getTotalTime() { + return totalTime; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ModelUtil.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ModelUtil.java new file mode 100644 index 000000000..69f65260a --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ModelUtil.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; + +public class ModelUtil { + public static Map createNamedResourceMap(final T[] resources) { + if ((resources != null) && (resources.length > 0)) { + final Map resourceMap = new TreeMap(); + for(T resource: resources) { + resourceMap.put(resource.getName().toString(), resource); + } + return resourceMap; + } else { + return Collections.emptyMap(); + } + } + + public static String toString(final Object obj) { + return (obj == null ? null : obj.toString()); + } + + public static Map createNamedMetricMap(final T[] metrics) { + if ((metrics != null) && (metrics.length > 0)) { + final Map metricMap = new TreeMap(); + for(T resource: metrics) { + metricMap.put(resource.getName(), resource); + } + return metricMap; + } else { + return Collections.emptyMap(); + } + } + + public static Map> createApplicationNamedMetricMap(final T[] metrics) { + if (metrics == null) { + return Collections.emptyMap(); + } else { + final Map> map = new TreeMap>(); + for (T metric: metrics) { + final String applicationName = metric.getApplication(); + final String name = metric.getName(); + Map serviceMap = map.get(applicationName); + if (serviceMap == null) { + serviceMap = new TreeMap(); + map.put(applicationName, serviceMap); + } + serviceMap.put(name, metric); + } + return map; + } + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/NamedMetric.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/NamedMetric.java new file mode 100644 index 000000000..93f3a30aa --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/NamedMetric.java @@ -0,0 +1,20 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + + + +public interface NamedMetric { + public String getName() ; +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/NamedResource.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/NamedResource.java new file mode 100644 index 000000000..c9ce11a4b --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/NamedResource.java @@ -0,0 +1,21 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import javax.xml.namespace.QName; + + +public interface NamedResource { + public QName getName() ; +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/OperationMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/OperationMetrics.java new file mode 100644 index 000000000..557a65d7c --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/OperationMetrics.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Operation Metrics + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class OperationMetrics extends Metrics implements NamedMetric { + private final String name; + + @JsonCreator + public OperationMetrics(@JsonProperty("name") String name, + @JsonProperty("successCount") int successCount, + @JsonProperty("faultCount") int faultCount, + @JsonProperty("totalCount") int totalCount, + @JsonProperty("averageTime") double averageTime, + @JsonProperty("minTime") long minTime, + @JsonProperty("maxTime") long maxTime, + @JsonProperty("totalTime") long totalTime) { + super(successCount, faultCount, totalCount, averageTime, minTime, maxTime, totalTime); + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Reference.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Reference.java new file mode 100644 index 000000000..d65dd40ca --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Reference.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Reference + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class Reference implements NamedResource { + private final QName name; + private final String interfaceName; + private final String promotedReference; + private final Map gateways; + + @JsonCreator + public Reference(@JsonProperty("name") QName name, + @JsonProperty("interface") String interfaceName, + @JsonProperty("promotedReference") String promotedReference, + @JsonProperty("gateways") Gateway[] gateways) { + this.name = name; + this.interfaceName = interfaceName; + this.promotedReference = promotedReference; + this.gateways = ModelUtil.createNamedResourceMap(gateways); + } + + public QName getName() { + return name; + } + + public String getInterfaceName() { + return interfaceName; + } + + public String getPromotedReference() { + return promotedReference; + } + + public Map getGateways() { + return gateways; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ReferenceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ReferenceMetrics.java new file mode 100644 index 000000000..eff3bb037 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ReferenceMetrics.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import java.util.Map; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Reference Metrics + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class ReferenceMetrics extends Metrics implements ApplicationNamedMetric { + private final String name; + private final String application; + private final Map operationMetrics; + private final Map gatewayMetrics; + + @JsonCreator + public ReferenceMetrics(@JsonProperty("name") String name, + @JsonProperty("application") String application, + @JsonProperty("successCount") int successCount, + @JsonProperty("faultCount") int faultCount, + @JsonProperty("totalCount") int totalCount, + @JsonProperty("averageTime") double averageTime, + @JsonProperty("minTime") long minTime, + @JsonProperty("maxTime") long maxTime, + @JsonProperty("totalTime") long totalTime, + @JsonProperty("operations") OperationMetrics[] operations, + @JsonProperty("gateways") GatewayMetrics[] gateways) { + super(successCount, faultCount, totalCount, averageTime, minTime, maxTime, totalTime); + this.name = name; + this.application = application; + this.operationMetrics = ModelUtil.createNamedMetricMap(operations); + this.gatewayMetrics = ModelUtil.createNamedMetricMap(gateways); + } + + public String getName() { + return name; + } + + public String getApplication() { + return application; + } + + public Map getOperationMetrics() { + return operationMetrics; + } + + public Map getGatewayMetrics() { + return gatewayMetrics; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Service.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Service.java new file mode 100644 index 000000000..6bc25c3d8 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Service.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Service + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class Service implements NamedResource { + private final QName name; + private final String interfaceName; + private final QName promotedService; + private final Map gateways; + private final Throttling throttling; + + @JsonCreator + public Service(@JsonProperty("name") QName name, + @JsonProperty("interface") String interfaceName, + @JsonProperty("promotedService") QName promotedService, + @JsonProperty("gateways") Gateway[] gateways, + @JsonProperty("throttling") Throttling throttling) { + this.name = name; + this.interfaceName = interfaceName; + this.promotedService = promotedService; + this.gateways = ModelUtil.createNamedResourceMap(gateways); + this.throttling = throttling; + } + + public QName getName() { + return name; + } + + public String getInterfaceName() { + return interfaceName; + } + + public QName getPromotedService() { + return promotedService; + } + + public Map getGateways() { + return gateways; + } + + public Throttling getThrottling() { + return throttling; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ServiceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ServiceMetrics.java new file mode 100644 index 000000000..2559b5abe --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/ServiceMetrics.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import java.util.Map; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Service Metrics + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class ServiceMetrics extends Metrics implements ApplicationNamedMetric { + private final String name; + private final String application; + private final Map operationMetrics; + private final Map gatewayMetrics; + + @JsonCreator + public ServiceMetrics(@JsonProperty("name") String name, + @JsonProperty("application") String application, + @JsonProperty("successCount") int successCount, + @JsonProperty("faultCount") int faultCount, + @JsonProperty("totalCount") int totalCount, + @JsonProperty("averageTime") double averageTime, + @JsonProperty("minTime") long minTime, + @JsonProperty("maxTime") long maxTime, + @JsonProperty("totalTime") long totalTime, + @JsonProperty("operations") OperationMetrics[] operations, + @JsonProperty("gateways") GatewayMetrics[] gateways) { + super(successCount, faultCount, totalCount, averageTime, minTime, maxTime, totalTime); + this.name = name; + this.application = application; + this.operationMetrics = ModelUtil.createNamedMetricMap(operations); + this.gatewayMetrics = ModelUtil.createNamedMetricMap(gateways); + } + + public String getName() { + return name; + } + + public String getApplication() { + return application; + } + + public Map getOperationMetrics() { + return operationMetrics; + } + + public Map getGatewayMetrics() { + return gatewayMetrics; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/SwitchYardMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/SwitchYardMetrics.java new file mode 100644 index 000000000..ec52490da --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/SwitchYardMetrics.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Metrics + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class SwitchYardMetrics extends Metrics implements NamedMetric { + private final String name; + + @JsonCreator + public SwitchYardMetrics(@JsonProperty("name") String name, + @JsonProperty("successCount") int successCount, + @JsonProperty("faultCount") int faultCount, + @JsonProperty("totalCount") int totalCount, + @JsonProperty("averageTime") double averageTime, + @JsonProperty("minTime") long minTime, + @JsonProperty("maxTime") long maxTime, + @JsonProperty("totalTime") long totalTime) { + super(successCount, faultCount, totalCount, averageTime, minTime, maxTime, totalTime); + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Throttling.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Throttling.java new file mode 100644 index 000000000..2400bdc3f --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/model/Throttling.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.model; + +import org.codehaus.jackson.annotate.JsonCreator; +import org.codehaus.jackson.annotate.JsonIgnoreProperties; +import org.codehaus.jackson.annotate.JsonProperty; + +/** + * SwitchYard Throttling + */ +@JsonIgnoreProperties(ignoreUnknown=true) +public class Throttling { + private final Boolean enabled; + private final Integer maxRequests; + private final Long timePeriod; + + @JsonCreator + public Throttling(@JsonProperty("enabled") Boolean enabled, + @JsonProperty("maxRequests") Integer maxRequests, + @JsonProperty("timePeriod") Long timePeriod) { + this.enabled = enabled; + this.maxRequests = maxRequests; + this.timePeriod = timePeriod; + } + + public Boolean isEnabled() { + return enabled; + } + + public Integer getMaxRequests() { + return maxRequests; + } + + public Long getTimePeriod() { + return timePeriod; + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/GetVersion.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/GetVersion.java new file mode 100644 index 000000000..b2b57c38e --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/GetVersion.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import org.rhq.modules.plugins.jbossas7.json.Operation; +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_GET_VERSION; + +/** + * Get Version operation + */ +public class GetVersion extends Operation { + public GetVersion() { + super(DMR_GET_VERSION, ADDRESS_SWITCHYARD); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadApplication.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadApplication.java new file mode 100644 index 000000000..3bab01899 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadApplication.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import org.rhq.modules.plugins.jbossas7.json.Operation; +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_READ_APPLICATION; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_NAME; + +/** + * Read Application operation + */ +public class ReadApplication extends Operation { + public ReadApplication() { + super(DMR_READ_APPLICATION, ADDRESS_SWITCHYARD); + } + + public ReadApplication(final String application) { + this(); + addAdditionalProperty(PARAM_NAME, application); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadComponentServiceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadComponentServiceMetrics.java new file mode 100644 index 000000000..4e1a70dee --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadComponentServiceMetrics.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_SHOW_METRICS; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_SERVICE_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_TYPE; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Read Application operation + */ +public class ReadComponentServiceMetrics extends Operation { + public ReadComponentServiceMetrics() { + this("*"); + } + + public ReadComponentServiceMetrics(final String service) { + super(DMR_SHOW_METRICS, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_TYPE, "componentService"); + addAdditionalProperty(PARAM_SERVICE_NAME, service); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadReference.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadReference.java new file mode 100644 index 000000000..e1daf8b1e --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadReference.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_READ_REFERENCE; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_APPLICATION_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_REFERENCE_NAME; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Read Application operation + */ +public class ReadReference extends Operation { + public ReadReference(final String application, final String reference) { + super(DMR_READ_REFERENCE, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_APPLICATION_NAME, application); + addAdditionalProperty(PARAM_REFERENCE_NAME, reference); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadReferenceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadReferenceMetrics.java new file mode 100644 index 000000000..b58f13b0e --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadReferenceMetrics.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_SHOW_METRICS; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_SERVICE_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_TYPE; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Read Application operation + */ +public class ReadReferenceMetrics extends Operation { + public ReadReferenceMetrics() { + this("*"); + } + + public ReadReferenceMetrics(final String service) { + super(DMR_SHOW_METRICS, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_TYPE, "reference"); + addAdditionalProperty(PARAM_SERVICE_NAME, service); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadService.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadService.java new file mode 100644 index 000000000..06366e3af --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadService.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_READ_SERVICE; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_APPLICATION_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_SERVICE_NAME; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Read Application operation + */ +public class ReadService extends Operation { + public ReadService(final String application, final String service) { + super(DMR_READ_SERVICE, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_APPLICATION_NAME, application); + addAdditionalProperty(PARAM_SERVICE_NAME, service); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadServiceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadServiceMetrics.java new file mode 100644 index 000000000..03882c627 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadServiceMetrics.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_SHOW_METRICS; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_SERVICE_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_TYPE; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Read Application operation + */ +public class ReadServiceMetrics extends Operation { + public ReadServiceMetrics() { + this("*"); + } + + public ReadServiceMetrics(final String service) { + super(DMR_SHOW_METRICS, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_TYPE, "service"); + addAdditionalProperty(PARAM_SERVICE_NAME, service); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadSwitchYardMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadSwitchYardMetrics.java new file mode 100644 index 000000000..54613628a --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ReadSwitchYardMetrics.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_SHOW_METRICS; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Read Application operation + */ +public class ReadSwitchYardMetrics extends Operation { + public ReadSwitchYardMetrics() { + super(DMR_SHOW_METRICS, ADDRESS_SWITCHYARD); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetComponentServiceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetComponentServiceMetrics.java new file mode 100644 index 000000000..3d13f843b --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetComponentServiceMetrics.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_RESET_METRICS; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_APPLICATION_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_TYPE; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Reset Metrics + */ +public class ResetComponentServiceMetrics extends Operation { + public ResetComponentServiceMetrics(final String applicationName, final String componentServiceName) { + super(DMR_RESET_METRICS, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_APPLICATION_NAME, applicationName); + addAdditionalProperty(PARAM_NAME, componentServiceName); + addAdditionalProperty(PARAM_TYPE, "componentService"); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetMetrics.java new file mode 100644 index 000000000..eca0f18c3 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetMetrics.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_RESET_METRICS; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Reset Metrics + */ +public class ResetMetrics extends Operation { + public ResetMetrics() { + super(DMR_RESET_METRICS, ADDRESS_SWITCHYARD); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetReferenceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetReferenceMetrics.java new file mode 100644 index 000000000..e594f523d --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetReferenceMetrics.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_RESET_METRICS; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_APPLICATION_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_TYPE; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Reset Metrics + */ +public class ResetReferenceMetrics extends Operation { + public ResetReferenceMetrics(final String applicationName, final String referenceName) { + super(DMR_RESET_METRICS, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_APPLICATION_NAME, applicationName); + addAdditionalProperty(PARAM_NAME, referenceName); + addAdditionalProperty(PARAM_TYPE, "reference"); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetServiceMetrics.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetServiceMetrics.java new file mode 100644 index 000000000..4471c2ddd --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/ResetServiceMetrics.java @@ -0,0 +1,34 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_RESET_METRICS; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_APPLICATION_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_TYPE; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Reset Metrics + */ +public class ResetServiceMetrics extends Operation { + public ResetServiceMetrics(final String applicationName, final String serviceName) { + super(DMR_RESET_METRICS, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_APPLICATION_NAME, applicationName); + addAdditionalProperty(PARAM_NAME, serviceName); + addAdditionalProperty(PARAM_TYPE, "service"); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/StartGateway.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/StartGateway.java new file mode 100644 index 000000000..71f75ab18 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/StartGateway.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_START_GATEWAY; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_APPLICATION_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_SERVICE_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_TYPE; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Reset Metrics + */ +public class StartGateway extends Operation { + public StartGateway(final String applicationName, final String compositeName, final String gatewayName, final String type) { + super(DMR_START_GATEWAY, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_APPLICATION_NAME, applicationName); + addAdditionalProperty(PARAM_SERVICE_NAME, compositeName); + addAdditionalProperty(PARAM_NAME, gatewayName); + addAdditionalProperty(PARAM_TYPE, type); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/StopGateway.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/StopGateway.java new file mode 100644 index 000000000..2eee769e6 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/StopGateway.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_STOP_GATEWAY; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_APPLICATION_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_SERVICE_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_TYPE; + +import org.rhq.modules.plugins.jbossas7.json.Operation; + +/** + * Reset Metrics + */ +public class StopGateway extends Operation { + public StopGateway(final String applicationName, final String compositeName, final String gatewayName, final String type) { + super(DMR_STOP_GATEWAY, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_APPLICATION_NAME, applicationName); + addAdditionalProperty(PARAM_SERVICE_NAME, compositeName); + addAdditionalProperty(PARAM_NAME, gatewayName); + addAdditionalProperty(PARAM_TYPE, type); + } +} diff --git a/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/UpdateThrottling.java b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/UpdateThrottling.java new file mode 100644 index 000000000..fae1993e5 --- /dev/null +++ b/release/admin/rhq/src/main/java/org/switchyard/rhq/plugin/operations/UpdateThrottling.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.rhq.plugin.operations; + +import static org.switchyard.rhq.plugin.SwitchYardConstants.ADDRESS_SWITCHYARD; +import static org.switchyard.rhq.plugin.SwitchYardConstants.DMR_UPDATE_THROTTLING; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_APPLICATION_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_SERVICE_NAME; +import static org.switchyard.rhq.plugin.SwitchYardConstants.PARAM_THROTTLING; + +import org.rhq.modules.plugins.jbossas7.json.Operation; +import org.switchyard.rhq.plugin.model.Throttling; + +/** + * Reset Metrics + */ +public class UpdateThrottling extends Operation { + public UpdateThrottling(final String applicationName, final String compositeName, final Boolean enabled, final Integer maxRequests) { + super(DMR_UPDATE_THROTTLING, ADDRESS_SWITCHYARD); + addAdditionalProperty(PARAM_APPLICATION_NAME, applicationName); + addAdditionalProperty(PARAM_SERVICE_NAME, compositeName); + addAdditionalProperty(PARAM_THROTTLING, new Throttling(enabled, maxRequests, null)); + } +} diff --git a/release/admin/rhq/src/main/resources/META-INF/rhq-plugin.xml b/release/admin/rhq/src/main/resources/META-INF/rhq-plugin.xml new file mode 100644 index 000000000..d7687b112 --- /dev/null +++ b/release/admin/rhq/src/main/resources/META-INF/rhq-plugin.xml @@ -0,0 +1,413 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/distribution/pom.xml b/release/distribution/pom.xml new file mode 100644 index 000000000..5475273f5 --- /dev/null +++ b/release/distribution/pom.xml @@ -0,0 +1,38 @@ + + + + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-release-distribution + jar + SwitchYard: Distribution Artifacts + Module containing extra distribution artifacts (e.g. license, readme) + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + diff --git a/release/distribution/src/main/resources/Contributors.txt b/release/distribution/src/main/resources/Contributors.txt new file mode 100644 index 000000000..00f8a41f5 --- /dev/null +++ b/release/distribution/src/main/resources/Contributors.txt @@ -0,0 +1,12 @@ +Individual contributors to the SwitchYard project are listed below. If your name +is missing please email kbabo@redhat.com. + +Antollini, Mario +Babo, Keith +Bevenius, Daniel +Bojan, Magesh +Cunningham, Thomas +Fennelly, Tom +Montenegro, Alejandro +Ward, David + diff --git a/release/distribution/src/main/resources/LICENSE-2.0.txt b/release/distribution/src/main/resources/LICENSE-2.0.txt new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/release/distribution/src/main/resources/LICENSE-2.0.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/release/distribution/src/main/resources/README.txt b/release/distribution/src/main/resources/README.txt new file mode 100644 index 000000000..5bba2636a --- /dev/null +++ b/release/distribution/src/main/resources/README.txt @@ -0,0 +1,22 @@ + +Welcome to SwitchYard 1.1! This doc contains some useful links to help you +get up and running with SwitchYard. + +Documentation +============= +The documentation landing page provides all the information you need to +get ramped up on how to install, configure, and use SwitchYard. + +https://docs.jboss.org/author/display/SWITCHYARDDOC/Home + +The community wiki is another source of useful information: + +http://community.jboss.org/en/switchyard + +Contact Us +============= +If you have questions or feedback on what you find in SwitchYard, please +drop by our forums or send an email to our users list. + +http://community.jboss.org/en/switchyard?view=discussions + diff --git a/release/docs/javadoc/pom.xml b/release/docs/javadoc/pom.xml new file mode 100644 index 000000000..23fbb1213 --- /dev/null +++ b/release/docs/javadoc/pom.xml @@ -0,0 +1,230 @@ + + + + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../../pom.xml + + 4.0.0 + switchyard-javadocs + jar + SwitchYard: Javadoc + SwitchYard Javadoc + + SwitchYard Public API - ${project.version} + + + + org.switchyard + switchyard-admin + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-remote + + + org.switchyard + switchyard-test + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-http + + + org.switchyard.components + switchyard-component-resteasy + + + org.switchyard.components + switchyard-component-common-camel + + + org.jboss.logging + jboss-logging-processor + provided + true + + + + + javadoc + + true + + javadoc + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack-artifact-sources + generate-resources + + unpack + + + + + org.switchyard + switchyard-api + sources + true + + org/switchyard/APILogger.java, + org/switchyard/APIMessages.java, + + + + org.switchyard + switchyard-remote + sources + true + + org/switchyard/remote/RemoteLogger.java, + org/switchyard/remote/RemoteMessages.java, + org/switchyard/remote/RemoteRegistry.java, + org/switchyard/remote/infinispan/*, + org/switchyard/remote/cluster/* + + + + org.switchyard + switchyard-admin + sources + true + + org/switchyard/admin/mbean + + + + org.switchyard + switchyard-test + sources + true + + org/switchyard/test/TestLogger.java, + org/switchyard/test/TestMessages.java + + + + org.switchyard.components + switchyard-component-common + sources + true + + org/switchyard/component/common/composer/BaseContextMapper.java, + org/switchyard/component/common/composer/BaseMessageComposer.java, + org/switchyard/component/common/composer/BaseRegexContextMapper.java, + org/switchyard/component/common/composer/BindingData.java, + org/switchyard/component/common/composer/ContextMapper.java, + org/switchyard/component/common/composer/MessageComposer.java, + org/switchyard/component/common/composer/RegexContextMapper.java, + org/switchyard/component/common/composer/label/* + + + + org.switchyard.components + switchyard-component-soap + sources + true + + org/switchyard/component/soap/composer/SOAPBindingData.java, + org/switchyard/component/soap/composer/SOAPMessageComposer.java, + org/switchyard/component/soap/composer/SOAPContextMapper.java + + + + org.switchyard.components + switchyard-component-http + sources + true + + org/switchyard/component/http/composer/HttpBindingData.java, + org/switchyard/component/http/composer/HttpMessageComposer.java, + org/switchyard/component/http/composer/HttpContextMapper.java + + + + org.switchyard.components + switchyard-component-resteasy + sources + true + + org/switchyard/component/resteasy/composer/RESTEasyBindingData.java, + org/switchyard/component/resteasy/composer/RESTEasyMessageComposer.java, + org/switchyard/component/resteasy/composer/RESTEasyContextMapper.java + + + + org.switchyard.components + switchyard-component-common-camel + sources + true + + org/switchyard/component/camel/common/composer/CamelBindingData.java, + org/switchyard/component/camel/common/composer/CamelMessageComposer.java, + org/switchyard/component/camel/common/composer/CamelContextMapper.java + + + + ${project.build.directory}/java-source + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + ${project.build.directory}/java-source + ${javadoc.branding} + ${javadoc.branding} +

${javadoc.branding}
+
${javadoc.branding}
+ + + + + javadoc + + process-resources + + + + + + + +
diff --git a/release/installer/assembly.xml b/release/installer/assembly.xml new file mode 100644 index 000000000..565140e70 --- /dev/null +++ b/release/installer/assembly.xml @@ -0,0 +1,76 @@ + + + + SwitchyardInstaller + false + + zip + + + + + true + scripts/installer.properties + installer.properties + ${installer.root.dir} + + + scripts/installer.ant.xml + build.xml + ${installer.root.dir}/ + + + ${bundle.dir}/xsl/standalone.xsl + ${installer.root.dir}/res + + + ${bundle.dir}/xsl/standalone-ha.xsl + ${installer.root.dir}/res + + + ${bundle.dir}/xsl/domain.xsl + ${installer.root.dir}/res + + + ${bundle.dir}/xsl/jbossws-spi_module.xsl + ${installer.root.dir}/res + + + ${bundle.dir}/xsl/jbossws-jboss720-server-integration_module.xsl + ${installer.root.dir}/res + + + + + + docs + ${installer.root.dir} + + + + + + false + + org.switchyard:switchyard-as7-standalone-bundle + + ${installer.root.dir}/res + switchyard-as7-bundle.zip + + + + diff --git a/release/installer/docs/LICENSE-2.0.txt b/release/installer/docs/LICENSE-2.0.txt new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/release/installer/docs/LICENSE-2.0.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/release/installer/docs/README.txt b/release/installer/docs/README.txt new file mode 100644 index 000000000..95392278a --- /dev/null +++ b/release/installer/docs/README.txt @@ -0,0 +1,29 @@ +SwitchYard JBoss EAP Standalone Installer +========================================= + +Installing Runtime +------------------ +This package contains resources for installing SwitchYard into a +JBoss Enterprise Application Platform installation. + +Prerequisites: + 1. Java Runtime + 2. Fully installed Ant available on the command line execution PATH. + 3. A JBoss EAP installation. + +Instructions: + 1. Open a terminal command prompt. + 2. Change directory into the root of the bundle. + 3. Execute command "ant". + +This script will ask you for the path to the JBoss EAP distribution and will +install all the necessary files required to run SwitchYard applications on +JBoss EAP including the set of quickstart example applications. + +Installing BPEL Console +----------------------- +Instructions: + 1. Execute command "ant install-bpel-console" + +The script will ask for the location of your EAP install where the console server and webapp will be deployed. + diff --git a/release/installer/pom.xml b/release/installer/pom.xml new file mode 100644 index 000000000..d0be57101 --- /dev/null +++ b/release/installer/pom.xml @@ -0,0 +1,96 @@ + + + + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-installer + pom + SwitchYard: Installer + SwitchYard Installer + + ${project.build.directory}/bundle + /switchyard-installer-${version.distro} + + + + org.switchyard + switchyard-as7-standalone-bundle + zip + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + maven-dependency-plugin + + + install-switchyard + generate-sources + + unpack + + + + + org.switchyard + switchyard-as7-standalone-bundle + zip + ${project.version} + xsl/* + + + ${bundle.dir} + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + assembly-installer + generate-test-resources + + single + + + false + switchyard-installer + + ${basedir}/assembly.xml + + + 493 + + + + + + + + diff --git a/release/installer/scripts/installer.ant.xml b/release/installer/scripts/installer.ant.xml new file mode 100644 index 000000000..abda96e3b --- /dev/null +++ b/release/installer/scripts/installer.ant.xml @@ -0,0 +1,270 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Downloading SwitchYard Tools Bundle ... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Downloading Overlord Commons Installer ... + + + Extracting Overlord Commons Installer ... + + + Retrieve Overlord Commons Artifacts ... + + + + + + + + + diff --git a/release/installer/scripts/installer.properties b/release/installer/scripts/installer.properties new file mode 100644 index 000000000..8614d2c6d --- /dev/null +++ b/release/installer/scripts/installer.properties @@ -0,0 +1,33 @@ +# Project version of the installer +project.version=${project.version} +server=eap +as.path=6 +as.version.major=${version.redhat.eap6} +as.version=${version.redhat.eap6}.${version.redhat.eap6.minor} +tools.version=2.0 + +# Update this property if you would like to use a different version of the +# SwitchYard tools. +switchyard.tools.url=http://downloads.jboss.org/switchyard/releases/v2.0.Final/switchyard-tools-2.0.0.Final.zip + +# For nightly builds, we use the following setting : +# (Please remove before release) +#switchyard.tools.url=https://hudson.jboss.org/hudson/job/SwitchYard-Release/lastSuccessfulBuild/artifact/tools/dist/target/switchyard-tools.zip + +# Directory that the AS zip has unzipped into +unzipped.dir=jboss-eap-6.1 + +# Product name +container.name=EAP + +# Overlord commons +overlord-commons.version=${version.overlord-commons} + +overlord-commons-installer.url=https://repository.jboss.org/nexus/service/local/repositories/thirdparty-releases/content/org/overlord/overlord-commons-installer/${version.overlord-commons}/overlord-commons-installer-${version.overlord-commons}.jar +overlord-commons-idp-eap6.url=https://repository.jboss.org/nexus/service/local/repositories/thirdparty-releases/content/org/overlord/overlord-commons-idp-eap6/${version.overlord-commons}/overlord-commons-idp-eap6-${version.overlord-commons}.war +overlord-commons-services.url=https://repository.jboss.org/nexus/service/local/repositories/thirdparty-releases/content/org/overlord/overlord-commons-services/${version.overlord-commons}/overlord-commons-services-${version.overlord-commons}.jar +overlord-commons-auth.url=https://repository.jboss.org/nexus/service/local/repositories/thirdparty-releases/content/org/overlord/overlord-commons-auth/${version.overlord-commons}/overlord-commons-auth-${version.overlord-commons}.jar +overlord-commons-auth-jboss7.url=https://repository.jboss.org/nexus/service/local/repositories/thirdparty-releases/content/org/overlord/overlord-commons-auth-jboss7/${version.overlord-commons}/overlord-commons-auth-jboss7-${version.overlord-commons}.jar +overlord-commons-auth-tomcat7.url=https://repository.jboss.org/nexus/service/local/repositories/thirdparty-releases/content/org/overlord/overlord-commons-auth-tomcat7/${version.overlord-commons}/overlord-commons-auth-tomcat7-${version.overlord-commons}.jar +overlord-commons-ant.url=https://repository.jboss.org/nexus/service/local/repositories/thirdparty-releases/content/org/overlord/overlord-commons-ant/${version.overlord-commons}/overlord-commons-ant-${version.overlord-commons}.jar + diff --git a/release/jboss-as7/bundle/assembly.xml b/release/jboss-as7/bundle/assembly.xml new file mode 100644 index 000000000..3f5740e1e --- /dev/null +++ b/release/jboss-as7/bundle/assembly.xml @@ -0,0 +1,38 @@ + + + + switchyard-as7-bundle + false + + zip + + + + + + ${staging.jboss.dir} + ${distro.root.dir} + 644 + 755 + + + xsl + ${distro.root.dir}/xsl + + + + diff --git a/release/jboss-as7/bundle/pom.xml b/release/jboss-as7/bundle/pom.xml new file mode 100644 index 000000000..7bf5a8643 --- /dev/null +++ b/release/jboss-as7/bundle/pom.xml @@ -0,0 +1,154 @@ + + + + + org.switchyard + switchyard-container-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-standalone-bundle + pom + SwitchYard: AS7 Bundle + SwitchYard AS7 Bundle + + ${project.build.directory}/jboss-switchyard + ${staging.dir}/jboss-as-${version.org.jboss.as} + / + ${project.build.directory}${distro.root.dir} + + + + org.switchyard + switchyard-release-distribution + + + org.switchyard + switchyard-as7-modules + zip + + + + + + maven-dependency-plugin + + + install-as7-bpms-layer + generate-sources + + unpack + + + + + org.kie + kie-eap-distributions-bpms-layer + ${version.org.kie} + zip + + + modules/layers.conf + ${staging.jboss.dir} + + + + install-as7-modules + generate-sources + + unpack + + + + + org.switchyard + switchyard-as7-modules + zip + ${project.version} + + + ${staging.jboss.dir} + + + + install-quickstarts + generate-sources + + unpack + + + + + org.switchyard.quickstarts + switchyard-quickstart-distro + zip + ${project.version} + + + camel-amqp-binding/** + ${staging.jboss.dir}/quickstarts + + + + install-distribution-files + generate-sources + + unpack + + + + + org.switchyard + switchyard-release-distribution + jar + ${project.version} + + + ${staging.jboss.dir} + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + generate-test-resources + + single + + + false + switchyard-as7-bundle + + ${basedir}/assembly.xml + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + diff --git a/release/jboss-as7/bundle/xsl/domain.xsl b/release/jboss-as7/bundle/xsl/domain.xsl new file mode 100644 index 000000000..537c0a8f4 --- /dev/null +++ b/release/jboss-as7/bundle/xsl/domain.xsl @@ -0,0 +1,198 @@ + + + + + + + + + + + + + + + + urn:jboss:domain:switchyard switchyard.xsd + + + + + + + + + + + + + + + + + + + :18001 + + + + + :18001 + + + + + + + + + + + + + + + + + + + + + + + + cluster + + + + + + + + + + + + + + + + + + + + + + + + + + + :18001 + + + + + :18001 + + + + + + + + + + + + + + + + + + + + + + switchyard + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + switchyard + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/bundle/xsl/jbossws-jboss720-server-integration_module.xsl b/release/jboss-as7/bundle/xsl/jbossws-jboss720-server-integration_module.xsl new file mode 100644 index 000000000..d533fc6c2 --- /dev/null +++ b/release/jboss-as7/bundle/xsl/jbossws-jboss720-server-integration_module.xsl @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + jbossws-jboss720-server-integration-4.2.0.Final.jar + + + + + diff --git a/release/jboss-as7/bundle/xsl/jbossws-spi_module.xsl b/release/jboss-as7/bundle/xsl/jbossws-spi_module.xsl new file mode 100644 index 000000000..472823317 --- /dev/null +++ b/release/jboss-as7/bundle/xsl/jbossws-spi_module.xsl @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + jbossws-spi-2.1.2.Final.jar + + + + + diff --git a/release/jboss-as7/bundle/xsl/standalone-ha.xsl b/release/jboss-as7/bundle/xsl/standalone-ha.xsl new file mode 100644 index 000000000..f68169f71 --- /dev/null +++ b/release/jboss-as7/bundle/xsl/standalone-ha.xsl @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + switchyard + + + + diff --git a/release/jboss-as7/bundle/xsl/standalone.xsl b/release/jboss-as7/bundle/xsl/standalone.xsl new file mode 100644 index 000000000..97cae235b --- /dev/null +++ b/release/jboss-as7/bundle/xsl/standalone.xsl @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + urn:jboss:domain:switchyard switchyard.xsd + + + + + + + + + + + + + + + + + + + + :18001 + + + + + :18001 + + + + + + + + + + + + + + + + + + + + + + + + cluster + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/extension/pom.xml b/release/jboss-as7/extension/pom.xml new file mode 100644 index 000000000..698a58f50 --- /dev/null +++ b/release/jboss-as7/extension/pom.xml @@ -0,0 +1,275 @@ + + + + + org.switchyard + switchyard-container-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-deploy-jboss-as7 + jar + SwitchYard: AS7 Extension + SwitchYard AS7 Extension and Subsystem + + + + org.switchyard + switchyard-admin + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-security + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-http + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard.components + switchyard-component-resteasy + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-jca + + + org.jboss.resteasy + resteasy-jaxrs + + + + log4j + log4j + + + org.apache.camel + camel-core + + + org.infinispan + infinispan-core + + + org.jboss.as + jboss-as-clustering-infinispan + + + org.jboss.as + jboss-as-controller + + + org.jboss.as + jboss-as-ee + + + org.jboss.as + jboss-as-network + + + org.jboss.as + jboss-as-server + + + org.jboss.as + jboss-as-naming + + + org.jboss.as + jboss-as-web + + + org.jboss.as + jboss-as-weld + + + org.jboss + jboss-dmr + + + org.jboss.ironjacamar + ironjacamar-core-api + + + org.jboss.logging + jboss-logging-spi + + + + + org.jboss.metadata + jboss-metadata-common + + + org.jboss.metadata + jboss-metadata-ear + + + org.jboss.metadata + jboss-metadata-web + + + org.jboss.modules + jboss-modules + + + org.jboss.msc + jboss-msc + + + org.jboss.logging + jboss-logging + + + org.jboss.logging + jboss-logging-processor + + + org.jboss + staxmapper + + + org.jboss + jboss-vfs + + + org.jboss.web + jbossweb + + + org.jboss.com.sun.httpserver + httpserver + + + + org.jboss.classfilewriter + jboss-classfilewriter + + + + org.apache.cxf + cxf-api + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.cxf + cxf-rt-frontend-jaxws + provided + + + org.apache.cxf + cxf-rt-ws-addr + + + org.apache.cxf + cxf-rt-ws-policy + + + org.apache.cxf + cxf-rt-ws-security + provided + + + org.apache.neethi + neethi + + + org.apache.ws.security + wss4j + provided + + + org.jboss.ws + jbossws-spi + provided + + + org.jboss.ws + jbossws-jboss720-server-integration + provided + + + org.jboss.ws.cxf + jbossws-cxf-server + provided + + + org.jboss.ws.cxf + jbossws-cxf-transports-httpserver + provided + + + org.jboss.ws.projects + jaxws-jboss-httpserver-httpspi + + + org.picketbox + picketbox + provided + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Attribute.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Attribute.java new file mode 100644 index 000000000..7b9707448 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Attribute.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + * + */ +public enum Attribute { + /** + * unknown attribute. + */ + UNKNOWN(null), + + /** + * identifier attribute. + */ + IDENTIFIER("identifier"), + + /** + * implClass attribute. + */ + IMPLCLASS("implClass"), + + /** + * names attribute. + */ + NAMES("names"); + + private final String _name; + + Attribute(final String name) { + _name = name; + } + + /** + * Get the local name of this attribute. + * + * @return the local name + */ + public String getLocalName() { + return _name; + } + + private static final Map MAP; + + static { + final Map map = new HashMap(); + for (Attribute element : values()) { + final String name = element.getLocalName(); + if (name != null) { + map.put(name, element); + } + } + MAP = map; + } + + /** + * Returns the Attribute for a given local name. + * + * @param localName the local name + * @return the Attribute + */ + public static Attribute forName(String localName) { + final Attribute element = MAP.get(localName); + return element == null ? UNKNOWN : element; + } + + /** + * Return the string representation of this Attribute. + * + * @return the string form + */ + public String toString() { + return getLocalName(); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Attributes.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Attributes.java new file mode 100644 index 000000000..e3c3feb23 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Attributes.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension; + +import org.jboss.as.controller.SimpleAttributeDefinition; +import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; +import org.jboss.as.controller.SimpleMapAttributeDefinition; +import org.jboss.as.controller.operations.validation.StringLengthValidator; +import org.jboss.dmr.ModelType; + +/** + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +interface Attributes { + SimpleAttributeDefinition IDENTIFIER = new SimpleAttributeDefinitionBuilder(CommonAttributes.IDENTIFIER, ModelType.STRING) + .setAllowNull(false) + .setMinSize(1) + .setAllowExpression(false) + .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) + .build(); + + SimpleAttributeDefinition IMPLCLASS = new SimpleAttributeDefinitionBuilder(CommonAttributes.IMPLCLASS, ModelType.STRING) + .setAllowNull(false) + .setMinSize(1) + .setAllowExpression(false) + .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) + .build(); + + SimpleMapAttributeDefinition PROPERTIES = new SimpleMapAttributeDefinition.Builder(CommonAttributes.PROPERTIES, true) + .setAllowExpression(true) + .build(); + + SimpleAttributeDefinition SOCKET_BINDING = new SimpleAttributeDefinitionBuilder(CommonAttributes.SOCKET_BINDING, ModelType.STRING) + .setAllowNull(true) + .setMinSize(1) + .setAllowExpression(true) + .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, true)) + .build(); +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/CommonAttributes.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/CommonAttributes.java new file mode 100644 index 000000000..faa9a1e3e --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/CommonAttributes.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +/** + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + * + */ +public interface CommonAttributes { + + /** + * The security-configs attribute. + */ + String SECURITY_CONFIGS = "security-configs"; + + /** + * The security-config attribute. + */ + String SECURITY_CONFIG = "security-config"; + + /** + * The component modules attribute. + */ + String MODULES = "modules"; + + /** + * The component module attribute. + */ + String MODULE = "module"; + + /** + * The component implementation identifier attribute. + */ + String IDENTIFIER = "identifier"; + + /** + * The component implementation class name attribute. + */ + String IMPLCLASS = "implClass"; + + /** + * The environment properties attribute. + */ + String PROPERTIES = "properties"; + + /** + * The socket-binding property value. + */ + String SOCKET_BINDING = "socket-binding"; + + /** + * The replaceable properties. + */ + String DOLLAR = "$"; + + /** + * The extensions element. + */ + String EXTENSIONS = "extensions"; + + /** + * The extension element. + */ + String EXTENSION = "extension"; + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Element.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Element.java new file mode 100644 index 000000000..88f7e9715 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Element.java @@ -0,0 +1,117 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + * + */ +public enum Element { + + /** + * unknown element. + */ + UNKNOWN(null), + + /** + * socket-binding element. + */ + SOCKET_BINDING("socket-binding"), + + /** + * security-configs element. + */ + SECURITY_CONFIGS("security-configs"), + + /** + * security-config element. + */ + SECURITY_CONFIG("security-config"), + + /** + * modules element. + */ + MODULES("modules"), + + /** + * module element. + */ + MODULE("module"), + + /** + * modules element. + */ + EXTENSIONS("extensions"), + + /** + * module element. + */ + EXTENSION("extension"), + + /** + * properties element. + */ + PROPERTIES("properties"); + + private final String _name; + + Element(final String name) { + _name = name; + } + + /** + * Get the local name of this element. + * + * @return the local name + */ + public String getLocalName() { + return _name; + } + + private static final Map MAP; + + static { + final Map map = new HashMap(); + for (Element element : values()) { + final String name = element.getLocalName(); + if (name != null) { + map.put(name, element); + } + } + MAP = map; + } + + /** + * Returns the Element for a given local name. + * + * @param localName the local name + * @return the Element + */ + public static Element forName(String localName) { + final Element element = MAP.get(localName); + return element == null ? UNKNOWN : element; + } + + /** + * Return the string representation of this Element. + * + * @return the string form + */ + public String toString() { + return getLocalName(); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ExtensionLogger.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ExtensionLogger.java new file mode 100644 index 000000000..04bfcbb61 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ExtensionLogger.java @@ -0,0 +1,132 @@ +package org.switchyard.as7.extension; + +import static org.jboss.logging.Logger.Level.ERROR; +import static org.jboss.logging.Logger.Level.WARN; + +import org.jboss.logging.Cause; +import org.jboss.logging.Logger; + +import org.jboss.logging.annotations.LogMessage; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageLogger; +import org.jboss.modules.ModuleLoadException; +/** + *

+ * This file is using the subset 40000-40399 for logger messages. + *

+ * + */ +@MessageLogger(projectCode = "SWITCHYARD") +public interface ExtensionLogger { + /** + * A root logger with the category of the package name. + */ + ExtensionLogger ROOT_LOGGER = Logger.getMessageLogger(ExtensionLogger.class, ExtensionLogger.class.getPackage().getName()); + + /** + * unableToDestroyWebContext method definition. + * @param context context + * @param e cause + */ + @LogMessage(level = ERROR) + @Message(id = 40000, value = "Unable to destroy web context: %s") + void unableToDestroyWebContext(String context, @Cause Exception e); + + /** + * unableToDetermineHostAddress method definition. + */ + @LogMessage(level = WARN) + @Message(id = 40001, value = "Unable to determine host address from connector. Using alias definition instead.") + void unableToDetermineHostAddress(); + + /** + * unableToInstantiateClass method definition. + * @param className class name + * @param ie cause + */ + @LogMessage(level = ERROR) + @Message(id = 40002, value = "Unable to instantiate class %s") + void unableToInstantiateClass(String className, @Cause InstantiationException ie); + + /** + * unableToAccessConstructor method definition. + * @param className class name + * @param iae cause + */ + @LogMessage(level = ERROR) + @Message(id = 40003, value = "Unable to access constructor for %s") + void unableToAccessConstructor(String className, @Cause IllegalAccessException iae); + + /** + * unableToLoadClass method definition. + * @param className class name + * @param cnfe cause + */ + @LogMessage(level = ERROR) + @Message(id = 40004, value = "Unable to load class %s") + void unableToLoadClass(String className, @Cause ClassNotFoundException cnfe); + + /** + * unableToLoadModule method definition. + * @param moduleId module ID + * @param mle cause + */ + @LogMessage(level = ERROR) + @Message(id = 40005, value = "Unable to load module %s") + void unableToLoadModule(String moduleId, @Cause ModuleLoadException mle); + + /** + * unableToStop method definition. + * @param componentName component name + * @param e cause + */ + @LogMessage(level = ERROR) + @Message(id = 40006, value = "Unable to stop %s") + void unableToStop(String componentName, @Cause Exception e); + + /** + * cannotReadPackage method definition. + * @param packageName package name + * @param e cause + */ + @LogMessage(level = WARN) + @Message(id = 40007, value = "Cannot read package: %s") + void cannotReadPackage(String packageName, @Cause Exception e); + + /** + * failedToParseURL method definition. + * @param url url + * @param e cause + */ + @LogMessage(level = WARN) + @Message(id = 40008, value = "Failed to parse URL: %s") + void failedToParseURL(String url, @Cause Exception e); + + /** + * noSocketBindingDefinitionFound method definition. + * @param host host + * @param port port + */ + @LogMessage(level = WARN) + @Message(id = 40009, value = "No socket binding definition is found for the default listener. Using host='%s', port='%s'") + void noSocketBindingDefinitionFound(String host, String port); + + /** + * defaultListenerIsNotHttpListener method definition. + * @param name listener name + */ + @LogMessage(level = WARN) + @Message(id = 40010, value = "The default listener '%s' is not a HTTP listener. Using HTTP protocol anyway.") + void defaultListenerIsNotHttpListener(String name); + + /** + * noDefaultListenerDefined method definition. + * @param schema schema + * @param host host + * @param port port + */ + @LogMessage(level = WARN) + @Message(id = 40011, value = "No default listener is found. Using schema='%s', host='%s', port='%s'") + void noDefaultListenerDefined(String schema, String host, String port); + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ExtensionMessages.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ExtensionMessages.java new file mode 100644 index 000000000..a15e948b8 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ExtensionMessages.java @@ -0,0 +1,98 @@ +package org.switchyard.as7.extension; + +import javax.xml.stream.XMLStreamException; + +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.logging.Cause; +import org.jboss.logging.Messages; +import org.jboss.logging.annotations.Message; +import org.jboss.logging.annotations.MessageBundle; +import org.switchyard.SwitchYardException; + +/** + *

+ * This file is using the subset 40400-40799 for logger messages. + *

+ * + */ +@MessageBundle(projectCode = "SWITCHYARD") +public interface ExtensionMessages { + /** + * The default messages. + */ + ExtensionMessages MESSAGES = Messages.getBundle(ExtensionMessages.class); + + /** + * alreadyDeclared method definition. + * @param localName local name + * @param location location + * @return XMLStreamException + */ + @Message(id = 40400, value = "%s already declared %s") + XMLStreamException alreadyDeclared(String localName, String location); + + /** + * errorStartingGateway method definition. + * @return String + */ + @Message(id = 40401, value = "Error starting gateway: ") + String errorStartingGateway(); + + /** + * unknownGateway method definition. + * @return String + */ + @Message(id = 40402, value = "Unknown gateway.") + String unknownGateway(); + + /** + * unableToCreateTempDirectory method definition. + * @param path path to temp directory + * @return RuntimeException + */ + @Message(id = 40403, value = "Unable to create temp directory %s") + RuntimeException unableToCreateTempDirectory(String path); + + /** + * contextAlreadyExists method definition. + * @param contextName context name + * @return RuntimeException + */ + @Message(id = 40404, value = "Context %s already exists!") + RuntimeException contextAlreadyExists(String contextName); + + /** + * couldNotInstantiateInterceptor method definition. + * @param interceptorClassName interceptor class name + * @param t cause + * @return SwitchYardException + */ + @Message(id = 40405, value = "Could not instantiate interceptor class: %s") + SwitchYardException couldNotInstantiateInterceptor(String interceptorClassName, @Cause Throwable t); + + /** + * noSuchOperationGet method definition. + * @param method the HTTP method + * @param pathInfo the HTTP method path info + * @return Exception + */ + @Message(id = 40406, value = "No such operation: / (HTTP %s PATH_INFO: %s)") + Exception noSuchOperationGet(String method, String pathInfo); + + /** + * extensionNotfound method definition. + * @param extensionClassName extension class name + * @return DeploymentUnitProcessingException + */ + @Message(id = 40407, value = "Could not find portable extension : %s") + DeploymentUnitProcessingException extensionNotfound(String extensionClassName); + + /** + * unableToStartContext method definition. + * @param contextPath the context path + * @return RuntimeException + */ + @Message(id = 40408, value = "Unable to start context : %s") + RuntimeException unableToStartContext(String contextPath, @Cause Throwable t); + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Operations.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Operations.java new file mode 100644 index 000000000..897957afa --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/Operations.java @@ -0,0 +1,290 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension; + +import org.jboss.as.controller.OperationDefinition; +import org.jboss.as.controller.SimpleAttributeDefinition; +import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; +import org.jboss.as.controller.SimpleOperationDefinitionBuilder; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.as.controller.descriptions.NonResolvingResourceDescriptionResolver; +import org.jboss.dmr.ModelType; + +/** + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +interface Operations { + + SimpleAttributeDefinition NAME = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.NAME, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition APPLICATION = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.APPLICATION, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition APPLICATION_NAME = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.APPLICATION_NAME, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition INTERFACE = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.INTERFACE, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition IMPLEMENTATION = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.IMPLEMENTATION, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition IMPLEMENTATION_CONFIGURATION = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.IMPLEMENTATION_CONFIGURATION, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition PROMOTED_REFERENCE = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.PROMOTED_REFERENCE, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition PROMOTED_SERVICE = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.PROMOTED_SERVICE, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition TYPE = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.TYPE, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition CONFIGURATION = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.CONFIGURATION, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition FROM = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.FROM, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition TO = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.TO, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition URL = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.URL, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition REFERENCE_NAME = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.REFERENCE_NAME, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition SERVICE_NAME = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.SERVICE_NAME, ModelType.STRING) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition SUCCESS_COUNT = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.SUCCESS_COUNT, ModelType.INT) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition FAULT_COUNT = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.FAULT_COUNT, ModelType.INT) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition TOTAL_COUNT = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.TOTAL_COUNT, ModelType.INT) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition AVERAGE_TIME = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.AVERAGE_TIME, ModelType.BIG_DECIMAL) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition MIN_TIME = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.MIN_TIME, ModelType.INT) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition MAX_TIME = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.MAX_TIME, ModelType.INT) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition TOTAL_TIME = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.TOTAL_TIME, ModelType.LONG) + .setAllowExpression(true) + .setAllowNull(true) + .build(); + + SimpleAttributeDefinition GATEWAYS = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.GATEWAYS, ModelType.LIST) + .setAllowExpression(true) + .setAllowNull(true) + .setMinSize(2) + .setMaxSize(2) + .build(); + + SimpleAttributeDefinition REFERENCES = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.GATEWAYS, ModelType.LIST) + .setAllowExpression(true) + .setAllowNull(true) + .setMinSize(2) + .setMaxSize(2) + .build(); + + SimpleAttributeDefinition TRANSFORMERS = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.TRANSFORMERS, ModelType.LIST) + .setAllowExpression(true) + .setAllowNull(true) + .setMinSize(3) + .setMaxSize(3) + .build(); + + SimpleAttributeDefinition ARTIFACTS = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.ARTIFACTS, ModelType.LIST) + .setAllowExpression(true) + .setAllowNull(true) + .setMinSize(2) + .setMaxSize(2) + .build(); + + SimpleAttributeDefinition VALIDATORS = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.VALIDATORS, ModelType.LIST) + .setAllowExpression(true) + .setAllowNull(true) + .setMinSize(2) + .setMaxSize(2) + .build(); + + SimpleAttributeDefinition PROPERTIES = SimpleAttributeDefinitionBuilder.create(ModelDescriptionConstants.PROPERTIES, ModelType.LIST) + .setAllowExpression(true) + .setAllowNull(true) + .setMinSize(2) + .setMaxSize(2) + .build(); + + SimpleAttributeDefinition SERVICES = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.SERVICES, ModelType.LIST) + .setAllowExpression(true) + .setAllowNull(true) + .setMinSize(5) + .setMaxSize(5) + .build(); + + SimpleAttributeDefinition COMPONENT_SERVICES = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.COMPONENT_SERVICES, ModelType.LIST) + .setAllowExpression(true) + .setAllowNull(true) + .setMinSize(5) + .setMaxSize(5) + .build(); + + SimpleAttributeDefinition THROTTLING = SimpleAttributeDefinitionBuilder.create(SwitchYardModelConstants.THROTTLING, ModelType.OBJECT) + .setAllowExpression(true) + .build(); + + OperationDefinition GET_VERSION = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.GET_VERSION, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .build(); + + OperationDefinition LIST_APPLICATIONS = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.LIST_APPLICATIONS, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setReplyParameters(NAME) + .setReplyType(ModelType.LIST) + .build(); + + OperationDefinition LIST_REFERENCES = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.LIST_REFERENCES, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(APPLICATION_NAME) + .setReplyParameters(NAME, APPLICATION) + .setReplyType(ModelType.LIST) + .build(); + + OperationDefinition LIST_SERVICES = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.LIST_SERVICES, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(APPLICATION_NAME) + .setReplyParameters(NAME, APPLICATION) + .setReplyType(ModelType.LIST) + .build(); + + OperationDefinition READ_APPLICATION = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.READ_APPLICATION, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(NAME) + .setReplyParameters(NAME, SERVICES, COMPONENT_SERVICES, TRANSFORMERS, ARTIFACTS, VALIDATORS, PROPERTIES) + .setReplyType(ModelType.LIST) + .build(); + + OperationDefinition READ_REFERENCE = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.READ_REFERENCE, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(REFERENCE_NAME, APPLICATION_NAME) + .setReplyParameters(NAME, APPLICATION, INTERFACE, PROMOTED_REFERENCE, GATEWAYS) + .setReplyType(ModelType.LIST) + .build(); + + OperationDefinition READ_SERVICE = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.READ_SERVICE, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(SERVICE_NAME, APPLICATION_NAME) + .setReplyParameters(NAME, APPLICATION, INTERFACE, PROMOTED_SERVICE, GATEWAYS) + .setReplyType(ModelType.LIST) + .build(); + + OperationDefinition USES_ARTIFACT = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.USES_ARTIFACT, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(NAME, URL) + .setReplyParameters(NAME) + .setReplyType(ModelType.LIST) + .build(); + + OperationDefinition SHOW_METRICS = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.SHOW_METRICS, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(SERVICE_NAME, TYPE) + .setReplyParameters(SUCCESS_COUNT, FAULT_COUNT, TOTAL_COUNT, AVERAGE_TIME, MIN_TIME, MAX_TIME, TOTAL_TIME) + .setReplyType(ModelType.LIST) + .build(); + + OperationDefinition RESET_METRICS = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.RESET_METRICS, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(NAME, APPLICATION_NAME) + .build(); + + OperationDefinition STOP_GATEWAY = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.STOP_GATEWAY, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(NAME, SERVICE_NAME, APPLICATION_NAME) + .build(); + + OperationDefinition START_GATEWAY = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.START_GATEWAY, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(NAME, SERVICE_NAME, APPLICATION_NAME) + .build(); + + OperationDefinition UPDATE_THROTTLING = new SimpleOperationDefinitionBuilder(SwitchYardModelConstants.UPDATE_THROTTLING, new NonResolvingResourceDescriptionResolver()) + .setReadOnly() + .setRuntimeOnly() + .setParameters(SERVICE_NAME, APPLICATION_NAME, THROTTLING) + .build(); +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardDeploymentMarker.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardDeploymentMarker.java new file mode 100644 index 000000000..f5d575317 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardDeploymentMarker.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import org.jboss.as.server.deployment.AttachmentKey; +import org.jboss.as.server.deployment.DeploymentUnit; + +/** + * Marker for top level deployments that contain a switchyard.xml file. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public final class SwitchYardDeploymentMarker { + + private static final AttachmentKey MARKER = AttachmentKey.create(Boolean.class); + + private SwitchYardDeploymentMarker() { + + } + /** + * Mark the top level deployment as being a SwitchYard deployment. If the deployment is not a top level deployment the parent is + * marked instead + * @param unit the deployment unit. + */ + public static void mark(DeploymentUnit unit) { + unit.putAttachment(MARKER, Boolean.TRUE); + } + + /** + * Checks if the {@link DeploymentUnit} is a SwitchYard deployment. + * @param unit the deployment unit + * @return true if the {@link DeploymentUnit} has a switchyard.xml in any of it's resource roots + */ + public static boolean isSwitchYardDeployment(DeploymentUnit unit) { + return unit.getAttachment(MARKER) != null; + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtension.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtension.java new file mode 100644 index 000000000..5da716b09 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtension.java @@ -0,0 +1,168 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; +import static org.switchyard.as7.extension.CommonAttributes.EXTENSION; +import static org.switchyard.as7.extension.CommonAttributes.MODULE; +import static org.switchyard.as7.extension.CommonAttributes.SECURITY_CONFIG; + +import java.util.Locale; + +import org.jboss.as.controller.Extension; +import org.jboss.as.controller.ExtensionContext; +import org.jboss.as.controller.PathElement; +import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; +import org.jboss.as.controller.ResourceBuilder; +import org.jboss.as.controller.ResourceDefinition; +import org.jboss.as.controller.SimpleResourceDefinition; +import org.jboss.as.controller.SubsystemRegistration; +import org.jboss.as.controller.descriptions.DescriptionProvider; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; +import org.jboss.as.controller.parsing.ExtensionParsingContext; +import org.jboss.as.controller.registry.ManagementResourceRegistration; +import org.jboss.dmr.ModelNode; +import org.jboss.logging.Logger; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemGetVersion; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemListApplications; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemListReferences; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemListServices; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemReadApplication; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemReadReference; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemReadService; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemResetMetrics; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemShowMetrics; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemStartGateway; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemStopGateway; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemUpdateThrottling; +import org.switchyard.as7.extension.admin.SwitchYardSubsystemUsesArtifact; +import org.switchyard.common.version.Versions; + +/** + * Domain extension used to initialize the SwitchYard subsystem. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardExtension implements Extension { + + private static final Logger LOGGER = Logger.getLogger("org.switchyard"); + + /** The subsystem name. */ + public static final String SUBSYSTEM_NAME = "switchyard"; + + /** Namespace for this subsystem. */ + public static final String NAMESPACE = "urn:jboss:domain:switchyard:1.0"; + + private static final PathElement SUBSYSTEM_PATH = PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME); + private static final PathElement SECURITY_CONFIG_PATH = PathElement.pathElement(SECURITY_CONFIG); + private static final PathElement MODULE_PATH = PathElement.pathElement(MODULE); + private static final PathElement EXTENSION_PATH = PathElement.pathElement(EXTENSION); + private static final String RESOURCE_NAME = SwitchYardExtension.class.getPackage().getName() + ".LocalDescriptions"; + + /** + * Create description resolver. + * @param keyPrefix a list of prefixes + * @return the decscription resolver + */ + public static StandardResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) { + StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME); + for (String kp : keyPrefix) { + prefix.append('.').append(kp); + } + return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, SwitchYardExtension.class.getClassLoader(), true, false); + } + + + /** {@inheritDoc} */ + @Override + public void initialize(final ExtensionContext context) { + // log SwitchYard notification message (includes version information) + LOGGER.info(Versions.getSwitchYardNotification()); + + final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, 1, 0); + subsystem.registerXMLElementWriter(SwitchYardSubsystemWriter.getInstance()); + + ResourceBuilder securityConfigsResource = ResourceBuilder.Factory.create(SECURITY_CONFIG_PATH, getResourceDescriptionResolver(SECURITY_CONFIG)) + .setAddOperation(SwitchYardSecurityConfigAdd.INSTANCE) + .setRemoveOperation(SwitchYardSecurityConfigRemove.INSTANCE) + .addReadWriteAttribute(Attributes.IDENTIFIER, null, new ReloadRequiredWriteAttributeHandler(Attributes.IDENTIFIER)) + .addReadWriteAttribute(Attributes.PROPERTIES, null, new ReloadRequiredWriteAttributeHandler(Attributes.PROPERTIES)); + + ResourceBuilder modulesResource = ResourceBuilder.Factory.create(MODULE_PATH, getResourceDescriptionResolver(MODULE)) + .setAddOperation(SwitchYardModuleAdd.INSTANCE) + .setRemoveOperation(SwitchYardModuleRemove.INSTANCE) + .addReadWriteAttribute(Attributes.IDENTIFIER, null, new ReloadRequiredWriteAttributeHandler(Attributes.IDENTIFIER)) + .addReadWriteAttribute(Attributes.IMPLCLASS, null, new ReloadRequiredWriteAttributeHandler(Attributes.IMPLCLASS)) + .addReadWriteAttribute(Attributes.PROPERTIES, null, new ReloadRequiredWriteAttributeHandler(Attributes.PROPERTIES)); + + ResourceBuilder extensionsResource = ResourceBuilder.Factory.create(EXTENSION_PATH, getResourceDescriptionResolver(EXTENSION)) + .setAddOperation(SwitchYardExtensionAdd.INSTANCE) + .setRemoveOperation(SwitchYardExtensionRemove.INSTANCE) + .addReadWriteAttribute(Attributes.IDENTIFIER, null, new ReloadRequiredWriteAttributeHandler(Attributes.IDENTIFIER)); + + ResourceDefinition subsystemResource = ResourceBuilder.Factory.createSubsystemRoot(SUBSYSTEM_PATH, getResourceDescriptionResolver(), SwitchYardSubsystemAdd.INSTANCE, SwitchYardSubsystemRemove.INSTANCE) + .addReadWriteAttribute(Attributes.SOCKET_BINDING, null, new ReloadRequiredWriteAttributeHandler(Attributes.SOCKET_BINDING)) + .addReadWriteAttribute(Attributes.PROPERTIES, null, new ReloadRequiredWriteAttributeHandler(Attributes.PROPERTIES)) + .addOperation(Operations.GET_VERSION, SwitchYardSubsystemGetVersion.INSTANCE) + .addOperation(Operations.LIST_APPLICATIONS, SwitchYardSubsystemListApplications.INSTANCE) + .addOperation(Operations.LIST_REFERENCES, SwitchYardSubsystemListReferences.INSTANCE) + .addOperation(Operations.LIST_SERVICES, SwitchYardSubsystemListServices.INSTANCE) + .addOperation(Operations.READ_APPLICATION, SwitchYardSubsystemReadApplication.INSTANCE) + .addOperation(Operations.READ_REFERENCE, SwitchYardSubsystemReadReference.INSTANCE) + .addOperation(Operations.READ_SERVICE, SwitchYardSubsystemReadService.INSTANCE) + .addOperation(Operations.USES_ARTIFACT, SwitchYardSubsystemUsesArtifact.INSTANCE) + .addOperation(Operations.SHOW_METRICS, SwitchYardSubsystemShowMetrics.INSTANCE) + .addOperation(Operations.RESET_METRICS, SwitchYardSubsystemResetMetrics.INSTANCE) + .addOperation(Operations.STOP_GATEWAY, SwitchYardSubsystemStopGateway.INSTANCE) + .addOperation(Operations.START_GATEWAY, SwitchYardSubsystemStartGateway.INSTANCE) + .addOperation(Operations.UPDATE_THROTTLING, SwitchYardSubsystemUpdateThrottling.INSTANCE) + .pushChild(securityConfigsResource).pop() + .pushChild(modulesResource).pop() + .pushChild(extensionsResource).pop() + .build(); + subsystem.registerSubsystemModel(subsystemResource); + + DescriptionProvider nullDescriptionProvider = new DescriptionProvider() { + @Override + public ModelNode getModelDescription(Locale locale) { + return new ModelNode(); + } + }; + + final ManagementResourceRegistration registration = subsystem.registerDeploymentModel(new SimpleResourceDefinition(SUBSYSTEM_PATH, getResourceDescriptionResolver("deployment"))); + registration.registerSubModel(new SimpleResourceDefinition(PathElement.pathElement(SwitchYardModelConstants.APPLICATION), getResourceDescriptionResolver())); + } + + /** {@inheritDoc} */ + @Override + public void initializeParsers(final ExtensionParsingContext context) { + context.setSubsystemXmlMapping(SUBSYSTEM_NAME, SwitchYardExtension.NAMESPACE, SwitchYardSubsystemReader.getInstance()); + } + + /** + * Create an Add subsystem operation. + * + * @return the operation node + */ + public static ModelNode createAddSubsystemOperation() { + final ModelNode subsystem = new ModelNode(); + subsystem.get(OP).set(ADD); + subsystem.get(OP_ADDR).add(ModelDescriptionConstants.SUBSYSTEM, SUBSYSTEM_NAME); + return subsystem; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtensionAdd.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtensionAdd.java new file mode 100644 index 000000000..03686c477 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtensionAdd.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import java.util.ArrayList; +import java.util.List; + +import org.jboss.as.controller.AbstractAddStepHandler; +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.PathAddress; +import org.jboss.as.controller.ServiceVerificationHandler; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.as.controller.registry.Resource; +import org.jboss.as.server.AbstractDeploymentChainStep; +import org.jboss.as.server.DeploymentProcessorTarget; +import org.jboss.as.server.deployment.Phase; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.as7.extension.deployment.SwitchYardModuleDependencyProcessor; + +/** + * The SwitchYard subsystem's extension add update handler. + */ +public final class SwitchYardExtensionAdd extends AbstractAddStepHandler { + + static final SwitchYardExtensionAdd INSTANCE = new SwitchYardExtensionAdd(); + + /** + * Global component names. + */ + private static List _extensionNames = new ArrayList(); + + private SwitchYardExtensionAdd() { + + } + + /** + * Get the list of configured extension names. + * + * @return the list of extensions + */ + public static List getExtensionNames() { + return _extensionNames; + } + + @Override + protected void populateModel(final ModelNode operation, final Resource resource) { + final ModelNode model = resource.getModel(); + + populateModel(operation, model); + } + + @Override + protected void populateModel(ModelNode operation, ModelNode subModel) { + } + + @Override + protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model, + ServiceVerificationHandler verificationHandler, List> newControllers) throws OperationFailedException { + final String moduleId = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue(); + _extensionNames.add(moduleId); + + context.addStep(new AbstractDeploymentChainStep() { + protected void execute(DeploymentProcessorTarget processorTarget) { + processorTarget.addDeploymentProcessor(SwitchYardExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, SwitchYardModuleAdd._priority++, new SwitchYardModuleDependencyProcessor(moduleId)); + } + }, OperationContext.Stage.RUNTIME); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtensionRemove.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtensionRemove.java new file mode 100644 index 000000000..9e1169039 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardExtensionRemove.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; + +/** + * The SwitchYard subsystem's extension add update handler. + */ +public final class SwitchYardExtensionRemove extends ReloadRequiredRemoveStepHandler { + + static final SwitchYardExtensionRemove INSTANCE = new SwitchYardExtensionRemove(); + + private SwitchYardExtensionRemove() { + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModelConstants.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModelConstants.java new file mode 100644 index 000000000..62e4d69dc --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModelConstants.java @@ -0,0 +1,236 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +/** + * SwitchYardModelConstants + * + * Constants used for AS7 management model integration. + * + * @author Rob Cernich + */ +public final class SwitchYardModelConstants { + + // operations + /** + * Constant for /subsystem=switchyard/:get-version operation. + */ + public static final String GET_VERSION = "get-version"; + /** + * Constant for /subsystem=switchyard/:list-applications operation. + */ + public static final String LIST_APPLICATIONS = "list-applications"; + /** + * Constant for /subsystem=switchyard/:list-references operation. + */ + public static final String LIST_REFERENCES = "list-references"; + /** + * Constant for /subsystem=switchyard/:list-services operation. + */ + public static final String LIST_SERVICES = "list-services"; + /** + * Constant for /subsystem=switchyard/:read-application operation. + */ + public static final String READ_APPLICATION = "read-application"; + /** + * Constant for /subsystem=switchyard/:read-reference operation. + */ + public static final String READ_REFERENCE = "read-reference"; + /** + * Constant for /subsystem=switchyard/:read-service operation. + */ + public static final String READ_SERVICE = "read-service"; + /** + * Constant for /subsystem=switchyard/:uses-artifact operation. + */ + public static final String USES_ARTIFACT = "uses-artifact"; + /** + * Constant for /subsystem=switchyard/:show-metrics operation. + */ + public static final String SHOW_METRICS = "show-metrics"; + /** + * Constant for /subsystem=switchyard/:reset-metrics operation. + */ + public static final String RESET_METRICS = "reset-metrics"; + /** + * Constant for /subsystem=switchyard/:stop-gateway operation. + */ + public static final String STOP_GATEWAY = "stop-gateway"; + /** + * Constant for /subsystem=switchyard/:start-gateway operation. + */ + public static final String START_GATEWAY = "start-gateway"; + /** + * Constant for /subsystem=switchyard/:update-throttling operation. + */ + public static final String UPDATE_THROTTLING = "update-throttling"; + + // nodes + /** + * Constant for model key: name. + */ + public static final String NAME = "name"; + /** + * Constant for model key: interface. + */ + public static final String INTERFACE = "interface"; + /** + * Constant for model key: type. + */ + public static final String TYPE = "type"; + /** + * Constant for model key: application. + */ + public static final String APPLICATION = "application"; + /** + * Constant for model key: application-name. + */ + public static final String APPLICATION_NAME = "application-name"; + /** + * Constant for model key: componentServices. + */ + public static final String COMPONENT_SERVICES = "componentServices"; + /** + * Constant for model key: configuration. + */ + public static final String CONFIGURATION = "configuration"; + /** + * Constant for model key: from. + */ + public static final String FROM = "from"; + /** + * Constant for model key: implementation. + */ + public static final String IMPLEMENTATION = "implementation"; + /** + * Constant for model key: implementationConfiguration. + */ + public static final String IMPLEMENTATION_CONFIGURATION = "implementationConfiguration"; + /** + * Constant for model key: gateway. + */ + public static final String GATEWAY = "gateway"; + /** + * Constant for model key: gateways. + */ + public static final String GATEWAYS = "gateways"; + /** + * Constant for model key: operations. + */ + public static final String OPERATIONS = "operations"; + /** + * Constant for model key: promotedReference. + */ + public static final String PROMOTED_REFERENCE = "promotedReference"; + /** + * Constant for model key: promotedService. + */ + public static final String PROMOTED_SERVICE = "promotedService"; + /** + * Constant for model key: reference-name. + */ + public static final String REFERENCE_NAME = "reference-name"; + /** + * Constant for model key: references. + */ + public static final String REFERENCES = "references"; + /** + * Constant for model key: service-name. + */ + public static final String SERVICE_NAME = "service-name"; + /** + * Constant for model key: services. + */ + public static final String SERVICES = "services"; + /** + * Constant for model key: state. + */ + public static final String STATE = "state"; + /** + * Constant for model key: throttling. + */ + public static final String THROTTLING = "throttling"; + /** + * Constant for model key: to. + */ + public static final String TO = "to"; + /** + * Constant for model key: transformations. + */ + public static final String TRANSFORMERS = "transformers"; + /** + * Constant for model key: artifacts. + */ + public static final String ARTIFACTS = "artifacts"; + /** + * Constant for model key: url. + */ + public static final String URL = "url"; + /** + * Constant for model key: validators. + */ + public static final String VALIDATORS = "validators"; + + /** + * Constant for model key: successCount. + */ + public static final String SUCCESS_COUNT = "successCount"; + + /** + * Constant for model key: faultCount. + */ + public static final String FAULT_COUNT = "faultCount"; + + /** + * Constant for model key: totalCount. + */ + public static final String TOTAL_COUNT = "totalCount"; + + /** + * Constant for model key: averageTime. + */ + public static final String AVERAGE_TIME = "averageTime"; + + /** + * Constant for model key: minTime. + */ + public static final String MIN_TIME = "minTime"; + + /** + * Constant for model key: maxTime. + */ + public static final String MAX_TIME = "maxTime"; + + /** + * Constant for model key: totalTime. + */ + public static final String TOTAL_TIME = "totalTime"; + + /** + * Constant for model key: enabled. + */ + public static final String ENABLED = "enabled"; + /** + * Constant for model key: maxRequests. + */ + public static final String MAX_REQUESTS = "maxRequests"; + /** + * Constant for model key: timePeriod. + */ + public static final String TIME_PERIOD = "timePeriod"; + + private SwitchYardModelConstants() { + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleAdd.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleAdd.java new file mode 100644 index 000000000..2251b95b0 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleAdd.java @@ -0,0 +1,117 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.jboss.as.controller.AbstractAddStepHandler; +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.PathAddress; +import org.jboss.as.controller.ServiceVerificationHandler; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.as.controller.registry.Resource; +import org.jboss.as.server.AbstractDeploymentChainStep; +import org.jboss.as.server.DeploymentProcessorTarget; +import org.jboss.as.server.deployment.Phase; +import org.jboss.as.web.WebSubsystemServices; +import org.jboss.dmr.ModelNode; +import org.jboss.jca.core.spi.rar.ResourceAdapterRepository; +import org.jboss.logging.Logger; +import org.jboss.msc.service.ServiceBuilder; +import org.jboss.msc.service.ServiceController; +import org.jboss.msc.service.ServiceController.Mode; +import org.jboss.msc.service.ServiceName; +import org.switchyard.as7.extension.deployment.SwitchYardModuleDependencyProcessor; +import org.switchyard.as7.extension.services.SwitchYardComponentService; +import org.switchyard.as7.extension.services.SwitchYardInjectorService; +import org.switchyard.deploy.Component; + +/** + * The SwitchYard subsystem's module add update handler. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class SwitchYardModuleAdd extends AbstractAddStepHandler { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + // TODO use ConnectorServices.RA_REPOSITORY_SERVICE instead once JBoss AS is updated to 7.1.1 or later + //private static final ServiceName RA_REPOSITORY_SERVICE_NAME = ConnectorServices.RA_REPOSITORY_SERVICE; + private static final ServiceName RA_REPOSITORY_SERVICE_NAME = ServiceName.JBOSS.append("rarepository"); + + static final SwitchYardModuleAdd INSTANCE = new SwitchYardModuleAdd(); + + /** + * Global component names. + */ + private static List _componentNames = new ArrayList(); + + /** + * Global priority. + */ + public static int _priority = 0x4005; + + private SwitchYardModuleAdd() { + + } + + /** + * Get the list of configured component names. + * + * @return the list of components + */ + public static List getComponentNames() { + return _componentNames; + } + + @Override + protected void populateModel(final ModelNode operation, final Resource resource) { + final ModelNode model = resource.getModel(); + + populateModel(operation, model); + } + + @Override + protected void populateModel(ModelNode operation, ModelNode subModel) { + subModel.get(CommonAttributes.IMPLCLASS).set(operation.get(CommonAttributes.IMPLCLASS)); + if (operation.hasDefined(CommonAttributes.PROPERTIES)) { + subModel.get(CommonAttributes.PROPERTIES).set(operation.get(CommonAttributes.PROPERTIES)); + } + } + + @Override + protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model, + ServiceVerificationHandler verificationHandler, List> newControllers) throws OperationFailedException { + final String moduleId = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue(); + _componentNames.add(moduleId); + + context.addStep(new AbstractDeploymentChainStep() { + protected void execute(DeploymentProcessorTarget processorTarget) { + processorTarget.addDeploymentProcessor(SwitchYardExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, _priority++, new SwitchYardModuleDependencyProcessor(moduleId)); + } + }, OperationContext.Stage.RUNTIME); + + final SwitchYardComponentService componentService = new SwitchYardComponentService(moduleId, model); + final ServiceBuilder componentServiceBuilder = context.getServiceTarget().addService(SwitchYardComponentService.SERVICE_NAME.append(moduleId), componentService); + componentServiceBuilder.addDependency(SwitchYardInjectorService.SERVICE_NAME, Map.class, componentService.getInjectedValues()) + .addDependency(RA_REPOSITORY_SERVICE_NAME, ResourceAdapterRepository.class, componentService.getResourceAdapterRepository()); + componentServiceBuilder.addDependency(WebSubsystemServices.JBOSS_WEB); + componentServiceBuilder.setInitialMode(Mode.ACTIVE); + newControllers.add(componentServiceBuilder.install()); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleRemove.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleRemove.java new file mode 100644 index 000000000..4912a956d --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleRemove.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; +import org.jboss.dmr.ModelNode; + +/** + * The SwitchYard subsystem's module add update handler. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class SwitchYardModuleRemove extends ReloadRequiredRemoveStepHandler { + + static final SwitchYardModuleRemove INSTANCE = new SwitchYardModuleRemove(); + + private SwitchYardModuleRemove() { + + } + @Override + protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { + super.performRuntime(context, operation, model); + } + + @Override + protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) + throws OperationFailedException { + super.recoverServices(context, operation, model); + + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSecurityConfigAdd.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSecurityConfigAdd.java new file mode 100644 index 000000000..e91e60f6b --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSecurityConfigAdd.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import java.util.List; +import java.util.Map; + +import org.jboss.as.controller.AbstractAddStepHandler; +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.PathAddress; +import org.jboss.as.controller.ServiceVerificationHandler; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.as.controller.registry.Resource; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceBuilder; +import org.jboss.msc.service.ServiceController; +import org.jboss.msc.service.ServiceController.Mode; +import org.jboss.msc.service.ServiceName; +import org.switchyard.as7.extension.services.SwitchYardInjectorService; +import org.switchyard.as7.extension.services.SwitchYardSecurityConfigService; +import org.switchyard.as7.extension.services.SwitchYardSecurityConfigService.SecurityConfig; +import org.switchyard.as7.extension.services.SwitchYardSystemSecurityService; +import org.switchyard.security.system.SystemSecurity; + +/** + * The SwitchYard subsystem's module add update handler. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class SwitchYardSecurityConfigAdd extends AbstractAddStepHandler { + + static final SwitchYardSecurityConfigAdd INSTANCE = new SwitchYardSecurityConfigAdd(); + + private SwitchYardSecurityConfigAdd() {} + + @Override + protected void populateModel(final ModelNode operation, final Resource resource) { + final ModelNode model = resource.getModel(); + populateModel(operation, model); + } + + @Override + protected void populateModel(ModelNode operation, ModelNode subModel) { + if (operation.hasDefined(CommonAttributes.PROPERTIES)) { + subModel.get(CommonAttributes.PROPERTIES).set(operation.get(CommonAttributes.PROPERTIES)); + } + } + + @Override + protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model, + ServiceVerificationHandler verificationHandler, List> newControllers) throws OperationFailedException { + String moduleId = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue(); + ServiceName serviceName = SwitchYardSecurityConfigService.SERVICE_NAME.append(moduleId); + SwitchYardSecurityConfigService securityConfigService = new SwitchYardSecurityConfigService(moduleId, model); + ServiceBuilder securityConfigServiceBuilder = context.getServiceTarget().addService(serviceName, securityConfigService); + securityConfigServiceBuilder.addDependency(SwitchYardSystemSecurityService.SERVICE_NAME, SystemSecurity.class, securityConfigService.getSystemSecurity()); + securityConfigServiceBuilder.addDependency(SwitchYardInjectorService.SERVICE_NAME, Map.class, securityConfigService.getInjectedValues()); + securityConfigServiceBuilder.setInitialMode(Mode.ACTIVE); + newControllers.add(securityConfigServiceBuilder.install()); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSecurityConfigRemove.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSecurityConfigRemove.java new file mode 100644 index 000000000..24862119d --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSecurityConfigRemove.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; +import org.jboss.dmr.ModelNode; + +/** + * The SwitchYard subsystem's security-config add update handler. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class SwitchYardSecurityConfigRemove extends ReloadRequiredRemoveStepHandler { + + static final SwitchYardSecurityConfigRemove INSTANCE = new SwitchYardSecurityConfigRemove(); + + private SwitchYardSecurityConfigRemove() { + + } + @Override + protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { + super.performRuntime(context, operation, model); + } + + @Override + protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) + throws OperationFailedException { + super.recoverServices(context, operation, model); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemAdd.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemAdd.java new file mode 100644 index 000000000..397460e18 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemAdd.java @@ -0,0 +1,139 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import static org.switchyard.as7.extension.CommonAttributes.MODULE; +import static org.switchyard.as7.extension.CommonAttributes.SECURITY_CONFIG; +import static org.switchyard.as7.extension.CommonAttributes.PROPERTIES; +import static org.switchyard.as7.extension.CommonAttributes.SOCKET_BINDING; + +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +import org.infinispan.Cache; +import org.jboss.as.clustering.infinispan.subsystem.CacheService; +import org.jboss.as.controller.AbstractBoottimeAddStepHandler; +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.ServiceVerificationHandler; +import org.jboss.as.controller.registry.Resource; +import org.jboss.as.network.SocketBinding; +import org.jboss.as.server.AbstractDeploymentChainStep; +import org.jboss.as.server.DeploymentProcessorTarget; +import org.jboss.as.server.deployment.Phase; +import org.jboss.dmr.ModelNode; +import org.jboss.logging.Logger; +import org.jboss.msc.service.ServiceBuilder; +import org.jboss.msc.service.ServiceBuilder.DependencyType; +import org.jboss.msc.service.ServiceController; +import org.jboss.msc.service.ServiceController.Mode; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.deployment.SwitchYardConfigDeploymentProcessor; +import org.switchyard.as7.extension.deployment.SwitchYardConfigProcessor; +import org.switchyard.as7.extension.deployment.SwitchYardDependencyProcessor; +import org.switchyard.as7.extension.deployment.SwitchYardDeploymentProcessor; +import org.switchyard.as7.extension.services.SwitchYardAdminService; +import org.switchyard.as7.extension.services.SwitchYardInjectorService; +import org.switchyard.as7.extension.services.SwitchYardServiceDomainManagerService; +import org.switchyard.as7.extension.services.SwitchYardSystemSecurityService; +import org.switchyard.as7.extension.util.ServerUtil; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.security.system.SystemSecurity; + +/** + * The SwitchYard subsystem add update handler. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public final class SwitchYardSubsystemAdd extends AbstractBoottimeAddStepHandler { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + static final SwitchYardSubsystemAdd INSTANCE = new SwitchYardSubsystemAdd(); + + // Private to ensure a singleton. + private SwitchYardSubsystemAdd() { + } + + @Override + protected void populateModel(final ModelNode operation, final Resource resource) throws OperationFailedException { + final ModelNode submodel = resource.getModel(); + populateModel(operation, submodel); + } + + @Override + protected void populateModel(final ModelNode operation, final ModelNode submodel) throws OperationFailedException { + if (operation.hasDefined(SOCKET_BINDING)) { + submodel.get(SOCKET_BINDING).set(operation.require(SOCKET_BINDING)); + } + if (operation.hasDefined(PROPERTIES)) { + submodel.get(PROPERTIES).set(operation.require(PROPERTIES)); + } + submodel.get(SECURITY_CONFIG).setEmptyObject(); + submodel.get(MODULE).setEmptyObject(); + } + + @Override + protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model, ServiceVerificationHandler verificationHandler, List> newControllers) { + LOG.trace("Performing boot time operation " + operation); + context.addStep(new AbstractDeploymentChainStep() { + protected void execute(DeploymentProcessorTarget processorTarget) { + int priority = 0x4000; + processorTarget.addDeploymentProcessor(SwitchYardExtension.SUBSYSTEM_NAME, Phase.PARSE, priority++, new SwitchYardConfigDeploymentProcessor()); + processorTarget.addDeploymentProcessor(SwitchYardExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, priority++, new SwitchYardDependencyProcessor()); + processorTarget.addDeploymentProcessor(SwitchYardExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, priority++, new SwitchYardConfigProcessor()); + processorTarget.addDeploymentProcessor(SwitchYardExtension.SUBSYSTEM_NAME, Phase.INSTALL, priority++, new SwitchYardDeploymentProcessor()); + } + }, OperationContext.Stage.RUNTIME); + LOG.info("Activating SwitchYard Subsystem"); + + ServerUtil.setRegistry(context.getServiceRegistry(false)); + final SwitchYardInjectorService injectorService = new SwitchYardInjectorService(); + final ServiceBuilder> injectorServiceBuilder = context.getServiceTarget().addService(SwitchYardInjectorService.SERVICE_NAME, injectorService); + if (operation.has(SOCKET_BINDING)) { + StringTokenizer sockets = new StringTokenizer(operation.get(SOCKET_BINDING).asString(), ","); + while (sockets.hasMoreTokens()) { + String socketName = sockets.nextToken(); + injectorServiceBuilder.addDependency(SocketBinding.JBOSS_BINDING_NAME.append(socketName), SocketBinding.class, injectorService.getSocketBinding(socketName)); + } + } + injectorServiceBuilder.setInitialMode(Mode.ACTIVE); + newControllers.add(injectorServiceBuilder.install()); + + // Add the AS7 Service for the SystemSecurity... + final SwitchYardSystemSecurityService systemSecurityService = new SwitchYardSystemSecurityService(); + newControllers.add(context.getServiceTarget() + .addService(SwitchYardSystemSecurityService.SERVICE_NAME, systemSecurityService) + .install()); + + // Add the AS7 Service for the ServiceDomainManager... + final SwitchYardServiceDomainManagerService serviceDomainManagerService = new SwitchYardServiceDomainManagerService(); + newControllers.add(context.getServiceTarget() + .addService(SwitchYardServiceDomainManagerService.SERVICE_NAME, serviceDomainManagerService) + .addDependency(SwitchYardSystemSecurityService.SERVICE_NAME, SystemSecurity.class, serviceDomainManagerService.getSystemSecurity()) + .addDependency(DependencyType.OPTIONAL, CacheService.getServiceName("cluster", null), Cache.class, serviceDomainManagerService.getCache()) + .install()); + + final SwitchYardAdminService adminService = new SwitchYardAdminService(); + final ServiceBuilder adminServiceBuilder = context.getServiceTarget().addService(SwitchYardAdminService.SERVICE_NAME, adminService); + adminServiceBuilder.setInitialMode(Mode.ACTIVE); + newControllers.add(adminServiceBuilder + .addDependency(SwitchYardInjectorService.SERVICE_NAME, Map.class, adminService.getSocketBindings()) + .addDependency(SwitchYardServiceDomainManagerService.SERVICE_NAME, ServiceDomainManager.class, adminService.getServiceDomainManager()) + .install()); + + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemReader.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemReader.java new file mode 100644 index 000000000..323f4fd84 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemReader.java @@ -0,0 +1,320 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; +import static org.jboss.as.controller.parsing.ParseUtils.missingRequired; +import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes; +import static org.jboss.as.controller.parsing.ParseUtils.requireNoContent; +import static org.jboss.as.controller.parsing.ParseUtils.requireNoNamespaceAttribute; +import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute; +import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement; +import static org.switchyard.as7.extension.CommonAttributes.EXTENSION; +import static org.switchyard.as7.extension.CommonAttributes.IMPLCLASS; +import static org.switchyard.as7.extension.CommonAttributes.MODULE; +import static org.switchyard.as7.extension.CommonAttributes.PROPERTIES; +import static org.switchyard.as7.extension.CommonAttributes.SECURITY_CONFIG; +import static org.switchyard.as7.extension.CommonAttributes.SOCKET_BINDING; + +import java.util.Collections; +import java.util.List; + +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; + +import org.jboss.as.controller.PathAddress; +import org.jboss.as.controller.PathElement; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.dmr.ModelNode; +import org.jboss.staxmapper.XMLElementReader; +import org.jboss.staxmapper.XMLExtendedStreamReader; + +/** + * A SwitchYard subsystem reader/parser. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +final class SwitchYardSubsystemReader implements XMLStreamConstants, XMLElementReader> { + + private static final SwitchYardSubsystemReader INSTANCE = new SwitchYardSubsystemReader(); + + private SwitchYardSubsystemReader() { + // forbidden instantiation + } + + static SwitchYardSubsystemReader getInstance() { + return INSTANCE; + } + + /** {@inheritDoc} */ + @Override + public void readElement(final XMLExtendedStreamReader reader, List list) throws XMLStreamException { + // Require no attributes + requireNoAttributes(reader); + // Add our subsystem's 'add' operation + ModelNode subsystem = SwitchYardExtension.createAddSubsystemOperation(); + list.add(subsystem); + // Elements + while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { + if (reader.getNamespaceURI().equals(SwitchYardExtension.NAMESPACE)) { + final Element element = Element.forName(reader.getLocalName()); + switch (element) { + case SOCKET_BINDING: + String sockets = null; + final int count = reader.getAttributeCount(); + for (int i = 0; i < count; i++) { + requireNoNamespaceAttribute(reader, i); + final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); + switch (attribute) { + case NAMES: + sockets = reader.getAttributeValue(i); + break; + default: + throw unexpectedAttribute(reader, i); + } + } + if (sockets != null) { + subsystem.get(SOCKET_BINDING).set(sockets); + } + requireNoContent(reader); + break; + case SECURITY_CONFIGS: + parseSecurityConfigsElement(reader, list); + break; + case MODULES: + parseModulesElement(reader, list); + break; + case EXTENSIONS: + parseExtensionsElement(reader, list); + break; + case PROPERTIES: + ModelNode properties = parsePropertiesElement("", reader); + if (properties != null) { + subsystem.get(PROPERTIES).set(properties); + } + break; + default: + throw unexpectedElement(reader); + } + } + } + } + + void parseSecurityConfigsElement(XMLExtendedStreamReader reader, List list) throws XMLStreamException { + + // Handle attributes + requireNoAttributes(reader); + + // Handle module elements + while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { + if (reader.getNamespaceURI().equals(SwitchYardExtension.NAMESPACE)) { + final Element element = Element.forName(reader.getLocalName()); + if (element == Element.SECURITY_CONFIG) { + parseSecurityConfigElement(reader, list); + } else { + throw unexpectedElement(reader); + } + } + } + } + + void parseSecurityConfigElement(XMLExtendedStreamReader reader, List list) throws XMLStreamException { + String identifier = null; + final int count = reader.getAttributeCount(); + for (int i = 0; i < count; i++) { + requireNoNamespaceAttribute(reader, i); + final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); + switch (attribute) { + case IDENTIFIER: + identifier = reader.getAttributeValue(i); + break; + default: + throw unexpectedAttribute(reader, i); + } + } + if (identifier == null) { + throw missingRequired(reader, Collections.singleton(Attribute.IDENTIFIER)); + } + + //Add the 'add' operation for each 'security-config' child + ModelNode securityConfigAdd = new ModelNode(); + securityConfigAdd.get(OP).set(ModelDescriptionConstants.ADD); + PathAddress addr = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, SwitchYardExtension.SUBSYSTEM_NAME), PathElement.pathElement(SECURITY_CONFIG, identifier)); + securityConfigAdd.get(OP_ADDR).set(addr.toModelNode()); + + while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { + final Element element1 = Element.forName(reader.getLocalName()); + switch (element1) { + case PROPERTIES: + ModelNode properties = parsePropertiesElement(identifier, reader); + if (properties != null) { + securityConfigAdd.get(PROPERTIES).set(properties); + } + break; + default: + throw unexpectedElement(reader); + } + } + + list.add(securityConfigAdd); + } + + void parseModulesElement(XMLExtendedStreamReader reader, List list) throws XMLStreamException { + + // Handle attributes + requireNoAttributes(reader); + + // Handle module elements + while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { + if (reader.getNamespaceURI().equals(SwitchYardExtension.NAMESPACE)) { + final Element element = Element.forName(reader.getLocalName()); + if (element == Element.MODULE) { + parseModuleElement(reader, list); + } else { + throw unexpectedElement(reader); + } + } + } + } + + void parseModuleElement(XMLExtendedStreamReader reader, List list) throws XMLStreamException { + String identifier = null; + String implClass = null; + final int count = reader.getAttributeCount(); + for (int i = 0; i < count; i++) { + requireNoNamespaceAttribute(reader, i); + final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); + switch (attribute) { + case IDENTIFIER: + identifier = reader.getAttributeValue(i); + break; + case IMPLCLASS: + implClass = reader.getAttributeValue(i); + break; + default: + throw unexpectedAttribute(reader, i); + } + } + if (identifier == null) { + throw missingRequired(reader, Collections.singleton(Attribute.IDENTIFIER)); + } + if (implClass == null) { + throw missingRequired(reader, Collections.singleton(Attribute.IMPLCLASS)); + } + + //Add the 'add' operation for each 'module' child + ModelNode moduleAdd = new ModelNode(); + moduleAdd.get(OP).set(ModelDescriptionConstants.ADD); + PathAddress addr = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, SwitchYardExtension.SUBSYSTEM_NAME), PathElement.pathElement(MODULE, identifier)); + moduleAdd.get(OP_ADDR).set(addr.toModelNode()); + moduleAdd.get(IMPLCLASS).set(implClass); + + while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { + final Element element1 = Element.forName(reader.getLocalName()); + switch (element1) { + case PROPERTIES: + ModelNode properties = parsePropertiesElement(identifier, reader); + if (properties != null) { + moduleAdd.get(PROPERTIES).set(properties); + } + break; + default: + throw unexpectedElement(reader); + } + } + + list.add(moduleAdd); + } + + ModelNode parsePropertiesElement(String identifier, XMLExtendedStreamReader reader) throws XMLStreamException { + + // Handle attributes + requireNoAttributes(reader); + + ModelNode properties = new ModelNode(); + StringBuffer configModel = new StringBuffer(); + + // Handle elements + while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { + if (reader.getNamespaceURI().equals(SwitchYardExtension.NAMESPACE)) { + final Element element = Element.forName(reader.getLocalName()); + String name = reader.getLocalName(); + String value = reader.getElementText(); + if (properties.has(name)) { + throw ExtensionMessages.MESSAGES.alreadyDeclared(element.getLocalName(), reader.getLocation().toString()); + } + + ModelNode property = new ModelNode(); + property.set(value); + properties.get(name).set(property); + configModel.append(element.toString()); + } + } + + return properties; + } + + + void parseExtensionsElement(XMLExtendedStreamReader reader, List list) throws XMLStreamException { + + // Handle attributes + requireNoAttributes(reader); + + // Handle module elements + while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { + if (reader.getNamespaceURI().equals(SwitchYardExtension.NAMESPACE)) { + final Element element = Element.forName(reader.getLocalName()); + if (element == Element.EXTENSION) { + parseExtensionElement(reader, list); + } else { + throw unexpectedElement(reader); + } + } + } + } + + void parseExtensionElement(XMLExtendedStreamReader reader, List list) throws XMLStreamException { + String identifier = null; + final int count = reader.getAttributeCount(); + for (int i = 0; i < count; i++) { + requireNoNamespaceAttribute(reader, i); + final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); + switch (attribute) { + case IDENTIFIER: + identifier = reader.getAttributeValue(i); + break; + default: + throw unexpectedAttribute(reader, i); + } + } + if (identifier == null) { + throw missingRequired(reader, Collections.singleton(Attribute.IDENTIFIER)); + } + + //Add the 'add' operation for each 'module' child + ModelNode moduleAdd = new ModelNode(); + moduleAdd.get(OP).set(ModelDescriptionConstants.ADD); + PathAddress addr = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, SwitchYardExtension.SUBSYSTEM_NAME), PathElement.pathElement(EXTENSION, identifier)); + moduleAdd.get(OP_ADDR).set(addr.toModelNode()); + + while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { + throw unexpectedElement(reader); + } + + list.add(moduleAdd); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemRemove.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemRemove.java new file mode 100644 index 000000000..bc0648abd --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemRemove.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; +import org.jboss.dmr.ModelNode; + +/** + * The SwitchYard subsystem add update handler. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class SwitchYardSubsystemRemove extends ReloadRequiredRemoveStepHandler { + + static final SwitchYardSubsystemRemove INSTANCE = new SwitchYardSubsystemRemove(); + + private SwitchYardSubsystemRemove() { + + } + @Override + protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { + super.performRuntime(context, operation, model); + } + + @Override + protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) + throws OperationFailedException { + super.recoverServices(context, operation, model); + + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemWriter.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemWriter.java new file mode 100644 index 000000000..a55e01e47 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/SwitchYardSubsystemWriter.java @@ -0,0 +1,107 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import java.util.Set; + +import javax.xml.stream.XMLStreamException; + +import org.jboss.as.controller.persistence.SubsystemMarshallingContext; +import org.jboss.dmr.ModelNode; +import org.jboss.dmr.Property; +import org.jboss.staxmapper.XMLElementWriter; +import org.jboss.staxmapper.XMLExtendedStreamWriter; + +/** + * A SwitchYard subsystem writer. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +final class SwitchYardSubsystemWriter implements XMLElementWriter { + + private static final SwitchYardSubsystemWriter INSTANCE = new SwitchYardSubsystemWriter(); + + private SwitchYardSubsystemWriter() { + // forbidden instantiation + } + + static SwitchYardSubsystemWriter getInstance() { + return INSTANCE; + } + + /** {@inheritDoc} */ + @Override + public void writeContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws XMLStreamException { + context.startSubsystemElement(SwitchYardExtension.NAMESPACE, false); + ModelNode node = context.getModelNode(); + if (node.hasDefined(CommonAttributes.SOCKET_BINDING)) { + ModelNode socketNames = node.get(CommonAttributes.SOCKET_BINDING); + writer.writeEmptyElement(Element.SOCKET_BINDING.getLocalName()); + writer.writeAttribute(Attribute.NAMES.getLocalName(), socketNames.asString()); + } + if (node.hasDefined(CommonAttributes.SECURITY_CONFIG)) { + ModelNode modules = node.get(CommonAttributes.SECURITY_CONFIG); + writer.writeStartElement(Element.SECURITY_CONFIGS.getLocalName()); + for (Property property : modules.asPropertyList()) { + writer.writeStartElement(Element.SECURITY_CONFIG.getLocalName()); + writer.writeAttribute(Attribute.IDENTIFIER.getLocalName(), property.getName()); + ModelNode entry = property.getValue(); + writeProperties(entry, writer); + writer.writeEndElement(); + } + writer.writeEndElement(); + } + if (node.hasDefined(CommonAttributes.MODULE)) { + ModelNode modules = node.get(CommonAttributes.MODULE); + writer.writeStartElement(Element.MODULES.getLocalName()); + for (Property property : modules.asPropertyList()) { + writer.writeStartElement(Element.MODULE.getLocalName()); + writer.writeAttribute(Attribute.IDENTIFIER.getLocalName(), property.getName()); + ModelNode entry = property.getValue(); + if (entry.hasDefined(CommonAttributes.IMPLCLASS)) { + writer.writeAttribute(Attribute.IMPLCLASS.getLocalName(), entry.get(CommonAttributes.IMPLCLASS).asString()); + } + writeProperties(entry, writer); + writer.writeEndElement(); + } + writer.writeEndElement(); + } + if (node.hasDefined(CommonAttributes.EXTENSION)) { + ModelNode modules = node.get(CommonAttributes.EXTENSION); + writer.writeStartElement(Element.EXTENSIONS.getLocalName()); + for (Property property : modules.asPropertyList()) { + writer.writeStartElement(Element.EXTENSION.getLocalName()); + writer.writeAttribute(Attribute.IDENTIFIER.getLocalName(), property.getName()); + writer.writeEndElement(); + } + writer.writeEndElement(); + } + writeProperties(node, writer); + writer.writeEndElement(); + } + + private static void writeProperties(final ModelNode node, final XMLExtendedStreamWriter writer) throws XMLStreamException { + if (node.hasDefined(CommonAttributes.PROPERTIES)) { + ModelNode properties = node.get(CommonAttributes.PROPERTIES); + writer.writeStartElement(Element.PROPERTIES.getLocalName()); + Set keys = properties.keys(); + for (String current : keys) { + writer.writeStartElement(current); + writer.writeCharacters(properties.get(current).asString()); + writer.writeEndElement(); + } + writer.writeEndElement(); + } + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/ModelNodeCreationUtil.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/ModelNodeCreationUtil.java new file mode 100644 index 000000000..f436a4ea9 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/ModelNodeCreationUtil.java @@ -0,0 +1,878 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INTERFACE; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROPERTIES; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TYPE; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION; +import static org.switchyard.as7.extension.SwitchYardModelConstants.ARTIFACTS; +import static org.switchyard.as7.extension.SwitchYardModelConstants.AVERAGE_TIME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.COMPONENT_SERVICES; +import static org.switchyard.as7.extension.SwitchYardModelConstants.CONFIGURATION; +import static org.switchyard.as7.extension.SwitchYardModelConstants.ENABLED; +import static org.switchyard.as7.extension.SwitchYardModelConstants.FAULT_COUNT; +import static org.switchyard.as7.extension.SwitchYardModelConstants.FROM; +import static org.switchyard.as7.extension.SwitchYardModelConstants.GATEWAYS; +import static org.switchyard.as7.extension.SwitchYardModelConstants.IMPLEMENTATION; +import static org.switchyard.as7.extension.SwitchYardModelConstants.IMPLEMENTATION_CONFIGURATION; +import static org.switchyard.as7.extension.SwitchYardModelConstants.MAX_REQUESTS; +import static org.switchyard.as7.extension.SwitchYardModelConstants.MAX_TIME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.MIN_TIME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.OPERATIONS; +import static org.switchyard.as7.extension.SwitchYardModelConstants.PROMOTED_REFERENCE; +import static org.switchyard.as7.extension.SwitchYardModelConstants.PROMOTED_SERVICE; +import static org.switchyard.as7.extension.SwitchYardModelConstants.REFERENCES; +import static org.switchyard.as7.extension.SwitchYardModelConstants.SERVICES; +import static org.switchyard.as7.extension.SwitchYardModelConstants.STATE; +import static org.switchyard.as7.extension.SwitchYardModelConstants.SUCCESS_COUNT; +import static org.switchyard.as7.extension.SwitchYardModelConstants.THROTTLING; +import static org.switchyard.as7.extension.SwitchYardModelConstants.TIME_PERIOD; +import static org.switchyard.as7.extension.SwitchYardModelConstants.TO; +import static org.switchyard.as7.extension.SwitchYardModelConstants.TOTAL_COUNT; +import static org.switchyard.as7.extension.SwitchYardModelConstants.TOTAL_TIME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.TRANSFORMERS; +import static org.switchyard.as7.extension.SwitchYardModelConstants.URL; +import static org.switchyard.as7.extension.SwitchYardModelConstants.VALIDATORS; + +import java.math.BigDecimal; +import java.util.Map; + +import org.jboss.dmr.ModelNode; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.ComponentReference; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.MessageMetrics; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.ServiceOperation; +import org.switchyard.admin.Throttling; +import org.switchyard.admin.Transformer; +import org.switchyard.admin.Validator; +import org.switchyard.config.model.switchyard.ArtifactModel; + +/** + * ModelNodeCreationUtil + * + * Utility class for creating AS7 management {@link ModelNode} object from + * {@link org.switchyard.admin.SwitchYard} admin objects. + * + * @author Rob Cernich + */ +final public class ModelNodeCreationUtil { + + /** + * Creates a new {@link ModelNode} tree from the {@link Application}. The + * tree has the form:
+ *

+     *      "name" => "name",
+     *      "services" => [
+     *          {
+     *              "name" => "serviceName",
+     *              "application" => "name",
+     *              "interface" => "interfaceName",
+     *              "promotedService" => "promotedServiceName",
+     *              "gateways" => [
+     *                  {
+     *                      "type" => "typeName",
+     *                      "configuration" => "<?binding.foo ..."
+     *                  },
+     *                  ...
+     *              ],
+     *          },
+     *          ...
+     *      ],
+     *      "references" => [
+     *          {
+     *              "name" => "referenceName",
+     *              "application" => "name",
+     *              "interface" => "interfaceName",
+     *              "promotedReference" => "promotedReferenceName",
+     *              "gateways" => [
+     *                  {
+     *                      "type" => "typeName",
+     *                      "configuration" => "<?binding.foo ..."
+     *                  },
+     *                  ...
+     *              ],
+     *          },
+     *          ...
+     *      ],
+     *      "componentServices" => [
+     *          {
+     *              "name" => "serviceName",
+     *              "application" => "name",
+     *              "interface" => "interfaceName",
+     *              "implementation" => "implementationTypeName",
+     *              "references" => [
+     *                  {
+     *                      "name" => "referenceName",
+     *                      "interface" => "interfaceName"
+     *                  },
+     *                  ...
+     *              ],
+     *          },
+     *          ...
+     *      ],
+     *      "transformers" => [
+     *          {
+     *              "from" => "fromType",
+     *              "to" => "toType",
+     *              "type" => "transformerType",
+     *          },
+     *          ...
+     *      ],
+     *      "artifacts" => [
+     *          {
+     *              "name" => "nameType",
+     *              "url" => "urlType",
+     *          },
+     *          ...
+     *      ],
+     *      "validators" => [
+     *          {
+     *              "name" => "typeName",
+     *              "type" => "XML",
+     *          },
+     *          ...
+     *      ],
+     *      "properties" => [
+     *          {
+     *              "key" => "some.key",
+     *              "value" => "value",
+     *          },
+     *          ...
+     *      ]
+     * 
+ * + * @param application the {@link Application} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createApplicationNode(Application application) { + ModelNode applicationNode = new ModelNode(); + ModelNode servicesNode = new ModelNode(); + for (Service service : application.getServices()) { + servicesNode.add(createServiceNode(service)); + } + + ModelNode referencesNode = new ModelNode(); + for (Reference reference : application.getReferences()) { + referencesNode.add(createReferenceNode(reference)); + } + + ModelNode componentServicesNode = new ModelNode(); + for (ComponentService componentService : application.getComponentServices()) { + componentServicesNode.add(createComopnentServiceNode(componentService)); + } + + ModelNode transformersNode = new ModelNode(); + for (Transformer transformer : application.getTransformers()) { + transformersNode.add(createTransformerNode(transformer)); + } + + ModelNode artifactsNode = new ModelNode(); + if (application.getConfig().getArtifacts() != null) { + for (ArtifactModel artifact : application.getConfig().getArtifacts().getArtifacts()) { + artifactsNode.add(createArtifactNode(artifact)); + } + } + + ModelNode validatorsNode = new ModelNode(); + if (application.getValidators() != null) { + for (Validator validator : application.getValidators()) { + validatorsNode.add(createValidatorNode(validator)); + } + } + + ModelNode propertiesNode = new ModelNode(); + if (application.getProperties() != null) { + for (Map.Entry property : application.getProperties().entrySet()) { + ModelNode propertyNode = new ModelNode(); + propertyNode.get("key").set(property.getKey()); + propertyNode.get(VALUE).set(property.getValue()); + propertiesNode.add(propertyNode); + } + } + + applicationNode.get(NAME).set(application.getName().toString()); + applicationNode.get(SERVICES).set(servicesNode); + applicationNode.get(REFERENCES).set(referencesNode); + applicationNode.get(COMPONENT_SERVICES).set(componentServicesNode); + applicationNode.get(TRANSFORMERS).set(transformersNode); + applicationNode.get(ARTIFACTS).set(artifactsNode); + applicationNode.get(VALIDATORS).set(validatorsNode); + applicationNode.get(PROPERTIES).set(propertiesNode); + + return applicationNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link Reference}. The tree + * has the form:
+ *
+     *      "name" => "referenceName",
+     *      "application" => "name",
+     *      "interface" => "interfaceName",
+     *      "promotedReference" => "promotedReferenceName",
+     *      "gateways" => [
+     *          {
+     *              "type" => "typeName",
+     *              "configuration" => "<?binding.foo ..."
+     *          },
+     *          ...
+     *      ]
+     * 
+ * + * @param reference the {@link Reference} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createReferenceNode(Reference reference) { + ModelNode referenceNode = new ModelNode(); + + referenceNode.get(NAME).set(reference.getName().toString()); + + referenceNode.get(APPLICATION).set(reference.getApplication().getName().toString()); + + String interfaceName = reference.getInterface(); + if (interfaceName == null) { + referenceNode.get(INTERFACE); + } else { + referenceNode.get(INTERFACE).set(interfaceName); + } + + String promotedReference = reference.getPromotedReference(); + if (promotedReference == null) { + referenceNode.get(PROMOTED_REFERENCE); + } else { + referenceNode.get(PROMOTED_REFERENCE).set(promotedReference); + } + + ModelNode gatewaysNode = new ModelNode(); + for (Binding gateway : reference.getGateways()) { + gatewaysNode.add(createGateway(gateway)); + } + referenceNode.get(GATEWAYS).set(gatewaysNode); + + return referenceNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link Service}. The tree + * has the form:
+ *
+     *      "name" => "serviceName",
+     *      "application" => "name",
+     *      "interface" => "interfaceName",
+     *      "promotedService" => "promotedServiceName",
+     *      "gateways" => [
+     *          {
+     *              "type" => "typeName",
+     *              "configuration" => "<?binding.foo ..."
+     *          },
+     *          ...
+     *      ],
+     *      "throttling" => {
+     *          "enabled" => "true",
+     *          "maxRequests" => "maxRequests",
+     *          "timePeriod" => "timePeriod"
+     *      }
+     * 
+ * + * @param service the {@link Service} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createServiceNode(Service service) { + ModelNode serviceNode = new ModelNode(); + + serviceNode.get(NAME).set(service.getName().toString()); + + serviceNode.get(APPLICATION).set(service.getApplication().getName().toString()); + + String interfaceName = service.getInterface(); + if (interfaceName == null) { + serviceNode.get(INTERFACE); + } else { + serviceNode.get(INTERFACE).set(interfaceName); + } + + ComponentService promotedService = service.getPromotedService(); + if (promotedService == null) { + serviceNode.get(PROMOTED_SERVICE); + } else { + serviceNode.get(PROMOTED_SERVICE).set(promotedService.getName().toString()); + } + + ModelNode gatewaysNode = new ModelNode(); + for (Binding gateway : service.getGateways()) { + gatewaysNode.add(createGateway(gateway)); + } + serviceNode.get(GATEWAYS).set(gatewaysNode); + + serviceNode.get(THROTTLING).set(createThrottlingToNode(service.getThrottling())); + + return serviceNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link ComponentService}. + * The tree has the form:
+ *
+     *      "name" => "serviceName",
+     *      "application" => "name",
+     *      "interface" => "interfaceName",
+     *      "implementation" => "implementationTypeName",
+     *      "references" => [
+     *          {
+     *              "name" => "referenceName",
+     *              "interface" => "interfaceName"
+     *          },
+     *          ...
+     *      ]
+     * 
+ * + * @param service the {@link ComponentService} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createComopnentServiceNode(ComponentService service) { + ModelNode serviceNode = new ModelNode(); + + serviceNode.get(NAME).set(service.getName().toString()); + + serviceNode.get(APPLICATION).set(service.getApplication().getName().toString()); + + String interfaceName = service.getInterface(); + if (interfaceName == null) { + serviceNode.get(INTERFACE); + } else { + serviceNode.get(INTERFACE).set(interfaceName); + } + + String implementation = service.getImplementation(); + if (implementation == null) { + serviceNode.get(IMPLEMENTATION); + } else { + serviceNode.get(IMPLEMENTATION).set(implementation); + } + + String implementationConfiguration = service.getImplementationConfiguration(); + if (implementationConfiguration == null) { + serviceNode.get(IMPLEMENTATION_CONFIGURATION); + } else { + serviceNode.get(IMPLEMENTATION_CONFIGURATION).set(implementationConfiguration); + } + + ModelNode referencesNode = new ModelNode(); + for (ComponentReference reference : service.getReferences()) { + referencesNode.add(createComponentReferenceNode(reference)); + } + serviceNode.get(REFERENCES).set(referencesNode); + + return serviceNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link Reference}. The tree + * has the form:
+ *
+     *      "name" => "referenceName",
+     *      "application => "applicationName",
+     * 
+ * + * @param reference the {@link Reference} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createSimpleReferenceNode(Reference reference) { + ModelNode referenceNode = new ModelNode(); + + referenceNode.get(NAME).set(reference.getName().toString()); + + referenceNode.get(APPLICATION).set(reference.getApplication().getName().toString()); + + return referenceNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link Service}. The tree + * has the form:
+ *
+     *      "name" => "serviceName",
+     *      "application => "applicationName",
+     * 
+ * + * @param service the {@link Service} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createSimpleServiceNode(Service service) { + ModelNode serviceNode = new ModelNode(); + + serviceNode.get(NAME).set(service.getName().toString()); + + serviceNode.get(APPLICATION).set(service.getApplication().getName().toString()); + + return serviceNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link Service}. The tree + * has the form:
+ *
+     *      "name" => "name",
+     *      "type" => "typeName",
+     *      "configuration" => "<?binding.foo ..."
+     *      "state" => "STARTED",
+     * 
+ * + * @param binding the {@link Binding} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createGateway(Binding binding) { + ModelNode gatewayNode = new ModelNode(); + + if (binding.getName() == null) { + gatewayNode.get(NAME); + } else { + gatewayNode.get(NAME).set(binding.getName()); + } + + if (binding.getType() == null) { + gatewayNode.get(TYPE); + } else { + gatewayNode.get(TYPE).set(binding.getType()); + } + + if (binding.getConfiguration() == null) { + gatewayNode.get(CONFIGURATION); + } else { + gatewayNode.get(CONFIGURATION).set(binding.getConfiguration()); + } + + gatewayNode.get(STATE).set(binding.getState().toString()); + + return gatewayNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link ComponentReference}. + * The tree has the form:
+ *
+     *      "name" => "referenceName",
+     *      "interface" => "interfaceName"
+     * 
+ * + * @param reference the {@link ComponentReference} used to populate the + * node. + * @return a new {@link ModelNode} + */ + public static ModelNode createComponentReferenceNode(ComponentReference reference) { + ModelNode referenceNode = new ModelNode(); + + if (reference.getName() == null) { + referenceNode.get(NAME); + } else { + referenceNode.get(NAME).set(reference.getName().toString()); + } + + if (reference.getInterface() == null) { + referenceNode.get(INTERFACE); + } else { + referenceNode.get(INTERFACE).set(reference.getInterface()); + } + + return referenceNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link Transformer}. The + * tree has the form:
+ *
+     *      "from" => "fromType",
+     *      "to" => "toType",
+     *      "type" => "transformerType",
+     * 
+ * + * @param transformation the {@link Transformer} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createTransformerNode(Transformer transformation) { + ModelNode transformationNode = new ModelNode(); + + if (transformation.getFrom() == null) { + transformationNode.get(FROM); + } else { + transformationNode.get(FROM).set(transformation.getFrom().toString()); + } + + if (transformation.getTo() == null) { + transformationNode.get(TO); + } else { + transformationNode.get(TO).set(transformation.getTo().toString()); + } + + if (transformation.getType() == null) { + transformationNode.get(TYPE); + } else { + transformationNode.get(TYPE).set(transformation.getType()); + } + + return transformationNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link ArtifactModel}. The + * tree has the form:
+ *
+     *      "name" => "nameType",
+     *      "url" => "urlType",
+     * 
+ * + * @param artifact the {@link ArtifactModel} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createArtifactNode(ArtifactModel artifact) { + ModelNode artifactNode = new ModelNode(); + artifactNode.get(NAME).set(artifact.getName()); + artifactNode.get(URL).set(artifact.getURL()); + return artifactNode; + } + + /** + * Creates a new {@link ModelNode} tree from the validtors. The tree has the + * form:
+ *
+     *      "name" => "typeName",
+     *      "type" => "XML",
+     * 
+ * + * @param validator the {@link Validator} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createValidatorNode(Validator validator) { + ModelNode validatorNode = new ModelNode(); + if (validator.getName() == null) { + validatorNode.get(NAME); + } else { + validatorNode.get(NAME).set(validator.getName().toString()); + } + if (validator.getType() == null) { + validatorNode.get(TYPE); + } else { + validatorNode.get(TYPE).set(validator.getType()); + } + return validatorNode; + } + + /** + * Adds metrics to an existing node from the {@link MessageMetrics}. The + * tree has the form:
+ *
+     *      "successCount" => "successCount",
+     *      "faultCount" => "faultCount",
+     *      "totalCount" => "totalCount",
+     *      "averageTime" => "averageTime",
+     *      "minTime" => "minTime",
+     *      "maxTime" => "maxTime",
+     *      "totalTime" => "totalTime"
+     * 
+ * + * @param node the node to add metrics to + * @param metrics the metrics to add to the node + * @return a new {@link ModelNode} + */ + public static ModelNode addMetricsToNode(ModelNode node, MessageMetrics metrics) { + + node.get(SUCCESS_COUNT).set(metrics.getSuccessCount()); + node.get(FAULT_COUNT).set(metrics.getFaultCount()); + node.get(TOTAL_COUNT).set(metrics.getTotalCount()); + node.get(AVERAGE_TIME).set(BigDecimal.valueOf(metrics.getAverageProcessingTime())); + node.get(MIN_TIME).set(metrics.getMinProcessingTime()); + node.get(MAX_TIME).set(metrics.getMaxProcessingTime()); + node.get(TOTAL_TIME).set(metrics.getTotalProcessingTime()); + + return node; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link Reference} for + * metrics. The tree has the form:
+ *
+     *      "name" => "referenceName",
+     *      "application" => "name",
+     *      "successCount" => "successCount",
+     *      "faultCount" => "faultCount",
+     *      "totalCount" => "totalCount",
+     *      "averageTime" => "averageTime",
+     *      "minTime" => "minTime",
+     *      "maxTime" => "maxTime",
+     *      "totalTime" => "totalTime",
+     *      "gateways" => [
+     *          {
+     *              "name" => "bindingName",
+     *              "type" => "bindingType",
+     *               "successCount" => "successCount",
+     *               "faultCount" => "faultCount",
+     *               "totalCount" => "totalCount",
+     *               "averageTime" => "averageTime",
+     *               "minTime" => "minTime",
+     *               "maxTime" => "maxTime",
+     *               "totalTime" => "totalTime",
+     *          },
+     *          ...
+     *      ],
+     *      "operations" => [
+     *          {
+     *              "name" => "operationName",
+     *               "successCount" => "successCount",
+     *               "faultCount" => "faultCount",
+     *               "totalCount" => "totalCount",
+     *               "averageTime" => "averageTime",
+     *               "minTime" => "minTime",
+     *               "maxTime" => "maxTime",
+     *               "totalTime" => "totalTime",
+     *          },
+     *          ...
+     *      ]
+     * 
+ * + * @param reference the {@link Reference} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createReferenceMetricsNode(Reference reference) { + ModelNode referenceNode = new ModelNode(); + + referenceNode.get(NAME).set(reference.getName().toString()); + referenceNode.get(APPLICATION).set(reference.getApplication().getName().toString()); + + addMetricsToNode(referenceNode, reference.getMessageMetrics()); + + ModelNode gatewaysNode = new ModelNode(); + for (Binding gateway : reference.getGateways()) { + ModelNode gatewayNode = new ModelNode(); + gatewayNode.get(NAME).set(gateway.getName()); + gatewayNode.get(TYPE).set(gateway.getType()); + addMetricsToNode(gatewayNode, gateway.getMessageMetrics()); + gatewaysNode.add(gatewayNode); + } + referenceNode.get(GATEWAYS).set(gatewaysNode); + + ModelNode operationsNode = new ModelNode(); + for (ServiceOperation operation : reference.getServiceOperations()) { + ModelNode operationNode = new ModelNode(); + operationNode.get(NAME).set(operation.getName()); + addMetricsToNode(operationNode, operation.getMessageMetrics()); + operationsNode.add(operationNode); + } + referenceNode.get(OPERATIONS).set(operationsNode); + + return referenceNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link Service} for + * metrics. The tree has the form:
+ *
+     *      "name" => "serviceName",
+     *      "application" => "name",
+     *      "successCount" => "successCount",
+     *      "faultCount" => "faultCount",
+     *      "totalCount" => "totalCount",
+     *      "averageTime" => "averageTime",
+     *      "minTime" => "minTime",
+     *      "maxTime" => "maxTime",
+     *      "totalTime" => "totalTime",
+     *      "operations" => [
+     *          {
+     *              "name" => "operationName",
+     *               "successCount" => "successCount",
+     *               "faultCount" => "faultCount",
+     *               "totalCount" => "totalCount",
+     *               "averageTime" => "averageTime",
+     *               "minTime" => "minTime",
+     *               "maxTime" => "maxTime",
+     *               "totalTime" => "totalTime",
+     *          },
+     *          ...
+     *      ],
+     *      "references" => [
+     *          {
+     *              "name" => "referenceName",
+     *               "successCount" => "successCount",
+     *               "faultCount" => "faultCount",
+     *               "totalCount" => "totalCount",
+     *               "averageTime" => "averageTime",
+     *               "minTime" => "minTime",
+     *               "maxTime" => "maxTime",
+     *               "totalTime" => "totalTime",
+     *          },
+     *          ...
+     *      ],
+     *      "gateways" => [
+     *          {
+     *              "name" => "bindingName",
+     *              "type" => "bindingType",
+     *               "successCount" => "successCount",
+     *               "faultCount" => "faultCount",
+     *               "totalCount" => "totalCount",
+     *               "averageTime" => "averageTime",
+     *               "minTime" => "minTime",
+     *               "maxTime" => "maxTime",
+     *               "totalTime" => "totalTime",
+     *          },
+     *          ...
+     *      ]
+     * 
+ * + * @param service the {@link Service} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createServiceMetricsNode(Service service) { + ModelNode serviceNode = new ModelNode(); + + serviceNode.get(NAME).set(service.getName().toString()); + serviceNode.get(APPLICATION).set(service.getApplication().getName().toString()); + addMetricsToNode(serviceNode, service.getPromotedService().getMessageMetrics()); + + ModelNode operationsNode = new ModelNode(); + for (ServiceOperation operation : service.getPromotedService().getServiceOperations()) { + ModelNode operationNode = new ModelNode(); + operationNode.get(NAME).set(operation.getName()); + addMetricsToNode(operationNode, operation.getMessageMetrics()); + operationsNode.add(operationNode); + } + serviceNode.get(OPERATIONS).set(operationsNode); + + ModelNode referencesNode = new ModelNode(); + for (ComponentReference reference : service.getPromotedService().getReferences()) { + ModelNode referenceNode = new ModelNode(); + referenceNode.get(NAME).set(reference.getName().toString()); + addMetricsToNode(referenceNode, reference.getMessageMetrics()); + referencesNode.add(referenceNode); + } + serviceNode.get(REFERENCES).set(referencesNode); + + ModelNode gatewaysNode = new ModelNode(); + for (Binding gateway : service.getGateways()) { + ModelNode gatewayNode = new ModelNode(); + gatewayNode.get(NAME).set(gateway.getName()); + gatewayNode.get(TYPE).set(gateway.getType()); + addMetricsToNode(gatewayNode, gateway.getMessageMetrics()); + gatewaysNode.add(gatewayNode); + } + serviceNode.get(GATEWAYS).set(gatewaysNode); + + return serviceNode; + } + + /** + * Creates a new {@link ModelNode} tree from the {@link ComponentService} for + * metrics. The tree has the form:
+ *
+     *      "name" => "serviceName",
+     *      "application" => "name",
+     *      "successCount" => "successCount",
+     *      "faultCount" => "faultCount",
+     *      "totalCount" => "totalCount",
+     *      "averageTime" => "averageTime",
+     *      "minTime" => "minTime",
+     *      "maxTime" => "maxTime",
+     *      "totalTime" => "totalTime",
+     *      "operations" => [
+     *          {
+     *              "name" => "operationName",
+     *               "successCount" => "successCount",
+     *               "faultCount" => "faultCount",
+     *               "totalCount" => "totalCount",
+     *               "averageTime" => "averageTime",
+     *               "minTime" => "minTime",
+     *               "maxTime" => "maxTime",
+     *               "totalTime" => "totalTime",
+     *          },
+     *          ...
+     *      ],
+     *      "references" => [
+     *          {
+     *              "name" => "referenceName",
+     *               "successCount" => "successCount",
+     *               "faultCount" => "faultCount",
+     *               "totalCount" => "totalCount",
+     *               "averageTime" => "averageTime",
+     *               "minTime" => "minTime",
+     *               "maxTime" => "maxTime",
+     *               "totalTime" => "totalTime",
+     *          },
+     *          ...
+     *      ]
+     * 
+ * + * @param componentService the {@link Service} used to populate the node. + * @return a new {@link ModelNode} + */ + public static ModelNode createComponentServiceMetricsNode(ComponentService componentService) { + ModelNode serviceNode = new ModelNode(); + + serviceNode.get(NAME).set(componentService.getName().toString()); + serviceNode.get(APPLICATION).set(componentService.getApplication().getName().toString()); + addMetricsToNode(serviceNode, componentService.getMessageMetrics()); + + ModelNode operationsNode = new ModelNode(); + for (ServiceOperation operation : componentService.getServiceOperations()) { + ModelNode operationNode = new ModelNode(); + operationNode.get(NAME).set(operation.getName()); + addMetricsToNode(operationNode, operation.getMessageMetrics()); + operationsNode.add(operationNode); + } + serviceNode.get(OPERATIONS).set(operationsNode); + + ModelNode referencesNode = new ModelNode(); + for (ComponentReference reference : componentService.getReferences()) { + ModelNode referenceNode = new ModelNode(); + referenceNode.get(NAME).set(reference.getName().toString()); + addMetricsToNode(referenceNode, reference.getMessageMetrics()); + referencesNode.add(referenceNode); + } + serviceNode.get(REFERENCES).set(referencesNode); + + return serviceNode; + } + + /** + * Creates a new node from the {@link Throttling}. The tree has the form:
+ *
+     *      "throttling" => {
+     *          "enabled" => "true",
+     *          "maxRequests" => "maxRequests",
+     *          "timePeriod" => "timePeriod"
+     *      }
+     * 
+ * + * @param throttling the throttling configuration to add to the node + * @return a new {@link ModelNode} + */ + public static ModelNode createThrottlingToNode(Throttling throttling) { + final ModelNode node = new ModelNode(); + if (throttling == null) { + return node; + } + node.get(ENABLED).set(throttling.isEnabled()); + node.get(MAX_REQUESTS).set(throttling.getMaxRequests()); + node.get(TIME_PERIOD).set(throttling.getTimePeriod()); + return node; + } + + private ModelNodeCreationUtil() { + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemGetVersion.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemGetVersion.java new file mode 100644 index 000000000..518d4858c --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemGetVersion.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.switchyard.common.version.Versions; + +/** + * SwitchYardSubsystemGetVersion + * + * Operation returning the release version of the SwitchYard subsystem. + * + * @author Rob Cernich + */ +public final class SwitchYardSubsystemGetVersion implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemGetVersion INSTANCE = new SwitchYardSubsystemGetVersion(); + + private SwitchYardSubsystemGetVersion() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + context.getResult().get("version").set(Versions.getSwitchYardVersion()); + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListApplications.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListApplications.java new file mode 100644 index 000000000..b4216587f --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListApplications.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemListApplications + * + * Operation returning the applications deployed on the SwitchYard subsystem. + * + * @author Rob Cernich + */ +public final class SwitchYardSubsystemListApplications implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemListApplications INSTANCE = new SwitchYardSubsystemListApplications(); + + private SwitchYardSubsystemListApplications() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ModelNode applications = context.getResult(); + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + for (Application application : switchYard.getApplications()) { + applications.add(application.getName().toString()); + } + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListReferences.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListReferences.java new file mode 100644 index 000000000..bdb1c1178 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListReferences.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.Reference; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemListReferences + * + * Operation returning the references deployed on the SwitchYard subsystem. + */ +public final class SwitchYardSubsystemListReferences implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemListReferences INSTANCE = new SwitchYardSubsystemListReferences(); + + private SwitchYardSubsystemListReferences() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ModelNode references = context.getResult(); + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + if (operation.hasDefined(APPLICATION_NAME)) { + final QName applicationName = QName.valueOf(operation.get(APPLICATION_NAME).asString()); + final Application application = switchYard.getApplication(applicationName); + if (application != null) { + for (Reference reference : application.getReferences()) { + references.add(ModelNodeCreationUtil.createSimpleReferenceNode(reference)); + } + } + } else { + for (Reference reference : switchYard.getReferences()) { + references.add(ModelNodeCreationUtil.createSimpleReferenceNode(reference)); + } + } + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListServices.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListServices.java new file mode 100644 index 000000000..4a1093bdb --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemListServices.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemListServices + * + * Operation returning the services deployed on the SwitchYard subsystem. + * + * @author Rob Cernich + */ +public final class SwitchYardSubsystemListServices implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemListServices INSTANCE = new SwitchYardSubsystemListServices(); + + private SwitchYardSubsystemListServices() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ModelNode services = context.getResult(); + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + if (operation.hasDefined(APPLICATION_NAME)) { + final QName applicationName = QName.valueOf(operation.get(APPLICATION_NAME).asString()); + final Application application = switchYard.getApplication(applicationName); + if (application != null) { + for (Service service : application.getServices()) { + services.add(ModelNodeCreationUtil.createSimpleServiceNode(service)); + } + } + } else { + for (Service service : switchYard.getServices()) { + services.add(ModelNodeCreationUtil.createSimpleServiceNode(service)); + } + } + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadApplication.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadApplication.java new file mode 100644 index 000000000..2fbbe2873 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadApplication.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemReadApplication + * + * Operation returning details of the applications deployed on the SwitchYard + * subsystem. + * + * @author Rob Cernich + */ +public final class SwitchYardSubsystemReadApplication implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemReadApplication INSTANCE = new SwitchYardSubsystemReadApplication(); + + private SwitchYardSubsystemReadApplication() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + + final ModelNode applications = context.getResult(); + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + if (operation.hasDefined(NAME)) { + final QName applicationName = QName.valueOf(operation.get(NAME).asString()); + final Application application = switchYard.getApplication(applicationName); + if (application != null) { + applications.add(ModelNodeCreationUtil.createApplicationNode(application)); + } + } else { + for (Application application : switchYard.getApplications()) { + applications.add(ModelNodeCreationUtil.createApplicationNode(application)); + } + } + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadReference.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadReference.java new file mode 100644 index 000000000..8d0b00ce7 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadReference.java @@ -0,0 +1,123 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.REFERENCE_NAME; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.Reference; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemReadReference + * + * Operation returning details of the references deployed on the SwitchYard + * subsystem. + */ +public final class SwitchYardSubsystemReadReference implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemReadReference INSTANCE = new SwitchYardSubsystemReadReference(); + + private SwitchYardSubsystemReadReference() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + + List references = Collections.emptyList(); + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + if (operation.hasDefined(APPLICATION_NAME)) { + final QName applicationName = QName.valueOf(operation.get(APPLICATION_NAME).asString()); + final Application application = switchYard.getApplication(applicationName); + if (application != null) { + if (operation.hasDefined(REFERENCE_NAME)) { + Reference reference = findReference(QName.valueOf(operation.get(REFERENCE_NAME).asString()), + application); + if (reference != null) { + references = Collections.singletonList(reference); + } + } else { + references = application.getReferences(); + } + } + } else if (operation.hasDefined(REFERENCE_NAME)) { + final QName referenceName = QName.valueOf(operation.get(REFERENCE_NAME).asString()); + references = new ArrayList(); + for (Application application : switchYard.getApplications()) { + Reference reference = findReference(referenceName, application); + if (reference != null) { + references.add(reference); + } + } + } else { + references = switchYard.getReferences(); + } + + addReferenceNodes(context.getResult(), references); + + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } + + private void addReferenceNodes(ModelNode result, List references) { + for (Reference reference : references) { + result.add(ModelNodeCreationUtil.createReferenceNode(reference)); + } + } + + /** + * TODO: should move this to Application + */ + private Reference findReference(QName referenceName, Application application) { + for (Reference reference : application.getReferences()) { + if (referenceName.equals(reference.getName())) { + return reference; + } + } + return null; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadService.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadService.java new file mode 100644 index 000000000..c48960f5f --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemReadService.java @@ -0,0 +1,125 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.SERVICE_NAME; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemReadApplication + * + * Operation returning details of the applications deployed on the SwitchYard + * subsystem. + * + * @author Rob Cernich + */ +public final class SwitchYardSubsystemReadService implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemReadService INSTANCE = new SwitchYardSubsystemReadService(); + + private SwitchYardSubsystemReadService() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + + List services = Collections.emptyList(); + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + if (operation.hasDefined(APPLICATION_NAME)) { + final QName applicationName = QName.valueOf(operation.get(APPLICATION_NAME).asString()); + final Application application = switchYard.getApplication(applicationName); + if (application != null) { + if (operation.hasDefined(SERVICE_NAME)) { + Service service = findService(QName.valueOf(operation.get(SERVICE_NAME).asString()), + application); + if (service != null) { + services = Collections.singletonList(service); + } + } else { + services = application.getServices(); + } + } + } else if (operation.hasDefined(SERVICE_NAME)) { + final QName serviceName = QName.valueOf(operation.get(SERVICE_NAME).asString()); + services = new ArrayList(); + for (Application application : switchYard.getApplications()) { + Service service = findService(serviceName, application); + if (service != null) { + services.add(service); + } + } + } else { + services = switchYard.getServices(); + } + + addServiceNodes(context.getResult(), services); + + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } + + private void addServiceNodes(ModelNode result, List services) { + for (Service service : services) { + result.add(ModelNodeCreationUtil.createServiceNode(service)); + } + } + + /** + * TODO: should move this to Application + */ + private Service findService(QName serviceName, Application application) { + for (Service service : application.getServices()) { + if (serviceName.equals(service.getName())) { + return service; + } + } + return null; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemResetMetrics.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemResetMetrics.java new file mode 100644 index 000000000..c9c869726 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemResetMetrics.java @@ -0,0 +1,106 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemShowMetrics + * + * Operation for resetting metrics for services/references deployed on the + * SwitchYard subsystem. + */ +public final class SwitchYardSubsystemResetMetrics implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemResetMetrics INSTANCE = new SwitchYardSubsystemResetMetrics(); + + private SwitchYardSubsystemResetMetrics() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + if (operation.hasDefined(NAME)) { + final QName serviceQName = QName.valueOf(operation.get(NAME).asString()); + final QName applicationQName = operation.hasDefined(APPLICATION_NAME) ? QName.valueOf(operation + .get(APPLICATION_NAME).asString()) : null; + APPLICATION_LOOP: for (Application application : switchYard.getApplications()) { + if (applicationQName == null || applicationQName.equals(application.getName())) { + for (Service service : application.getServices()) { + if (serviceQName.equals(service.getName())) { + // XXX: we should really be doing this on + // the service + service.getPromotedService().resetMessageMetrics(); + if (applicationQName == null) { + continue APPLICATION_LOOP; + } else { + break APPLICATION_LOOP; + } + } + } + for (Reference reference : application.getReferences()) { + if (serviceQName.equals(reference.getName())) { + reference.resetMessageMetrics(); + if (applicationQName == null) { + continue APPLICATION_LOOP; + } else { + break APPLICATION_LOOP; + } + } + } + } + } + } else { + switchYard.resetMessageMetrics(); + } + + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemShowMetrics.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemShowMetrics.java new file mode 100644 index 000000000..14647d925 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemShowMetrics.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.switchyard.as7.extension.SwitchYardModelConstants.SERVICE_NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.TYPE; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemShowMetrics + * + * Operation returning metrics for services deployed on the SwitchYard subsystem. + */ +public final class SwitchYardSubsystemShowMetrics implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemShowMetrics INSTANCE = new SwitchYardSubsystemShowMetrics(); + + private SwitchYardSubsystemShowMetrics() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + if (operation.hasDefined(SERVICE_NAME)) { + final String serviceName = operation.get(SERVICE_NAME).asString(); + final String type = operation.get(TYPE).asString(); + final QName serviceQName = QName.valueOf(serviceName); + for (Application application : switchYard.getApplications()) { + if (type == null || "*".equals(type) || "service".equals(type)) { + for (Service service : application.getServices()) { + if ("*".equals(serviceName) || serviceQName.equals(service.getName())) { + context.getResult().add(ModelNodeCreationUtil.createServiceMetricsNode(service)); + } + } + } + if (type == null || "*".equals(type) || "reference".equals(type)) { + for (Reference reference : application.getReferences()) { + if ("*".equals(serviceName) || serviceQName.equals(reference.getName())) { + context.getResult().add(ModelNodeCreationUtil.createReferenceMetricsNode(reference)); + } + } + } + if (type == null || "*".equals(type) || "componentService".equals(type)) { + for (ComponentService componentService : application.getComponentServices()) { + if ("*".equals(serviceName) || serviceQName.equals(componentService.getName())) { + context.getResult().add(ModelNodeCreationUtil.createComponentServiceMetricsNode(componentService)); + } + } + } + } + } else { + context.getResult().add( + ModelNodeCreationUtil.addMetricsToNode( + new ModelNode(), switchYard.getMessageMetrics())); + } + + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemStartGateway.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemStartGateway.java new file mode 100644 index 000000000..ef5dcf213 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemStartGateway.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.SERVICE_NAME; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemStartGateway + * + * Operation for starting a gateway. + */ +public final class SwitchYardSubsystemStartGateway implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemStartGateway INSTANCE = new SwitchYardSubsystemStartGateway(); + + private SwitchYardSubsystemStartGateway() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + final Binding binding; + final String bindingName = operation.get(NAME).asString(); + final Application application = switchYard.getApplication(QName.valueOf(operation.get(APPLICATION_NAME) + .asString())); + if (application == null) { + binding = null; + } else { + final QName serviceQName = QName.valueOf(operation.get(SERVICE_NAME).asString()); + final Service service = application.getService(serviceQName); + if (service == null) { + final Reference reference = application.getReference(serviceQName); + if (reference == null) { + binding = null; + } else { + binding = reference.getGateway(bindingName); + } + } else { + binding = service.getGateway(bindingName); + } + } + if (binding != null) { + try { + binding.start(); + context.stepCompleted(); + } catch (Throwable e) { + throw new OperationFailedException(new ModelNode().set("Error starting gateway: " + + e.getMessage())); + } + return; + } + throw new OperationFailedException(new ModelNode().set("Unknown gateway.")); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemStopGateway.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemStopGateway.java new file mode 100644 index 000000000..d8ec5ed8b --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemStopGateway.java @@ -0,0 +1,106 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.SERVICE_NAME; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemStopGateway + * + * Operation for stopping a gateway. + */ +public final class SwitchYardSubsystemStopGateway implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemStopGateway INSTANCE = new SwitchYardSubsystemStopGateway(); + + private SwitchYardSubsystemStopGateway() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + final Binding binding; + final String bindingName = operation.get(NAME).asString(); + final Application application = switchYard.getApplication(QName.valueOf(operation.get(APPLICATION_NAME) + .asString())); + if (application == null) { + binding = null; + } else { + final QName serviceQName = QName.valueOf(operation.get(SERVICE_NAME).asString()); + final Service service = application.getService(serviceQName); + if (service == null) { + final Reference reference = application.getReference(serviceQName); + if (reference == null) { + binding = null; + } else { + binding = reference.getGateway(bindingName); + } + } else { + binding = service.getGateway(bindingName); + } + } + if (binding != null) { + try { + binding.stop(); + context.stepCompleted(); + } catch (Throwable e) { + throw new OperationFailedException(new ModelNode().set( + ExtensionMessages.MESSAGES.errorStartingGateway() + + e.getMessage())); + } + return; + } + throw new OperationFailedException(new ModelNode().set( + ExtensionMessages.MESSAGES.unknownGateway())); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUpdateThrottling.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUpdateThrottling.java new file mode 100644 index 000000000..8ecbb4b3c --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUpdateThrottling.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.switchyard.as7.extension.SwitchYardModelConstants.APPLICATION_NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.ENABLED; +import static org.switchyard.as7.extension.SwitchYardModelConstants.MAX_REQUESTS; +import static org.switchyard.as7.extension.SwitchYardModelConstants.SERVICE_NAME; +import static org.switchyard.as7.extension.SwitchYardModelConstants.THROTTLING; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; +import org.switchyard.admin.Throttling; +import org.switchyard.as7.extension.services.SwitchYardAdminService; + +/** + * SwitchYardSubsystemStartGateway + * + * Operation for starting a gateway. + */ +public final class SwitchYardSubsystemUpdateThrottling implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemUpdateThrottling INSTANCE = new SwitchYardSubsystemUpdateThrottling(); + + private SwitchYardSubsystemUpdateThrottling() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + final Application application = switchYard.getApplication(QName.valueOf(operation.get(APPLICATION_NAME) + .asString())); + final QName serviceQName = QName.valueOf(operation.get(SERVICE_NAME).asString()); + final Service service = application.getService(serviceQName); + try { + final Throttling throttling = service.getThrottling(); + final ModelNode throttlingNode = operation.get(THROTTLING); + if (throttlingNode != null) { + final ModelNode enabled = throttlingNode.get(ENABLED); + final ModelNode maxRequests = throttlingNode.get(MAX_REQUESTS); + throttling.update(enabled == null || !enabled.isDefined() ? null : enabled.asBoolean(), + maxRequests == null || !maxRequests.isDefined() ? null : maxRequests.asInt()); + } + context.stepCompleted(); + } catch (Throwable e) { + throw new OperationFailedException(new ModelNode().set("Error updating throttling: " + + e.getMessage())); + } + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUsesArtifact.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUsesArtifact.java new file mode 100644 index 000000000..177572dab --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/admin/SwitchYardSubsystemUsesArtifact.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.admin; + +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; +import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.URL; + +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.OperationStepHandler; +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.ServiceController; +import org.switchyard.admin.Application; +import org.switchyard.admin.SwitchYard; +import org.switchyard.as7.extension.services.SwitchYardAdminService; +import org.switchyard.config.model.switchyard.ArtifactModel; + +/** + * SwitchYardSubsystemUsesArtifact + * + * Operation returning the applications which depend on a given artifact. + */ +public final class SwitchYardSubsystemUsesArtifact implements OperationStepHandler { + + /** + * The global instance for this operation. + */ + public static final SwitchYardSubsystemUsesArtifact INSTANCE = new SwitchYardSubsystemUsesArtifact(); + + private SwitchYardSubsystemUsesArtifact() { + // forbidden inheritance + } + + /* + * (non-Javadoc) + * + * @see + * org.jboss.as.controller.OperationStepHandler#execute(org.jboss.as.controller + * .OperationContext, org.jboss.dmr.ModelNode) + */ + @Override + public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { + + context.addStep(new OperationStepHandler() { + @Override + public void execute(final OperationContext context, final ModelNode operation) + throws OperationFailedException { + final ModelNode applications = context.getResult(); + final ServiceController controller = context.getServiceRegistry(false).getRequiredService( + SwitchYardAdminService.SERVICE_NAME); + + String name = operation.hasDefined(NAME) ? operation.get(NAME).asString() : null; + String url = operation.hasDefined(URL) ? operation.get(URL).asString() : null; + + SwitchYard switchYard = SwitchYard.class.cast(controller.getService().getValue()); + for (Application application : switchYard.getApplications()) { + if (application.getConfig().getArtifacts() == null) { + continue; + } + for (ArtifactModel artiact : application.getConfig().getArtifacts().getArtifacts()) { + // check for name match if a name filter was provided + if (name != null && !name.equals(artiact.getName())) { + continue; + } + // check for url match if a URL fiter was provided + if (url != null && !url.equals(artiact.getURL())) { + continue; + } + applications.add(application.getName().toString()); + } + } + context.stepCompleted(); + } + }, OperationContext.Stage.RUNTIME); + context.stepCompleted(); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/JBoss7PackageScanClassResolver.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/JBoss7PackageScanClassResolver.java new file mode 100644 index 000000000..f903a1637 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/JBoss7PackageScanClassResolver.java @@ -0,0 +1,85 @@ +package org.switchyard.as7.extension.camel; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Enumeration; +import java.util.Set; + +import org.apache.camel.impl.DefaultPackageScanClassResolver; +import org.apache.camel.spi.PackageScanFilter; +import org.jboss.logging.Logger; +import org.jboss.vfs.VFS; +import org.jboss.vfs.VirtualFile; +import org.switchyard.as7.extension.ExtensionLogger; + +/** + * VFS-compatible version of DefaultPackageScanClassResolver. + */ +public class JBoss7PackageScanClassResolver extends DefaultPackageScanClassResolver { + + private static final Logger LOG = Logger.getLogger(JBoss7PackageScanClassResolver.class); + + protected void find(PackageScanFilter test, String packageName, ClassLoader loader, Set> classes) { + if (LOG.isTraceEnabled()) { + LOG.tracef("Searching for: %s in package: %s using classloader: %s", + new Object[]{test, packageName, loader.getClass().getName()}); + } + + Enumeration urls; + try { + urls = getResources(loader, packageName); + if (!urls.hasMoreElements()) { + LOG.trace("No URLs returned by classloader"); + } + } catch (IOException ioe) { + ExtensionLogger.ROOT_LOGGER.cannotReadPackage(packageName, ioe); + return; + } + + while (urls.hasMoreElements()) { + URL url = urls.nextElement(); + LOG.tracef("URL from classloader: %s", url); + + if (url.toString().startsWith("vfs:")) { + try { + VirtualFile vfsDir = VFS.getChild(url); + handleDirectory(vfsDir, null, classes, test); + } catch (URISyntaxException uriEx) { + ExtensionLogger.ROOT_LOGGER.failedToParseURL(url.toString(), uriEx); + } + } + + } + } + + private void handleDirectory(VirtualFile file, + String path, + Set> classes, + PackageScanFilter test) { + + for (VirtualFile child : file.getChildren()) { + String newPath = (path == null) ? child.getName() : (path + '/' + child.getName()); + + if (child.isDirectory()) { + handleDirectory(child, newPath, classes, test); + } else { + handleFile(child, classes, test); + } + } + } + + private void handleFile(VirtualFile file, Set> classes, PackageScanFilter test) { + if (file.getName().endsWith(".class")) { + String fqn = file.getPathName(); + String qn; + if (fqn.indexOf("jar/") != -1) { + qn = fqn.substring(fqn.indexOf("jar/") + 4); + } else { + qn = fqn.substring(fqn.indexOf("/") + 1); + } + + addIfMatching(test, qn, classes); + } + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/JBossThreadPoolFactory.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/JBossThreadPoolFactory.java new file mode 100644 index 000000000..d848967e7 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/JBossThreadPoolFactory.java @@ -0,0 +1,177 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.camel; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionHandler; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.apache.camel.spi.ThreadPoolFactory; +import org.apache.camel.spi.ThreadPoolProfile; +import org.apache.camel.util.concurrent.RejectableScheduledThreadPoolExecutor; +import org.apache.camel.util.concurrent.RejectableThreadPoolExecutor; +import org.apache.camel.util.concurrent.SizedScheduledExecutorService; +import org.jboss.as.naming.context.NamespaceContextSelector; + +/** + * ThreadPoolFactory specific to JBoss which allows the namespace context to be + * set for any threads created by Camel and allows for the resolution of the CDI + * BeanManager (in addition to anything else useful in java:comp). + * + * This class is identical to Camel's DefaultThreadPoolFactory with the exception of + * the overloaded ThreadPoolExecutors. There is no clean way to replace those using + * DefaultThreadPoolFactory directly, so we need to replicate that code and modify + * the behavior inline. + */ +public class JBossThreadPoolFactory implements ThreadPoolFactory { + + private NamespaceContextSelector _contextSelector; + + public JBossThreadPoolFactory(NamespaceContextSelector contextSelector) { + _contextSelector = contextSelector; + } + + @Override + public ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) { + RejectedExecutionHandler rejectedExecutionHandler = profile.getRejectedExecutionHandler(); + if (rejectedExecutionHandler == null) { + rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy(); + } + + ScheduledThreadPoolExecutor answer = new RejectableScheduledThreadPoolExecutor( + profile.getPoolSize(), threadFactory, rejectedExecutionHandler) { + + protected void beforeExecute(Thread t, Runnable r) { + super.beforeExecute(t, r); + before(); + } + protected void afterExecute(Runnable r, Throwable t) { + super.afterExecute(r, t); + after(); + } + }; + + // need to wrap the thread pool in a sized to guard against the problem that the + // JDK created thread pool has an unbounded queue (see class javadoc), which mean + // we could potentially keep adding tasks, and run out of memory. + if (profile.getMaxPoolSize() > 0) { + return new SizedScheduledExecutorService(answer, profile.getMaxQueueSize()); + } else { + return answer; + } + } + + public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { + return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, + TimeUnit.SECONDS, new SynchronousQueue()) { + + protected void beforeExecute(Thread t, Runnable r) { + super.beforeExecute(t, r); + before(); + } + protected void afterExecute(Runnable r, Throwable t) { + super.afterExecute(r, t); + after(); + } + }; + } + + + @Override + public ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory factory) { + return newThreadPool(profile.getPoolSize(), + profile.getMaxPoolSize(), + profile.getKeepAliveTime(), + profile.getTimeUnit(), + profile.getMaxQueueSize(), + profile.getRejectedExecutionHandler(), + factory); + } + + public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, + int maxQueueSize, RejectedExecutionHandler rejectedExecutionHandler, + ThreadFactory threadFactory) throws IllegalArgumentException { + + // the core pool size must be higher than 0 + if (corePoolSize < 1) { + throw new IllegalArgumentException("CorePoolSize must be >= 1, was " + corePoolSize); + } + + // validate max >= core + if (maxPoolSize < corePoolSize) { + throw new IllegalArgumentException("MaxPoolSize must be >= corePoolSize, was " + maxPoolSize + " >= " + corePoolSize); + } + + BlockingQueue workQueue; + if (corePoolSize == 0 && maxQueueSize <= 0) { + // use a synchronous queue for direct-handover (no tasks stored on the queue) + workQueue = new SynchronousQueue(); + // and force 1 as pool size to be able to create the thread pool by the JDK + corePoolSize = 1; + maxPoolSize = 1; + } else if (maxQueueSize <= 0) { + // use a synchronous queue for direct-handover (no tasks stored on the queue) + workQueue = new SynchronousQueue(); + } else { + // bounded task queue to store tasks on the queue + workQueue = new LinkedBlockingQueue(maxQueueSize); + } + + ThreadPoolExecutor answer = new RejectableThreadPoolExecutor( + corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue) { + + protected void beforeExecute(Thread t, Runnable r) { + super.beforeExecute(t, r); + before(); + } + + protected void afterExecute(Runnable r, Throwable t) { + super.afterExecute(r, t); + after(); + } + }; + answer.setThreadFactory(threadFactory); + if (rejectedExecutionHandler == null) { + rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy(); + } + answer.setRejectedExecutionHandler(rejectedExecutionHandler); + return answer; + } + + + /** + * Called from beforeExecute in all ThreadExecutors created by this class. + */ + private void before() { + // establish naming context for the current thread + NamespaceContextSelector.pushCurrentSelector(_contextSelector); + } + + /** + * Called from afterExecute in all ThreadExecutors created by this class. + */ + private void after() { + // clean up naming context + NamespaceContextSelector.popCurrentSelector(); + } +} + + diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/NamespaceContextPolicy.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/NamespaceContextPolicy.java new file mode 100644 index 000000000..d06d9c0c1 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/NamespaceContextPolicy.java @@ -0,0 +1,55 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.camel; + +import org.apache.camel.Exchange; +import org.apache.camel.Route; +import org.apache.camel.impl.RoutePolicySupport; +import org.jboss.as.naming.context.NamespaceContextSelector; + +/** + * A RoutePolicy implementation which pushes the namespace context at the + * beginning of an exchange and pops it at the completion of the exchange. These + * callbacks are invoked on happy and failure paths. + */ +public class NamespaceContextPolicy extends RoutePolicySupport { + + /** + * The name this policy uses when stored in the Camel registry. + */ + public static final String POLICY_REF = "org.switchyard.namespaceContextPolicy"; + + private NamespaceContextSelector _selector; + + /** + * Create a new NamespaceContextPolicy. + * @param selector the context selector to use. + */ + public NamespaceContextPolicy(NamespaceContextSelector selector) { + _selector = selector; + } + + @Override + public void onExchangeBegin(Route route, Exchange exchange) { + NamespaceContextSelector.pushCurrentSelector(_selector); + } + + @Override + public void onExchangeDone(Route route, Exchange exchange) { + // guard against an empty namespace stack + if (NamespaceContextSelector.getCurrentSelector() != null) { + NamespaceContextSelector.popCurrentSelector(); + } + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/HttpServerDestination.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/HttpServerDestination.java new file mode 100644 index 000000000..e980915bf --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/HttpServerDestination.java @@ -0,0 +1,182 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.switchyard.as7.extension.camel.cxf; + +import java.io.IOException; +import java.net.URL; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.cxf.Bus; +import org.apache.cxf.BusFactory; +import org.apache.cxf.common.logging.LogUtils; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.service.model.EndpointInfo; +import org.apache.cxf.transport.http.DestinationRegistry; +import org.apache.cxf.transport.http_jaxws_spi.HttpHandlerImpl; +import org.apache.cxf.transport.http_jaxws_spi.JAXWSHttpSpiDestination; +import org.jboss.ws.httpserver_httpspi.HttpExchangeDelegate; +import org.jboss.wsf.stack.cxf.addons.transports.httpserver.HttpServerEngine; +import org.jboss.wsf.stack.cxf.addons.transports.httpserver.HttpServerEngineFactory; + +import org.jboss.com.sun.net.httpserver.HttpExchange; +import org.jboss.com.sun.net.httpserver.HttpHandler; + +/** + * HTTP destination to be used with the JDK6 httpserver; this extends the + * basic JAXWSHttpSpiDestination with all the mechanisms for properly + * handling destination and factory life-cycles. + * + * @author alessio.soldano@jboss.com + * @since 19-Aug-2010 + * + */ +public class HttpServerDestination extends JAXWSHttpSpiDestination +{ + static final Logger LOG = LogUtils.getL7dLogger(HttpServerDestination.class); + + private HttpServerEngineFactory serverEngineFactory; + private HttpServerEngine engine; + private URL url; + + public HttpServerDestination(Bus b, DestinationRegistry registry, EndpointInfo ei) throws IOException + { + super(b, registry, ei); + this.serverEngineFactory = getServerEngineFactory(); + getAddressValue(ei, true); //generate address if not specified + this.url = new URL(ei.getAddress()); + } + + @Override + protected Logger getLogger() + { + return LOG; + } + + public void finalizeConfig() + { + engine = serverEngineFactory.retrieveHttpServerEngine(url.getPort()); + if (engine == null) + { + try + { + engine = serverEngineFactory.createHttpServerEngine(url.getHost(), url.getPort(), url.getProtocol()); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + } + if (!url.getProtocol().equals(engine.getProtocol())) + { + throw new IllegalStateException("Port " + engine.getPort() + " is configured with wrong protocol \"" + + engine.getProtocol() + "\" for \"" + url + "\""); + } + } + + protected HttpServerEngineFactory getServerEngineFactory() + { + HttpServerEngineFactory serverEngineFactory = getBus().getExtension(HttpServerEngineFactory.class); + // If it's not there, then create it and register it. + // Spring may override it later, but we need it here for default + // with no spring configuration. + if (serverEngineFactory == null) + { + serverEngineFactory = new HttpServerEngineFactory(bus); + } + return serverEngineFactory; + } + + /** + * Activate receipt of incoming messages. + */ + protected void activate() + { + LOG.log(Level.FINE, "Activating receipt of incoming messages"); + String addr = endpointInfo.getAddress(); + try + { + new URL(addr); + } + catch (Exception e) + { + throw new Fault(e); + } + engine.addHandler(addr, new Handler(this, SecurityActions.getContextClassLoader())); + } + + /** + * Deactivate receipt of incoming messages. + */ + protected void deactivate() + { + LOG.log(Level.FINE, "Deactivating receipt of incoming messages"); + engine.removeHandler(endpointInfo.getAddress()); + } + + class Handler extends HttpHandlerImpl implements HttpHandler + { + + private ClassLoader classLoader; + + public Handler(JAXWSHttpSpiDestination destination, ClassLoader classLoader) + { + super(destination); + this.classLoader = classLoader; + } + + @Override + public void handle(HttpExchange ex) throws IOException + { + ClassLoader origClassLoader = SecurityActions.getContextClassLoader(); + final Bus origBus = BusFactory.getThreadDefaultBus(); + if (bus != null) { + BusFactory.setThreadDefaultBus(bus); + } + try + { + SecurityActions.setContextClassLoader(this.classLoader); + this.handle(new HttpExchangeDelegate(ex)); + } + catch (Exception e) + { + LOG.throwing(Handler.class.getName(), "handle(" + HttpExchange.class.getName() + " ex)", e); + if (e instanceof IOException) + { + throw (IOException) e; + } + else + { + throw new RuntimeException(e); + } + } + finally + { + if (bus != null) { + SecurityActions.setContextClassLoader(origClassLoader); + BusFactory.setThreadDefaultBus(origBus); + } + } + } + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/HttpServerDestinationFactory.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/HttpServerDestinationFactory.java new file mode 100644 index 000000000..17d1d2762 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/HttpServerDestinationFactory.java @@ -0,0 +1,50 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2011, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.switchyard.as7.extension.camel.cxf; + +import java.io.IOException; + +import org.apache.cxf.Bus; +import org.apache.cxf.common.injection.NoJSR250Annotations; +import org.apache.cxf.service.model.EndpointInfo; +import org.apache.cxf.transport.http.AbstractHTTPDestination; +import org.apache.cxf.transport.http.DestinationRegistry; +import org.apache.cxf.transport.http.HttpDestinationFactory; + + +/** + * Factory for HttpServerDestination + * + * @author alessio.soldano@jboss.com + * @since 22-Apr-2011 + * + */ +@NoJSR250Annotations() +public class HttpServerDestinationFactory implements HttpDestinationFactory +{ + @Override + public AbstractHTTPDestination createDestination(EndpointInfo endpointInfo, Bus bus, DestinationRegistry registry) + throws IOException + { + return new HttpServerDestination(bus, registry, endpointInfo); + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/SecurityActions.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/SecurityActions.java new file mode 100644 index 000000000..99f3025d5 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/camel/cxf/SecurityActions.java @@ -0,0 +1,82 @@ +/* + * JBoss, Home of Professional Open Source. + * Copyright 2011, Red Hat Middleware LLC, and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.switchyard.as7.extension.camel.cxf; + +import java.security.AccessController; +import java.security.PrivilegedAction; + +/** + * + * @author alessio.soldano@jboss.com + * @since 22-Feb-2011 + * + */ +class SecurityActions +{ + /** + * Get context classloader. + * + * @return the current context classloader + */ + static ClassLoader getContextClassLoader() + { + SecurityManager sm = System.getSecurityManager(); + if (sm == null) + { + return Thread.currentThread().getContextClassLoader(); + } + else + { + return AccessController.doPrivileged(new PrivilegedAction() { + public ClassLoader run() + { + return Thread.currentThread().getContextClassLoader(); + } + }); + } + } + + /** + * Set context classloader. + * + * @param classLoader the classloader + */ + static void setContextClassLoader(final ClassLoader classLoader) + { + if (System.getSecurityManager() == null) + { + Thread.currentThread().setContextClassLoader(classLoader); + } + else + { + AccessController.doPrivileged(new PrivilegedAction() + { + public Object run() + { + Thread.currentThread().setContextClassLoader(classLoader); + return null; + } + }); + } + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/cluster/RemoteEndpointListener.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/cluster/RemoteEndpointListener.java new file mode 100644 index 000000000..1eb692a55 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/cluster/RemoteEndpointListener.java @@ -0,0 +1,214 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.cluster; + +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.net.InetAddress; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.naming.NamingException; +import javax.xml.namespace.QName; + +import org.apache.catalina.Container; +import org.apache.catalina.Host; +import org.apache.catalina.Loader; +import org.apache.catalina.Wrapper; +import org.apache.catalina.connector.Connector; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.startup.ContextConfig; +import org.apache.coyote.http11.Http11Protocol; +import org.apache.tomcat.InstanceManager; +import org.jboss.as.server.ServerEnvironment; +import org.jboss.as.web.deployment.WebCtxLoader; +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.as7.extension.ExtensionLogger; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.util.ServerUtil; +import org.switchyard.component.sca.RemoteEndpointPublisher; +import org.switchyard.component.sca.SwitchYardRemotingServlet; + +/** + * Publishes standalone HTTP endpoint. + */ +public class RemoteEndpointListener implements RemoteEndpointPublisher { + + private static final String SERVER_TEMP_DIR = System.getProperty(ServerEnvironment.SERVER_TEMP_DIR); + private static final String SERVLET_NAME = "SwitchYardRemotingServlet"; + + private static Logger _log = Logger.getLogger(RemoteEndpointListener.class); + + private String _contextName; + private StandardContext _serverContext; + private Map _services = new ConcurrentHashMap(); + private boolean _disableRemoteTransaction = false; + + private boolean _started; + + /** + * Constructor. + */ + public RemoteEndpointListener() { + } + + @Override + public void init(String context) { + _contextName = context; + } + + @Override + public synchronized void start() throws Exception { + // If the remote listener is already started, just return. + if (_started) { + return; + } + + Host host = ServerUtil.getDefaultHost().getHost(); + _serverContext = (StandardContext) host.findChild("/" + _contextName); + if (_serverContext == null) { + _serverContext = new StandardContext(); + _serverContext.setPath("/" + _contextName); + File docBase = new File(SERVER_TEMP_DIR, _contextName); + if (!docBase.exists()) { + if (!docBase.mkdirs()) { + throw ExtensionMessages.MESSAGES.unableToCreateTempDirectory(docBase.getPath()); + } + } + _serverContext.setDocBase(docBase.getPath()); + _serverContext.addLifecycleListener(new ContextConfig()); + + final Loader loader = new WebCtxLoader(Thread.currentThread().getContextClassLoader()); + loader.setContainer(host); + _serverContext.setLoader(loader); + _serverContext.setInstanceManager(new LocalInstanceManager()); + + Wrapper wrapper = _serverContext.createWrapper(); + wrapper.setName(SERVLET_NAME); + wrapper.setServletClass(SwitchYardRemotingServlet.class.getName()); + wrapper.setLoadOnStartup(1); + _serverContext.addChild(wrapper); + _serverContext.addServletMapping("/*", SERVLET_NAME); + + + host.addChild(_serverContext); + _serverContext.create(); + _serverContext.start(); + + + SwitchYardRemotingServlet remotingServlet = (SwitchYardRemotingServlet) wrapper.getServlet(); + remotingServlet.setEndpointPublisher(this); + _log.info("Published Remote Service Endpoint " + _serverContext.getPath()); + + _started = true; + } else { + throw ExtensionMessages.MESSAGES.contextAlreadyExists(_contextName); + } + } + + @Override + public synchronized void stop() throws Exception { + if (_serverContext != null) { + // Destroy the web context unless if it is default + if (!_serverContext.getPath().equals("/")) { + try { + Container container = _serverContext.getParent(); + container.removeChild(_serverContext); + _serverContext.stop(); + _serverContext.destroy(); + _log.info("Destroyed HTTP context " + _serverContext.getPath()); + } catch (Exception e) { + ExtensionLogger.ROOT_LOGGER.unableToDestroyWebContext(_contextName, e); + } + } + } + } + + /** + * Return the address. + * + * @return An address string + */ + public String getAddress() { + String hostAddress = null; + Connector connector = ServerUtil.getDefaultConnector(); + if (connector.getProtocolHandler() instanceof Http11Protocol) { + Http11Protocol protocol = (Http11Protocol) connector.getProtocolHandler(); + InetAddress address = protocol.getAddress(); + hostAddress = address.getHostAddress(); + } else { + ExtensionLogger.ROOT_LOGGER.unableToDetermineHostAddress(); + hostAddress = ServerUtil.getDefaultHost().getHost().findAliases()[0]; + } + + return connector.getScheme() + "://" + hostAddress + ":" + connector.getPort() + "/" + _contextName; + } + + private static class LocalInstanceManager implements InstanceManager { + LocalInstanceManager() { + } + @Override + public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { + return Class.forName(className).newInstance(); + } + + @Override + public Object newInstance(String fqcn, ClassLoader classLoader) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { + return Class.forName(fqcn, false, classLoader).newInstance(); + } + + @Override + public Object newInstance(Class c) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException { + return c.newInstance(); + } + + @Override + public void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException { + throw new IllegalStateException(); + } + + @Override + public void destroyInstance(Object o) throws IllegalAccessException, InvocationTargetException { + } + } + + @Override + public void addService(QName serviceName, ServiceDomain domain) { + _services.put(serviceName, domain); + } + + @Override + public void removeService(QName serviceName, ServiceDomain domain) { + _services.remove(serviceName); + } + + @Override + public ServiceDomain getDomain(QName serviceName) { + return _services.get(serviceName); + } + + @Override + public RemoteEndpointPublisher setDisableRemoteTransaction(boolean disable) { + _disableRemoteTransaction = disable; + return this; + } + + @Override + public boolean isDisableRemoteTransaction() { + return _disableRemoteTransaction; + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardCdiIntegrationProcessor.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardCdiIntegrationProcessor.java new file mode 100644 index 000000000..37e9e4507 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardCdiIntegrationProcessor.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import java.util.List; + +import javax.enterprise.inject.spi.Extension; + +import org.apache.log4j.Logger; +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.as.weld.WeldDeploymentMarker; +import org.jboss.as.weld.deployment.WeldAttachments; +import org.jboss.as.weld.deployment.WeldPortableExtensions; +import org.jboss.modules.Module; +import org.jboss.weld.bootstrap.spi.Metadata; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; + +/** + * Deployment processor that installs the SwitchYard CDI extension. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardCdiIntegrationProcessor implements DeploymentUnitProcessor { + + private static final String SWITCHYARD_CDI_EXTENSION = "org.switchyard.component.bean.SwitchYardCDIServiceDiscovery"; + private static final String DELTASPIKE_CDI_EXTENSION = "org.apache.deltaspike.core.api.provider.BeanManagerProvider"; + + private static Logger _logger = Logger.getLogger(SwitchYardCdiIntegrationProcessor.class); + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#deploy(org.jboss.as.server.deployment.DeploymentPhaseContext) + */ + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + if (!SwitchYardDeploymentMarker.isSwitchYardDeployment(deploymentUnit)) { + return; + } + + if (WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) { + // Add the Weld portable extension + final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent(); + synchronized (parent) { + checkExtension(SWITCHYARD_CDI_EXTENSION, deploymentUnit, parent); + checkExtension(DELTASPIKE_CDI_EXTENSION, deploymentUnit, parent); + } + } else { + _logger.debug("SwitchYard Application for deployment unit '" + deploymentUnit.getName() + "' does not appear to contain CDI Beans " + + "(no META-INF/beans.xml file in unit). Not attaching SwitchYard CDI Discovery Extension to deployment."); + } + } + + private void checkExtension(final String extensionName, DeploymentUnit deploymentUnit, DeploymentUnit parent) throws DeploymentUnitProcessingException { + final Module module = deploymentUnit.getAttachment(Attachments.MODULE); + Class extensionClass = null; + try { + extensionClass = module.getClassLoader().loadClass(extensionName); + } catch (ClassNotFoundException cnfe) { + throw new DeploymentUnitProcessingException(cnfe); + } + if (extensionClass != null) { + WeldPortableExtensions extensions = WeldPortableExtensions.getPortableExtensions(deploymentUnit); + extensions.tryRegisterExtension(extensionClass, deploymentUnit); + } else { + throw ExtensionMessages.MESSAGES.extensionNotfound(extensionName); + } + } + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#undeploy(org.jboss.as.server.deployment.DeploymentUnit) + */ + @Override + public void undeploy(DeploymentUnit context) { + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardConfigDeploymentProcessor.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardConfigDeploymentProcessor.java new file mode 100644 index 000000000..022971545 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardConfigDeploymentProcessor.java @@ -0,0 +1,78 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import org.jboss.as.ee.structure.DeploymentType; +import org.jboss.as.ee.structure.DeploymentTypeMarker; +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.as.server.deployment.module.ResourceRoot; +import org.jboss.vfs.VirtualFile; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; + +/** + * DU processor that finds switchyard.xml file and attaches the information to the deployment. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardConfigDeploymentProcessor implements DeploymentUnitProcessor { + + private static final String SWITCHYARD_XML = "META-INF/switchyard.xml"; + private static final String SWITCHYARD_XML_WAR = "WEB-INF/switchyard.xml"; + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#deploy(org.jboss.as.server.deployment.DeploymentPhaseContext) + */ + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); + final VirtualFile switchyardXml; + + if (DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { + // switchyard.xml file located in /WEB-INF + final VirtualFile warSwitchYardXml = deploymentRoot.getRoot().getChild(SWITCHYARD_XML_WAR); + if (warSwitchYardXml.exists()) { + switchyardXml = warSwitchYardXml; + } else { + // fall back to original location + switchyardXml = deploymentRoot.getRoot().getChild(SWITCHYARD_XML); + } + } else { + switchyardXml = deploymentRoot.getRoot().getChild(SWITCHYARD_XML); + } + + if (!switchyardXml.exists()) { + return; + } + final String archiveName = deploymentUnit.getName(); + final String deploymentName = archiveName.substring(0, archiveName.lastIndexOf('.')); + final SwitchYardMetaData switchYardMetaData = new SwitchYardMetaData(archiveName, deploymentName); + switchYardMetaData.setSwitchYardFile(switchyardXml); + + deploymentUnit.putAttachment(SwitchYardMetaData.ATTACHMENT_KEY, switchYardMetaData); + SwitchYardDeploymentMarker.mark(deploymentUnit); + } + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#undeploy(org.jboss.as.server.deployment.DeploymentUnit) + */ + @Override + public void undeploy(DeploymentUnit context) { + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardConfigProcessor.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardConfigProcessor.java new file mode 100644 index 000000000..e52eb5db4 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardConfigProcessor.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import java.io.IOException; +import java.io.InputStream; + +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.logging.Logger; +import org.jboss.modules.Module; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; +import org.switchyard.common.property.CompoundPropertyResolver; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardConfigProcessor implements DeploymentUnitProcessor { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#deploy(org.jboss.as.server.deployment.DeploymentPhaseContext) + */ + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + + if (!SwitchYardDeploymentMarker.isSwitchYardDeployment(deploymentUnit)) { + LOG.debug("Ignoring deployment unit '" + deploymentUnit.getName() + "' as it is not recognized as being a SwitchYard Application."); + return; + } + SwitchYardMetaData switchYardMetaData = deploymentUnit.getAttachment(SwitchYardMetaData.ATTACHMENT_KEY); + + ClassLoader origCL = Thread.currentThread().getContextClassLoader(); + InputStream is = null; + try { + final Module module = deploymentUnit.getAttachment(Attachments.MODULE); + Thread.currentThread().setContextClassLoader(module.getClassLoader()); + is = switchYardMetaData.getSwitchYardFile().openStream(); + SwitchYardModel switchyardModel = new ModelPuller().pull(is); + JBossPropertyResolver.set(deploymentUnit, switchyardModel); + switchYardMetaData.setSwitchYardModel(switchyardModel); + LOG.debug("Successfully parsed SwitchYard configuration for deployment unit '" + deploymentUnit.getName() + "'."); + } catch (IOException ioe) { + throw new DeploymentUnitProcessingException(ioe); + } finally { + Thread.currentThread().setContextClassLoader(origCL); + if (is != null) { + try { + is.close(); + } catch (IOException ioe) { + LOG.error(ioe); + } + } + } + + } + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#undeploy(org.jboss.as.server.deployment.DeploymentUnit) + */ + @Override + public void undeploy(DeploymentUnit context) { + // TODO Auto-generated method stub + + } + + private static final class JBossPropertyResolver implements PropertyResolver { + + private final org.jboss.metadata.property.PropertyResolver _wrapped; + + private JBossPropertyResolver(org.jboss.metadata.property.PropertyResolver wrapped) { + _wrapped = wrapped; + } + + /** + * {@inheritDoc} + */ + @Override + public Object resolveProperty(String key) { + return key != null ? _wrapped.resolve(key) : null; + } + + private static void set(DeploymentUnit deploymentUnit, SwitchYardModel switchyardModel) { + org.jboss.metadata.property.PropertyResolver wrapped = deploymentUnit.getAttachment(org.jboss.as.ee.metadata.property.Attachments.FINAL_PROPERTY_RESOLVER); + if (wrapped != null) { + Configuration config = switchyardModel.getModelConfiguration(); + config.setPropertyResolver(CompoundPropertyResolver.compact(config.getPropertyResolver(), new JBossPropertyResolver(wrapped))); + } + } + + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDependencyProcessor.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDependencyProcessor.java new file mode 100644 index 000000000..f6a821b45 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDependencyProcessor.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.as.server.deployment.module.ModuleDependency; +import org.jboss.as.server.deployment.module.ModuleSpecification; +import org.jboss.modules.Module; +import org.jboss.modules.ModuleIdentifier; +import org.jboss.modules.ModuleLoader; +import org.jboss.modules.filter.PathFilter; +import org.jboss.modules.filter.PathFilters; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; + +/** + * DU processor which adds dependencies for runtime modules needed for SwitchYard deployments. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardDependencyProcessor implements DeploymentUnitProcessor { + + private static final PathFilter META_INF_FILTER = PathFilters.isChildOf("META-INF"); + private static final ModuleIdentifier SWITCHYARD_ID = ModuleIdentifier.create("org.switchyard"); + private static final ModuleIdentifier SWITCHYARD_API_ID = ModuleIdentifier.create("org.switchyard.api"); + private static final ModuleIdentifier SWITCHYARD_COMMON_ID = ModuleIdentifier.create("org.switchyard.common"); + private static final ModuleIdentifier SWITCHYARD_COMMON_CAMEL_ID = ModuleIdentifier.create("org.switchyard.common.camel"); + private static final ModuleIdentifier SWITCHYARD_BUS_CAMEL = ModuleIdentifier.create("org.switchyard.bus.camel"); + private static final ModuleIdentifier SWITCHYARD_CONFIG_ID = ModuleIdentifier.create("org.switchyard.config"); + private static final ModuleIdentifier SWITCHYARD_RUNTIME_ID = ModuleIdentifier.create("org.switchyard.runtime"); + private static final ModuleIdentifier SWITCHYARD_TRANSFORM_ID = ModuleIdentifier.create("org.switchyard.transform"); + private static final ModuleIdentifier SWITCHYARD_VALIDATE_ID = ModuleIdentifier.create("org.switchyard.validate"); + private static final ModuleIdentifier DELTASPIKE_ID = ModuleIdentifier.create("org.apache.deltaspike.core-api"); + + /** + * Construct SwitchYard dependency processor. + */ + public SwitchYardDependencyProcessor() { + } + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#deploy(org.jboss.as.server.deployment.DeploymentPhaseContext) + */ + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); + if (!SwitchYardDeploymentMarker.isSwitchYardDeployment(deploymentUnit)) { + return; + } + + final ModuleLoader moduleLoader = Module.getBootModuleLoader(); + + moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, SWITCHYARD_ID, false, false, true, false)); + moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, SWITCHYARD_API_ID, false, false, false, false)); + moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, SWITCHYARD_COMMON_ID, false, false, false, false)); + moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, DELTASPIKE_ID, false, false, false, false)); + moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, SWITCHYARD_BUS_CAMEL, false, false, false, false)); + moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, SWITCHYARD_COMMON_CAMEL_ID, false, false, false, false)); + moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, SWITCHYARD_CONFIG_ID, false, false, false, false)); + ModuleDependency dep = new ModuleDependency(moduleLoader, SWITCHYARD_RUNTIME_ID, false, false, true, false); + dep.addImportFilter(META_INF_FILTER, true); + moduleSpecification.addSystemDependency(dep); + dep = new ModuleDependency(moduleLoader, SWITCHYARD_TRANSFORM_ID, false, false, true, false); + dep.addImportFilter(META_INF_FILTER, true); + moduleSpecification.addSystemDependency(dep); + dep = new ModuleDependency(moduleLoader, SWITCHYARD_VALIDATE_ID, false, false, true, false); + dep.addImportFilter(META_INF_FILTER, true); + moduleSpecification.addSystemDependency(dep); + } + + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#undeploy(org.jboss.as.server.deployment.DeploymentUnit) + */ + @Override + public void undeploy(DeploymentUnit deploymentUnit) { + + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeployment.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeployment.java new file mode 100644 index 000000000..8eb9011f8 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeployment.java @@ -0,0 +1,231 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import java.util.List; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.PathElement; +import org.jboss.as.naming.context.NamespaceContextSelector; +import org.jboss.as.server.deployment.AttachmentKey; +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.dmr.ModelNode; +import org.jboss.modules.Module; +import org.jboss.msc.service.ServiceController; +import org.switchyard.ServiceDomain; +import org.switchyard.admin.Application; +import org.switchyard.admin.base.BaseSwitchYard; +import org.switchyard.as7.extension.SwitchYardExtension; +import org.switchyard.as7.extension.SwitchYardModelConstants; +import org.switchyard.as7.extension.admin.ModelNodeCreationUtil; +import org.switchyard.as7.extension.camel.JBossThreadPoolFactory; +import org.switchyard.as7.extension.camel.NamespaceContextPolicy; +import org.switchyard.as7.extension.services.SwitchYardAdminService; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.ActivatorLoader; +import org.switchyard.deploy.Component; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.internal.Deployment; + +/** + * Represents a single AS7 deployment containing a SwitchYard application. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardDeployment { + + /** The attachment key. */ + public static final AttachmentKey ATTACHMENT_KEY = AttachmentKey + .create(SwitchYardDeployment.class); + + private final DeploymentUnit _deployUnit; + private SwitchYardDeploymentState _deploymentState; + private Deployment _deployment; + private ServiceDomainManager _domainManager; + private ServiceDomain _appServiceDomain; + private NamespaceContextSelector _contextSelector; + + /** + * Creates a new SwitchYard deployment. + * + * @param deploymentUnit deployment reference + * @param config switchyard configuration + * @param domainManager Service Domain Manager instance. + */ + public SwitchYardDeployment(final DeploymentUnit deploymentUnit, final SwitchYardModel config, ServiceDomainManager domainManager) { + _deployUnit = deploymentUnit; + _deployment = new Deployment(config); + _domainManager = domainManager; + } + + /** + * Create the application. + */ + public void create() { + } + + /** + * Destroy the application. + */ + public void destroy() { + } + + /** + * Set by SwitchYardService before start() is called to allow the namespace + * context to be set for any threads created in the application. + * @param contextSelector NamespaceContextSelector + */ + public void setNamespaceContextSelector(NamespaceContextSelector contextSelector) { + _contextSelector = contextSelector; + } + + /** + * Start the application. + * + * @param components the list of components + */ + public void start(final List components) { + final Module module = _deployUnit.getAttachment(Attachments.MODULE); + ClassLoader origCL = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(module.getClassLoader()); + setDeploymentState(SwitchYardDeploymentState.INITIALIZING); + + _appServiceDomain = _domainManager.createDomain(getName(_deployment.getConfig()), _deployment.getConfig()); + + // Override the default Camel ThreadPoolFactory to allow for naming + // context to be set on any threads created within Camel + SwitchYardCamelContext camelCtx = (SwitchYardCamelContext) + _appServiceDomain.getProperty(SwitchYardCamelContext.CAMEL_CONTEXT_PROPERTY); + camelCtx.getExecutorServiceManager().setThreadPoolFactory( + new JBossThreadPoolFactory(_contextSelector)); + + // Configure policy ref which can be used for Camel routes which may + // not execute on camel threads (e.g. quartz) + camelCtx.getWritebleRegistry().put( + NamespaceContextPolicy.POLICY_REF, new NamespaceContextPolicy(_contextSelector)); + + List activators = ActivatorLoader.createActivators( + _appServiceDomain, components, _deployment.getActivationTypes()); + _deployment.init(_appServiceDomain, activators); + setDeploymentState(SwitchYardDeploymentState.STARTING); + _deployment.start(); + setDeploymentState(SwitchYardDeploymentState.STARTED); + registerManagementNodes(); + } finally { + Thread.currentThread().setContextClassLoader(origCL); + } + } + + /** + * Stop the application. + */ + public void stop() { + ClassLoader origCL = Thread.currentThread().getContextClassLoader(); + try { + final Module module = _deployUnit.getAttachment(Attachments.MODULE); + Thread.currentThread().setContextClassLoader(module.getClassLoader()); + if (_deploymentState == SwitchYardDeploymentState.STARTED) { + _deployment.stop(); + setDeploymentState(SwitchYardDeploymentState.STOPPED); + unregisterManagementNodes(); + } + if (_deploymentState == SwitchYardDeploymentState.STARTING + || _deploymentState == SwitchYardDeploymentState.STOPPED) { + _deployment.destroy(); + setDeploymentState(SwitchYardDeploymentState.DESTROYED); + } + } finally { + Thread.currentThread().setContextClassLoader(origCL); + } + } + + /** + * Set the deployment state. + * + * @param deploymentState the deployment state + */ + public void setDeploymentState(SwitchYardDeploymentState deploymentState) { + this._deploymentState = deploymentState; + } + + /** + * Get the deployment state. + * + * @return DeploymentState + */ + public SwitchYardDeploymentState getDeploymentState() { + return _deploymentState; + } + + /** + * Get the application domain. + * + * @return ServiceDomain + */ + public ServiceDomain getDomain() { + return _appServiceDomain; + } + + private void registerManagementNodes() { + QName applicationName = _deployment.getName(); + if (applicationName == null) { + return; + } + + ServiceController adminService = _deployUnit.getServiceRegistry().getService( + SwitchYardAdminService.SERVICE_NAME); + if (adminService == null) { + return; + } + + BaseSwitchYard switchYard = BaseSwitchYard.class.cast(adminService.getValue()); + if (switchYard == null) { + return; + } + + ModelNode deployNode = _deployUnit.createDeploymentSubModel(SwitchYardExtension.SUBSYSTEM_NAME, + PathElement.pathElement(SwitchYardModelConstants.APPLICATION, applicationName.toString())); + + Application application = switchYard.getApplication(applicationName); + if (application == null) { + return; + } + deployNode.set(ModelNodeCreationUtil.createApplicationNode(application)); + } + + private void unregisterManagementNodes() { + QName applicationName = _deployment.getName(); + if (applicationName == null) { + return; + } + _deployUnit.createDeploymentSubModel(SwitchYardExtension.SUBSYSTEM_NAME, + PathElement.pathElement(SwitchYardModelConstants.APPLICATION, applicationName.toString())).clear(); + } + + private QName getName(SwitchYardModel config) { + if (config == null) { + return null; + } + QName name = config.getQName(); + if (name == null && config.getComposite() != null) { + name = config.getComposite().getQName(); + } + return name; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentProcessor.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentProcessor.java new file mode 100644 index 000000000..494b641e5 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentProcessor.java @@ -0,0 +1,202 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import java.util.HashSet; +import java.util.Set; + +import org.jboss.as.clustering.infinispan.subsystem.CacheService; +import org.jboss.as.connector.util.ConnectorServices; +import org.jboss.as.ee.component.EEModuleDescription; +import org.jboss.as.naming.context.NamespaceContextSelector; +import org.jboss.as.naming.deployment.JndiNamingDependencyProcessor; +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.as.weld.WeldDeploymentMarker; +import org.jboss.as.weld.WeldStartService; +import org.jboss.as.weld.services.BeanManagerService; +import org.jboss.logging.Logger; +import org.jboss.metadata.ear.spec.EarMetaData; +import org.jboss.modules.Module; +import org.jboss.msc.service.ServiceBuilder; +import org.jboss.msc.service.ServiceBuilder.DependencyType; +import org.jboss.msc.service.ServiceController.Mode; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.ServiceTarget; +import org.jboss.msc.value.ImmediateValue; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; +import org.switchyard.as7.extension.SwitchYardModuleAdd; +import org.switchyard.as7.extension.services.SwitchYardComponentService; +import org.switchyard.as7.extension.services.SwitchYardService; +import org.switchyard.as7.extension.services.SwitchYardServiceDomainManagerService; +import org.switchyard.component.jca.config.model.InboundConnectionModel; +import org.switchyard.component.jca.config.model.JCABindingModel; +import org.switchyard.component.jca.config.model.OutboundConnectionModel; +import org.switchyard.component.jca.config.model.ResourceAdapterModel; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.deploy.Component; +import org.switchyard.deploy.ServiceDomainManager; + +/** + * Deployment processor that installs the SwitchYard service and all other dependent services. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardDeploymentProcessor implements DeploymentUnitProcessor { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + /** + * Construct SwitchYard deployment processor with a list of component modules. + */ + public SwitchYardDeploymentProcessor() { + } + + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + if (!SwitchYardDeploymentMarker.isSwitchYardDeployment(deploymentUnit)) { + return; + } + final DeploymentUnit parent = deploymentUnit.getParent(); + Boolean initializeInOrder = false; + if (parent != null) { + final EarMetaData earConfig = deploymentUnit.getParent().getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA); + if (earConfig != null) { + initializeInOrder = earConfig.getInitializeInOrder(); + } + } + doDeploy(phaseContext, deploymentUnit, initializeInOrder); + } + + private void doDeploy(DeploymentPhaseContext phaseContext, final DeploymentUnit deploymentUnit, final Boolean initializeInOrder) { + LOG.info("Deploying SwitchYard application '" + deploymentUnit.getName() + "'"); + + ServiceDomainManager domainManager = + (ServiceDomainManager) phaseContext.getServiceRegistry().getRequiredService(SwitchYardServiceDomainManagerService.SERVICE_NAME).getService().getValue(); + + final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); + SwitchYardMetaData metaData = deploymentUnit.getAttachment(SwitchYardMetaData.ATTACHMENT_KEY); + SwitchYardDeployment deployment = new SwitchYardDeployment(deploymentUnit, metaData.getSwitchYardModel(), domainManager); + SwitchYardService container = new SwitchYardService(deployment); + final ServiceName switchyardServiceName = deploymentUnit.getServiceName().append(SwitchYardService.SERVICE_NAME); + final ServiceBuilder switchyardServiceBuilder = serviceTarget.addService(switchyardServiceName, container); + for (String componentName : SwitchYardModuleAdd.getComponentNames()) { + switchyardServiceBuilder.addDependency(SwitchYardComponentService.SERVICE_NAME.append(componentName), Component.class, container.getComponent()); + } + // ensure naming context is fully initialized before we start + switchyardServiceBuilder.addDependency(JndiNamingDependencyProcessor.serviceName(deploymentUnit)); + + final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); + if (moduleDescription != null) { + container.getNamespaceSelector().setValue(new ImmediateValue(moduleDescription.getNamespaceContextSelector())); + } + + // Only add a dependency on the Weld BeanManager if the deployment has beans (i.e. Weld Metadata)... + if (WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) { + final ServiceName beanManagerServiceName = deploymentUnit.getServiceName().append(BeanManagerService.NAME); + switchyardServiceBuilder.addDependency(beanManagerServiceName); + if (deploymentUnit.getParent() == null) { + final ServiceName weldStartServiceName = deploymentUnit.getServiceName().append(WeldStartService.SERVICE_NAME); + switchyardServiceBuilder.addDependency(weldStartServiceName); + } else { + final ServiceName weldStartServiceName = deploymentUnit.getParent().getServiceName().append(WeldStartService.SERVICE_NAME); + switchyardServiceBuilder.addDependency(weldStartServiceName); + } + } + + // Collect all the resource adapters referenced from SwitchYard configuration + Set resourceAdapters = new HashSet(); + ClassLoader origCl = Thread.currentThread().getContextClassLoader(); + try { + final Module module = deploymentUnit.getAttachment(Attachments.MODULE); + Thread.currentThread().setContextClassLoader(module.getClassLoader()); + CompositeModel composite = metaData.getSwitchYardModel().getComposite(); + if (composite != null) { + for (CompositeServiceModel service : composite.getServices()) { + for (BindingModel binding : service.getBindings()) { + if (binding instanceof JCABindingModel) { + JCABindingModel jcabinding = JCABindingModel.class.cast(binding); + InboundConnectionModel ic = jcabinding.getInboundConnection(); + if (ic != null) { + ResourceAdapterModel ra = ic.getResourceAdapter(); + if (ra != null && ra.getName() != null && !ra.getName().isEmpty()) { + resourceAdapters.add(ra.getName()); + } + } + } + } + } + for (CompositeReferenceModel reference : composite.getReferences()) { + for (BindingModel binding : reference.getBindings()) { + if (binding instanceof JCABindingModel) { + JCABindingModel jcabinding = JCABindingModel.class.cast(binding); + OutboundConnectionModel oc = jcabinding.getOutboundConnection(); + if (oc != null) { + ResourceAdapterModel ra = oc.getResourceAdapter(); + if (ra != null && ra.getName() != null && !ra.getName().isEmpty()) { + resourceAdapters.add(ra.getName()); + } + } + } + } + } + } else { + LOG.info("A composite element is missing from the switchyard.xml"); + } + } finally { + Thread.currentThread().setContextClassLoader(origCl); + } + for (String raName : resourceAdapters) { + switchyardServiceBuilder.addDependency(ConnectorServices.RESOURCE_ADAPTER_SERVICE_PREFIX + .append(stripDotRarSuffix(raName))); + } + + // Add dependency in the order defined in ear config + if (initializeInOrder) { + final DeploymentUnit parent = deploymentUnit.getParent(); + ServiceName previousServiceName = parent.getAttachment(SwitchYardMetaData.SERVICENAME_ATTACHMENT_KEY); + if (previousServiceName != null) { + switchyardServiceBuilder.addDependency(previousServiceName); + } + parent.putAttachment(SwitchYardMetaData.SERVICENAME_ATTACHMENT_KEY, switchyardServiceName); + } + + switchyardServiceBuilder.addDependency(DependencyType.OPTIONAL, CacheService.getServiceName("cluster", null)); + + switchyardServiceBuilder.setInitialMode(Mode.ACTIVE); + switchyardServiceBuilder.install(); + } + + private String stripDotRarSuffix(final String raName) { + if (raName == null) { + return null; + } + if (raName.endsWith(".rar")) { + return raName.substring(0, raName.indexOf(".rar")); + } + return raName; + } + + @Override + public void undeploy(DeploymentUnit deploymentUnit) { + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentState.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentState.java new file mode 100644 index 000000000..39e75aabc --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentState.java @@ -0,0 +1,46 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +/** + * Represents the state of SwitchYard deployment. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public enum SwitchYardDeploymentState { + /** + * Indicates state being initialized. + */ + INITIALIZING, + + /** + * Indicates state being started. + */ + STARTING, + + /** + * Indicates started state. + */ + STARTED, + + /** + * Indicates stopped state. + */ + STOPPED, + + /** + * Indicates destroyed state. + */ + DESTROYED +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardMetaData.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardMetaData.java new file mode 100644 index 000000000..420ba527e --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardMetaData.java @@ -0,0 +1,108 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import org.jboss.as.server.deployment.AttachmentKey; +import org.jboss.modules.ModuleIdentifier; +import org.jboss.msc.service.ServiceName; +import org.jboss.vfs.VirtualFile; +import org.switchyard.config.model.switchyard.SwitchYardModel; + +/** + * Information about a SwitchYard deployment that is attached to the DU. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardMetaData { + + /** The attachment key. */ + public static final AttachmentKey ATTACHMENT_KEY = AttachmentKey.create(SwitchYardMetaData.class); + + /** The service name attachment key. */ + public static final AttachmentKey SERVICENAME_ATTACHMENT_KEY = AttachmentKey.create(ServiceName.class); + + /** The service name attachment key. */ + public static final AttachmentKey BEAN_COMPONENT_ATTACHMENT_KEY = AttachmentKey.create(ModuleIdentifier.class); + + /** The name of the SwitchYard archive. */ + private String _archiveName = null; + + /** The deployment name. The SwitchYard archive name without the .esb suffix */ + private String _deploymentName = null; + + private VirtualFile _switchYardFile = null; + + private SwitchYardModel _switchYardModel = null; + + /** + * Create a new SwitchYard metadata. + * @param archiveName name of the deployment archive + * @param deploymentName name of the deployment + */ + public SwitchYardMetaData(String archiveName, String deploymentName) { + _archiveName = archiveName; + _deploymentName = deploymentName; + } + + /** + * Gets the name of the archive that this metadata came from. + * + * @return String The name of the archive that this metadata came from. + */ + public final String getArchiveName() { + return _archiveName; + } + + /** + * The deployment name is the name of the .esb archive without the .esb suffix. + * + * @return String The name of the deployment. This is the archive name without the .esb suffix. + */ + public String getDeploymentName() { + return _deploymentName; + } + + + /** + * Getter for the file containing the SwitchYard configuration. + * @return switchyardFile SwitchYard configuration file + */ + public VirtualFile getSwitchYardFile() { + return _switchYardFile; + } + + /** + * Setter for the file containing the SwitchYard configuration. + * @param switchYardFile SwitchYard configuration file + */ + public void setSwitchYardFile(VirtualFile switchYardFile) { + _switchYardFile = switchYardFile; + } + + /** + * Getter for SwitchYard Model. + * @param switchYardModel the SwitchYardModel to set + */ + public void setSwitchYardModel(SwitchYardModel switchYardModel) { + this._switchYardModel = switchYardModel; + } + + /** + * Setter for SwitchYard Model. + * @return the SwitchYardModel + */ + public SwitchYardModel getSwitchYardModel() { + return _switchYardModel; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardModuleDependencyProcessor.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardModuleDependencyProcessor.java new file mode 100644 index 000000000..13704d7e1 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardModuleDependencyProcessor.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.as.server.deployment.module.ModuleDependency; +import org.jboss.as.server.deployment.module.ModuleSpecification; +import org.jboss.as.weld.WeldDeploymentMarker; +import org.jboss.metadata.ear.spec.EarMetaData; +import org.jboss.modules.Module; +import org.jboss.modules.ModuleIdentifier; +import org.jboss.modules.ModuleLoader; +import org.jboss.modules.filter.PathFilter; +import org.jboss.modules.filter.PathFilters; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; + +/** + * DU processor which adds a module dependency for modules needed for SwitchYard deployments. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class SwitchYardModuleDependencyProcessor implements DeploymentUnitProcessor { + + private static final PathFilter META_INF_FILTER = PathFilters.isChildOf("META-INF"); + private static final ModuleIdentifier SWITCHYARD_BEAN_ID = ModuleIdentifier.create("org.switchyard.component.bean"); + + private String _moduleId; + + /** + * Construct SwitchYard module dependency processor. + * + * @param moduleId The module identifier + */ + public SwitchYardModuleDependencyProcessor(String moduleId) { + _moduleId = moduleId; + } + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#deploy(org.jboss.as.server.deployment.DeploymentPhaseContext) + */ + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); + if (!SwitchYardDeploymentMarker.isSwitchYardDeployment(deploymentUnit)) { + return; + } + + ModuleLoader moduleLoader = Module.getBootModuleLoader(); + ModuleDependency dep = new ModuleDependency(moduleLoader, ModuleIdentifier.fromString(_moduleId), false, false, true, false); + dep.addImportFilter(META_INF_FILTER, true); + moduleSpecification.addSystemDependency(dep); + + if (WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit) && (deploymentUnit.getParent() != null)) { + final EarMetaData earConfig = deploymentUnit.getParent().getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA); + if (earConfig != null) { + final ModuleIdentifier beanComponent = deploymentUnit.getParent().getAttachment(SwitchYardMetaData.BEAN_COMPONENT_ATTACHMENT_KEY); + if (beanComponent == null) { + moduleLoader = Module.getBootModuleLoader(); + moduleSpecification = deploymentUnit.getParent().getAttachment(Attachments.MODULE_SPECIFICATION); + dep = new ModuleDependency(moduleLoader, SWITCHYARD_BEAN_ID, false, false, true, false); + dep.addImportFilter(META_INF_FILTER, true); + moduleSpecification.addSystemDependency(dep); + deploymentUnit.getParent().putAttachment(SwitchYardMetaData.BEAN_COMPONENT_ATTACHMENT_KEY, SWITCHYARD_BEAN_ID); + } + } + } + } + + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#undeploy(org.jboss.as.server.deployment.DeploymentUnit) + */ + @Override + public void undeploy(DeploymentUnit deploymentUnit) { + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpoint.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpoint.java new file mode 100644 index 000000000..184dad3d7 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpoint.java @@ -0,0 +1,82 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.http; + +import org.apache.catalina.Container; +import org.apache.catalina.core.StandardContext; +import org.jboss.logging.Logger; +import org.switchyard.component.common.Endpoint; + +/** + * A JBossWeb HTTP endpoint. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JBossWebEndpoint implements Endpoint { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + private StandardContext _context; + + /** + * Construct a JBossWebEndpoint with the given context. + * @param context The StandardContext + */ + public JBossWebEndpoint(final StandardContext context) { + _context = context; + } + + /** + * Sets the context associated with this HTTP endpoint. + * @return The StandardContext + */ + public StandardContext getContext() { + return _context; + } + + /** + * Sets the context associated with this HTTP endpoint. + * @param context The StandardContext + */ + public void setContext(StandardContext context) { + _context = context; + } + + /** + * {@inheritDoc} + */ + public void start() { + } + + /** + * {@inheritDoc} + */ + public void stop() { + if (_context != null) { + // Destroy the web context unless if it is default + if (!_context.getPath().equals("/")) { + try { + Container container = _context.getParent(); + container.removeChild(_context); + _context.stop(); + _context.destroy(); + LOG.info("Destroyed HTTP context " + _context.getPath()); + } catch (Exception e) { + LOG.error("Unable to destroy web context", e); + } + } + } + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpointPublisher.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpointPublisher.java new file mode 100644 index 000000000..f31a4effc --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpointPublisher.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.http; + +import java.lang.reflect.InvocationTargetException; +import java.io.File; + +import javax.naming.NamingException; + +import org.apache.catalina.Host; +import org.apache.catalina.Loader; +import org.apache.catalina.Wrapper; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.startup.ContextConfig; +import org.apache.tomcat.InstanceManager; +import org.jboss.as.server.ServerEnvironment; +import org.jboss.as.web.deployment.WebCtxLoader; +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.util.ServerUtil; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.http.InboundHandler; +import org.switchyard.component.http.HttpGatewayServlet; +import org.switchyard.component.http.endpoint.EndpointPublisher; + +/** + * Publishes standalone HTTP endpoint. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JBossWebEndpointPublisher implements EndpointPublisher { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + private static final String SERVER_TEMP_DIR = System.getProperty(ServerEnvironment.SERVER_TEMP_DIR); + private static final String SERVLET_NAME = "HttpGatewayServlet"; + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, String context, InboundHandler handler) throws Exception { + + Host host = ServerUtil.getDefaultHost().getHost(); + StandardContext serverContext = (StandardContext) host.findChild("/" + context); + if (serverContext == null) { + serverContext = new StandardContext(); + serverContext.setPath("/" + context); + File docBase = new File(SERVER_TEMP_DIR, context); + if (!docBase.exists()) { + if (!docBase.mkdirs()) { + throw ExtensionMessages.MESSAGES.unableToCreateTempDirectory(docBase.getPath()); + } + } + serverContext.setDocBase(docBase.getPath()); + serverContext.addLifecycleListener(new ContextConfig()); + + final Loader loader = new WebCtxLoader(Thread.currentThread().getContextClassLoader()); + loader.setContainer(host); + serverContext.setLoader(loader); + serverContext.setInstanceManager(new LocalInstanceManager()); + + Wrapper wrapper = serverContext.createWrapper(); + wrapper.setName(SERVLET_NAME); + wrapper.setServletClass(HttpGatewayServlet.class.getName()); + wrapper.setServlet(new HttpGatewayServlet()); + wrapper.setLoadOnStartup(1); + serverContext.addChild(wrapper); + serverContext.addServletMapping("/*", SERVLET_NAME); + + host.addChild(serverContext); + serverContext.create(); + serverContext.start(); + HttpGatewayServlet instance = (HttpGatewayServlet) wrapper.getServlet(); + instance.setHandler(handler); + LOG.info("Published HTTP context " + serverContext.getPath()); + } else { + throw ExtensionMessages.MESSAGES.contextAlreadyExists(context); + } + return new JBossWebEndpoint(serverContext); + } + + private static class LocalInstanceManager implements InstanceManager { + LocalInstanceManager() { + } + @Override + public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { + return Class.forName(className).newInstance(); + } + + @Override + public Object newInstance(String fqcn, ClassLoader classLoader) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { + return Class.forName(fqcn, false, classLoader).newInstance(); + } + + @Override + public Object newInstance(Class c) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException { + return c.newInstance(); + } + + @Override + public void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException { + throw new IllegalStateException(); + } + + @Override + public void destroyInstance(Object o) throws IllegalAccessException, InvocationTargetException { + } + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResource.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResource.java new file mode 100644 index 000000000..d8216902a --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResource.java @@ -0,0 +1,103 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.resteasy; + +import java.util.List; + +import org.apache.catalina.Container; +import org.apache.catalina.core.StandardContext; +import org.jboss.logging.Logger; +import org.jboss.resteasy.spi.Registry; +import org.switchyard.as7.extension.ExtensionLogger; +import org.switchyard.component.common.Endpoint; + +/** + * A standalone RESTEasy resource. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyResource implements Endpoint { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + private StandardContext _context; + private List> _classes; + + /** + * Sets the context associated with this resource deployment. + * @return The StandardContext + */ + public StandardContext getContext() { + return _context; + } + + /** + * Sets the context associated with this resource deployment. + * @param context The StandardContext + */ + public void setContext(StandardContext context) { + _context = context; + } + + /** + * Gets the list of classes associated with this resource deployment. + * @return The List of classes + */ + public List> getClasses() { + return _classes; + } + + /** + * Sets the list of classes associated with this resource deployment. + * @param classes The List of classes + */ + public void setClasses(List> classes) { + _classes = classes; + } + + /** + * {@inheritDoc} + */ + public void start() { + } + + /** + * {@inheritDoc} + */ + public void stop() { + if ((_context != null) && _context.isStarted()) { + Registry registry = (Registry)_context.getServletContext().getAttribute(Registry.class.getName()); + if (registry != null) { + // Remove registrations + for (Class clazz : _classes) { + LOG.debug("Stopping ... " + clazz); + registry.removeRegistrations(clazz); + } + // Destroy the web context unless if it is default + if ((registry.getSize() == 0) && (!_context.getPath().equals("/"))) { + try { + Container container = _context.getParent(); + container.removeChild(_context); + _context.stop(); + _context.destroy(); + LOG.info("Destroyed RESTEasy context " + _context.getPath()); + } catch (Exception e) { + ExtensionLogger.ROOT_LOGGER.unableToDestroyWebContext(_context.getPath(), e); + } + } + } + } + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResourcePublisher.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResourcePublisher.java new file mode 100644 index 000000000..0336625ac --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResourcePublisher.java @@ -0,0 +1,150 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.resteasy; + +import java.lang.reflect.InvocationTargetException; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import java.util.Map; +import javax.naming.NamingException; + +import org.apache.catalina.Host; +import org.apache.catalina.Loader; +import org.apache.catalina.Wrapper; +import org.apache.catalina.core.StandardContext; +import org.apache.catalina.startup.ContextConfig; +import org.apache.tomcat.InstanceManager; +import org.jboss.as.server.ServerEnvironment; +import org.jboss.as.web.deployment.WebCtxLoader; +import org.jboss.logging.Logger; +import org.jboss.resteasy.spi.Registry; +import org.switchyard.ServiceDomain; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.util.ServerUtil; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.resteasy.resource.ResourcePublisher; + +/** + * Creates a RESTEasy resource on AS7. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyResourcePublisher implements ResourcePublisher { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + private static final String LISTENER_CLASS = "org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap"; + private static final String SERVER_TEMP_DIR = System.getProperty(ServerEnvironment.SERVER_TEMP_DIR); + private static final String SERVLET_NAME = "RestEasy"; + private static final String SERVLET_CLASS = "org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher"; + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, String context, List instances, Map contextParams) throws Exception { + Host host = ServerUtil.getDefaultHost().getHost(); + StandardContext serverContext = (StandardContext) host.findChild("/" + context); + if (serverContext == null) { + serverContext = new StandardContext(); + serverContext.setPath("/" + context); + File docBase = new File(SERVER_TEMP_DIR, context); + if (!docBase.exists()) { + if (!docBase.mkdirs()) { + throw ExtensionMessages.MESSAGES.unableToCreateTempDirectory(docBase.getPath()); + } + } + serverContext.setDocBase(docBase.getPath()); + serverContext.addLifecycleListener(new ContextConfig()); + + final Loader loader = new WebCtxLoader(instances.get(0).getClass().getClassLoader()); + loader.setContainer(host); + serverContext.setLoader(loader); + serverContext.setInstanceManager(new LocalInstanceManager()); + + Wrapper wrapper = serverContext.createWrapper(); + wrapper.setName(SERVLET_NAME); + wrapper.setServletClass(SERVLET_CLASS); + wrapper.setLoadOnStartup(1); + serverContext.addChild(wrapper); + serverContext.addServletMapping("/*", SERVLET_NAME); + serverContext.addApplicationListener(LISTENER_CLASS); + + if (contextParams != null) { + for (Map.Entry cp : contextParams.entrySet()) { + serverContext.addParameter(cp.getKey(), cp.getValue()); + } + } + + host.addChild(serverContext); + serverContext.create(); + serverContext.start(); + LOG.info("Published RESTEasy context " + serverContext.getPath()); + } + while (serverContext.isStarting()) { + try { + Thread.sleep(100); + } catch (InterruptedException ie) { + // Ignore + if (LOG.isDebugEnabled()) { + LOG.debug("Spent sometime to start context."); + } + } + } + if (serverContext.isStarted()) { + Registry registry = (Registry)serverContext.getServletContext().getAttribute(Registry.class.getName()); + List> classes = new ArrayList>(); + // Add as singleton instance + for (Object instance : instances) { + registry.addSingletonResource(instance); + classes.add(instance.getClass()); + } + RESTEasyResource resource = new RESTEasyResource(); + resource.setClasses(classes); + resource.setContext(serverContext); + return resource; + } else { + throw ExtensionMessages.MESSAGES.unableToStartContext(context, new RuntimeException("Context not yet started")); + } + } + + private static class LocalInstanceManager implements InstanceManager { + LocalInstanceManager() { + } + @Override + public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { + return Class.forName(className).newInstance(); + } + + @Override + public Object newInstance(String fqcn, ClassLoader classLoader) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { + return Class.forName(fqcn, false, classLoader).newInstance(); + } + + @Override + public Object newInstance(Class c) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException { + return c.newInstance(); + } + + @Override + public void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException { + throw new IllegalStateException(); + } + + @Override + public void destroyInstance(Object o) throws IllegalAccessException, InvocationTargetException { + } + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardAdminService.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardAdminService.java new file mode 100644 index 000000000..a2efc1f4b --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardAdminService.java @@ -0,0 +1,97 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.services; + +import java.util.Map; + +import org.jboss.msc.service.Service; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.StartContext; +import org.jboss.msc.service.StartException; +import org.jboss.msc.service.StopContext; +import org.jboss.msc.value.InjectedValue; +import org.switchyard.admin.SwitchYard; +import org.switchyard.admin.base.BaseSwitchYard; +import org.switchyard.admin.base.SwitchYardBuilder; +import org.switchyard.deploy.ServiceDomainManager; + +/** + * SwitchYardAdminService + * + * Provides a {@link SwitchYard} instance as an AS7 {@link Service}. + * + * @author Rob Cernich + */ +public class SwitchYardAdminService implements Service { + + /** + * The name used to resolve the SwitchYard administration service. + */ + public final static ServiceName SERVICE_NAME = ServiceName.of("SwitchYardAdminService"); + + @SuppressWarnings("rawtypes") + private final InjectedValue _socketBindings = new InjectedValue(); + private final InjectedValue _serviceDomainManager = new InjectedValue(); + private SwitchYard _switchYard; + private SwitchYardBuilder _syBuilder; + + /** + * Create a new SwitchYardAdminService. + */ + public SwitchYardAdminService() {} + + @Override + public SwitchYard getValue() throws IllegalStateException, IllegalArgumentException { + return _switchYard; + } + + @Override + public void start(StartContext context) throws StartException { + _syBuilder = new SwitchYardBuilder(); + _syBuilder.init(_serviceDomainManager.getValue()); + _switchYard = _syBuilder.getSwitchYard(); + + // add in the configured socket bindings + ((BaseSwitchYard)_switchYard).addSocketBindingNames(_socketBindings.getValue().keySet()); + + // TODO: add in configured properties + // _switchYard.addProperties(properties); + } + + @Override + public void stop(StopContext context) { + _syBuilder.destroy(); + _switchYard = null; + } + + /** + * Injection point for SwitchYard socket bindings. + * + * @return injected socket bindings map. + * @see SwitchYardInjectorService + */ + @SuppressWarnings("rawtypes") + public final InjectedValue getSocketBindings() { + return _socketBindings; + } + + /** + * Injection point for ServiceDomainManager. + * + * @return the ServiceDomainManager + */ + public InjectedValue getServiceDomainManager() { + return _serviceDomainManager; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardComponentService.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardComponentService.java new file mode 100644 index 000000000..a6e4e478d --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardComponentService.java @@ -0,0 +1,155 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.services; + +import java.util.Map; +import java.util.Set; + +import javax.xml.namespace.QName; + +import org.jboss.dmr.ModelNode; +import org.jboss.jca.core.spi.rar.ResourceAdapterRepository; +import org.jboss.logging.Logger; +import org.jboss.modules.Module; +import org.jboss.modules.ModuleIdentifier; +import org.jboss.modules.ModuleLoadException; +import org.jboss.msc.inject.Injector; +import org.jboss.msc.service.Service; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.StartContext; +import org.jboss.msc.service.StartException; +import org.jboss.msc.service.StopContext; +import org.jboss.msc.value.InjectedValue; +import org.switchyard.as7.extension.CommonAttributes; +import org.switchyard.as7.extension.ExtensionLogger; +import org.switchyard.config.Configuration; +import org.switchyard.config.ConfigurationPuller; +import org.switchyard.config.Configurations; +import org.switchyard.deploy.Component; + +/** + * The SwitchYard Component service. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardComponentService implements Service { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + /** + * Represents a SwitchYard Component initializer service name. + */ + public static final ServiceName SERVICE_NAME = ServiceName.of("SwitchYardComponentService"); + + private final InjectedValue _injectedValues = new InjectedValue(); + private final InjectedValue _resourceAdapterRepository = new InjectedValue(); + + private String _moduleId; + private ModelNode _model; + private Component _component; + + /** + * Constructs a SwitchYard Component service. + * + * @param moduleId the module identifier + * @param model the Module's model operation + */ + public SwitchYardComponentService(String moduleId, ModelNode model) { + _moduleId = moduleId; + _model = model; + } + + @Override + public Component getValue() throws IllegalStateException, + IllegalArgumentException { + return _component; + } + + @Override + public void start(StartContext context) throws StartException { + Class componentClass; + String className = _model.get(CommonAttributes.IMPLCLASS).asString(); + try { + componentClass = Module.loadClassFromCallerModuleLoader(ModuleIdentifier.fromString(_moduleId), className); + try { + _component = (Component) componentClass.newInstance(); + ModelNode properties = _model.hasDefined(CommonAttributes.PROPERTIES) ? _model.get(CommonAttributes.PROPERTIES) : null; + _component.init(createEnvironmentConfig(properties)); + LOG.debug("Initialized component " + _component); + _component.addResourceDependency(_resourceAdapterRepository.getValue()); + } catch (InstantiationException ie) { + ExtensionLogger.ROOT_LOGGER.unableToInstantiateClass(className, ie); + } catch (IllegalAccessException iae) { + ExtensionLogger.ROOT_LOGGER.unableToAccessConstructor(className, iae); + } + } catch (ClassNotFoundException cnfe) { + ExtensionLogger.ROOT_LOGGER.unableToLoadClass(className, cnfe); + } catch (ModuleLoadException mle) { + ExtensionLogger.ROOT_LOGGER.unableToLoadModule(_moduleId, mle); + } + } + + private Configuration createEnvironmentConfig(ModelNode properties) { + Configuration envConfig = Configurations.newConfiguration(); + if (properties != null) { + Set propertyNames = properties.keys(); + if (propertyNames != null) { + for (String propertyName : propertyNames) { + Configuration propConfig = new ConfigurationPuller().pull(new QName(propertyName)); + String value = properties.get(propertyName).asString(); + if (value.startsWith(CommonAttributes.DOLLAR)) { + String key = value.substring(1); + String injectedValue = (String) _injectedValues.getValue().get(key); + if (injectedValue != null) { + propConfig.setValue(injectedValue); + envConfig.addChild(propConfig); + } + } else { + propConfig.setValue(value); + envConfig.addChild(propConfig); + } + } + } + } + return envConfig; + } + + @Override + public void stop(StopContext context) { + LOG.info("Stopping SwitchYard component " + _component.getName()); + try { + _component.destroy(); + } catch (Exception e) { + ExtensionLogger.ROOT_LOGGER.unableToStop(_component.getName(), e); + } + } + + /** + * Injection point for injectValues. + * + * @return a map of injected values + */ + public InjectedValue getInjectedValues() { + return _injectedValues; + } + + /** + * Injection point for ResourceAdapterRepository. + * @return ResourceAdapterRepository + */ + public Injector getResourceAdapterRepository() { + return _resourceAdapterRepository; + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardInjectorService.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardInjectorService.java new file mode 100644 index 000000000..6813ebada --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardInjectorService.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.services; + +import java.util.HashMap; +import java.util.Map; +import org.jboss.as.network.SocketBinding; +import org.jboss.logging.Logger; +import org.jboss.msc.service.Service; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.StartContext; +import org.jboss.msc.service.StartException; +import org.jboss.msc.service.StopContext; +import org.jboss.msc.value.InjectedValue; +import org.switchyard.common.net.SocketAddr; + +/** + * The SwitchYard Dependencies Injector service. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardInjectorService implements Service> { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + /** + * Represents a SwitchYard Dependencies Injector service name. + */ + public static final ServiceName SERVICE_NAME = ServiceName.of("SwitchYardInjectorService"); + + private final Map _injectedValues = new HashMap(); + private final Map> _socketBindings = new HashMap>(); + + /** + * Constructs a SwitchYard Dependencies Injector service. + */ + public SwitchYardInjectorService() { + } + + @Override + public Map getValue() throws IllegalStateException, + IllegalArgumentException { + return _injectedValues; + } + + @Override + public void start(StartContext context) throws StartException { + for (String key : _socketBindings.keySet()) { + SocketBinding binding = _socketBindings.get(key).getValue(); + SocketAddr addr = new SocketAddr(binding.getAddress().getHostAddress(), binding.getPort()); + LOG.trace("Injecting socket binding '" + addr + "'"); + _injectedValues.put(key, addr.toString()); + } + } + + @Override + public void stop(StopContext context) { + + } + + /** + * Injection point for SocketBindings. + * + * @param name the name of the SocketBinding + * @return the SocketBinding + */ + public InjectedValue getSocketBinding(String name) { + InjectedValue binding = _socketBindings.get(name); + if (binding == null) { + binding = new InjectedValue(); + _socketBindings.put(name, binding); + } + return binding; + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardSecurityConfigService.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardSecurityConfigService.java new file mode 100644 index 000000000..c2238c3e7 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardSecurityConfigService.java @@ -0,0 +1,157 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.services; + +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.jboss.dmr.ModelNode; +import org.jboss.msc.service.Service; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.StartContext; +import org.jboss.msc.service.StartException; +import org.jboss.msc.service.StopContext; +import org.jboss.msc.value.InjectedValue; +import org.switchyard.as7.extension.CommonAttributes; +import org.switchyard.as7.extension.services.SwitchYardSecurityConfigService.SecurityConfig; +import org.switchyard.common.lang.Strings; +import org.switchyard.security.context.SecurityContext; +import org.switchyard.security.crypto.PrivateCrypto; +import org.switchyard.security.crypto.PublicCrypto; +import org.switchyard.security.system.DefaultSystemSecurity; +import org.switchyard.security.system.SystemSecurity; + +/** + * The SwitchYard SecurityConfig service. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SwitchYardSecurityConfigService implements Service { + + /** + * Represents a SwitchYard SecurityConfig initializer service name. + */ + public static final ServiceName SERVICE_NAME = ServiceName.of("SwitchYardSecurityConfigService"); + + private final InjectedValue _systemSecurity = new InjectedValue(); + private final InjectedValue _injectedValues = new InjectedValue(); + + private String _moduleId; + private ModelNode _model; + private SecurityConfig _securityConfig; + + /** + * Constructs a SwitchYard SecurityConfig service. + * + * @param moduleId the module identifier + * @param model the Module's model operation + */ + public SwitchYardSecurityConfigService(String moduleId, ModelNode model) { + _moduleId = moduleId; + _model = model; + } + + @Override + public SecurityConfig getValue() throws IllegalStateException, + IllegalArgumentException { + return _securityConfig; + } + + @Override + public void start(StartContext context) throws StartException { + ModelNode propertiesModel = _model.hasDefined(CommonAttributes.PROPERTIES) ? _model.get(CommonAttributes.PROPERTIES) : null; + Properties securityProps = toProperties(propertiesModel); + _securityConfig = new SecurityConfig(securityProps); + DefaultSystemSecurity systemSecurity = (DefaultSystemSecurity)getSystemSecurity().getValue(); + if (SecurityContext.class.getName().equals(_moduleId)) { + String timeoutMillis = Strings.trimToNull(securityProps.getProperty("timeoutMillis")); + if (timeoutMillis != null) { + systemSecurity.setSecurityContextTimeoutMillis(Long.valueOf(timeoutMillis)); + } + } + if (PrivateCrypto.class.getName().equals(_moduleId)) { + systemSecurity.setPrivateCrypto(new PrivateCrypto(securityProps)); + } + if (PublicCrypto.class.getName().equals(_moduleId)) { + systemSecurity.setPublicCrypto(new PublicCrypto(securityProps)); + } + } + + private Properties toProperties(ModelNode propertiesModel) { + Properties properties = new Properties(); + if (propertiesModel != null) { + Set names = propertiesModel.keys(); + if (names != null) { + for (String name : names) { + String value = propertiesModel.get(name).asString(); + if (value.startsWith(CommonAttributes.DOLLAR)) { + String key = value.substring(1); + String injectedValue = (String)_injectedValues.getValue().get(key); + if (injectedValue != null) { + properties.setProperty(name, injectedValue); + } + } else { + properties.setProperty(name, value); + } + } + } + } + return properties; + } + + @Override + public void stop(StopContext context) { + } + + /** + * SystemSecurity injection point. + * + * @return injected SystemSecurity + */ + public InjectedValue getSystemSecurity() { + return _systemSecurity; + } + + /** + * Injection point for injectValues. + * + * @return a map of injected values + */ + public InjectedValue getInjectedValues() { + return _injectedValues; + } + + /** + * SecurityConfig. + */ + public static final class SecurityConfig { + private final Properties _properties; + /** + * Creates a new SecurityConfig with the specified properties. + * @param properties the properties + */ + public SecurityConfig(Properties properties) { + _properties = properties; + } + /** + * Gets the properties. + * @return the properties + */ + public Properties getProperties() { + return _properties; + } + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardService.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardService.java new file mode 100644 index 000000000..d487aa72a --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardService.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.services; + +import java.util.ArrayList; +import java.util.List; + +import org.jboss.as.naming.context.NamespaceContextSelector; +import org.jboss.logging.Logger; +import org.jboss.msc.service.Service; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.StartContext; +import org.jboss.msc.service.StartException; +import org.jboss.msc.service.StopContext; +import org.jboss.msc.value.InjectedValue; +import org.switchyard.as7.extension.deployment.SwitchYardDeployment; +import org.switchyard.deploy.Component; +import org.switchyard.runtime.event.ExchangeCompletionEvent; +import org.switchyard.runtime.event.ExchangeInitiatedEvent; + +/** + * The SwitchYard service associated with deployments. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardService implements Service { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + /** + * Represents a SwitchYard service name. + */ + public static final ServiceName SERVICE_NAME = ServiceName.of("SwitchYardService"); + + private final InjectedValue _namespaceSelector = new InjectedValue(); + + private final List> _components = new ArrayList>(); + private SwitchYardDeployment _switchyardDeployment; + + /** + * Constructs a SwitchYard service. + * + * @param switchyardDeployment the deployment instance + */ + public SwitchYardService(SwitchYardDeployment switchyardDeployment) { + _switchyardDeployment = switchyardDeployment; + } + + @Override + public SwitchYardDeployment getValue() throws IllegalStateException, IllegalArgumentException { + return _switchyardDeployment; + } + + @SuppressWarnings("unchecked") + @Override + public void start(StartContext context) throws StartException { + try { + NamespaceContextSelector selector = _namespaceSelector.getValue(); + NamespaceContextSelector.pushCurrentSelector(selector); + LOG.info("Starting SwitchYard service"); + List components = new ArrayList(); + for (InjectedValue component : _components) { + components.add(component.getValue()); + } + _switchyardDeployment.setNamespaceContextSelector(selector); + _switchyardDeployment.start(components); + } catch (Exception e) { + try { + _switchyardDeployment.stop(); + } catch (Exception ex) { + LOG.error(ex); + } + throw new StartException(e); + } finally { + NamespaceContextSelector.popCurrentSelector(); + } + } + + @Override + public void stop(StopContext context) { + _switchyardDeployment.stop(); + } + + /** + * Injection point for NamespaceContextSelector. + * + * @return the NamespaceContextSelector + */ + public InjectedValue getNamespaceSelector() { + return _namespaceSelector; + } + + /** + * Injection point for Component. + * + * @return the component added + */ + public InjectedValue getComponent() { + InjectedValue component = new InjectedValue(); + if (!_components.contains(component)) { + _components.add(component); + } + return component; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardServiceDomainManagerService.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardServiceDomainManagerService.java new file mode 100644 index 000000000..1c7b08723 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardServiceDomainManagerService.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.services; + +import org.infinispan.Cache; +import org.jboss.msc.service.Service; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.StartContext; +import org.jboss.msc.service.StartException; +import org.jboss.msc.service.StopContext; +import org.jboss.msc.value.InjectedValue; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.security.system.SystemSecurity; + +/** + * ServiceDomainManager Service for AS7 deployments. + * + * @author tom.fennelly@gmail.com + */ +public class SwitchYardServiceDomainManagerService implements Service { + + /** + * The name used to resolve the ServiceDomainManager. + */ + public final static ServiceName SERVICE_NAME = ServiceName.of(SwitchYardServiceDomainManagerService.class.getSimpleName()); + + private ServiceDomainManager _domainManager; + + private final InjectedValue _systemSecurity = new InjectedValue(); + private final InjectedValue _cache = new InjectedValue(); + + @Override + public void start(StartContext startContext) throws StartException { + _domainManager = new ServiceDomainManager(getSystemSecurity().getValue()); + } + + @Override + public void stop(StopContext stopContext) { + } + + @Override + public ServiceDomainManager getValue() throws IllegalStateException, IllegalArgumentException { + return _domainManager; + } + + /** + * SystemSecurity injection point. + * + * @return injected SystemSecurity + */ + public InjectedValue getSystemSecurity() { + return _systemSecurity; + } + + /** + * Cache injection point. + * + * @return injected Cache + */ + public InjectedValue getCache() { + return _cache; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardSystemSecurityService.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardSystemSecurityService.java new file mode 100644 index 000000000..fb97852f3 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/services/SwitchYardSystemSecurityService.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.services; + +import org.jboss.msc.service.Service; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.StartContext; +import org.jboss.msc.service.StartException; +import org.jboss.msc.service.StopContext; +import org.switchyard.security.system.DefaultSystemSecurity; +import org.switchyard.security.system.SystemSecurity; + +/** + * SystemSecurity Service for AS7 deployments. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public class SwitchYardSystemSecurityService implements Service { + + /** + * The name used to resolve the SystemSecurity. + */ + public final static ServiceName SERVICE_NAME = ServiceName.of(SwitchYardSystemSecurityService.class.getSimpleName()); + + private SystemSecurity _systemSecurity = null; + + @Override + public void start(StartContext startContext) throws StartException { + _systemSecurity = new DefaultSystemSecurity(); + } + + @Override + public void stop(StopContext stopContext) { + _systemSecurity = null; + } + + @Override + public SystemSecurity getValue() throws IllegalStateException, IllegalArgumentException { + return _systemSecurity; + } + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/util/ServerUtil.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/util/ServerUtil.java new file mode 100644 index 000000000..9abaa8966 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/util/ServerUtil.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.util; + +import org.apache.catalina.connector.Connector; +import org.jboss.as.server.deployment.AttachmentKey; +import org.jboss.as.web.VirtualHost; +import org.jboss.as.web.WebSubsystemServices; +import org.jboss.metadata.web.jboss.JBossWebMetaData; +import org.jboss.msc.service.ServiceController; +import org.jboss.msc.service.ServiceRegistry; + +/** + * Utility class for AS7 related functions. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class ServerUtil { + + /** + * The attachment key for web.xml. + */ + public static final AttachmentKey JBOSSWEB_METADATA_KEY = AttachmentKey.create(JBossWebMetaData.class); + + private static ServiceRegistry _registry; + private static String _host = "default-host"; + + private ServerUtil() { + } + + /** + * Set the JBoss container's Service Registry. + * @param registry the ServiceRegistry + */ + public static void setRegistry(ServiceRegistry registry) { + _registry = registry; + } + + /** + * Get the JBoss container's Service Registry. + * @return the ServiceRegistry + */ + public static ServiceRegistry getRegistry() { + return _registry; + } + + /** + * Set the JBoss container's Host Name. + * @param host the name of the host + */ + public static void setHostName(String host) { + _host = host; + } + + /** + * Get the JBoss container's Host Name. + * @return the name of the host + */ + public static String getHostName() { + return _host; + } + + /** + * Get the JBoss container's VirtualHost. + * @return the VirtualHost + */ + public static VirtualHost getDefaultHost() { + ServiceController service = (ServiceController)_registry.getService(WebSubsystemServices.JBOSS_WEB_HOST.append(_host)); + return service != null ? service.getValue() : null; + } + + /** + * Get the JBoss container's DefaultConnector. + * @return the DefaultConnector + */ + public static Connector getDefaultConnector() { + ServiceController service = (ServiceController)_registry.getService( + WebSubsystemServices.JBOSS_WEB_CONNECTOR.append("http")); + return service != null ? service.getValue() : null; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/Interceptors.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/Interceptors.java new file mode 100644 index 000000000..b098c552e --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/Interceptors.java @@ -0,0 +1,303 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.ws; + +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.cxf.common.util.StringUtils; +import org.apache.cxf.feature.Feature; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.interceptor.OneWayProcessorInterceptor; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.ws.addressing.WSAddressingFeature; +import org.apache.cxf.ws.addressing.soap.DecoupledFaultHandler; +import org.apache.cxf.ws.policy.AssertionInfo; +import org.apache.cxf.ws.policy.AssertionInfoMap; +import org.apache.cxf.ws.security.policy.SP12Constants; +import org.apache.cxf.ws.security.policy.model.SignedEncryptedParts; +import org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JInInterceptor; +import org.apache.neethi.Assertion; +import org.jboss.security.SecurityContextAssociation; +import org.jboss.wsf.spi.deployment.Endpoint; +import org.jboss.wsf.stack.cxf.configuration.BusHolder; +import org.jboss.wsf.stack.cxf.configuration.NonSpringBusHolder; +import org.jboss.wsf.stack.cxf.deployment.EndpointImpl; +import org.jboss.wsf.stack.cxf.security.authentication.SubjectCreatingInterceptor; +import org.jboss.wsf.stack.cxf.security.authentication.SubjectCreatingPolicyInterceptor; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.common.type.reflect.FieldAccess; +import org.switchyard.component.soap.AddressingInterceptor; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.config.model.InterceptorModel; +import org.switchyard.component.soap.config.model.InterceptorsModel; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.config.model.property.PropertiesModel; +import org.switchyard.security.credential.ConfidentialityCredential; + +/** + * Interceptor functions. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +public final class Interceptors { + + private static final String SLASH_STR = "/"; + private static final String QUESTION_MARK_STR = "?"; + private static final String QUESTION_MARK_REGEXP_STR = "\\?"; + private static final String NULL_STR = "null"; + private static final String HTTP_POST = "POST"; + + private static final Class[][] PARAMETER_TYPES = new Class[][]{ + new Class[]{Map.class}, + new Class[0] + }; + + /** + * Adds any binding model-configured inInterceptors and outInterceptors to the endpoint. + * @param endpoint the endpoint + * @param bindingModel the binding model + * @param loader the classloader to use + */ + public static void addInterceptors(Endpoint endpoint, SOAPBindingModel bindingModel, ClassLoader loader) { + BusHolder busHolder = endpoint.getService().getDeployment().getAttachment(BusHolder.class); + if (busHolder instanceof NonSpringBusHolder) { + List list = new FieldAccess>(NonSpringBusHolder.class, "endpoints").read(busHolder); + for (Object o : list) { + for (org.apache.cxf.endpoint.Endpoint e : ((EndpointImpl)o).getService().getEndpoints().values()) { + checkAddressingEnabled(e); + e.getInInterceptors().add(new SwitchYardURIMappingInterceptor()); + e.getInInterceptors().add(new SwitchYardDispatchInterceptor()); + e.getInInterceptors().add(new SwitchYardEncryptionConfidentialityInterceptor()); + e.getInInterceptors().addAll(getConfiguredInInterceptors(bindingModel, loader)); + e.getOutInterceptors().addAll(getConfiguredOutInterceptors(bindingModel, loader)); + e.getOutInterceptors().add(new SwitchYardSecurityCleanupOutInterceptor()); + e.getOutFaultInterceptors().add(new SwitchYardSecurityCleanupOutFaultInterceptor()); + } + } + } + } + + private static void checkAddressingEnabled(org.apache.cxf.endpoint.Endpoint e) { + for (Feature feature : e.getActiveFeatures()) { + if (feature instanceof WSAddressingFeature) { + //TODO: remove this DecoupledFaultHandler once CXF is upgraded, see JBWS-3516 + e.getInInterceptors().add(new DecoupledFaultHandler()); + e.getOutInterceptors().add(new AddressingInterceptor()); + e.getOutFaultInterceptors().add(new AddressingInterceptor()); + break; + } + } + } + + /** + * Gets any binding model-configured inInterceptors. + * @param the type of Interceptor + * @param bindingModel the binding model + * @param loader the classloader to use + * @return the inInterceptors + */ + public static > List getConfiguredInInterceptors(SOAPBindingModel bindingModel, ClassLoader loader) { + if (bindingModel != null) { + return getConfiguredInterceptors(bindingModel.getInInterceptors(), loader); + } + return null; + } + + /** + * Gets any binding model-configured outInterceptors. + * @param the type of Interceptor + * @param bindingModel the binding model + * @param loader the classloader to use + * @return the outInterceptors + */ + public static > List getConfiguredOutInterceptors(SOAPBindingModel bindingModel, ClassLoader loader) { + if (bindingModel != null) { + return getConfiguredInterceptors(bindingModel.getOutInterceptors(), loader); + } + return null; + } + + private static > List getConfiguredInterceptors(InterceptorsModel interceptorsModel, ClassLoader loader) { + List interceptors = new ArrayList(); + if (interceptorsModel != null) { + for (InterceptorModel interceptorModel : interceptorsModel.getInterceptors()) { + if (interceptorModel != null) { + @SuppressWarnings("unchecked") + Class interceptorClass = (Class)interceptorModel.getClazz(loader); + if (interceptorClass != null) { + PropertiesModel propertiesModel = interceptorModel.getProperties(); + Map properties = propertiesModel != null ? propertiesModel.toMap() : new HashMap(); + T interceptor = newInterceptor(interceptorClass, properties); + if (interceptor != null) { + if (interceptor instanceof SubjectCreatingInterceptor) { + ((SubjectCreatingInterceptor)interceptor).setPropagateContext(true); + } else if (interceptor instanceof SubjectCreatingPolicyInterceptor) { + ((SubjectCreatingPolicyInterceptor)interceptor).setPropagateContext(true); + } + interceptors.add(interceptor); + } + } + } + } + } + return interceptors; + } + + private static > T newInterceptor(Class interceptorClass, Map properties) { + T interceptor = null; + Constructor constructor = getConstructor(interceptorClass); + Class[] parameterTypes = constructor != null ? constructor.getParameterTypes() : new Class[0]; + try { + if (parameterTypes.length == 0) { + interceptor = Construction.construct(interceptorClass); + } else if (parameterTypes.length == 1) { + interceptor = Construction.construct(interceptorClass, parameterTypes, new Object[]{properties}); + } + } catch (Throwable t) { + throw ExtensionMessages.MESSAGES.couldNotInstantiateInterceptor(interceptorClass.getName(), t); + } + return interceptor; + } + + private static > Constructor getConstructor(Class interceptorClass) { + Constructor constructor = null; + for (Class[] parameterTypes : PARAMETER_TYPES) { + try { + constructor = interceptorClass.getConstructor(parameterTypes); + if (constructor != null) { + break; + } + } catch (Throwable t) { + // keep checkstyle happy ("at least one statement") + t.getMessage(); + } + } + return constructor; + } + + private static final class SwitchYardEncryptionConfidentialityInterceptor extends AbstractPhaseInterceptor { + private SwitchYardEncryptionConfidentialityInterceptor() { + super(Phase.POST_PROTOCOL); + getAfter().add(PolicyBasedWSS4JInInterceptor.class.getName()); + } + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(Message message) throws Fault { + AssertionInfoMap aim = message.get(AssertionInfoMap.class); + if (aim != null) { + // http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/ws-securitypolicy-1.2-spec-os.html#_Toc161826515 + Collection ais = aim.getAssertionInfo(SP12Constants.ENCRYPTED_PARTS); + if (ais != null) { + for (AssertionInfo ai : ais) { + Assertion a = ai.getAssertion(); + if (a instanceof SignedEncryptedParts) { + SignedEncryptedParts sep = (SignedEncryptedParts)a; + if (!sep.isIgnorable() && !sep.isOptional()) { + InboundHandler.getCredentials().add(new ConfidentialityCredential(true)); + break; + } + } + } + } + } + } + } + + private static class SwitchYardSecurityCleanupInterceptor extends AbstractPhaseInterceptor { + private SwitchYardSecurityCleanupInterceptor() { + super(Phase.POST_LOGICAL_ENDING); + } + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(Message message) throws Fault { + InboundHandler.unsetCredentials(); + SecurityContextAssociation.clearSecurityContext(); + } + /** + * {@inheritDoc} + */ + @Override + public void handleFault(Message message) { + InboundHandler.unsetCredentials(); + SecurityContextAssociation.clearSecurityContext(); + } + } + + private static final class SwitchYardDispatchInterceptor extends AbstractPhaseInterceptor { + private SwitchYardDispatchInterceptor() { + super(Phase.POST_PROTOCOL); + } + @Override + public void handleMessage(Message message) throws Fault { + // SWITCHYARD-1936 : prevent timing issues with web container by using original thread + message.setContextualProperty(OneWayProcessorInterceptor.USE_ORIGINAL_THREAD, true); + } + } + + private static final class SwitchYardURIMappingInterceptor extends AbstractPhaseInterceptor { + + private SwitchYardURIMappingInterceptor() { + super(Phase.PRE_PROTOCOL); + } + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(Message message) throws Fault { + String method = (String)message.get(Message.HTTP_REQUEST_METHOD); + if (method.equals(HTTP_POST)) { + return; + } + + String path = (String)message.get(Message.PATH_INFO); + String basePath = (String)message.get(Message.BASE_PATH); + if (basePath == null) { + basePath = SLASH_STR; + } + String rest = StringUtils.diff(path, basePath); + String opName = StringUtils.getFirstNotEmpty(rest, SLASH_STR); + if (opName.indexOf(QUESTION_MARK_STR) != -1) { + opName = opName.split(QUESTION_MARK_REGEXP_STR)[0]; + } + // Funny, we have to check for a 'null' String :) + if ((opName == null) || opName.equals(NULL_STR)) { + String pathInfo = (String)message.get(Message.PATH_INFO); + pathInfo = pathInfo.split(NULL_STR)[0]; + if (!pathInfo.endsWith(SLASH_STR)) { + pathInfo = pathInfo.concat(SLASH_STR); + } + throw new Fault(ExtensionMessages.MESSAGES.noSuchOperationGet(method, pathInfo)); + } + } + } + // class simple names must be unique + private static final class SwitchYardSecurityCleanupOutInterceptor extends SwitchYardSecurityCleanupInterceptor {} + private static final class SwitchYardSecurityCleanupOutFaultInterceptor extends SwitchYardSecurityCleanupInterceptor {} + + private Interceptors() {} + +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpoint.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpoint.java new file mode 100644 index 000000000..d8196d20c --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpoint.java @@ -0,0 +1,142 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.ws; + +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Map; +import java.util.ServiceLoader; + +import javax.xml.ws.WebServiceException; + +import org.jboss.as.security.plugins.SecurityDomainContext; +import org.jboss.as.webservices.security.SecurityDomainContextAdaptor; +import org.jboss.logging.Logger; +import org.jboss.wsf.spi.classloading.ClassLoaderProvider; +import org.jboss.wsf.spi.metadata.webservices.JBossWebservicesFactory; +import org.jboss.wsf.spi.metadata.webservices.JBossWebservicesMetaData; +import org.jboss.wsf.spi.metadata.webservices.WebservicesMetaData; +import org.jboss.wsf.spi.publish.Context; +import org.jboss.wsf.spi.publish.EndpointPublisher; +import org.jboss.wsf.spi.publish.EndpointPublisherFactory; +import org.switchyard.ServiceDomain; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.WebServicePublishException; +import org.switchyard.component.soap.config.model.EndpointConfigModel; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.endpoint.BaseWebService; + +/** + * Wrapper for JBossWS endpoints. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JBossWSEndpoint implements Endpoint { + + private static final Logger LOGGER = Logger.getLogger("org.switchyard"); + + private static final String HOST = "default-host"; + private static final EndpointPublisherFactory FACTORY; + + private EndpointPublisher _publisher; + private Context _context; + + /** + * Construct a JBossWS endpoint on default host. + * @throws Exception If a publisher could not be created + */ + public JBossWSEndpoint() throws Exception { + _publisher = FACTORY.newEndpointPublisher(HOST); + } + + /** + * Construct a JBossWS endpoint on specified host. + * @param host The host on which the pubhlisher should created + * @throws Exception if a publisher could not be created + */ + public JBossWSEndpoint(String host) throws Exception { + _publisher = FACTORY.newEndpointPublisher(host); + } + + /** + * {@inheritDoc} + */ + public void publish(ServiceDomain domain, String contextRoot, Map urlPatternToClassNameMap, WebservicesMetaData wsMetadata, SOAPBindingModel bindingModel, InboundHandler handler) throws Exception { + EndpointConfigModel epcModel = bindingModel.getEndpointConfig(); + JBossWebservicesMetaData jbwsMetadata = null; + if (epcModel != null) { + String configName = epcModel.getConfigName(); + String configFile = epcModel.getConfigFile(); + if (configFile != null) { + URL jbwsURL = Classes.getResource(configFile, getClass()); + try { + JBossWebservicesFactory factory = new JBossWebservicesFactory(jbwsURL); + jbwsMetadata = factory.load(jbwsURL); + } catch (WebServiceException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.error("Unable to load jboss-webservices metadata", e); + } + jbwsMetadata = new JBossWebservicesMetaData("/", configName, configFile, jbwsURL, null, null, null); + } + } + } + ClassLoader tccl = Classes.getTCCL(); + _context = _publisher.publish(contextRoot, tccl, urlPatternToClassNameMap, wsMetadata, jbwsMetadata); + for (org.jboss.wsf.spi.deployment.Endpoint ep : _context.getEndpoints()) { + BaseWebService wsProvider = (BaseWebService)ep.getInstanceProvider().getInstance(BaseWebService.class.getName()).getValue(); + wsProvider.setInvocationClassLoader(tccl); + // Hook the handler + wsProvider.setConsumer(handler); + // Hook the interceptors + Interceptors.addInterceptors(ep, bindingModel, tccl); + // Set the security domain + ep.setSecurityDomainContext(new SwitchYardSecurityDomainContext( + domain.getServiceSecurity(bindingModel.getService().getComponentService().getSecurity()).getSecurityDomain(), + ep.getSecurityDomainContext())); + } + } + + /** + * {@inheritDoc} + */ + public void start() { + } + + /** + * {@inheritDoc} + */ + public void stop() { + if (_context != null && _publisher != null) { + try { + //undeploy endpoints + _publisher.destroy(_context); + } catch (Exception e) { + LOGGER.error(e); + } + } + } + + static { + try { + ClassLoader loader = ClassLoaderProvider.getDefaultProvider().getWebServiceSubsystemClassLoader(); + FACTORY = ServiceLoader.load(EndpointPublisherFactory.class, loader).iterator().next(); + } catch (Exception e) { + throw new WebServicePublishException(e); + } + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpointPublisher.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpointPublisher.java new file mode 100644 index 000000000..e269efc60 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpointPublisher.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.ws; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.ws.WebServiceFeature; +import javax.xml.ws.soap.AddressingFeature; +import javax.xml.ws.soap.MTOMFeature; + +import org.jboss.logging.Logger; +import org.jboss.wsf.spi.metadata.webservices.PortComponentMetaData; +import org.jboss.wsf.spi.metadata.webservices.WebserviceDescriptionMetaData; +import org.jboss.wsf.spi.metadata.webservices.WebservicesMetaData; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.WebServicePublishException; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.endpoint.AbstractEndpointPublisher; + +/** + * Handles publishing of Webservice Endpoints on JBossWS stack. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JBossWSEndpointPublisher extends AbstractEndpointPublisher { + + private static final Logger LOGGER = Logger.getLogger("org.switchyard"); + + private static final String SEI = "org.switchyard.component.soap.endpoint.BaseWebService"; + private static final String RESPONSE_STATUS_HANDLER = "ResponseStatusHandler"; + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, final SOAPBindingModel config, final String bindingId, final InboundHandler handler, WebServiceFeature... features) { + JBossWSEndpoint wsEndpoint = null; + try { + initialize(config); + Map map = new HashMap(); + map.put("/" + config.getPort().getServiceName(), SEI); + Boolean addressingEnabled = false; + Boolean addressingRequired = false; + Boolean mtomEnabled = false; + Integer mtomThreshold = -1; + for (WebServiceFeature feature : features) { + if (feature instanceof AddressingFeature) { + AddressingFeature addrFeature = (AddressingFeature)feature; + addressingEnabled = addrFeature.isEnabled(); + addressingRequired = addrFeature.isRequired(); + LOGGER.info("Addressing [enabled = " + addrFeature.isEnabled() + ", required = " + addrFeature.isRequired() + "]"); + } else if (feature instanceof MTOMFeature) { + MTOMFeature mtom = (MTOMFeature)feature; + mtomEnabled = mtom.isEnabled(); + mtomThreshold = mtom.getThreshold(); + LOGGER.info("MTOM [enabled = " + mtom.isEnabled() + ", threshold = " + mtom.getThreshold() + "]"); + } + } + PortComponentMetaData portComponent = new PortComponentMetaData(config.getServiceName() + + ":" + config.getPort().getServiceQName().getLocalPart() + + ":" + config.getPort().getPortQName().getLocalPart(), + config.getPort().getPortQName(), + SEI, null, config.getPort().getServiceQName().getLocalPart(), + null, "/" + config.getPort().getServiceName(), + addressingEnabled, addressingRequired, "ALL", mtomEnabled, mtomThreshold, + false, config.getPort().getServiceQName(), null, null); + WebserviceDescriptionMetaData wsDescMetaData = new WebserviceDescriptionMetaData(config.getServiceName().getLocalPart(), getWsdlLocation(), null, new PortComponentMetaData[]{portComponent}); + WebservicesMetaData wsMetadata = new WebservicesMetaData(null, new WebserviceDescriptionMetaData[]{wsDescMetaData}); + + wsEndpoint = new JBossWSEndpoint(); + if (config.getContextPath() != null) { + wsEndpoint.publish(domain, getContextRoot(), map, wsMetadata, config, handler); + } else { + wsEndpoint.publish(domain, getContextPath(), map, wsMetadata, config, handler); + } + } catch (Exception e) { + throw new WebServicePublishException(e); + } + return wsEndpoint; + } +} diff --git a/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/SwitchYardSecurityDomainContext.java b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/SwitchYardSecurityDomainContext.java new file mode 100644 index 000000000..37e179088 --- /dev/null +++ b/release/jboss-as7/extension/src/main/java/org/switchyard/as7/extension/ws/SwitchYardSecurityDomainContext.java @@ -0,0 +1,64 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.ws; + +import java.security.Principal; +import java.util.Set; + +import javax.security.auth.Subject; + + +import org.jboss.as.webservices.security.SecurityDomainContextAdaptor; +import org.jboss.wsf.spi.security.SecurityDomainContext; + +public class SwitchYardSecurityDomainContext implements SecurityDomainContext { + + private SecurityDomainContext _context; + private String _domain; + + public SwitchYardSecurityDomainContext(String domain, SecurityDomainContext context) { + _domain = domain; + _context = context; + } + + @Override + public boolean isValid(Principal principal, Object credential, Subject activeSubject) { + return _context.isValid(principal, credential, activeSubject); + } + + @Override + public boolean doesUserHaveRole(Principal principal, Set roles) { + return _context.doesUserHaveRole(principal, roles); + } + + @Override + public String getSecurityDomain() { + if (_domain != null) { + return _domain; + } else { + return _context.getSecurityDomain(); + } + } + + @Override + public Set getUserRoles(Principal principal) { + return _context.getUserRoles(principal); + } + + @Override + public void pushSubjectContext(final Subject subject, final Principal principal, final Object credential) { + _context.pushSubjectContext(subject, principal, credential); + } +} diff --git a/release/jboss-as7/extension/src/main/resources/META-INF/cxf/bus-extensions.txt b/release/jboss-as7/extension/src/main/resources/META-INF/cxf/bus-extensions.txt new file mode 100644 index 000000000..304ca67e5 --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/META-INF/cxf/bus-extensions.txt @@ -0,0 +1 @@ +org.switchyard.as7.extension.camel.cxf.HttpServerDestinationFactory::true \ No newline at end of file diff --git a/release/jboss-as7/extension/src/main/resources/META-INF/services/javax.xml.ws.spi.Provider b/release/jboss-as7/extension/src/main/resources/META-INF/services/javax.xml.ws.spi.Provider new file mode 100644 index 000000000..9fa98e7ef --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/META-INF/services/javax.xml.ws.spi.Provider @@ -0,0 +1 @@ +org.jboss.wsf.stack.cxf.client.ProviderImpl diff --git a/release/jboss-as7/extension/src/main/resources/META-INF/services/org.apache.camel.spi.PackageScanClassResolver b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.apache.camel.spi.PackageScanClassResolver new file mode 100644 index 000000000..6ad495f2c --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.apache.camel.spi.PackageScanClassResolver @@ -0,0 +1 @@ +org.switchyard.as7.extension.camel.JBoss7PackageScanClassResolver diff --git a/release/jboss-as7/extension/src/main/resources/META-INF/services/org.jboss.as.controller.Extension b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.jboss.as.controller.Extension new file mode 100644 index 000000000..8dfdd377b --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.jboss.as.controller.Extension @@ -0,0 +1 @@ +org.switchyard.as7.extension.SwitchYardExtension diff --git a/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.http.endpoint.EndpointPublisher b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.http.endpoint.EndpointPublisher new file mode 100644 index 000000000..4927d2d56 --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.http.endpoint.EndpointPublisher @@ -0,0 +1,13 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +org.switchyard.as7.extension.http.JBossWebEndpointPublisher diff --git a/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.resteasy.resource.ResourcePublisher b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.resteasy.resource.ResourcePublisher new file mode 100644 index 000000000..10c144eb8 --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.resteasy.resource.ResourcePublisher @@ -0,0 +1,13 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +org.switchyard.as7.extension.resteasy.RESTEasyResourcePublisher diff --git a/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.sca.RemoteEndpointPublisher b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.sca.RemoteEndpointPublisher new file mode 100644 index 000000000..df4f9448a --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.sca.RemoteEndpointPublisher @@ -0,0 +1,13 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +org.switchyard.as7.extension.cluster.RemoteEndpointListener diff --git a/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.soap.endpoint.EndpointPublisher b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.soap.endpoint.EndpointPublisher new file mode 100644 index 000000000..96a1a8ac5 --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/META-INF/services/org.switchyard.component.soap.endpoint.EndpointPublisher @@ -0,0 +1 @@ +org.switchyard.as7.extension.ws.JBossWSEndpointPublisher diff --git a/release/jboss-as7/extension/src/main/resources/org/switchyard/as7/extension/LocalDescriptions.properties b/release/jboss-as7/extension/src/main/resources/org/switchyard/as7/extension/LocalDescriptions.properties new file mode 100644 index 000000000..2cc267943 --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/org/switchyard/as7/extension/LocalDescriptions.properties @@ -0,0 +1,104 @@ +# subsystem details +switchyard=The configuration of the SwitchYard subsystem. +switchyard.add=Operation creating the SwitchYard subsystem. +switchyard.remove=Operation to remove the SwitchYard subsystem. +switchyard.socket-binding=A comma seperated list of socket binding ports +switchyard.properties=Global properties shared across SwitchYard subsystem +switchyard.deployment=Runtime resources exposed by SwitchYard components in the deployment. +switchyard.deployment.application=Details of SwitchYard application in a deployment. + +# security-config details +switchyard.security-configs=List of SwitchYard security configs +switchyard.security-config=A SwitchYard security config +switchyard.security-config.identifier=Unique identifier for the security config +switchyard.security-config.properties=Properties specific to the security config +switchyard.security-config.add=Operation creating the SwitchYard security config. +switchyard.security-config.remove=Operation to remove the SwitchYard security config. + +# module details +switchyard.modules=List of SwitchYard components +switchyard.module=A SwitchYard component module +switchyard.module.identifier=Unique identifier for the component +switchyard.module.implClass=The component implementation class +switchyard.module.properties=Properties specific to the component +switchyard.module.add=Operation creating the SwitchYard component module. +switchyard.module.remove=Operation to remove the SwitchYard component module. + +# extension details +switchyard.extensions=List of SwitchYard extensions +switchyard.extension=A SwitchYard extension module +switchyard.extension.identifier=Unique identifier for the extension +switchyard.extension.add=Operation creating the SwitchYard extension module. +switchyard.extension.remove=Operation to remove the SwitchYard extension module. + +# get-version operation +switchyard.get-version=Operation returning the release version of the SwitchYard subsystem. +switchyard.get-version.reply=The version of the SwitchYard subsystem. + +# list-applications operation +switchyard.list-applications=Operation returning the names of all applications deployed on the SwitchYard subsystem. +switchyard.list-applications.reply=The names of all known SwitchYard applications. + +# list-services operation +switchyard.list-services=Operation returning the names of services deployed on the SwitchYard subsystem. +switchyard.list-services.param.application-name=Only return services exposed by the named application. The specified value must be convertible to a QName through QName.valueOf(). +switchyard.list-services.reply=The names of known services. +switchyard.list-services.reply.name=The name of the service. +switchyard.list-services.reply.application=The name of the containing application. + +# read-service operation +switchyard.read-service=Operation returning details for the specified services. If service-name and application-name are specified the named service is returned. If only service-name is specified, all services with the specified name are returned. If only application-name is specified, details for all services exported by the application will be returned. If no service-name or application-name are specified, details for all services known to the SwitchYard subsystem will be returned. +switchyard.read-service.param.service-name=The name of the requested service. The specified value must be convertible to a QName through QName.valueOf(). +switchyard.read-service.param.application-name=The name of an application. The specified value must be convertible to a QName through QName.valueOf(). +switchyard.read-service.reply=A list of services. +switchyard.read-service.reply.name=The service's name. +switchyard.read-service.reply.application=The containing application's name. +switchyard.read-service.reply.interface=The service's interface name. +switchyard.read-service.reply.promotedService=The component service promoted by this service. +switchyard.read-service.reply.implementation=The service's implementation type name (can be used to resolve a component). +switchyard.read-service.reply.implementationConfiguration=The service's raw implementation configuration. +switchyard.read-service.reply.gateways=The service's gateways. +switchyard.read-service.reply.gateways.gateway=The gateway type name (e.g. soap). +switchyard.read-service.reply.gateways.configuration=The raw configuration for the gateway binding. +switchyard.read-service.reply.references=The references used by this service. +switchyard.read-service.reply.references.name=The name of the reference. +switchyard.read-service.reply.references.interface=The referenced interface. + +# read-application operation +switchyard.read-application=Operation returning details for the specified application. If name is not specified, but type is specified, details are returned for all applications known to the SwitchYard subsystem. +switchyard.read-application.param.name=The name of the application. The specified value must be convertible to a QName through QName.valueOf(). +switchyard.read-application.reply=A list of applications. +switchyard.read-application.reply.name=The name of the artifact module. +switchyard.read-application.reply.services=The list of services exported by the application. +switchyard.read-application.reply.componentServices=The list of service components contained by the application. +switchyard.read-application.reply.transformers=The list of transformers contributed by the application. +switchyard.read-application.reply.transformer.from=The from type supported by the transformer. +switchyard.read-application.reply.transformer.to=The to type produced by the transformer. +switchyard.read-application.reply.transformer.type=The type of transformer (e.g. Java). +switchyard.read-application.reply.artifacts=The list of service artifact modules used by the application. +switchyard.read-application.reply.artifact.name=The artifact name. +switchyard.read-application.reply.artifact.url=The artifact URL. +switchyard.read-application.reply.url=The repository URL where the artifact module resides. +switchyard.read-application.reply.validators=The list of message validators used by the application. +switchyard.read-application.reply.validator.name=The QName for the type being validated. +switchyard.read-application.reply.validator.type=The type of validator (e.g. XML, Java, etc.). + +# uses-artifacts operation +switchyard.uses-artifacts=Operation returning the names of all applications which use a given service artifact module. +switchyard.uses-artifacts.uses-artifacts=Operation returning the one of the applications which use a given service artifact module. +switchyard.uses-artifacts.param.name=The name of the service artifact module. +switchyard.uses-artifacts.param.url=The url of the service artifact module. +switchyard.uses-artifacts.reply=The names of SwitchYard applications which reference the specified service artifact. If name or url are not specified, a list of all applications which reference artifacts is returned. +switchyard.uses-artifacts.reply.name=SwitchYard application name. + +# show-metrics operation +switchyard.show-metrics=Operation returning metrics for the specified service. If no service-name is specified, cumulative metrics for the SwitchYard runtime will be returned. +switchyard.show-metrics.param.service-name=The name of the requested service. The specified value must be convertible to a QName through QName.valueOf(). +switchyard.show-metrics.reply=A listing of service metrics. +switchyard.show-metrics.reply.successCount=The number of successful service invocations. +switchyard.show-metrics.reply.faultCount=The number of failed service invocations. +switchyard.show-metrics.reply.totalCount=The total number of service invocations. +switchyard.show-metrics.reply.averageTime=The average response time for a service. +switchyard.show-metrics.reply.minTime=The minimum response time for a service. +switchyard.show-metrics.reply.maxTime=The maximum response time for a service. +switchyard.show-metrics.reply.totalTime=The accumulated response time for all invocations of a service. diff --git a/release/jboss-as7/extension/src/main/resources/schema/jboss-switchyard.xsd b/release/jboss-as7/extension/src/main/resources/schema/jboss-switchyard.xsd new file mode 100644 index 000000000..7706f371c --- /dev/null +++ b/release/jboss-as7/extension/src/main/resources/schema/jboss-switchyard.xsd @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/README b/release/jboss-as7/modules/README new file mode 100644 index 000000000..e8f7b0c3b --- /dev/null +++ b/release/jboss-as7/modules/README @@ -0,0 +1,29 @@ +SwitchYard AS7 Deployment stuff +=============================== +1. Extract the contents of build/target/switchyard.deployer.zip to JBoss AS7 root directory +2. Edit standalone.xml or domain.xml according to the configuration used and add the following + + + ... + + + + ... + + +3. To add a component extract the contents of components/{component}/build/target/switchyard.deployer.zip to JBoss AS7 root directory +4. Add the component modules + + + + + + + + + +5. Deploy m1app +6. Test with soapUI client diff --git a/release/jboss-as7/modules/assembly.xml b/release/jboss-as7/modules/assembly.xml new file mode 100644 index 000000000..8fd715c6b --- /dev/null +++ b/release/jboss-as7/modules/assembly.xml @@ -0,0 +1,137 @@ + + + + + JBossAS7 + false + + zip + + + + + src/main/resources/layers.conf + /modules + false + + + + + src/main/resources/switchyard/core/assembly-component.xml + + + src/main/resources/switchyard/components/bean/assembly-component.xml + src/main/resources/switchyard/components/bpel/assembly-component.xml + src/main/resources/switchyard/components/bpm/assembly-component.xml + src/main/resources/switchyard/components/camel/assembly-component.xml + src/main/resources/switchyard/components/camel/amqp/assembly-component.xml + src/main/resources/switchyard/components/camel/atom/assembly-component.xml + src/main/resources/switchyard/components/camel/core/assembly-component.xml + src/main/resources/switchyard/components/camel/cxf/assembly-component.xml + src/main/resources/switchyard/components/camel/file/assembly-component.xml + src/main/resources/switchyard/components/camel/ftp/assembly-component.xml + src/main/resources/switchyard/components/camel/jms/assembly-component.xml + src/main/resources/switchyard/components/camel/jpa/assembly-component.xml + src/main/resources/switchyard/components/camel/mail/assembly-component.xml + src/main/resources/switchyard/components/camel/mqtt/assembly-component.xml + src/main/resources/switchyard/components/camel/netty/assembly-component.xml + src/main/resources/switchyard/components/camel/quartz/assembly-component.xml + src/main/resources/switchyard/components/camel/sap/assembly-component.xml + src/main/resources/switchyard/components/camel/rss/assembly-component.xml + src/main/resources/switchyard/components/camel/sql/assembly-component.xml + src/main/resources/switchyard/components/camel/switchyard/assembly-component.xml + src/main/resources/switchyard/components/http/assembly-component.xml + src/main/resources/switchyard/components/sca/assembly-component.xml + src/main/resources/switchyard/components/resteasy/assembly-component.xml + src/main/resources/switchyard/components/rules/assembly-component.xml + src/main/resources/switchyard/components/soap/assembly-component.xml + src/main/resources/switchyard/components/jca/assembly-component.xml + + + src/main/resources/switchyard/components/common/assembly-component.xml + src/main/resources/switchyard/components/common/camel/assembly-component.xml + src/main/resources/switchyard/components/common/knowledge/assembly-component.xml + + src/main/resources/switchyard/console/assembly-component.xml + + + src/main/resources/external/apache/ws/commons/axiom/api/assembly-component.xml + src/main/resources/external/apache/ws/commons/axiom/impl/assembly-component.xml + src/main/resources/external/apache/abdera/core/assembly-component.xml + src/main/resources/external/apache/abdera/i18n/assembly-component.xml + src/main/resources/external/apache/abdera/parser/assembly-component.xml + src/main/resources/external/hapi-osgi-base/assembly-component.xml + src/main/resources/external/apache/commons/collections/assembly-component.xml + src/main/resources/external/apache/mina/assembly-component.xml + src/main/resources/external/apache/commons/net/assembly-component.xml + src/main/resources/external/apache/commons/lang3/assembly-component.xml + src/main/resources/external/apache/deltaspike/core-api/assembly-component.xml + src/main/resources/external/batik/assembly-component.xml + src/main/resources/external/beanshell/assembly-component.xml + + + src/main/resources/external/camel/bindy/assembly-component.xml + src/main/resources/external/camel/atom/assembly-component.xml + src/main/resources/external/camel/cdi/assembly-component.xml + src/main/resources/external/camel/core/assembly-component.xml + src/main/resources/external/camel/cxf/assembly-component.xml + src/main/resources/external/camel/ftp/assembly-component.xml + src/main/resources/external/camel/hl7/assembly-component.xml + src/main/resources/external/camel/jms/assembly-component.xml + src/main/resources/external/camel/jaxb/assembly-component.xml + src/main/resources/external/camel/jpa/assembly-component.xml + src/main/resources/external/camel/mail/assembly-component.xml + src/main/resources/external/camel/mqtt/assembly-component.xml + src/main/resources/external/camel/mina2/assembly-component.xml + src/main/resources/external/camel/mvel/assembly-component.xml + src/main/resources/external/camel/netty/assembly-component.xml + src/main/resources/external/camel/quartz/assembly-component.xml + src/main/resources/external/camel/rss/assembly-component.xml + src/main/resources/external/camel/ognl/assembly-component.xml + src/main/resources/external/camel/script/assembly-component.xml + src/main/resources/external/camel/soap/assembly-component.xml + src/main/resources/external/camel/spring/assembly-component.xml + src/main/resources/external/camel/sap/assembly-component.xml + src/main/resources/external/camel/saxon/assembly-component.xml + src/main/resources/external/camel/sql/assembly-component.xml + + src/main/resources/external/dozer/assembly-component.xml + src/main/resources/external/freemarker/assembly-component.xml + src/main/resources/external/groovy/assembly-component.xml + src/main/resources/external/jcraft/jsch/assembly-component.xml + src/main/resources/external/jruby/assembly-component.xml + src/main/resources/external/milyn/assembly-component.xml + src/main/resources/external/ognl/assembly-component.xml + src/main/resources/external/opencsv/assembly-component.xml + src/main/resources/external/python/assembly-component.xml + src/main/resources/external/quartz/assembly-component.xml + src/main/resources/external/rome/assembly-component.xml + src/main/resources/external/rhino/assembly-component.xml + src/main/resources/external/saaj-impl/assembly-component.xml + src/main/resources/external/saxon/assembly-component.xml + src/main/resources/external/saxonhe95/assembly-component.xml + src/main/resources/external/spring/assembly-component.xml + src/main/resources/external/springframework/assembly-component.xml + src/main/resources/external/ws-impl/assembly-component.xml + src/main/resources/external/xstream/assembly-component.xml + + + src/main/resources/external/jbossws/jbossws-spi/assembly-component.xml + src/main/resources/external/jbossws/jbossws-jboss720-server-integration/assembly-component.xml + + + diff --git a/release/jboss-as7/modules/pom.xml b/release/jboss-as7/modules/pom.xml new file mode 100644 index 000000000..57d33dd86 --- /dev/null +++ b/release/jboss-as7/modules/pom.xml @@ -0,0 +1,759 @@ + + + + + org.switchyard + switchyard-container-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-modules + SwitchYard: AS7 Modules + SwitchYard AS7 Modules + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + package + + single + + + false + switchyard.deployer + + ${basedir}/assembly.xml + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-common-cdi + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-admin + + + org.switchyard + switchyard-extensions-java + + + org.switchyard + switchyard-extensions-wsdl + + + org.switchyard + switchyard-remote + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-security + + + org.switchyard + switchyard-security-jboss + + + org.switchyard + switchyard-serial + + + org.switchyard + switchyard-serial-jackson + + + + org.switchyard + switchyard-bus-camel + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-transform + + + org.switchyard + switchyard-validate + + + org.switchyard + switchyard-deploy-jboss-as7 + + + org.switchyard.components + switchyard-component-bpel + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-bpm + + + org.switchyard.components + switchyard-component-camel + + + org.switchyard.components + switchyard-component-camel-amqp + + + org.switchyard.components + switchyard-component-camel-atom + + + org.switchyard.components + switchyard-component-camel-core + + + org.switchyard.components + switchyard-component-camel-cxf + + + org.switchyard.components + switchyard-component-camel-file + + + org.switchyard.components + switchyard-component-camel-ftp + + + org.switchyard.components + switchyard-component-camel-jms + + + org.switchyard.components + switchyard-component-camel-jpa + + + org.switchyard.components + switchyard-component-camel-mail + + + org.switchyard.components + switchyard-component-camel-mqtt + + + org.switchyard.components + switchyard-component-camel-netty + + + org.switchyard.components + switchyard-component-camel-quartz + + + org.switchyard.components + switchyard-component-camel-rss + + + org.switchyard.components + switchyard-component-camel-sap + + + com.sap.conn.jco + sapjco3 + + + + + org.switchyard.components + switchyard-component-camel-sql + + + org.switchyard.components + switchyard-component-camel-switchyard + + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-common-camel + + + org.switchyard.components + switchyard-component-common-knowledge + + + org.switchyard.components + switchyard-component-resteasy + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard.components + switchyard-component-rules + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-http + + + org.switchyard.components + switchyard-component-jca + + + org.switchyard.console + switchyard-console-application + resources + + + + com.h2database + h2 + + + + org.riftsaw + engine + + + org.jboss.soa.bpel + riftsaw-agents + + + org.jboss.soa.bpel + riftsaw-bpel-api + + + org.jboss.soa.bpel + riftsaw-bpel-compiler + + + org.jboss.soa.bpel + riftsaw-bpel-dao + + + org.jboss.soa.bpel + riftsaw-bpel-epr + + + org.jboss.soa.bpel + riftsaw-bpel-obj + + + org.jboss.soa.bpel + riftsaw-bpel-ql + + + org.jboss.soa.bpel + riftsaw-bpel-runtime + + + org.jboss.soa.bpel + riftsaw-bpel-schemas + + + org.jboss.soa.bpel + riftsaw-bpel-store + + + org.jboss.soa.bpel + riftsaw-dao-jpa + + + org.jboss.soa.bpel + riftsaw-dao-jpa-hibernate + + + org.jboss.soa.bpel + riftsaw-jacob + + + org.jboss.soa.bpel + riftsaw-scheduler-simple + + + org.jboss.soa.bpel + riftsaw-utils + + + + org.apache.xmlgraphics + batik-dom + + + org.apache.xmlgraphics + batik-svg-dom + + + org.apache.xmlgraphics + batik-svggen + + + org.apache.xmlgraphics + batik-util + + + org.apache.xmlgraphics + batik-css + + + org.apache.xmlgraphics + batik-ext + + + org.apache.xmlgraphics + batik-xml + + + org.apache.xmlgraphics + batik-transcoder + + + org.apache.xmlgraphics + batik-bridge + + + org.apache.xmlgraphics + batik-gvt + + + org.apache.xmlgraphics + batik-script + + + org.apache.xmlgraphics + batik-awt-util + + + org.apache.xmlgraphics + batik-parser + + + org.apache.xmlgraphics + batik-anim + + + org.apache.xmlgraphics + batik-codec + + + org.beanshell + bsh + + + org.apache.ws.commons.axiom + axiom-impl + + + xml-apis + xml-apis-ext + + + xml-apis + xml-apis + + + + org.riftsaw.console + riftsaw-bpel2svg + + + org.riftsaw.console + riftsaw-console-integration + + + org.riftsaw.console + riftsaw-bpaf + + + org.jboss.bpm + activity-monitor-model + + + org.jboss.bpm + gwt-console-rpc + + + org.jboss.bpm + gwt-console-server-integration + + + org.overlord + overlord-commons-services + + + org.codehaus.jettison + jettison + + + + org.springframework + spring-aop + + + org.springframework + spring-beans + + + org.springframework + spring-context + + + org.springframework + spring-core + + + org.springframework + spring-expression + + + org.springframework + spring-tx + + + org.springframework + spring-jms + + + org.springframework + spring-jdbc + + + org.springframework + spring-orm + + + + org.apache.camel + camel-bindy + + + org.apache.camel + camel-atom + + + org.apache.camel + camel-core + + + org.apache.camel + camel-cdi + + + deltaspike-core-impl + org.apache.deltaspike.core + + + deltaspike-cdictrl-api + org.apache.deltaspike.cdictrl + + + + + org.apache.camel + camel-spring + + + org.apache.camel + camel-hl7 + + + org.apache.camel + camel-jaxb + + + org.apache.camel + camel-jms + + + org.apache.camel + camel-jpa + + + org.apache.camel + camel-ftp + + + org.apache.camel + camel-mail + + + org.apache.camel + camel-mqtt + + + org.apache.camel + camel-mina2 + + + org.apache.camel + camel-mvel + + + org.apache.camel + camel-netty + + + org.apache.camel + camel-quartz + + + org.apache.camel + camel-rss + + + org.apache.camel + camel-ognl + + + org.apache.camel + camel-script + + + org.apache.camel + camel-sql + + + org.apache.camel + camel-soap + + + org.apache.camel + camel-cxf + + + org.apache.camel + camel-saxon + + + org.fusesource + camel-sap + + + com.sap.conn.jco + sapjco3 + + + + + org.quartz-scheduler + quartz + + + rhino + js + + + org.apache.deltaspike.core + deltaspike-core-api + + + + org.clojure + clojure + + + + ognl + ognl + + + + org.apache.ws.commons.axiom + axiom-api + + + org.apache.abdera + abdera-core + + + org.apache.abdera + abdera-i18n + + + org.apache.abdera + abdera-parser + + + com.thoughtworks.xstream + xstream + + + org.python + jython + + + net.sourceforge.saxon + saxonhe + + + net.sf.saxon + Saxon-HE + + + org.apache.xmlbeans + xmlbeans + + + org.freemarker + freemarker + + + org.codehaus.groovy + groovy-all + + + org.milyn + milyn-smooks-all + + + net.sf.dozer + dozer + + + net.sf.opencsv + opencsv + + + rome + rome + + + wsdl4j + wsdl4j + + + com.jcraft + jsch + + + org.jruby + jruby + + + commons-net + commons-net + + + commons-collections + commons-collections + + + org.apache.commons + commons-lang3 + + + + org.jboss.ws + jbossws-spi + + + org.jboss.ws + jbossws-jboss720-server-integration + + + ca.uhn.hapi + hapi-osgi-base + + + org.apache.mina + mina-core + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/README.md b/release/jboss-as7/modules/src/main/resources/external/README.md new file mode 100644 index 000000000..707f33ab0 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/README.md @@ -0,0 +1 @@ +Only external (non SwitchYard) modules should be located in this folder. \ No newline at end of file diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/abdera/core/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/core/assembly-component.xml new file mode 100644 index 000000000..5c1d816eb --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/core/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/abdera/core/module.xml + /modules/system/layers/soa/org/apache/abdera/abdera-core/main + true + + + + + /modules/system/layers/soa/org/apache/abdera/abdera-core/main + + org.apache.abdera:abdera-core + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/abdera/core/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/core/module.xml new file mode 100644 index 000000000..ef959c472 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/core/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/abdera/i18n/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/i18n/assembly-component.xml new file mode 100644 index 000000000..2454cf017 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/i18n/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/abdera/i18n/module.xml + /modules/system/layers/soa/org/apache/abdera/abdera-i18n/main + true + + + + + /modules/system/layers/soa/org/apache/abdera/abdera-i18n/main + + org.apache.abdera:abdera-i18n + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/abdera/i18n/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/i18n/module.xml new file mode 100644 index 000000000..28e0540a3 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/i18n/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/abdera/parser/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/parser/assembly-component.xml new file mode 100644 index 000000000..d4ab79594 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/parser/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/abdera/parser/module.xml + /modules/system/layers/soa/org/apache/abdera/abdera-parser/main + true + + + + + /modules/system/layers/soa/org/apache/abdera/abdera-parser/main + + org.apache.abdera:abdera-parser + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/abdera/parser/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/parser/module.xml new file mode 100644 index 000000000..64fed7760 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/abdera/parser/module.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/commons/collections/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/commons/collections/assembly-component.xml new file mode 100644 index 000000000..5b47915eb --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/commons/collections/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/commons/collections/module.xml + /modules/system/layers/soa/org/apache/commons/collections/main + true + + + + + /modules/system/layers/soa/org/apache/commons/collections/main + + commons-collections:commons-collections + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/commons/collections/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/commons/collections/module.xml new file mode 100644 index 000000000..f3faf5a83 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/commons/collections/module.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/commons/lang3/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/commons/lang3/assembly-component.xml new file mode 100644 index 000000000..6a2859de0 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/commons/lang3/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/commons/lang3/module.xml + /modules/system/layers/soa/org/apache/commons/lang3/main + true + + + + + /modules/system/layers/soa/org/apache/commons/lang3/main + + org.apache.commons:commons-lang3 + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/commons/lang3/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/commons/lang3/module.xml new file mode 100644 index 000000000..a3ee0120e --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/commons/lang3/module.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/commons/net/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/commons/net/assembly-component.xml new file mode 100644 index 000000000..c86a52ff2 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/commons/net/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/commons/net/module.xml + /modules/system/layers/soa/org/apache/commons/net/main + true + + + + + /modules/system/layers/soa/org/apache/commons/net/main + + commons-net:commons-net + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/commons/net/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/commons/net/module.xml new file mode 100644 index 000000000..234aae6e4 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/commons/net/module.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/deltaspike/core-api/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/deltaspike/core-api/assembly-component.xml new file mode 100644 index 000000000..0dc9eb67d --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/deltaspike/core-api/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/deltaspike/core-api/module.xml + /modules/system/layers/soa/org/apache/deltaspike/core-api/main + true + + + + + /modules/system/layers/soa/org/apache/deltaspike/core-api/main + + org.apache.deltaspike.core:deltaspike-core-api + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/deltaspike/core-api/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/deltaspike/core-api/module.xml new file mode 100644 index 000000000..3ad01143d --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/deltaspike/core-api/module.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/mina/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/mina/assembly-component.xml new file mode 100644 index 000000000..533931711 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/mina/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/mina/module.xml + /modules/system/layers/soa/org/apache/mina/main + true + + + + + /modules/system/layers/soa/org/apache/mina/main + + org.apache.mina:mina-core + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/mina/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/mina/module.xml new file mode 100644 index 000000000..148ceffaa --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/mina/module.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/api/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/api/assembly-component.xml new file mode 100644 index 000000000..1010c28ba --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/api/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/ws/commons/axiom/api/module.xml + /modules/system/layers/soa/org/apache/ws/commons/axiom/axiom-api/main + true + + + + + /modules/system/layers/soa/org/apache/ws/commons/axiom/axiom-api/main + + org.apache.ws.commons.axiom:axiom-api + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/api/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/api/module.xml new file mode 100644 index 000000000..5e698ff4c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/api/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/impl/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/impl/assembly-component.xml new file mode 100644 index 000000000..12eca1e86 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/impl/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/apache/ws/commons/axiom/impl/module.xml + /modules/system/layers/soa/org/apache/ws/commons/axiom/axiom-impl/main + true + + + + + /modules/system/layers/soa/org/apache/ws/commons/axiom/axiom-impl/main + + org.apache.ws.commons.axiom:axiom-impl + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/impl/module.xml b/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/impl/module.xml new file mode 100644 index 000000000..7ff551dcd --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/apache/ws/commons/axiom/impl/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/batik/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/batik/assembly-component.xml new file mode 100644 index 000000000..704157e36 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/batik/assembly-component.xml @@ -0,0 +1,66 @@ + + + + + + src/main/resources/external/batik/module.xml + /modules/system/layers/soa/org/apache/xmlgraphics/main + true + + + + + /modules/system/layers/soa/org/apache/xmlgraphics/main + + org.apache.xmlgraphics:batik-anim + org.apache.xmlgraphics:batik-awt-util + org.apache.xmlgraphics:batik-bridge + org.apache.xmlgraphics:batik-codec + org.apache.xmlgraphics:batik-css + org.apache.xmlgraphics:batik-dom + org.apache.xmlgraphics:batik-ext + org.apache.xmlgraphics:batik-gvt + org.apache.xmlgraphics:batik-parser + org.apache.xmlgraphics:batik-script + org.apache.xmlgraphics:batik-svg-dom + org.apache.xmlgraphics:batik-svggen + org.apache.xmlgraphics:batik-transcoder + org.apache.xmlgraphics:batik-util + org.apache.xmlgraphics:batik-xml + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + /modules/system/layers/soa/org/apache/xmlgraphics/main + + org.apache.ws.commons.axiom:axiom-api + org.apache.ws.commons.axiom:axiom-impl + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + /modules/system/layers/soa/org/apache/xmlgraphics/main + + xml-apis:xml-apis-ext + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/batik/module.xml b/release/jboss-as7/modules/src/main/resources/external/batik/module.xml new file mode 100644 index 000000000..3b1d5019c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/batik/module.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/beanshell/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/beanshell/assembly-component.xml new file mode 100644 index 000000000..a4ea2c2b7 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/beanshell/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/beanshell/module.xml + /modules/system/layers/soa/org/beanshell/main + true + + + + + /modules/system/layers/soa/org/beanshell/main + + org.beanshell:bsh + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/beanshell/module.xml b/release/jboss-as7/modules/src/main/resources/external/beanshell/module.xml new file mode 100644 index 000000000..feeb53ac7 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/beanshell/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/atom/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/atom/assembly-component.xml new file mode 100644 index 000000000..e8f838bbd --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/atom/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/atom/module.xml + /modules/system/layers/soa/org/apache/camel/atom/main + true + + + + + /modules/system/layers/soa/org/apache/camel/atom/main + + org.apache.camel:camel-atom + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/atom/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/atom/module.xml new file mode 100644 index 000000000..24aa7520c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/atom/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/bindy/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/bindy/assembly-component.xml new file mode 100644 index 000000000..c93427b1e --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/bindy/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/bindy/module.xml + /modules/system/layers/soa/org/apache/camel/bindy/main + true + + + + + /modules/system/layers/soa/org/apache/camel/bindy/main + + org.apache.camel:camel-bindy + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/bindy/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/bindy/module.xml new file mode 100644 index 000000000..15a21ab7f --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/bindy/module.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/cdi/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/cdi/assembly-component.xml new file mode 100644 index 000000000..647c59c85 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/cdi/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/cdi/module.xml + /modules/system/layers/soa/org/apache/camel/cdi/main + true + + + + + /modules/system/layers/soa/org/apache/camel/cdi/main + + org.apache.camel:camel-cdi + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/cdi/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/cdi/module.xml new file mode 100644 index 000000000..fa2d962df --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/cdi/module.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/core/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/core/assembly-component.xml new file mode 100644 index 000000000..1f9263d5a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/core/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/core/module.xml + /modules/system/layers/soa/org/apache/camel/core/main + true + + + + + /modules/system/layers/soa/org/apache/camel/core/main + + org.apache.camel:camel-core + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/core/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/core/module.xml new file mode 100644 index 000000000..d02b9f771 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/core/module.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/cxf/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/cxf/assembly-component.xml new file mode 100644 index 000000000..5468b5b71 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/cxf/assembly-component.xml @@ -0,0 +1,36 @@ + + + + + + src/main/resources/external/camel/cxf/module.xml + /modules/system/layers/soa/org/apache/camel/cxf/main + true + + + + + /modules/system/layers/soa/org/apache/camel/cxf/main + + org.apache.camel:camel-cxf + org.apache.camel:camel-cxf-transport + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/cxf/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/cxf/module.xml new file mode 100644 index 000000000..59ca46397 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/cxf/module.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/ftp/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/ftp/assembly-component.xml new file mode 100644 index 000000000..b9e8e2dba --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/ftp/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/ftp/module.xml + /modules/system/layers/soa/org/apache/camel/ftp/main + true + + + + + /modules/system/layers/soa/org/apache/camel/ftp/main + + org.apache.camel:camel-ftp + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/ftp/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/ftp/module.xml new file mode 100644 index 000000000..cff15ce8d --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/ftp/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/hl7/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/hl7/assembly-component.xml new file mode 100644 index 000000000..31fa49c5b --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/hl7/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/hl7/module.xml + /modules/system/layers/soa/org/apache/camel/hl7/main + true + + + + + /modules/system/layers/soa/org/apache/camel/hl7/main + + org.apache.camel:camel-hl7 + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/hl7/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/hl7/module.xml new file mode 100644 index 000000000..9adc88d61 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/hl7/module.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/jaxb/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/jaxb/assembly-component.xml new file mode 100644 index 000000000..c15886839 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/jaxb/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/jaxb/module.xml + /modules/system/layers/soa/org/apache/camel/jaxb/main + true + + + + + /modules/system/layers/soa/org/apache/camel/jaxb/main + + org.apache.camel:camel-jaxb + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/jaxb/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/jaxb/module.xml new file mode 100644 index 000000000..539f19623 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/jaxb/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/jms/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/jms/assembly-component.xml new file mode 100644 index 000000000..bf421738f --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/jms/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/jms/module.xml + /modules/system/layers/soa/org/apache/camel/jms/main + true + + + + + /modules/system/layers/soa/org/apache/camel/jms/main + + org.apache.camel:camel-jms + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/jms/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/jms/module.xml new file mode 100644 index 000000000..29d9202a1 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/jms/module.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/jpa/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/jpa/assembly-component.xml new file mode 100644 index 000000000..4bab03a98 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/jpa/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/jpa/module.xml + /modules/system/layers/soa/org/apache/camel/jpa/main + true + + + + + /modules/system/layers/soa/org/apache/camel/jpa/main + + org.apache.camel:camel-jpa + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/jpa/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/jpa/module.xml new file mode 100644 index 000000000..76c732a3e --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/jpa/module.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/mail/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/mail/assembly-component.xml new file mode 100644 index 000000000..c9cd47c83 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/mail/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/mail/module.xml + /modules/system/layers/soa/org/apache/camel/mail/main + true + + + + + /modules/system/layers/soa/org/apache/camel/mail/main + + org.apache.camel:camel-mail + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/mail/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/mail/module.xml new file mode 100644 index 000000000..22c64793e --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/mail/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/mina2/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/mina2/assembly-component.xml new file mode 100644 index 000000000..d795c0e2e --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/mina2/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/mina2/module.xml + /modules/system/layers/soa/org/apache/camel/mina2/main + true + + + + + /modules/system/layers/soa/org/apache/camel/mina2/main + + org.apache.camel:camel-mina2 + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/mina2/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/mina2/module.xml new file mode 100644 index 000000000..eb74666e7 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/mina2/module.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/mqtt/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/mqtt/assembly-component.xml new file mode 100644 index 000000000..85a8d52a5 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/mqtt/assembly-component.xml @@ -0,0 +1,39 @@ + + + + + + src/main/resources/external/camel/mqtt/module.xml + /modules/system/layers/soa/org/apache/camel/mqtt/main + true + + + + + /modules/system/layers/soa/org/apache/camel/mqtt/main + + org.apache.camel:camel-mqtt + org.fusesource.mqtt-client:mqtt-client + org.fusesource.hawtdispatch:hawtdispatch + org.fusesource.hawtdispatch:hawtdispatch-transport + org.fusesource.hawtbuf:hawtbuf + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + true + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/mqtt/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/mqtt/module.xml new file mode 100644 index 000000000..a7b7f6def --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/mqtt/module.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/mvel/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/mvel/assembly-component.xml new file mode 100644 index 000000000..7084af28a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/mvel/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/mvel/module.xml + /modules/system/layers/soa/org/apache/camel/mvel/main + true + + + + + /modules/system/layers/soa/org/apache/camel/mvel/main + + org.apache.camel:camel-mvel + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/mvel/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/mvel/module.xml new file mode 100644 index 000000000..2b33aac8d --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/mvel/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/netty/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/netty/assembly-component.xml new file mode 100644 index 000000000..8e66cb6e1 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/netty/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/netty/module.xml + /modules/system/layers/soa/org/apache/camel/netty/main + true + + + + + /modules/system/layers/soa/org/apache/camel/netty/main + + org.apache.camel:camel-netty + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/netty/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/netty/module.xml new file mode 100644 index 000000000..4bd9a1e17 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/netty/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/ognl/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/ognl/assembly-component.xml new file mode 100644 index 000000000..8a1d989fb --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/ognl/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/ognl/module.xml + /modules/system/layers/soa/org/apache/camel/ognl/main + true + + + + + /modules/system/layers/soa/org/apache/camel/ognl/main + + org.apache.camel:camel-ognl + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/ognl/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/ognl/module.xml new file mode 100644 index 000000000..1be8bfc28 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/ognl/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/quartz/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/quartz/assembly-component.xml new file mode 100644 index 000000000..3919b3350 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/quartz/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/quartz/module.xml + /modules/system/layers/soa/org/apache/camel/quartz/main + true + + + + + /modules/system/layers/soa/org/apache/camel/quartz/main + + org.apache.camel:camel-quartz + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/quartz/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/quartz/module.xml new file mode 100644 index 000000000..8e6221237 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/quartz/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/rss/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/rss/assembly-component.xml new file mode 100644 index 000000000..bf35fbaa7 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/rss/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/rss/module.xml + /modules/system/layers/soa/org/apache/camel/rss/main + true + + + + + /modules/system/layers/soa/org/apache/camel/rss/main + + org.apache.camel:camel-rss + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/rss/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/rss/module.xml new file mode 100644 index 000000000..5c2906767 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/rss/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/sap/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/sap/assembly-component.xml new file mode 100644 index 000000000..3a2cb42f6 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/sap/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/sap/module.xml + /modules/system/layers/soa/org/fusesource/camel/sap/main + true + + + + + /modules/system/layers/soa/org/fusesource/camel/sap/main + + org.fusesource:camel-sap + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/sap/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/sap/module.xml new file mode 100644 index 000000000..87873357b --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/sap/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/saxon/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/saxon/assembly-component.xml new file mode 100644 index 000000000..3a273fe07 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/saxon/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/saxon/module.xml + /modules/system/layers/soa/org/apache/camel/saxon/main + true + + + + + /modules/system/layers/soa/org/apache/camel/saxon/main + + org.apache.camel:camel-saxon + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/saxon/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/saxon/module.xml new file mode 100644 index 000000000..00ff991f6 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/saxon/module.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/script/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/script/assembly-component.xml new file mode 100644 index 000000000..cb8755e19 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/script/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/script/module.xml + /modules/system/layers/soa/org/apache/camel/script/main + true + + + + + /modules/system/layers/soa/org/apache/camel/script/main + + org.apache.camel:camel-script + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/script/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/script/module.xml new file mode 100644 index 000000000..77539b110 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/script/module.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/soap/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/soap/assembly-component.xml new file mode 100644 index 000000000..c2f9aa672 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/soap/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/soap/module.xml + /modules/system/layers/soa/org/apache/camel/soap/main + true + + + + + /modules/system/layers/soa/org/apache/camel/soap/main + + org.apache.camel:camel-soap + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/soap/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/soap/module.xml new file mode 100644 index 000000000..28e4ca4f8 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/soap/module.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/spring/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/spring/assembly-component.xml new file mode 100644 index 000000000..479647a50 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/spring/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/spring/module.xml + /modules/system/layers/soa/org/apache/camel/spring/main + true + + + + + /modules/system/layers/soa/org/apache/camel/spring/main + + org.apache.camel:camel-spring + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/spring/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/spring/module.xml new file mode 100644 index 000000000..0f5ae0e52 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/spring/module.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/sql/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/camel/sql/assembly-component.xml new file mode 100644 index 000000000..d8d96cdbf --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/sql/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/camel/sql/module.xml + /modules/system/layers/soa/org/apache/camel/sql/main + true + + + + + /modules/system/layers/soa/org/apache/camel/sql/main + + org.apache.camel:camel-sql + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/camel/sql/module.xml b/release/jboss-as7/modules/src/main/resources/external/camel/sql/module.xml new file mode 100644 index 000000000..b0c2b3c24 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/camel/sql/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/clojure/module.xml b/release/jboss-as7/modules/src/main/resources/external/clojure/module.xml new file mode 100644 index 000000000..880f2ca56 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/clojure/module.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/dozer/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/dozer/assembly-component.xml new file mode 100644 index 000000000..491c03b18 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/dozer/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/dozer/module.xml + /modules/system/layers/soa/net/sf/dozer/main + true + + + + + /modules/system/layers/soa/net/sf/dozer/main + + net.sf.dozer:dozer + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/dozer/module.xml b/release/jboss-as7/modules/src/main/resources/external/dozer/module.xml new file mode 100644 index 000000000..138a13fa2 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/dozer/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/freemarker/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/freemarker/assembly-component.xml new file mode 100644 index 000000000..6887dfb7a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/freemarker/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/freemarker/module.xml + /modules/system/layers/soa/org/freemarker/main + true + + + + + /modules/system/layers/soa/org/freemarker/main + + org.freemarker:freemarker + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/freemarker/module.xml b/release/jboss-as7/modules/src/main/resources/external/freemarker/module.xml new file mode 100644 index 000000000..b559f93d5 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/freemarker/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/groovy/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/groovy/assembly-component.xml new file mode 100644 index 000000000..594f9f375 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/groovy/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/groovy/module.xml + /modules/system/layers/soa/org/codehaus/groovy/main + true + + + + + /modules/system/layers/soa/org/codehaus/groovy/main + + org.codehaus.groovy:groovy-all + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/groovy/module.xml b/release/jboss-as7/modules/src/main/resources/external/groovy/module.xml new file mode 100644 index 000000000..f809f3375 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/groovy/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/hapi-osgi-base/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/hapi-osgi-base/assembly-component.xml new file mode 100644 index 000000000..ab4825e66 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/hapi-osgi-base/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/hapi-osgi-base/module.xml + /modules/system/layers/soa/ca/uhn/hapi-osgi-base/main + true + + + + + /modules/system/layers/soa/ca/uhn/hapi-osgi-base/main + + ca.uhn.hapi:hapi-osgi-base + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/hapi-osgi-base/module.xml b/release/jboss-as7/modules/src/main/resources/external/hapi-osgi-base/module.xml new file mode 100644 index 000000000..88c03fb1b --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/hapi-osgi-base/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/jbossws/jbossws-jboss720-server-integration/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/jbossws/jbossws-jboss720-server-integration/assembly-component.xml new file mode 100644 index 000000000..5a3733500 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/jbossws/jbossws-jboss720-server-integration/assembly-component.xml @@ -0,0 +1,28 @@ + + + + + + /modules/system/layers/base/org/jboss/as/webservices/main + + org.jboss.ws:jbossws-jboss720-server-integration + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/jbossws/jbossws-spi/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/jbossws/jbossws-spi/assembly-component.xml new file mode 100644 index 000000000..6616a079a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/jbossws/jbossws-spi/assembly-component.xml @@ -0,0 +1,28 @@ + + + + + + /modules/system/layers/base/org/jboss/ws/spi/main + + org.jboss.ws:jbossws-spi + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/jcraft/jsch/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/jcraft/jsch/assembly-component.xml new file mode 100644 index 000000000..5d8cabee1 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/jcraft/jsch/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/jcraft/jsch/module.xml + /modules/system/layers/soa/com/jcraft/jsch/main + true + + + + + /modules/system/layers/soa/com/jcraft/jsch/main + + com.jcraft:jsch + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/jcraft/jsch/module.xml b/release/jboss-as7/modules/src/main/resources/external/jcraft/jsch/module.xml new file mode 100644 index 000000000..8fef2fcc1 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/jcraft/jsch/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/jruby/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/jruby/assembly-component.xml new file mode 100644 index 000000000..1c506f176 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/jruby/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/jruby/module.xml + /modules/system/layers/soa/org/jruby/main + true + + + + + /modules/system/layers/soa/org/jruby/main + + org.jruby:jruby + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/jruby/module.xml b/release/jboss-as7/modules/src/main/resources/external/jruby/module.xml new file mode 100644 index 000000000..aa2759644 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/jruby/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/milyn/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/milyn/assembly-component.xml new file mode 100644 index 000000000..7f9724784 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/milyn/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/milyn/module.xml + /modules/system/layers/soa/org/milyn/main + true + + + + + /modules/system/layers/soa/org/milyn/main + + org.milyn:milyn-smooks-all + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/milyn/module.xml b/release/jboss-as7/modules/src/main/resources/external/milyn/module.xml new file mode 100644 index 000000000..e6047abbc --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/milyn/module.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/ognl/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/ognl/assembly-component.xml new file mode 100644 index 000000000..a0d4c0450 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/ognl/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/ognl/module.xml + /modules/system/layers/soa/ognl/main + true + + + + + /modules/system/layers/soa/ognl/main + + ognl:ognl + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/ognl/module.xml b/release/jboss-as7/modules/src/main/resources/external/ognl/module.xml new file mode 100644 index 000000000..eb855450d --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/ognl/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/opencsv/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/opencsv/assembly-component.xml new file mode 100644 index 000000000..e7e32f191 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/opencsv/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/opencsv/module.xml + /modules/system/layers/soa/net/sf/opencsv/main + true + + + + + /modules/system/layers/soa/net/sf/opencsv/main + + net.sf.opencsv:opencsv + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/opencsv/module.xml b/release/jboss-as7/modules/src/main/resources/external/opencsv/module.xml new file mode 100644 index 000000000..2e5977814 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/opencsv/module.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/python/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/python/assembly-component.xml new file mode 100644 index 000000000..d503792bc --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/python/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/python/module.xml + /modules/system/layers/soa/org/python/main + true + + + + + /modules/system/layers/soa/org/python/main + + org.python:jython + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/python/module.xml b/release/jboss-as7/modules/src/main/resources/external/python/module.xml new file mode 100644 index 000000000..0f3e2ac7c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/python/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/quartz/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/quartz/assembly-component.xml new file mode 100644 index 000000000..5f0990199 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/quartz/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/quartz/module.xml + /modules/system/layers/soa/org/quartz-scheduler/quartz/main + true + + + + + /modules/system/layers/soa/org/quartz-scheduler/quartz/main + + org.quartz-scheduler:quartz + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/quartz/module.xml b/release/jboss-as7/modules/src/main/resources/external/quartz/module.xml new file mode 100644 index 000000000..749c747d9 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/quartz/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/rhino/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/rhino/assembly-component.xml new file mode 100644 index 000000000..5bd6982f3 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/rhino/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/rhino/module.xml + /modules/system/layers/soa/rhino/main + true + + + + + /modules/system/layers/soa/rhino/main + + rhino:js + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/rhino/module.xml b/release/jboss-as7/modules/src/main/resources/external/rhino/module.xml new file mode 100644 index 000000000..fc9d6ab8b --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/rhino/module.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/rome/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/rome/assembly-component.xml new file mode 100644 index 000000000..1716b795f --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/rome/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/rome/module.xml + /modules/system/layers/soa/rome/rome/1.0 + true + + + + + /modules/system/layers/soa/rome/rome/1.0 + + rome:rome + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/rome/module.xml b/release/jboss-as7/modules/src/main/resources/external/rome/module.xml new file mode 100644 index 000000000..d90a83527 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/rome/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/saaj-impl/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/saaj-impl/assembly-component.xml new file mode 100644 index 000000000..24c8052d0 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/saaj-impl/assembly-component.xml @@ -0,0 +1,25 @@ + + + + + + src/main/resources/external/saaj-impl/module.xml + /modules/system/layers/soa/org/switchyard/component/soap/saaj-impl/main + true + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/saaj-impl/module.xml b/release/jboss-as7/modules/src/main/resources/external/saaj-impl/module.xml new file mode 100644 index 000000000..e91795b26 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/saaj-impl/module.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/saxon/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/saxon/assembly-component.xml new file mode 100644 index 000000000..d453331d9 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/saxon/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/saxon/module.xml + /modules/system/layers/soa/net/sourceforge/saxon/main + true + + + + + /modules/system/layers/soa/net/sourceforge/saxon/main + + net.sourceforge.saxon:saxonhe + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/saxon/module.xml b/release/jboss-as7/modules/src/main/resources/external/saxon/module.xml new file mode 100644 index 000000000..371fdaa6e --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/saxon/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/saxonhe95/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/saxonhe95/assembly-component.xml new file mode 100644 index 000000000..2b5504d1a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/saxonhe95/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/saxonhe95/module.xml + /modules/system/layers/soa/net/sf/saxon/main + true + + + + + /modules/system/layers/soa/net/sf/saxon/main + + net.sf.saxon:Saxon-HE + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/saxonhe95/module.xml b/release/jboss-as7/modules/src/main/resources/external/saxonhe95/module.xml new file mode 100644 index 000000000..363ff3192 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/saxonhe95/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/spring/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/spring/assembly-component.xml new file mode 100644 index 000000000..dfba29024 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/spring/assembly-component.xml @@ -0,0 +1,27 @@ + + + + + + src/main/resources/external/spring/module.xml + /modules/system/layers/soa/org/springframework/spring/main + true + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/spring/module.xml b/release/jboss-as7/modules/src/main/resources/external/spring/module.xml new file mode 100644 index 000000000..e93081e14 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/spring/module.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/springframework/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/springframework/assembly-component.xml new file mode 100644 index 000000000..880bd23a9 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/springframework/assembly-component.xml @@ -0,0 +1,44 @@ + + + + + + src/main/resources/external/springframework/module.xml + /modules/system/layers/soa/org/springframework/main + true + + + + + /modules/system/layers/soa/org/springframework/main + + org.springframework:spring-aop + org.springframework:spring-beans + org.springframework:spring-core + org.springframework:spring-context + org.springframework:spring-expression + org.springframework:spring-jms + org.springframework:spring-jdbc + org.springframework:spring-tx + org.springframework:spring-jdbc + org.springframework:spring-orm + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/springframework/module.xml b/release/jboss-as7/modules/src/main/resources/external/springframework/module.xml new file mode 100644 index 000000000..5a836baa3 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/springframework/module.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/ws-impl/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/ws-impl/assembly-component.xml new file mode 100644 index 000000000..74261a4c8 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/ws-impl/assembly-component.xml @@ -0,0 +1,25 @@ + + + + + + src/main/resources/external/ws-impl/module.xml + /modules/system/layers/soa/org/switchyard/component/soap/ws-impl/main + true + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/ws-impl/module.xml b/release/jboss-as7/modules/src/main/resources/external/ws-impl/module.xml new file mode 100644 index 000000000..e9d5644af --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/ws-impl/module.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/xstream/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/external/xstream/assembly-component.xml new file mode 100644 index 000000000..7a184326a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/xstream/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/xstream/module.xml + /modules/system/layers/soa/com/thoughtworks/xstream/main + true + + + + + /modules/system/layers/soa/com/thoughtworks/xstream/main + + com.thoughtworks.xstream:xstream + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/modules/src/main/resources/external/xstream/module.xml b/release/jboss-as7/modules/src/main/resources/external/xstream/module.xml new file mode 100644 index 000000000..22ff83108 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/external/xstream/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/layers.conf b/release/jboss-as7/modules/src/main/resources/layers.conf new file mode 100644 index 000000000..a5fad8a1a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/layers.conf @@ -0,0 +1 @@ +layers=soa,bpms diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/README.md b/release/jboss-as7/modules/src/main/resources/switchyard/README.md new file mode 100644 index 000000000..885d6ebd8 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/README.md @@ -0,0 +1 @@ +Only SwitchYard modules (no external) should be located in this folder. \ No newline at end of file diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/bean/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/bean/assembly-component.xml new file mode 100644 index 000000000..8745680d6 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/bean/assembly-component.xml @@ -0,0 +1,36 @@ + + + + + + + src/main/resources/switchyard/components/bean/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/bean/main + true + + + + + false + + org.switchyard.components:switchyard-component-bean + + /modules/system/layers/soa/org/switchyard/component/bean/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/bean/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/bean/resources/module.xml new file mode 100644 index 000000000..1a57fa628 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/bean/resources/module.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/bpel/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/bpel/assembly-component.xml new file mode 100644 index 000000000..c5e0c0dd7 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/bpel/assembly-component.xml @@ -0,0 +1,256 @@ + + + + + + + src/main/resources/switchyard/components/bpel/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/bpel/main + true + + + + + false + + org.switchyard.components:switchyard-component-bpel + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.riftsaw:engine + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-agents + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-api + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-compiler + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-dao + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-epr + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-obj + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-ql + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-runtime + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-schemas + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-bpel-store + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-dao-jpa + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-dao-jpa-hibernate + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-jacob + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-scheduler-simple + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.soa.bpel:riftsaw-utils + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.bpm:activity-monitor-model + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + + false + + org.jboss.bpm:gwt-console-rpc + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.jboss.bpm:gwt-console-server-integration + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.riftsaw.console:riftsaw-bpel2svg + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.riftsaw.console:riftsaw-console-integration + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.riftsaw.console:riftsaw-bpaf + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + false + + org.overlord:overlord-commons-services + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + + false + + org.apache.xmlbeans:xmlbeans + + /modules/system/layers/soa/org/switchyard/component/bpel/main + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/bpel/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/bpel/resources/module.xml new file mode 100644 index 000000000..8ccf852f0 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/bpel/resources/module.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/bpm/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/bpm/assembly-component.xml new file mode 100644 index 000000000..c39c67308 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/bpm/assembly-component.xml @@ -0,0 +1,34 @@ + + + + + + src/main/resources/switchyard/components/bpm/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/bpm/main + true + + + + + false + + org.switchyard.components:switchyard-component-bpm + + /modules/system/layers/soa/org/switchyard/component/bpm/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/bpm/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/bpm/resources/module.xml new file mode 100644 index 000000000..0bd611279 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/bpm/resources/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/amqp/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/amqp/assembly-component.xml new file mode 100644 index 000000000..5009744a1 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/amqp/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/amqp/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/amqp/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-amqp + + /modules/system/layers/soa/org/switchyard/component/camel/amqp/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/amqp/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/amqp/resources/module.xml new file mode 100644 index 000000000..6805ca979 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/amqp/resources/module.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/assembly-component.xml new file mode 100644 index 000000000..234eff837 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel + + /modules/system/layers/soa/org/switchyard/component/camel/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/atom/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/atom/assembly-component.xml new file mode 100644 index 000000000..a290ef32c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/atom/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/atom/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/atom/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-atom + + /modules/system/layers/soa/org/switchyard/component/camel/atom/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/atom/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/atom/resources/module.xml new file mode 100644 index 000000000..ad97e38cd --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/atom/resources/module.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/core/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/core/assembly-component.xml new file mode 100644 index 000000000..244bb13ff --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/core/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/core/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/core/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-core + + /modules/system/layers/soa/org/switchyard/component/camel/core/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/core/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/core/resources/module.xml new file mode 100644 index 000000000..f21545118 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/core/resources/module.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/cxf/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/cxf/assembly-component.xml new file mode 100644 index 000000000..92a2a574f --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/cxf/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/cxf/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/cxf/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-cxf + + /modules/system/layers/soa/org/switchyard/component/camel/cxf/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/cxf/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/cxf/resources/module.xml new file mode 100644 index 000000000..5750042c6 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/cxf/resources/module.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/file/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/file/assembly-component.xml new file mode 100644 index 000000000..c31e19960 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/file/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/file/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/file/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-file + + /modules/system/layers/soa/org/switchyard/component/camel/file/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/file/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/file/resources/module.xml new file mode 100644 index 000000000..32a519d33 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/file/resources/module.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/ftp/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/ftp/assembly-component.xml new file mode 100644 index 000000000..e8945245c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/ftp/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/ftp/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/ftp/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-ftp + + /modules/system/layers/soa/org/switchyard/component/camel/ftp/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/ftp/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/ftp/resources/module.xml new file mode 100644 index 000000000..563225410 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/ftp/resources/module.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jms/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jms/assembly-component.xml new file mode 100644 index 000000000..9a04e61c8 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jms/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/jms/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/jms/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-jms + + /modules/system/layers/soa/org/switchyard/component/camel/jms/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jms/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jms/resources/module.xml new file mode 100644 index 000000000..16c49cfef --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jms/resources/module.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jpa/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jpa/assembly-component.xml new file mode 100644 index 000000000..00f761c0b --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jpa/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/jpa/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/jpa/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-jpa + + /modules/system/layers/soa/org/switchyard/component/camel/jpa/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jpa/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jpa/resources/module.xml new file mode 100644 index 000000000..cd04926eb --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/jpa/resources/module.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mail/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mail/assembly-component.xml new file mode 100644 index 000000000..2f44625b3 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mail/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/mail/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/mail/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-mail + + /modules/system/layers/soa/org/switchyard/component/camel/mail/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mail/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mail/resources/module.xml new file mode 100644 index 000000000..49d220a8c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mail/resources/module.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mqtt/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mqtt/assembly-component.xml new file mode 100644 index 000000000..3e6a9a9db --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mqtt/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/mqtt/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/mqtt/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-mqtt + + /modules/system/layers/soa/org/switchyard/component/camel/mqtt/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mqtt/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mqtt/resources/module.xml new file mode 100644 index 000000000..356b9bff0 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/mqtt/resources/module.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/netty/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/netty/assembly-component.xml new file mode 100644 index 000000000..43280718e --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/netty/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/netty/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/netty/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-netty + + /modules/system/layers/soa/org/switchyard/component/camel/netty/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/netty/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/netty/resources/module.xml new file mode 100644 index 000000000..ac78e9b2f --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/netty/resources/module.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/quartz/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/quartz/assembly-component.xml new file mode 100644 index 000000000..ad67798e9 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/quartz/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/quartz/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/quartz/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-quartz + + /modules/system/layers/soa/org/switchyard/component/camel/quartz/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/quartz/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/quartz/resources/module.xml new file mode 100644 index 000000000..52df5de6f --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/quartz/resources/module.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/resources/module.xml new file mode 100644 index 000000000..62586be4f --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/resources/module.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/rss/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/rss/assembly-component.xml new file mode 100644 index 000000000..2e2c5a282 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/rss/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/rss/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/rss/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-rss + + /modules/system/layers/soa/org/switchyard/component/camel/rss/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/rss/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/rss/resources/module.xml new file mode 100644 index 000000000..b79eb72b6 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/rss/resources/module.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sap/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sap/assembly-component.xml new file mode 100644 index 000000000..bc8229922 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sap/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/sap/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/sap/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-sap + + /modules/system/layers/soa/org/switchyard/component/camel/sap/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sap/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sap/resources/module.xml new file mode 100644 index 000000000..4a451078a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sap/resources/module.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sql/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sql/assembly-component.xml new file mode 100644 index 000000000..f4273857c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sql/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/sql/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/sql/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-sql + + /modules/system/layers/soa/org/switchyard/component/camel/sql/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sql/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sql/resources/module.xml new file mode 100644 index 000000000..01b4b73fa --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/sql/resources/module.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/switchyard/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/switchyard/assembly-component.xml new file mode 100644 index 000000000..8dc84bb70 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/switchyard/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/camel/switchyard/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/camel/switchyard/main + true + + + + + false + + org.switchyard.components:switchyard-component-camel-switchyard + + /modules/system/layers/soa/org/switchyard/component/camel/switchyard/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/switchyard/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/switchyard/resources/module.xml new file mode 100644 index 000000000..311781bdc --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/camel/switchyard/resources/module.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/clojure/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/clojure/assembly-component.xml new file mode 100644 index 000000000..a5fae58c0 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/clojure/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/clojure/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/clojure/main + true + + + + + false + + org.switchyard.components:switchyard-component-clojure + + /modules/system/layers/soa/org/switchyard/component/clojure/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/clojure/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/clojure/resources/module.xml new file mode 100644 index 000000000..9ac765f11 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/clojure/resources/module.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/common/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/assembly-component.xml new file mode 100644 index 000000000..a2e18b6a5 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/assembly-component.xml @@ -0,0 +1,34 @@ + + + + + + src/main/resources/switchyard/components/common/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/common/main + true + + + + + false + + org.switchyard.components:switchyard-component-common + + /modules/system/layers/soa/org/switchyard/component/common/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/common/camel/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/camel/assembly-component.xml new file mode 100644 index 000000000..ef7fbbbd5 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/camel/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/common/camel/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/common/camel/main + true + + + + + false + + org.switchyard.components:switchyard-component-common-camel + + /modules/system/layers/soa/org/switchyard/component/common/camel/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/common/camel/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/camel/resources/module.xml new file mode 100644 index 000000000..da61a5f86 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/camel/resources/module.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/common/knowledge/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/knowledge/assembly-component.xml new file mode 100644 index 000000000..3a572091b --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/knowledge/assembly-component.xml @@ -0,0 +1,34 @@ + + + + + + src/main/resources/switchyard/components/common/knowledge/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/common/knowledge/main + true + + + + + false + + org.switchyard.components:switchyard-component-common-knowledge + + /modules/system/layers/soa/org/switchyard/component/common/knowledge/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/common/knowledge/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/knowledge/resources/module.xml new file mode 100644 index 000000000..9592c4bff --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/knowledge/resources/module.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/common/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/resources/module.xml new file mode 100644 index 000000000..28ec3d88f --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/common/resources/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/hornetq/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/hornetq/assembly-component.xml new file mode 100644 index 000000000..0d0d9ab66 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/hornetq/assembly-component.xml @@ -0,0 +1,37 @@ + + + + + + + src/main/resources/switchyard/components/hornetq/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/hornetq/main + true + + + + + + false + + org.switchyard.components:switchyard-component-hornetq + + /modules/system/layers/soa/org/switchyard/component/hornetq/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/hornetq/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/hornetq/resources/module.xml new file mode 100644 index 000000000..fdfdd4ac5 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/hornetq/resources/module.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/http/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/http/assembly-component.xml new file mode 100644 index 000000000..22a5bbb95 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/http/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/http/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/http/main + true + + + + + false + + org.switchyard.components:switchyard-component-http + + /modules/system/layers/soa/org/switchyard/component/http/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/http/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/http/resources/module.xml new file mode 100644 index 000000000..b6d3a4230 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/http/resources/module.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/jca/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/jca/assembly-component.xml new file mode 100644 index 000000000..90b628b97 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/jca/assembly-component.xml @@ -0,0 +1,37 @@ + + + + + + + src/main/resources/switchyard/components/jca/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/jca/main + true + + + + + + false + + org.switchyard.components:switchyard-component-jca + + /modules/system/layers/soa/org/switchyard/component/jca/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/jca/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/jca/resources/module.xml new file mode 100644 index 000000000..eea3df6d3 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/jca/resources/module.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/resteasy/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/resteasy/assembly-component.xml new file mode 100644 index 000000000..f15cb72bb --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/resteasy/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/resteasy/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/resteasy/main + true + + + + + false + + org.switchyard.components:switchyard-component-resteasy + + /modules/system/layers/soa/org/switchyard/component/resteasy/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/resteasy/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/resteasy/resources/module.xml new file mode 100644 index 000000000..0477d9650 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/resteasy/resources/module.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/rules/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/rules/assembly-component.xml new file mode 100644 index 000000000..1e935dfdd --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/rules/assembly-component.xml @@ -0,0 +1,34 @@ + + + + + + src/main/resources/switchyard/components/rules/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/rules/main + true + + + + + false + + org.switchyard.components:switchyard-component-rules + + /modules/system/layers/soa/org/switchyard/component/rules/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/rules/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/rules/resources/module.xml new file mode 100644 index 000000000..2ff0e60f1 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/rules/resources/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/sca/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/sca/assembly-component.xml new file mode 100644 index 000000000..a864be3c1 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/sca/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/sca/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/sca/main + true + + + + + false + + org.switchyard.components:switchyard-component-sca + + /modules/system/layers/soa/org/switchyard/component/sca/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/sca/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/sca/resources/module.xml new file mode 100644 index 000000000..3fa92b806 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/sca/resources/module.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/soap/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/soap/assembly-component.xml new file mode 100644 index 000000000..95a63ecb3 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/soap/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + + src/main/resources/switchyard/components/soap/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/soap/main + true + + + + + false + + org.switchyard.components:switchyard-component-soap + + /modules/system/layers/soa/org/switchyard/component/soap/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/components/soap/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/components/soap/resources/module.xml new file mode 100644 index 000000000..d354f4014 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/components/soap/resources/module.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/console/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/console/assembly-component.xml new file mode 100644 index 000000000..4ac5b5c0a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/console/assembly-component.xml @@ -0,0 +1,36 @@ + + + + + + src/main/resources/switchyard/console/resources/module.xml + /modules/system/layers/soa/org/jboss/as/console/eap + true + + + + + + false + + org.switchyard.console:switchyard-console-application:jar:resources + + /modules/system/layers/soa/org/jboss/as/console/eap + ${artifact.artifactId}-${artifact.classifier}.${artifact.extension} + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/console/resources/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/console/resources/module.xml new file mode 100644 index 000000000..414438682 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/console/resources/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/admin/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/admin/module.xml new file mode 100644 index 000000000..0cc319536 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/admin/module.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/api/extensions/java/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/api/extensions/java/module.xml new file mode 100644 index 000000000..9775289b2 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/api/extensions/java/module.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/api/extensions/wsdl/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/api/extensions/wsdl/module.xml new file mode 100644 index 000000000..1e7e51d6d --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/api/extensions/wsdl/module.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/api/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/api/module.xml new file mode 100644 index 000000000..70d225432 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/api/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/assembly-component.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/assembly-component.xml new file mode 100644 index 000000000..ae992b14c --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/assembly-component.xml @@ -0,0 +1,269 @@ + + + + + + src/main/resources/switchyard/core/api/module.xml + /modules/system/layers/soa/org/switchyard/api/main + true + + + src/main/resources/switchyard/core/api/extensions/java/module.xml + /modules/system/layers/soa/org/switchyard/api/extensions/java/main + true + + + src/main/resources/switchyard/core/api/extensions/wsdl/module.xml + /modules/system/layers/soa/org/switchyard/api/extensions/wsdl/main + true + + + src/main/resources/switchyard/core/admin/module.xml + /modules/system/layers/soa/org/switchyard/admin/main + true + + + src/main/resources/switchyard/core/common/module.xml + /modules/system/layers/soa/org/switchyard/common/main + true + + + src/main/resources/switchyard/core/common/camel/module.xml + /modules/system/layers/soa/org/switchyard/common/camel/main + true + + + src/main/resources/switchyard/core/common/cdi/module.xml + /modules/system/layers/soa/org/switchyard/common/cdi/main + true + + + src/main/resources/switchyard/core/config/module.xml + /modules/system/layers/soa/org/switchyard/config/main + true + + + src/main/resources/switchyard/core/remote/module.xml + /modules/system/layers/soa/org/switchyard/remote/main + true + + + src/main/resources/switchyard/core/runtime/module.xml + /modules/system/layers/soa/org/switchyard/runtime/main + true + + + src/main/resources/switchyard/core/security/module.xml + /modules/system/layers/soa/org/switchyard/security/main + true + + + src/main/resources/switchyard/core/serial/module.xml + /modules/system/layers/soa/org/switchyard/serial/main + true + + + src/main/resources/switchyard/core/transform/module.xml + /modules/system/layers/soa/org/switchyard/transform/main + true + + + src/main/resources/switchyard/core/validate/module.xml + /modules/system/layers/soa/org/switchyard/validate/main + true + + + src/main/resources/switchyard/core/deploy/module.xml + /modules/system/layers/soa/org/switchyard/deploy/main + true + + + src/main/resources/switchyard/core/jaxb-impl/module.xml + /modules/system/layers/soa/org/switchyard/jaxb-impl/main + true + + + src/main/resources/switchyard/core/bus/camel/module.xml + /modules/system/layers/soa/org/switchyard/bus/camel/main + true + + + src/main/resources/switchyard/core/module.xml + /modules/system/layers/soa/org/switchyard/main + true + + + + + false + + org.switchyard:switchyard-api + + /modules/system/layers/soa/org/switchyard/api/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-admin + + /modules/system/layers/soa/org/switchyard/admin/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-common + + /modules/system/layers/soa/org/switchyard/common/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-common-camel + + /modules/system/layers/soa/org/switchyard/common/camel/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-common-cdi + + /modules/system/layers/soa/org/switchyard/common/cdi/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-config + + /modules/system/layers/soa/org/switchyard/config/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-extensions-java + + /modules/system/layers/soa/org/switchyard/api/extensions/java/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-extensions-wsdl + + /modules/system/layers/soa/org/switchyard/api/extensions/wsdl/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-transform + + /modules/system/layers/soa/org/switchyard/transform/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-validate + + /modules/system/layers/soa/org/switchyard/validate/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-remote + + /modules/system/layers/soa/org/switchyard/remote/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-runtime + + /modules/system/layers/soa/org/switchyard/runtime/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-security + org.switchyard:switchyard-security-jboss + + /modules/system/layers/soa/org/switchyard/security/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-serial + org.switchyard:switchyard-serial-jackson + + + /modules/system/layers/soa/org/switchyard/serial/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-bus-camel + + /modules/system/layers/soa/org/switchyard/bus/camel/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-deploy + + /modules/system/layers/soa/org/switchyard/deploy/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + false + + org.switchyard:switchyard-deploy-jboss-as7 + + /modules/system/layers/soa/org/switchyard/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/bus/camel/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/bus/camel/module.xml new file mode 100644 index 000000000..382826eb2 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/bus/camel/module.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/common/camel/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/common/camel/module.xml new file mode 100644 index 000000000..b28014c00 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/common/camel/module.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/common/cdi/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/common/cdi/module.xml new file mode 100644 index 000000000..d3ea3d251 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/common/cdi/module.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/common/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/common/module.xml new file mode 100644 index 000000000..d04065ebe --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/common/module.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/config/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/config/module.xml new file mode 100644 index 000000000..621500af2 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/config/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/deploy/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/deploy/module.xml new file mode 100644 index 000000000..d4cc5b106 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/deploy/module.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/jaxb-impl/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/jaxb-impl/module.xml new file mode 100644 index 000000000..3751071ac --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/jaxb-impl/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/module.xml new file mode 100644 index 000000000..6eb6965be --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/module.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/remote/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/remote/module.xml new file mode 100644 index 000000000..1d4a95219 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/remote/module.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/runtime/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/runtime/module.xml new file mode 100644 index 000000000..96b2d07da --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/runtime/module.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/security/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/security/module.xml new file mode 100644 index 000000000..93928d26b --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/security/module.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/serial/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/serial/module.xml new file mode 100644 index 000000000..1ec60125a --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/serial/module.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/transform/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/transform/module.xml new file mode 100644 index 000000000..52bc11761 --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/transform/module.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/modules/src/main/resources/switchyard/core/validate/module.xml b/release/jboss-as7/modules/src/main/resources/switchyard/core/validate/module.xml new file mode 100644 index 000000000..9cadedfbc --- /dev/null +++ b/release/jboss-as7/modules/src/main/resources/switchyard/core/validate/module.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/openshift/express/cartridge/assembly.xml b/release/jboss-as7/openshift/express/cartridge/assembly.xml new file mode 100644 index 000000000..298f535c4 --- /dev/null +++ b/release/jboss-as7/openshift/express/cartridge/assembly.xml @@ -0,0 +1,63 @@ + + OpenShiftCartridge + false + + tar.gz + + + + ${cartridge.dir}/modules + modules + + + 755 + + + + + diff --git a/release/jboss-as7/openshift/express/cartridge/pom.xml b/release/jboss-as7/openshift/express/cartridge/pom.xml new file mode 100644 index 000000000..d390f9f8f --- /dev/null +++ b/release/jboss-as7/openshift/express/cartridge/pom.xml @@ -0,0 +1,95 @@ + + + + + org.switchyard + switchyard-as7-openshift-express-parent + 1.0.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-openshift-express-cartridge + jar + SwitchYard: AS7 OpenShift Express Cartridge Modules + SwitchYard AS7 OpenShift Express Cartridge Modules + + ${project.build.directory}/cartridge + + + + + maven-dependency-plugin + + + install-as7-bpms-layer + generate-sources + + unpack + + + + + org.kie + kie-eap-distributions-bpms-layer + ${version.org.kie} + zip + + + modules/layers.conf + ${cartridge.dir} + + + + install-as7-modules + generate-sources + + unpack + + + + + org.switchyard + switchyard-as7-modules + zip + ${project.version} + + + ${cartridge.dir} + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + generate-test-resources + + single + + + false + + ${basedir}/assembly.xml + + + + + + + + diff --git a/release/jboss-as7/openshift/express/cartridge/src/main/resources/hibernate-validator/module.xml b/release/jboss-as7/openshift/express/cartridge/src/main/resources/hibernate-validator/module.xml new file mode 100644 index 000000000..8cefb0134 --- /dev/null +++ b/release/jboss-as7/openshift/express/cartridge/src/main/resources/hibernate-validator/module.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/openshift/express/cartridge/src/main/resources/soap/module.xml b/release/jboss-as7/openshift/express/cartridge/src/main/resources/soap/module.xml new file mode 100644 index 000000000..0e23d75af --- /dev/null +++ b/release/jboss-as7/openshift/express/cartridge/src/main/resources/soap/module.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/openshift/express/cartridge/src/main/resources/ws-impl/module.xml b/release/jboss-as7/openshift/express/cartridge/src/main/resources/ws-impl/module.xml new file mode 100644 index 000000000..1d9852c39 --- /dev/null +++ b/release/jboss-as7/openshift/express/cartridge/src/main/resources/ws-impl/module.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/openshift/express/cartridge/src/main/resources/ws/module.xml b/release/jboss-as7/openshift/express/cartridge/src/main/resources/ws/module.xml new file mode 100644 index 000000000..5e4c8f2e3 --- /dev/null +++ b/release/jboss-as7/openshift/express/cartridge/src/main/resources/ws/module.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/openshift/express/dist/assembly.xml b/release/jboss-as7/openshift/express/dist/assembly.xml new file mode 100644 index 000000000..36844c1d6 --- /dev/null +++ b/release/jboss-as7/openshift/express/dist/assembly.xml @@ -0,0 +1,103 @@ + + switchyard-as7-openshift-express + false + + zip + + + + + ${staging.jboss.dir} + + *.jar + *.txt + + ${distro.root.dir} + + + ${staging.jboss.dir}/bin + + domain.* + standalone.conf + standalone.conf.bat + ws*.* + + + *.sh + *.bat + + 755 + keep + ${distro.root.dir}bin + + + ${staging.jboss.dir}/bin + + domain.* + *.sh + *.bat + standalone.conf + standalone.conf.bat + ws*.* + + 644 + keep + ${distro.root.dir}bin + + + ${staging.jboss.dir}/bundles + ${distro.root.dir}bundles + + + ${staging.jboss.dir}/docs + ${distro.root.dir}docs + + + ${staging.jboss.dir}/modules + ${distro.root.dir}modules + + + ${staging.jboss.dir}/welcome-content + ${distro.root.dir}welcome-content + + + ${staging.jboss.dir}/standalone + ${distro.root.dir}standalone + + **/standalone*.xml + + + + src/main/resources + ${distro.root.dir}standalone/configuration + + standalone.xml + + + + ${staging.jboss.dir}/standalone + ${distro.root.dir}standalone + + **/standalone*.xml + + + + ${staging.jboss.dir}/standalone + ${distro.root.dir}standalone + + **/standalone*.xml + + + + src/main/resources + ${distro.root.dir}bin + + standalone.conf + standalone.conf.bat + + 755 + + + diff --git a/release/jboss-as7/openshift/express/dist/pom.xml b/release/jboss-as7/openshift/express/dist/pom.xml new file mode 100644 index 000000000..6092fb2ef --- /dev/null +++ b/release/jboss-as7/openshift/express/dist/pom.xml @@ -0,0 +1,187 @@ + + + + + org.switchyard + switchyard-as7-openshift-express-parent + 1.0.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-openshift-express-dist + jar + SwitchYard: AS7 OpenShift Express Distribution + SwitchYard AS7 OpenShift Express Distribution + + ${project.build.directory}/jboss-switchyard + ${staging.dir}/jboss-as-${version.jbossas.openshift} + /switchyard-as7-${version.distro}/ + ${project.build.directory}${distro.root.dir} + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + maven-dependency-plugin + + + stage-jboss + generate-sources + + unpack + + + + + org.jboss.as + jboss-as-dist + zip + + + + + **/org/jboss/as/messaging/**,**/org/jboss/osgi/** + ${staging.dir} + + + + install-switchyard-cartridge + generate-sources + + unpack + + + + + org.switchyard + switchyard-as7-openshift-express-cartridge + tar.gz + ${project.version} + + + ${staging.jboss.dir} + + + + install-distribution-files + generate-sources + + unpack + + + + + org.switchyard + switchyard-release-distribution + jar + ${project.version} + + + ${staging.jboss.dir} + + + + unzip-distro + process-test-classes + + unpack + + + + + org.switchyard + switchyard-as7-openshift-express-dist + zip + ${project.version} + + + ${project.build.directory} + + + + unpack-tests + process-test-classes + + unpack + + + + + org.switchyard + switchyard-as7-tests + test-jar + ${project.version} + + + **/*/CamelJMSBindingQuickstartTest.class, **/*/HornetqBindingQuickstartTest.class, **/*/BpelServiceJmsBindingQuickstartTest.class, **/*/JCA*HornetQQuickstartTest.class, **/*/PolicyTransactionDemoQuickstartTest.class + ${project.build.testOutputDirectory} + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + generate-test-resources + + single + + + false + switchyard-as7-openshift-express + + ${basedir}/assembly.xml + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${switchyard.jboss.home} + ${project.version} + + + + jboss.home + ${switchyard.jboss.home} + + + module.path + ${switchyard.jboss.home}/modules + + + false + true + always + + + + + diff --git a/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.conf b/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.conf new file mode 100644 index 000000000..6020142dc --- /dev/null +++ b/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.conf @@ -0,0 +1,7 @@ +# +# Specify options to pass to the Java VM. +# +if [ "x$JAVA_OPTS" = "x" ]; then + JAVA_OPTS="-Xmx123m -XX:MaxPermSize=85m -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000" +fi + diff --git a/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.conf.bat b/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.conf.bat new file mode 100644 index 000000000..b60fdd643 --- /dev/null +++ b/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.conf.bat @@ -0,0 +1,29 @@ +rem ### -*- batch file -*- ###################################################### +rem # ## +rem # JBoss Bootstrap Script Configuration ## +rem # ## +rem ############################################################################# + +rem # $Id: run.conf.bat 88820 2009-05-13 15:25:44Z dimitris@jboss.org $ + +rem # +rem # This batch file is executed by run.bat to initialize the environment +rem # variables that run.bat uses. It is recommended to use this file to +rem # configure these variables, rather than modifying run.bat itself. +rem # + +if not "x%JAVA_OPTS%" == "x" goto JAVA_OPTS_SET + +rem # JVM memory allocation pool parameters - modify as appropriate. +set "JAVA_OPTS=-Xms64M -Xmx123m -XX:MaxPermSize=85m" + +rem # Reduce the RMI GCs to once per hour for Sun JVMs. +set "JAVA_OPTS=%JAVA_OPTS% -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000" + +rem # Warn when resolving remote XML DTDs or schemas. +set "JAVA_OPTS=%JAVA_OPTS% -Dorg.jboss.resolver.warning=true" + +rem # Make Byteman classes visible in all module loaders +rem # This is necessary to inject Byteman rules into AS7 deployments +set "JAVA_OPTS=%JAVA_OPTS% -Djboss.modules.system.pkgs=org.jboss.byteman" +:JAVA_OPTS_SET diff --git a/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.xml b/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.xml new file mode 100644 index 000000000..debfde678 --- /dev/null +++ b/release/jboss-as7/openshift/express/dist/src/main/resources/standalone.xml @@ -0,0 +1,332 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/openshift/express/dist/src/test/resources/arquillian.xml b/release/jboss-as7/openshift/express/dist/src/test/resources/arquillian.xml new file mode 100644 index 000000000..0954115e7 --- /dev/null +++ b/release/jboss-as7/openshift/express/dist/src/test/resources/arquillian.xml @@ -0,0 +1,12 @@ + + + + + + 120 + standalone.xml + + + diff --git a/release/jboss-as7/openshift/express/pom.xml b/release/jboss-as7/openshift/express/pom.xml new file mode 100644 index 000000000..234aa945f --- /dev/null +++ b/release/jboss-as7/openshift/express/pom.xml @@ -0,0 +1,31 @@ + + + + + org.switchyard + switchyard-as7-openshift-parent + 1.0.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-openshift-express-parent + pom + SwitchYard: AS7 OpenShift Express Parent + SwitchYard AS7 OpenShift Express Parent + + cartridge + dist + + diff --git a/release/jboss-as7/openshift/pom.xml b/release/jboss-as7/openshift/pom.xml new file mode 100644 index 000000000..dbcd47b03 --- /dev/null +++ b/release/jboss-as7/openshift/pom.xml @@ -0,0 +1,124 @@ + + + + + org.switchyard + switchyard-container-parent + 1.0.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-openshift-parent + pom + SwitchYard: AS7 OpenShift Parent + SwitchYard AS7 OpenShift Parent + + express + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + + org.jboss.as + jboss-as-parent + ${version.jbossas.openshift} + pom + import + + + + org.jboss.arquillian + arquillian-junit + ${version.arquillian.openshift} + + + org.jboss.arquillian.junit + arquillian-junit-container + ${version.arquillian.openshift} + + + org.jboss.arquillian.container + arquillian-container-test-spi + ${version.arquillian.openshift} + + + org.jboss.arquillian.container + arquillian-container-spi + ${version.arquillian.openshift} + + + org.jboss.arquillian.container + arquillian-container-test-api + ${version.arquillian.openshift} + + + org.jboss.arquillian.container + arquillian-jbossas-managed-6 + ${version.arquillian.openshift} + + + org.jboss.arquillian.container + arquillian-container-test-impl-base + ${version.arquillian.openshift} + + + org.jboss.arquillian.core + arquillian-core-api + ${version.arquillian.openshift} + + + org.jboss.arquillian.core + arquillian-core-impl-base + ${version.arquillian.openshift} + + + org.jboss.arquillian.junit + arquillian-junit-core + ${version.arquillian.openshift} + + + org.jboss.arquillian.test + arquillian-test-impl-base + ${version.arquillian.openshift} + + + org.jboss.arquillian.test + arquillian-test-spi + ${version.arquillian.openshift} + + + org.jboss.as + jboss-as-dist + ${version.jbossas.openshift} + zip + + + org.jboss.as + jboss-as-arquillian-container-managed + ${version.jbossas.openshift} + + + + diff --git a/release/jboss-as7/pom.xml b/release/jboss-as7/pom.xml new file mode 100644 index 000000000..918f5bc99 --- /dev/null +++ b/release/jboss-as7/pom.xml @@ -0,0 +1,713 @@ + + + + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-container-parent + pom + SwitchYard: Container Parent + SwitchYard Container Parent + + tests + extension + modules + bundle + + + + org.switchyard + switchyard-release-distribution + + + + org.jvnet.mock-javamail + mock-javamail + test + + + org.switchyard + switchyard-release-testutil + test + + + org.jboss.shrinkwrap + shrinkwrap-impl-base + + + org.jboss.shrinkwrap + shrinkwrap-api + + + org.jboss.shrinkwrap + shrinkwrap-spi + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-api + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-impl-maven + + + org.jboss.as + jboss-as-server + + + + + com.h2database + h2 + provided + + + commons-codec + commons-codec + test + + + org.apache.activemq + activemq-broker + + + org.apache.activemq + activemq-mqtt + + + + org.switchyard.quickstarts + switchyard-transform-json + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-transform-smooks + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-transform-jaxb + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-transform-xslt + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-transform-dozer + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-service + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-bean-service + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-file-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-cxf-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-hl7 + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-jms-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-jpa-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-ftp-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-mail-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-mqtt-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-netty-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-quartz-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-rss-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-sap-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-saxon + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-sql-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-camel-soap-proxy-reverse-service + war + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-ear-deployment-ear-assembly + ear + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-http-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-remote-invoker + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-rest-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-rules-camel-cbr + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-rules-interview + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-rules-interview-container + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-rules-interview-dtable + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-soap-addressing + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-soap-attachment + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-soap-binding-rpc + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-soap-mtom + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-bpm-service + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-bpel-say-hello + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-bpel-loan-approval + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-bpel-jms-binding + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-validate-xml + test + + + * + * + + + + + org.switchyard.quickstarts + switchyard-jca-inflow-hornetq + test + + + org.jboss.as + jboss-as-connector + + + + + org.switchyard.quickstarts + switchyard-jca-outbound-hornetq + test + + + org.jboss.as + jboss-as-connector + + + + + org.switchyard.quickstarts + switchyard-camel-bus-cdi + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-orders + war + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-transaction + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-helpdesk + war + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-library + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-basic + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-security-propagation-basic + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-cert + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-saml + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-wss-signencrypt + test + + + * + * + + + + + org.switchyard.quickstarts.demos + switchyard-demo-policy-security-wss-username + test + + + * + * + + + + + + + wildfly + + false + + + wildfly + + + + eap + + true + + + standalone + + + + openshift + + false + + + openshift + + + + diff --git a/release/jboss-as7/standalone/dist/assembly-final.xml b/release/jboss-as7/standalone/dist/assembly-final.xml new file mode 100644 index 000000000..389db88fb --- /dev/null +++ b/release/jboss-as7/standalone/dist/assembly-final.xml @@ -0,0 +1,33 @@ + + SwitchYard + false + + zip + + + + + ${staging.jboss.dir} + + *.txt + standalone/**/standalone*.xml + domain/**/domain*.xml + modules/system/layers/bpms/** + modules/system/layers/soa/** + modules/layers.conf + quickstarts/** + + + quickstarts/bpel-xts-subordinate-wsba/** + quickstarts/bpel-xts-wsat/** + quickstarts/demos/webapp-deploy/** + standalone/configuration/standalone_xml_history/** + + 644 + 755 + ${distro.root.dir} + + + diff --git a/release/jboss-as7/standalone/dist/pom.xml b/release/jboss-as7/standalone/dist/pom.xml new file mode 100644 index 000000000..46f583921 --- /dev/null +++ b/release/jboss-as7/standalone/dist/pom.xml @@ -0,0 +1,359 @@ + + + + + org.switchyard + switchyard-as7-standalone-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-standalone-dist + jar + SwitchYard: AS7 Distribution + SwitchYard AS7 Distribution + + ${project.build.directory}/jboss-switchyard + jboss-eap-${version.redhat.eap6} + ${staging.dir}/${redhat.eap6.dir} + ${staging.dir}/configs + switchyard-${project.version}-EAP${version.redhat.eap6}.${version.redhat.eap6.minor} + / + /switchyard-as7-installer-${version.distro} + ${staging.jboss.dir} + ${distro.file.final}.zip + + + + org.switchyard + switchyard-as7-standalone-bundle + zip + + + * + * + + + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + org.jboss.arquillian.container + arquillian-container-test-api + test + + + org.jboss.as + jboss-as-arquillian-container-managed + test + + + org.jboss.as + jboss-as-arquillian-common + test + + + org.jboss.as + jboss-as-arquillian-testenricher-msc + test + + + org.jboss.as + jboss-as-arquillian-protocol-jmx + test + + + org.jboss.shrinkwrap.descriptors + shrinkwrap-descriptors-impl-javaee + test + + + + org.jboss.ws.cxf + jbossws-cxf-client + test + + + org.jboss.ws.cxf + jbossws-cxf-factories + test + + + org.jboss.ws.cxf + jbossws-cxf-transports-httpserver + test + + + org.apache.cxf + cxf-rt-core + test + + + org.apache.cxf + cxf-rt-frontend-simple + test + + + org.apache.cxf + cxf-rt-frontend-jaxws + test + + + org.apache.cxf + cxf-rt-bindings-soap + test + + + org.apache.cxf + cxf-rt-bindings-xml + test + + + org.apache.cxf + cxf-rt-databinding-jaxb + test + + + org.apache.camel + camel-hl7 + test + + + org.apache.camel + camel-mina2 + test + + + org.picketlink + picketlink-federation + test + + + + + + src/test/resources + true + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + org.apache.maven.plugins + maven-enforcer-plugin + + + enforce-property + + enforce + + + + + eap.home + You must set eap.home property! + + + true + + + + + + maven-dependency-plugin + + + unpack-bundle + generate-sources + + unpack + + + + + org.switchyard + switchyard-as7-standalone-bundle + zip + ${project.version} + + + ${staging.jboss.dir} + + + + unpack-tests + generate-sources + + unpack + + + + + org.switchyard + switchyard-as7-tests + test-jar + ${project.version} + + + **/*/CamelSOAPProxyQuickstartTest.class, **/*/HelpDeskDemoQuickstartTest.class + ${project.build.testOutputDirectory} + + + + + + org.codehaus.mojo + xml-maven-plugin + + + generate-sources + + transform + + + + + true + + + src/main/resources + + standalone.xml + standalone-ha.xml + standalone-full-ha.xml + standalone-full.xml + + ${staging.jboss.dir}/standalone/configuration + ${staging.jboss.dir}/xsl/standalone.xsl + + + ${staging.jboss.dir}/standalone/configuration + + standalone-ha.xml + standalone-full-ha.xml + + ${staging.jboss.dir}/standalone/configuration + ${staging.jboss.dir}/xsl/standalone-ha.xsl + + + src/main/resources + + domain.xml + + ${staging.jboss.dir}/domain/configuration + ${staging.jboss.dir}/xsl/domain.xsl + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + assembly-full-dist + generate-sources + + single + + + false + ${distro.file.final} + + ${basedir}/assembly-final.xml + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + -Xms512m -Xmx512m + + ${eap.home} + ${project.version} + + + + jboss.home + ${eap.home} + + + module.path + ${eap.home}/modules + + + server-config + standalone-full.xml + + + jboss.options + -Xms256m -Xmx1024m -XX:MaxPermSize=512m + + + false + true + always + + + + + + + default + + + eap.home + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + prepare + process-test-classes + + + + + + + + + run + + + + + + + + + diff --git a/release/jboss-as7/standalone/dist/src/main/resources/domain.xml b/release/jboss-as7/standalone/dist/src/main/resources/domain.xml new file mode 100644 index 000000000..e9963de4c --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/main/resources/domain.xml @@ -0,0 +1,1407 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + NIO + 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + jms.queue.DLQ + jms.queue.ExpiryQueue + 0 + 10485760 + PAGE + 2097152 + 10 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${jboss.messaging.cluster.password:CHANGE ME!!} + true + NIO + 2 + + + + + + + + + + + + + + + + + + messaging-group + 5000 + netty + + + + + messaging-group + 10000 + + + + +
jms
+ netty + +
+
+ + + + + + + + + + + + jms.queue.DLQ + jms.queue.ExpiryQueue + 0 + 1000 + 10485760 + PAGE + 2097152 + 10 + + + + + + + + + + + + + + + + + + + true + true + 1000 + 1.0 + -1 + + + + + + + + + + + + + + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/release/jboss-as7/standalone/dist/src/main/resources/standalone-full-ha.xml b/release/jboss-as7/standalone/dist/src/main/resources/standalone-full-ha.xml new file mode 100644 index 000000000..19b00244c --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/main/resources/standalone-full-ha.xml @@ -0,0 +1,538 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${jboss.messaging.cluster.password:CHANGE ME!!} + true + NIO + 2 + + + + + + + + + + + + + + + + + + messaging-group + 5000 + netty + + + + + messaging-group + 10000 + + + + +
jms
+ netty + +
+
+ + + + + + + + + + + + jms.queue.DLQ + jms.queue.ExpiryQueue + 0 + 1000 + 10485760 + PAGE + 2097152 + 10 + + + + + + + + + + + + + + + + + + + true + true + 1000 + 1.0 + -1 + + + + + + + + + + + + + + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/release/jboss-as7/standalone/dist/src/main/resources/standalone-full.xml b/release/jboss-as7/standalone/dist/src/main/resources/standalone-full.xml new file mode 100644 index 000000000..401dbcb82 --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/main/resources/standalone-full.xml @@ -0,0 +1,441 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + NIO + 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + jms.queue.DLQ + jms.queue.ExpiryQueue + 0 + 10485760 + PAGE + 2097152 + 10 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/release/jboss-as7/standalone/dist/src/main/resources/standalone-ha.xml b/release/jboss-as7/standalone/dist/src/main/resources/standalone-ha.xml new file mode 100644 index 000000000..370beb439 --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/main/resources/standalone-ha.xml @@ -0,0 +1,419 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/release/jboss-as7/standalone/dist/src/main/resources/standalone-osgi.xml b/release/jboss-as7/standalone/dist/src/main/resources/standalone-osgi.xml new file mode 100644 index 000000000..283380da4 --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/main/resources/standalone-osgi.xml @@ -0,0 +1,366 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/release/jboss-as7/standalone/dist/src/main/resources/standalone.xml b/release/jboss-as7/standalone/dist/src/main/resources/standalone.xml new file mode 100644 index 000000000..b4be56ad5 --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/main/resources/standalone.xml @@ -0,0 +1,339 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/release/jboss-as7/standalone/dist/src/test/java/org/switchyard/test/PatchingApplicationArchiveProcessor.java b/release/jboss-as7/standalone/dist/src/test/java/org/switchyard/test/PatchingApplicationArchiveProcessor.java new file mode 100644 index 000000000..1766142c1 --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/test/java/org/switchyard/test/PatchingApplicationArchiveProcessor.java @@ -0,0 +1,122 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; +import org.jboss.arquillian.test.spi.TestClass; +import org.jboss.osgi.spi.BundleInfo; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ArchivePath; +import org.jboss.shrinkwrap.api.ArchivePaths; +import org.jboss.shrinkwrap.api.Node; +import org.jboss.shrinkwrap.api.asset.Asset; +import org.jboss.shrinkwrap.api.container.ManifestContainer; + +/** + * This patches up the dependencies for OSGi bundles deployed as plain JAR + * files. Arquillian does not add these dependencies if the JAR is an OSGi + * budle, even if the OSGi subsystem is not enabled. + */ +public class PatchingApplicationArchiveProcessor implements ApplicationArchiveProcessor { + + private static final List defaultDependencies = new ArrayList(); + + static { + defaultDependencies.add("deployment.arquillian-service"); + defaultDependencies.add("org.jboss.modules"); + defaultDependencies.add("org.jboss.msc"); + } + + /* + * copied from org.jboss.as.arquillian.protocol.jmx.JMXProtocolPackager. + * addModulesManifestDependencies() + * + * We need to add the dependencies even if the bundle contains osgi + * metadata. + */ + @Override + public void process(Archive appArchive, TestClass testClass) { + if (appArchive instanceof ManifestContainer == false) + throw new IllegalArgumentException("ManifestContainer expected " + appArchive); + + final Manifest manifest = getOrCreateManifest(appArchive); + + // We need it enriched... + // Don't enrich with Modules Dependencies if this is a OSGi bundle + if (!BundleInfo.isValidBundleManifest(manifest)) { + return; + } + + Attributes attributes = manifest.getMainAttributes(); + if (attributes.getValue(Attributes.Name.MANIFEST_VERSION.toString()) == null) { + attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); + } + String value = attributes.getValue("Dependencies"); + StringBuffer moduleDeps = new StringBuffer(value != null && value.trim().length() > 0 ? value + : "org.jboss.modules"); + for (String dep : defaultDependencies) { + if (moduleDeps.indexOf(dep) < 0) + moduleDeps.append("," + dep); + } + + // log.debugf("Add dependencies: %s", moduleDeps); + attributes.putValue("Dependencies", moduleDeps.toString()); + + // Add the manifest to the archive + ArchivePath manifestPath = ArchivePaths.create(JarFile.MANIFEST_NAME); + appArchive.delete(manifestPath); + appArchive.add(new Asset() { + public InputStream openStream() { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + manifest.write(baos); + return new ByteArrayInputStream(baos.toByteArray()); + } catch (IOException ex) { + throw new IllegalStateException("Cannot write manifest", ex); + } + } + }, manifestPath); + } + + /* + * Copied from org.jboss.as.arquillian.protocol.jmx.ManifestUtils + */ + private Manifest getOrCreateManifest(Archive archive) { + Manifest manifest; + try { + Node node = archive.get(JarFile.MANIFEST_NAME); + if (node == null) { + manifest = new Manifest(); + Attributes attributes = manifest.getMainAttributes(); + attributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); + } else { + manifest = new Manifest(node.getAsset().openStream()); + } + return manifest; + } catch (Exception ex) { + throw new IllegalStateException("Cannot obtain manifest", ex); + } + } + +} diff --git a/release/jboss-as7/standalone/dist/src/test/java/org/switchyard/test/SwitchYardContainerExtension.java b/release/jboss-as7/standalone/dist/src/test/java/org/switchyard/test/SwitchYardContainerExtension.java new file mode 100644 index 000000000..4590f41fd --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/test/java/org/switchyard/test/SwitchYardContainerExtension.java @@ -0,0 +1,30 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test; + +import org.jboss.arquillian.container.test.spi.client.deployment.ApplicationArchiveProcessor; +import org.jboss.arquillian.core.spi.LoadableExtension; + +/** + * Workaround issue in Arquillian where dependencies are not added properly for + * deployments with OSGi metadata. + */ +public class SwitchYardContainerExtension implements LoadableExtension { + + @Override + public void register(ExtensionBuilder builder) { + builder.service(ApplicationArchiveProcessor.class, PatchingApplicationArchiveProcessor.class); + } + +} diff --git a/release/jboss-as7/standalone/dist/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension b/release/jboss-as7/standalone/dist/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension new file mode 100644 index 000000000..afa4d53c0 --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/test/resources/META-INF/services/org.jboss.arquillian.core.spi.LoadableExtension @@ -0,0 +1 @@ +org.switchyard.test.SwitchYardContainerExtension \ No newline at end of file diff --git a/release/jboss-as7/standalone/dist/src/test/resources/arquillian.xml b/release/jboss-as7/standalone/dist/src/test/resources/arquillian.xml new file mode 100644 index 000000000..3474cd6ee --- /dev/null +++ b/release/jboss-as7/standalone/dist/src/test/resources/arquillian.xml @@ -0,0 +1,13 @@ + + + + + + 120 + standalone-full.xml + + + diff --git a/release/jboss-as7/standalone/pom.xml b/release/jboss-as7/standalone/pom.xml new file mode 100644 index 000000000..1e75c3b21 --- /dev/null +++ b/release/jboss-as7/standalone/pom.xml @@ -0,0 +1,30 @@ + + + + + org.switchyard + switchyard-container-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-standalone-parent + pom + SwitchYard: AS7 Standalone Parent + SwitchYard AS7 Standalone Parent + + dist + + diff --git a/release/jboss-as7/tests/RunningTests.txt b/release/jboss-as7/tests/RunningTests.txt new file mode 100644 index 000000000..f43961494 --- /dev/null +++ b/release/jboss-as7/tests/RunningTests.txt @@ -0,0 +1,25 @@ +The test cases in this project are designed to be executed during packaging of a +distribution (e.g. as7 standalone dist), but they can be run out of your IDE +(e.g. Run As->JUnit Test) when your test runner is configured with the +following: + + * VM arguments: (e.g. using -D) + * jboss.home= + (e.g. ~/test/switchyard/switchyard-1.0-SNAPSHOT/jboss-eap-6.1) + * module.path=/modules + (e.g. ~/test/switchyard/switchyard-1.0-SNAPSHOT/jboss-eap-6.1/modules) + * server-config=standalone-full.xml + * arquillian.xml= + (e.g. ~/src/git/switchyard/release/jboss-as7/standalone/dist/src/test/resources/arquillian.xml) + + And to enable debugging of the container: (optional) + * jboss.options="-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n -Xmx512m -XX:MaxPermSize=128m" + + * Environment variables: + * JBOSS_HOME= + (e.g. ~/test/switchyard/switchyard-1.0-SNAPSHOT/jboss-eap-6.1) + * SWITCHYARD_VERSION= (e.g. 1.0.0-SNAPSHOT) + +In addition to the above, you will also need to enable the "dev-test" profile +in your IDE (defined in the project's pom). (This provides as7 container +support when running the tests.) diff --git a/release/jboss-as7/tests/pom.xml b/release/jboss-as7/tests/pom.xml new file mode 100644 index 000000000..bf4e9d977 --- /dev/null +++ b/release/jboss-as7/tests/pom.xml @@ -0,0 +1,129 @@ + + + + + org.switchyard + switchyard-container-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-as7-tests + jar + SwitchYard: AS7 Release Distribution Tests + SwitchYard AS7 Release Distribution Tests + + + org.switchyard + switchyard-test + + + org.switchyard + switchyard-remote + + + org.switchyard.components + switchyard-component-bean + + + org.switchyard.components + switchyard-component-jca + + + org.switchyard.components + switchyard-component-soap + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + + + org.switchyard.components + switchyard-component-test-mixin-http + + + org.switchyard + switchyard-release-testutil + + + org.jboss.arquillian.junit + arquillian-junit-container + + + org.jboss.shrinkwrap.descriptors + shrinkwrap-descriptors-impl-javaee + + + org.jboss.as + jboss-as-arquillian-common + + + org.apache.activemq + activemq-broker + + + org.apache.activemq + activemq-mqtt + + + org.fusesource.mqtt-client + mqtt-client + + + org.apache.camel + camel-hl7 + test + + + org.picketlink + picketlink-federation + test + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + + dev-test + + + org.jboss.as + jboss-as-arquillian-container-managed + test + + + + + diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReference.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReference.java new file mode 100644 index 000000000..b32a067b0 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReference.java @@ -0,0 +1,7 @@ +package org.switchyard.test.jca; + +import java.util.Map; + +public interface JCACCIReference { + public Map onMessage(Map body); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceBindingTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceBindingTest.java new file mode 100644 index 000000000..fcaeb8c07 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceBindingTest.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca; + +import java.io.IOException; +import java.net.URL; + +import javax.naming.InitialContext; +import javax.resource.cci.InteractionSpec; +import javax.resource.cci.MappedRecord; +import javax.resource.cci.Record; + +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.asset.UrlAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; +import org.jboss.shrinkwrap.descriptor.api.Descriptors; +import org.jboss.shrinkwrap.descriptor.api.beans10.BeansDescriptor; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.type.Classes; +import org.switchyard.test.jca.mockra.InteractionListener; +import org.switchyard.test.jca.mockra.MockConnectionFactory; +import org.switchyard.test.jca.mockra.MockRecordFactory; +import org.switchyard.test.jca.mockra.MockResourceAdapter; +import org.switchyard.test.jca.mockra.MockResourceAdapterUtil; + +/** + * Functional test for JCA CCI Reference binding. + */ +@RunWith(Arquillian.class) +public class JCACCIReferenceBindingTest { + + private static final String TEST_CONFIG = "org/switchyard/test/jca/switchyard-outbound-cci-test.xml"; + private static final String DEPLOYMENT_STRUCTURE = "org/switchyard/test/jca/cci-test-app-deployment-structure.xml"; + private static final String JNDI_PROPERTIES = "org/switchyard/test/jca/outbound-jms-jndi.properties"; + private static final String APP_NAME = "switchyard-JCACCIReferenceBindingTest.jar"; + + private MockResourceAdapter _adapter; + private MockRecordFactory _recordFactory; + + @ArquillianResource + InitialContext _context; + + @Deployment(order = 1, name = MockResourceAdapterUtil.ADAPTER_ARCHIVE_NAME) + public static ResourceAdapterArchive createResourceAdapter() throws IOException { + return MockResourceAdapterUtil.createMockResourceAdapterArchive(); + } + + @Deployment(order = 2) + public static JavaArchive createDeployment() throws Exception { + URL testConfigUrl = Classes.getResource(TEST_CONFIG); + URL deploymentStructureUrl = Classes.getResource(DEPLOYMENT_STRUCTURE); + URL jndiProperties = Classes.getResource(JNDI_PROPERTIES); + String beansXml = Descriptors.create(BeansDescriptor.class).exportAsString(); + return ShrinkWrap.create(JavaArchive.class, APP_NAME) + .addClass(JCACCIReference.class) + .addClass(JCACCIReferenceService.class) + .addClass(JCACCIReferenceServiceImpl.class) + .addAsResource(new UrlAsset(jndiProperties), "jndi.properties") + .addAsManifestResource(new UrlAsset(deploymentStructureUrl), "jboss-deployment-structure.xml") + .addAsManifestResource(new UrlAsset(testConfigUrl), "switchyard.xml") + .addAsManifestResource(new StringAsset(beansXml), "beans.xml"); + } + + @Before + public void before() { + try { + _recordFactory = new MockRecordFactory(); + MockConnectionFactory factory = (MockConnectionFactory) _context.lookup(MockResourceAdapterUtil.JNDI_CONNECTION_FACTORY); + factory.setInteractionListener(new InteractionListener() { + public Record onExecute(InteractionSpec spec, Record input) { + MappedRecord mapped = (MappedRecord) input; + mapped.put("name", "Hello, " + mapped.get("name") + "!"); + return mapped; + } + public boolean onExecute(InteractionSpec spec, Record input, Record output) {return true;} + }); + _adapter = (MockResourceAdapter) _context.lookup(MockResourceAdapterUtil.JNDI_ADAPTER); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testOutboundCCI() throws Exception { + _adapter.fireCreateEndpoint(); + MappedRecord input = _recordFactory.createMappedRecord("testOutboundCCI input"); + input.put("name", "Uragasumi"); + Record result = _adapter.fireDelivery(input); + _adapter.fireRelease(); + Assert.assertTrue(result instanceof MappedRecord); + Assert.assertEquals("Hello, Uragasumi!", MappedRecord.class.cast(result).get("name")); + } +} + diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceService.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceService.java new file mode 100644 index 000000000..46321a3e1 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceService.java @@ -0,0 +1,7 @@ +package org.switchyard.test.jca; + +import java.util.Map; + +public interface JCACCIReferenceService { + public Map onMessage(Map map); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceServiceImpl.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceServiceImpl.java new file mode 100644 index 000000000..5b430da3d --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIReferenceServiceImpl.java @@ -0,0 +1,19 @@ +package org.switchyard.test.jca; + +import java.util.Map; + +import javax.inject.Inject; + +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; + +@Service(JCACCIReferenceService.class) +public class JCACCIReferenceServiceImpl implements JCACCIReferenceService { + @Inject @Reference + private JCACCIReference service; + + @Override + public Map onMessage(Map map) { + return service.onMessage(map); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIService.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIService.java new file mode 100644 index 000000000..a2483f2c7 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIService.java @@ -0,0 +1,7 @@ +package org.switchyard.test.jca; + +import java.util.Map; + +public interface JCACCIService { + public Map onMessage(Map map); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIServiceBindingTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIServiceBindingTest.java new file mode 100644 index 000000000..0bd675b31 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIServiceBindingTest.java @@ -0,0 +1,160 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca; + +import java.io.IOException; +import java.net.URL; + +import javax.naming.InitialContext; +import javax.resource.cci.MappedRecord; +import javax.resource.cci.Record; + +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.asset.UrlAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; +import org.jboss.shrinkwrap.descriptor.api.Descriptors; +import org.jboss.shrinkwrap.descriptor.api.beans10.BeansDescriptor; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.type.Classes; +import org.switchyard.test.jca.mockra.MockRecordFactory; +import org.switchyard.test.jca.mockra.MockResourceAdapter; +import org.switchyard.test.jca.mockra.MockResourceAdapterUtil; + +/** + * Functional test for JCA CCI Service binding. + */ +@RunWith(Arquillian.class) +public class JCACCIServiceBindingTest { + + private static final String TEST_CONFIG = "org/switchyard/test/jca/switchyard-inbound-cci-test.xml"; + private static final String DEPLOYMENT_STRUCTURE = "org/switchyard/test/jca/cci-test-app-deployment-structure.xml"; + private static final String APP_NAME = "switchyard-JCACCIServiceBindingTest.jar"; + + private MockResourceAdapter _adapter; + private MockRecordFactory _recordFactory; + + @ArquillianResource + private InitialContext _context; + + @Deployment(order = 1, name = MockResourceAdapterUtil.ADAPTER_ARCHIVE_NAME) + public static ResourceAdapterArchive createResourceAdapter() throws IOException { + return MockResourceAdapterUtil.createMockResourceAdapterArchive(); + } + + @Deployment(order = 2) + public static JavaArchive createDeployment() throws Exception { + URL testConfigUrl = Classes.getResource(TEST_CONFIG); + URL deploymentStructureUrl = Classes.getResource(DEPLOYMENT_STRUCTURE); + String beansXml = Descriptors.create(BeansDescriptor.class).exportAsString(); + return ShrinkWrap.create(JavaArchive.class, APP_NAME) + .addClass(JCACCIService.class) + .addClass(JCACCIServiceImpl.class) + .addAsManifestResource(new UrlAsset(deploymentStructureUrl), "jboss-deployment-structure.xml") + .addAsManifestResource(new UrlAsset(testConfigUrl), "switchyard.xml") + .addAsManifestResource(new StringAsset(beansXml), "beans.xml"); + } + + @Before + public void before() { + try { + _recordFactory = new MockRecordFactory(); + _adapter = (MockResourceAdapter) _context.lookup(MockResourceAdapterUtil.JNDI_ADAPTER); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testInflowCCI() throws Exception { + _adapter.fireCreateEndpoint(); + MappedRecord input = _recordFactory.createMappedRecord("testInflowCCI input"); + input.put("input", "World"); + Record result = _adapter.fireDelivery(input); + _adapter.fireRelease(); + + Assert.assertTrue(result instanceof MappedRecord); + Assert.assertEquals("Hello World !", ((MappedRecord)result).get("input")); + } + + @Test + public void testInflowCCIWithBeforeAfterDelivery() throws Exception { + _adapter.fireCreateEndpoint(); + _adapter.fireBeforeDelivery(); + MappedRecord input1 = _recordFactory.createMappedRecord("testInflowCCIWithBeforeAfterDelivery input1"); + input1.put("input", "World2"); + Record result1 = _adapter.fireDelivery(input1); + _adapter.fireAfterDelivery(); + + Assert.assertTrue(result1 instanceof MappedRecord); + Assert.assertEquals("Hello World2 !", ((MappedRecord)result1).get("input")); + } + + @Test + public void testInflowCCIReuseReleasedEndpoint() throws Exception { + _adapter.fireCreateEndpoint(); + MappedRecord input1 = _recordFactory.createMappedRecord("testInflowCCIReuseReleasedEndpoint input1"); + input1.put("input", "World3"); + Record result1 = _adapter.fireDelivery(input1); + Assert.assertTrue(result1 instanceof MappedRecord); + Assert.assertEquals("Hello World3 !", ((MappedRecord)result1).get("input")); + _adapter.fireRelease(); + + MappedRecord input2 = _recordFactory.createMappedRecord("testInflowCCIReuseReleasedEndpoint input2"); + input2.put("input", "World4"); + Record result2 = _adapter.fireDelivery(input2); + Assert.assertTrue(result2 instanceof MappedRecord); + Assert.assertEquals("Hello World4 !", ((MappedRecord)result2).get("input")); + } + + @Test(expected = RuntimeException.class) + public void testInflowCCIErrorMultipleDelivery() throws Exception { + _adapter.fireCreateEndpoint(); + _adapter.fireBeforeDelivery(); + MappedRecord input1 = _recordFactory.createMappedRecord("testInflowCCIErrorMultipleDelivery input1"); + input1.put("input", "World5"); + MappedRecord input2 = _recordFactory.createMappedRecord("testInflowCCIErrorMultipleDelivery input2"); + input2.put("input", "World6"); + Record result1 = _adapter.fireDelivery(input1); + Record result2 = _adapter.fireDelivery(input2); + } + + @Test(expected = RuntimeException.class) + public void testInflowCCIErrorAfterDeliveryWithoutBefore() throws Exception { + _adapter.fireCreateEndpoint(); + MappedRecord input1 = _recordFactory.createMappedRecord("testInflowCCIErrorAfterDeliveryWithoutBefore input1"); + input1.put("input", "World7"); + Record result1 = _adapter.fireDelivery(input1); + _adapter.fireAfterDelivery(); + } + + @Test(expected = RuntimeException.class) + public void testInflowCCIErrorBeforeDeliveryWithoutPreviousAfter() throws Exception { + _adapter.fireCreateEndpoint(); + _adapter.fireBeforeDelivery(); + MappedRecord input1 = _recordFactory.createMappedRecord("testInflowCCIErrorBeforeDeliveryWithoutPreviousAfter input1"); + input1.put("input", "World8"); + Record result1 = _adapter.fireDelivery(input1); + + _adapter.fireBeforeDelivery(); + } +} + diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIServiceImpl.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIServiceImpl.java new file mode 100644 index 000000000..218de223d --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIServiceImpl.java @@ -0,0 +1,14 @@ +package org.switchyard.test.jca; + +import java.util.Map; + +import org.switchyard.component.bean.Service; + +@Service(JCACCIService.class) +public class JCACCIServiceImpl implements JCACCIService { + @Override + public Map onMessage(Map map) { + map.put("input", "Hello " + map.get("input") + " !"); + return map; + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReference.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReference.java new file mode 100644 index 000000000..e9d2fc43e --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReference.java @@ -0,0 +1,7 @@ +package org.switchyard.test.jca; + +import java.io.InputStream; + +public interface JCACCIStreamReference { + public InputStream onMessage(InputStream body); +} \ No newline at end of file diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceBindingTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceBindingTest.java new file mode 100644 index 000000000..70f9b096c --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceBindingTest.java @@ -0,0 +1,127 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import javax.naming.InitialContext; +import javax.resource.cci.InteractionSpec; +import javax.resource.cci.Record; + +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.asset.UrlAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; +import org.jboss.shrinkwrap.descriptor.api.Descriptors; +import org.jboss.shrinkwrap.descriptor.api.beans10.BeansDescriptor; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.type.Classes; +import org.switchyard.component.jca.processor.cci.StreamableRecord; +import org.switchyard.test.jca.mockra.InteractionListener; +import org.switchyard.test.jca.mockra.MockConnectionFactory; +import org.switchyard.test.jca.mockra.MockResourceAdapter; +import org.switchyard.test.jca.mockra.MockResourceAdapterUtil; + +/** + * Functional test for outbound JCA CCI with streamable record. + * + * @author Tomohisa Igarashi + * @author Antti Laisi + * + */ +@RunWith(Arquillian.class) +public class JCACCIStreamReferenceBindingTest { + + private static final String TEST_CONFIG = "org/switchyard/test/jca/switchyard-outbound-cci-stream-test.xml"; + private static final String DEPLOYMENT_STRUCTURE = "org/switchyard/test/jca/cci-test-app-deployment-structure.xml"; + private static final String APP_NAME = "switchyard-JCACCIStreamReferenceBindingTest.jar"; + + private MockResourceAdapter _adapter; + + @ArquillianResource + InitialContext _context; + + @Deployment(order = 1, name = MockResourceAdapterUtil.ADAPTER_ARCHIVE_NAME) + public static ResourceAdapterArchive createResourceAdapter() throws IOException { + return MockResourceAdapterUtil.createMockResourceAdapterArchive(); + } + + @Deployment(order = 2) + public static JavaArchive createDeployment() throws Exception { + URL testConfigUrl = Classes.getResource(TEST_CONFIG); + URL deploymentStructureUrl = Classes.getResource(DEPLOYMENT_STRUCTURE); + String beansXml = Descriptors.create(BeansDescriptor.class).exportAsString(); + return ShrinkWrap.create(JavaArchive.class, APP_NAME) + .addClass(MyStreamableRecordCCIEndpoint.class) + .addClass(JCACCIStreamReference.class) + .addClass(JCACCIStreamReferenceService.class) + .addClass(JCACCIStreamReferenceServiceImpl.class) + .addAsManifestResource(new UrlAsset(deploymentStructureUrl), "jboss-deployment-structure.xml") + .addAsManifestResource(new UrlAsset(testConfigUrl), "switchyard.xml") + .addAsManifestResource(new StringAsset(beansXml), "beans.xml"); + } + + @Before + public void before() { + try { + MockConnectionFactory factory = (MockConnectionFactory) _context.lookup(MockResourceAdapterUtil.JNDI_CONNECTION_FACTORY); + factory.setInteractionListener(new InteractionListener() { + public Record onExecute(InteractionSpec spec, Record input) { return null; } + public boolean onExecute(InteractionSpec spec, Record input, Record output) { + StreamableRecord in = (StreamableRecord) input; + StreamableRecord out = (StreamableRecord) output; + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + in.write(baos); + String msg = "Hello, " + new String(baos.toByteArray()) + "!"; + out.read(new ByteArrayInputStream(msg.getBytes())); + } catch(Exception e) { + e.printStackTrace(); + Assert.fail(e.getMessage()); + } + return true; + } + }); + _adapter = (MockResourceAdapter) _context.lookup(MockResourceAdapterUtil.JNDI_ADAPTER); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testOutboundCCI() throws Exception { + _adapter.fireCreateEndpoint(); + StreamableRecord input = new StreamableRecord(); + InputStream payload = new ByteArrayInputStream("Antti".getBytes()); + input.read(payload); + Record result = _adapter.fireDelivery(input); + _adapter.fireRelease(); + Assert.assertTrue(result instanceof StreamableRecord); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + StreamableRecord.class.cast(result).write(baos); + Assert.assertEquals("Hello, Antti!", new String(baos.toByteArray())); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceService.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceService.java new file mode 100644 index 000000000..aeaee1989 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceService.java @@ -0,0 +1,7 @@ +package org.switchyard.test.jca; + +import java.io.InputStream; + +public interface JCACCIStreamReferenceService { + public InputStream onMessage(InputStream body); +} \ No newline at end of file diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceServiceImpl.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceServiceImpl.java new file mode 100644 index 000000000..544ea43ae --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCACCIStreamReferenceServiceImpl.java @@ -0,0 +1,19 @@ +package org.switchyard.test.jca; + +import java.io.InputStream; + +import javax.inject.Inject; + +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; + +@Service(JCACCIStreamReferenceService.class) +public class JCACCIStreamReferenceServiceImpl implements JCACCIStreamReferenceService { + @Inject @Reference + private JCACCIStreamReference service; + + @Override + public InputStream onMessage(InputStream body) { + return service.onMessage(body); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSFault.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSFault.java new file mode 100644 index 000000000..a1c4b907c --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSFault.java @@ -0,0 +1,8 @@ +package org.switchyard.test.jca; + +@SuppressWarnings("serial") +public class JCAJMSFault extends Exception { + public JCAJMSFault(String message) { + super(message); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReference.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReference.java new file mode 100644 index 000000000..c55c1ce6e --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReference.java @@ -0,0 +1,5 @@ +package org.switchyard.test.jca; + +public interface JCAJMSReference { + public void onMessage(String body); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceBindingTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceBindingTest.java new file mode 100644 index 000000000..77023c542 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceBindingTest.java @@ -0,0 +1,271 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca; + +import java.net.URL; + +import javax.jms.BytesMessage; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.ObjectMessage; +import javax.jms.Session; +import javax.jms.TextMessage; + +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.logging.Logger; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.asset.UrlAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.descriptor.api.Descriptors; +import org.jboss.shrinkwrap.descriptor.api.beans10.BeansDescriptor; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.type.Classes; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +/** + * Functional test for JCA reference binding. + */ +@RunWith(Arquillian.class) +public class JCAJMSReferenceBindingTest { + + private static final String TEST_CONFIG = "org/switchyard/test/jca/switchyard-outbound-jms-test.xml"; + private static final String CAMEL_ROUTE = "org/switchyard/test/jca/switchyard-outbound-jms-camel-test-route.xml"; + private static final String JNDI_PROPERTIES = "org/switchyard/test/jca/outbound-jms-jndi.properties"; + private static final String DEST_JNDI_PROPERTIES = "org/switchyard/test/jca/outbound-jms-destination-jndi.properties"; + private static final String INPUT_TX_QUEUE = "TestQueue"; + private static final String INPUT_NOTX_QUEUE = "NonTransactedTestQueue"; + private static final String OUTPUT_QUEUE = "ResultQueue"; + private static final String OUTPUT_PROP_QUEUE = "ResultPropQueue"; + private static final String OUTPUT_PHYSICAL_NAME_QUEUE = "ResultPhysicalNameQueue"; + private Logger _logger = Logger.getLogger(JCAJMSReferenceBindingTest.class); + private HornetQMixIn _hqMixIn; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws Exception { + ResourceDeployer.addQueue(INPUT_TX_QUEUE); + ResourceDeployer.addQueue(INPUT_NOTX_QUEUE); + ResourceDeployer.addQueue(OUTPUT_QUEUE); + ResourceDeployer.addQueue(OUTPUT_PROP_QUEUE); + ResourceDeployer.addQueue(OUTPUT_PHYSICAL_NAME_QUEUE + "_physical", OUTPUT_PHYSICAL_NAME_QUEUE + "_jndi"); + + URL testConfigUrl = Classes.getResource(TEST_CONFIG); + URL camelRouteUrl = Classes.getResource(CAMEL_ROUTE); + URL jndiProperties = Classes.getResource(JNDI_PROPERTIES); + URL destJndiProperties = Classes.getResource(DEST_JNDI_PROPERTIES); + String beansXml = Descriptors.create(BeansDescriptor.class).exportAsString(); + return ShrinkWrap.create(JavaArchive.class, "switchyard-JCAJMSReferenceBindingTest.jar") + .addClass(JCAJMSTransactionService.class) + .addClass(JCAJMSTransactionServiceImpl.class) + .addClass(JCAJMSReference.class) + .addClass(JCAJMSReferenceText.class) + .addClass(JCAJMSReferencePhysicalName.class) + .addClass(JCAJMSReferenceService.class) + .addClass(JCAJMSReferenceServiceImpl.class) + .addClass(JCAJMSFault.class) + .addClass(MyJMSContextMapper.class) + .addClass(MyJMSMessageComposer.class) + .addAsManifestResource(new UrlAsset(testConfigUrl), "switchyard.xml") + .addAsManifestResource(new StringAsset(beansXml), "beans.xml") + .addAsResource(new UrlAsset(jndiProperties), "jndi.properties") + .addAsResource(new UrlAsset(destJndiProperties), "destination-jndi.properties") + .addAsResource(new UrlAsset(camelRouteUrl), "camel-route.xml"); + } + + @Before + public void before() { + _hqMixIn = new HornetQMixIn(false).setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + _hqMixIn.initialize(); + } + + @After + public void after() { + try { + _hqMixIn.uninitialize(); + ResourceDeployer.removeQueue(INPUT_TX_QUEUE); + ResourceDeployer.removeQueue(INPUT_NOTX_QUEUE); + ResourceDeployer.removeQueue(OUTPUT_QUEUE); + ResourceDeployer.removeQueue(OUTPUT_PROP_QUEUE); + ResourceDeployer.removeQueue(OUTPUT_PHYSICAL_NAME_QUEUE + "_physical"); + } catch (Exception e) { + _logger.warn(e); + } + } + + @Test + public void testUnmanagedOutboundJMS() throws Exception { + String payload = "onMessage"; + Session session = _hqMixIn.createJMSSession(); + + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_NOTX_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(OUTPUT_QUEUE)); + javax.jms.Message msg = consumer.receive(3000); + consumer.close(); + Assert.assertNotNull(msg); + Assert.assertTrue(msg instanceof ObjectMessage); + Assert.assertEquals(payload+"test", ObjectMessage.class.cast(msg).getObject().toString()); + Assert.assertEquals("testVal", msg.getStringProperty("testProp")); + } finally { + session.close(); + } + } + + @Test + public void testUnmanagedOutboundJMSSpecifyingMessageType() throws Exception { + String payload = "onMessageText"; + Session session = _hqMixIn.createJMSSession(); + + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_NOTX_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(OUTPUT_QUEUE)); + javax.jms.Message msg = consumer.receive(3000); + consumer.close(); + Assert.assertNotNull(msg); + Assert.assertTrue(msg instanceof TextMessage); + Assert.assertEquals(payload+"test", TextMessage.class.cast(msg).getText()); + Assert.assertEquals("testVal", msg.getStringProperty("testProp")); + } finally { + session.close(); + } + } + + @Test + public void testManagedOutboundJMS() throws Exception { + String payload = "onMessageManaged"; + Session session = _hqMixIn.createJMSSession(); + + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_TX_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(OUTPUT_QUEUE)); + javax.jms.Message msg = consumer.receive(3000); + consumer.close(); + Assert.assertNotNull(msg); + Assert.assertTrue(msg instanceof ObjectMessage); + Assert.assertEquals(payload+"test", ObjectMessage.class.cast(msg).getObject().toString()); + Assert.assertEquals("testVal", msg.getStringProperty("testProp")); + } finally { + session.close(); + } + } + + @Test + public void testManagedOutboundJMSSetHeaderFromCamelRoute() throws Exception { + String payload = "onMessageCamel"; + Session session = _hqMixIn.createJMSSession(); + + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_TX_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(OUTPUT_QUEUE)); + javax.jms.Message msg = consumer.receive(3000); + consumer.close(); + Assert.assertNotNull(msg); + Assert.assertTrue(msg instanceof ObjectMessage); + Assert.assertEquals(payload, ObjectMessage.class.cast(msg).getObject().toString()); + Assert.assertEquals("jmscorrelation-onMessageCamel", msg.getJMSCorrelationID()); + } finally { + session.close(); + } + } + + @Test + public void testManagedOutboundJMSWithContextProperty() throws Exception { + String payload = "onMessageContextProperty"; + Session session = _hqMixIn.createJMSSession(); + + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_TX_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(OUTPUT_PROP_QUEUE)); + javax.jms.Message msg = consumer.receive(3000); + consumer.close(); + Assert.assertNotNull(msg); + Assert.assertTrue(msg instanceof BytesMessage); + BytesMessage bmsg = BytesMessage.class.cast(msg); + byte[] bytes = new byte[(int)bmsg.getBodyLength()]; + bmsg.readBytes(bytes); + Assert.assertEquals(payload + "test", new String(bytes)); + } finally { + session.close(); + } + } + + @Test + public void testManagedOutboundJMSWithPhysicalDestinationName() throws Exception { + String payload = "onMessagePhysicalName"; + Session session = _hqMixIn.createJMSSession(); + + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_TX_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(OUTPUT_PHYSICAL_NAME_QUEUE + "_physical")); + javax.jms.Message msg = consumer.receive(3000); + consumer.close(); + Assert.assertNotNull(msg); + Assert.assertTrue(msg instanceof TextMessage); + Assert.assertEquals(payload+"test", TextMessage.class.cast(msg).getText()); + Assert.assertEquals("testVal", msg.getStringProperty("testProp")); + } finally { + session.close(); + } + } +} + diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferencePhysicalName.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferencePhysicalName.java new file mode 100644 index 000000000..fa5466514 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferencePhysicalName.java @@ -0,0 +1,5 @@ +package org.switchyard.test.jca; + +public interface JCAJMSReferencePhysicalName { + public void onMessagePhysicalName(String body); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceService.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceService.java new file mode 100644 index 000000000..dfaf0039f --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceService.java @@ -0,0 +1,11 @@ +package org.switchyard.test.jca; + +public interface JCAJMSReferenceService { + public void onMessage(String body); + + public void onMessageText(String body); + + public void onMessageContextProperty(String body) throws Exception; + + public void onMessagePhysicalName(String body); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceServiceImpl.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceServiceImpl.java new file mode 100644 index 000000000..e5d71e768 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceServiceImpl.java @@ -0,0 +1,47 @@ +package org.switchyard.test.jca; + +import javax.inject.Inject; + +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.ReferenceInvoker; +import org.switchyard.component.bean.Service; +import org.switchyard.component.jca.processor.JMSProcessor; + +@Service(JCAJMSReferenceService.class) +public class JCAJMSReferenceServiceImpl implements JCAJMSReferenceService { + + @Inject @Reference + private JCAJMSReference service; + + @Inject @Reference + private JCAJMSReferenceText serviceText; + + @Inject @Reference("JCAJMSReference") + private ReferenceInvoker referenceInvoker; + + @Inject @Reference + private JCAJMSReferencePhysicalName servicePhysicalName; + + @Override + public void onMessage(String name) { + service.onMessage(name); + } + + @Override + public void onMessageText(String name) { + serviceText.onMessageText(name); + } + + @Override + public void onMessageContextProperty(String name) throws Exception { + referenceInvoker.newInvocation("onMessage") + .setProperty(JMSProcessor.CONTEXT_PROPERTY_PREFIX + JMSProcessor.KEY_DESTINATION, "ResultPropQueue") + .setProperty(JMSProcessor.CONTEXT_PROPERTY_PREFIX + JMSProcessor.KEY_MESSAGE_TYPE, "Bytes") + .invoke(name); + } + + @Override + public void onMessagePhysicalName(String name) { + servicePhysicalName.onMessagePhysicalName(name); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceText.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceText.java new file mode 100644 index 000000000..c57eb7889 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSReferenceText.java @@ -0,0 +1,5 @@ +package org.switchyard.test.jca; + +public interface JCAJMSReferenceText { + public void onMessageText(String body); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSService.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSService.java new file mode 100644 index 000000000..8b9a072bb --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSService.java @@ -0,0 +1,19 @@ +package org.switchyard.test.jca; + +public interface JCAJMSService { + public void onMessage(String body); + + public void onMessage_fault_rollback(String name); + + public void onMessage_fault_commit(String name) throws JCAJMSFault; + + public String onMessage_inout(String name); + + public String onMessage_inout_fault(String name) throws JCAJMSFault; + + public String onMessage_inout_context_property(String name); + + public String onMessage_inout_physical_name(String name); + + public String onMessage_inout_physical_name_fault(String name) throws JCAJMSFault; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSServiceBindingTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSServiceBindingTest.java new file mode 100644 index 000000000..5277d0350 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSServiceBindingTest.java @@ -0,0 +1,310 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca; + +import java.net.URL; + +import javax.jms.BytesMessage; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.TextMessage; + +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.logging.Logger; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.asset.UrlAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.descriptor.api.Descriptors; +import org.jboss.shrinkwrap.descriptor.api.beans10.BeansDescriptor; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.type.Classes; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +/** + * Functional tests for JCA service binding. + */ +@RunWith(Arquillian.class) +public class JCAJMSServiceBindingTest { + + private static final String TEST_CONFIG = "org/switchyard/test/jca/switchyard-inbound-jms-test.xml"; + private static final String INPUT_QUEUE = "TestQueue"; + private static final String INPUT_INOUT_QUEUE = "InOutTestQueue"; + private static final String INPUT_INOUT_PHYSICAL_NAME_QUEUE = "InOutPhysicalNameTestQueue"; + private static final String INOUT_REPLY_TO_QUEUE = "InOutTestQueue_replyTo"; + private static final String INOUT_REPLY_TO_PHYSICAL_NAME_QUEUE = "InOutPhysicalNameTestQueue_replyTo"; + private static final String INOUT_FAULT_TO_QUEUE = "InOutTestQueue_faultTo"; + private static final String INOUT_FAULT_TO_PHYSICAL_NAME_QUEUE = "InOutPhysicalNameTestQueue_faultTo"; + private static final String RESULT_QUEUE = "StoreResultQueue"; + private static final String FAULT_QUEUE = "StoreFaultQueue"; + + private Logger _logger = Logger.getLogger(JCAJMSServiceBindingTest.class); + private HornetQMixIn _hqMixIn; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws Exception { + ResourceDeployer.addQueue(INPUT_QUEUE); + ResourceDeployer.addQueue(INPUT_INOUT_QUEUE); + ResourceDeployer.addQueue(INPUT_INOUT_PHYSICAL_NAME_QUEUE + "_physical", INPUT_INOUT_PHYSICAL_NAME_QUEUE + "_jndi"); + ResourceDeployer.addQueue(INOUT_REPLY_TO_QUEUE); + ResourceDeployer.addQueue(INOUT_REPLY_TO_PHYSICAL_NAME_QUEUE + "_physical", INOUT_REPLY_TO_PHYSICAL_NAME_QUEUE + "_jndi"); + ResourceDeployer.addQueue(INOUT_FAULT_TO_QUEUE); + ResourceDeployer.addQueue(INOUT_FAULT_TO_PHYSICAL_NAME_QUEUE + "_physical", INOUT_FAULT_TO_PHYSICAL_NAME_QUEUE + "_jndi"); + ResourceDeployer.addQueue(RESULT_QUEUE); + ResourceDeployer.addQueue(FAULT_QUEUE); + + URL testConfigUrl = Classes.getResource(TEST_CONFIG); + String beansXml = Descriptors.create(BeansDescriptor.class).exportAsString(); + return ShrinkWrap.create(JavaArchive.class, "switchyard-JCAJMSServiceBindingTest.jar") + .addClass(JCAJMSService.class) + .addClass(JCAJMSServiceImpl.class) + .addClass(JCAJMSFault.class) + .addClass(MyJMSContextMapper.class) + .addClass(MyJMSMessageComposer.class) + .addAsManifestResource(new UrlAsset(testConfigUrl), "switchyard.xml") + .addAsManifestResource(new StringAsset(beansXml), "beans.xml"); + } + + @Before + public void before() { + _hqMixIn = new HornetQMixIn(false).setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + _hqMixIn.initialize(); + } + + @After + public void after() { + try { + _hqMixIn.uninitialize(); + ResourceDeployer.removeQueue(INPUT_QUEUE); + ResourceDeployer.removeQueue(INPUT_INOUT_QUEUE); + ResourceDeployer.removeQueue(INPUT_INOUT_PHYSICAL_NAME_QUEUE + "_physical"); + ResourceDeployer.removeQueue(INOUT_REPLY_TO_QUEUE); + ResourceDeployer.removeQueue(INOUT_REPLY_TO_PHYSICAL_NAME_QUEUE + "_physical"); + ResourceDeployer.removeQueue(INOUT_FAULT_TO_QUEUE); + ResourceDeployer.removeQueue(INOUT_FAULT_TO_PHYSICAL_NAME_QUEUE + "_physical"); + ResourceDeployer.removeQueue(RESULT_QUEUE); + ResourceDeployer.removeQueue(FAULT_QUEUE); + } catch (Exception e) { + _logger.warn(e); + } + + } + + @Test + public void testInflowJMS() throws Exception { + Session session = _hqMixIn.createJMSSession(); + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText("onMessage"); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(RESULT_QUEUE)); + assertMessage(consumer.receive(3000), TextMessage.class, "onMessagetesttest"); + Assert.assertNull(consumer.receive(3000)); + consumer.close(); + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(FAULT_QUEUE)); + Assert.assertNull(consumer.receive(3000)); + consumer.close(); + } finally { + session.close(); + } + } + + @Test + public void testInflowJMS_fault_rollback() throws Exception { + Session session = _hqMixIn.createJMSSession(); + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText("onMessage_fault_rollback"); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(FAULT_QUEUE)); + assertMessage(consumer.receive(3000), TextMessage.class, "faultmessagetest"); + assertMessage(consumer.receive(3000), TextMessage.class, "faultmessagetest"); + assertMessage(consumer.receive(3000), TextMessage.class, "faultmessagetest"); + assertMessage(consumer.receive(3000), TextMessage.class, "faultmessagetest"); + Assert.assertNull(consumer.receive(3000)); + consumer.close(); + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(RESULT_QUEUE)); + assertMessage(consumer.receive(3000), TextMessage.class, "onMessage_fault_rollbacktesttest"); + Assert.assertNull(consumer.receive(3000)); + consumer.close(); + } finally { + session.close(); + } + } + + @Test + public void testInflowJMS_fault_commit() throws Exception { + Session session = _hqMixIn.createJMSSession(); + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText("onMessage_fault_commit"); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(FAULT_QUEUE)); + assertMessage(consumer.receive(3000), TextMessage.class, "faultmessagetest"); + Assert.assertNull(consumer.receive(3000)); + consumer.close(); + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(RESULT_QUEUE)); + assertMessage(consumer.receive(3000), TextMessage.class, "onMessage_fault_committesttest"); + Assert.assertNull(consumer.receive(3000)); + consumer.close(); + } finally { + session.close(); + } + } + + @Test + public void testInflowJMS_inout() throws Exception { + String payload = "onMessage_inout"; + Session session = _hqMixIn.createJMSSession(); + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_INOUT_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(INOUT_REPLY_TO_QUEUE)); + assertMessage(consumer.receive(3000), TextMessage.class, payload + "_replyTo"); + consumer.close(); + } finally { + session.close(); + } + } + + @Test + public void testInflowJMS_inout_fault() throws Exception { + String payload = "onMessage_inout_fault"; + Session session = _hqMixIn.createJMSSession(); + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_INOUT_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(INOUT_FAULT_TO_QUEUE)); + assertMessage(consumer.receive(3000), TextMessage.class, "org.switchyard.test.jca.JCAJMSFault: " + payload + "_faultTo"); + consumer.close(); + } finally { + session.close(); + } + } + + @Test + public void testInflowJMS_inout_context_property() throws Exception { + String payload = "onMessage_inout_context_property"; + Session session = _hqMixIn.createJMSSession(); + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_INOUT_QUEUE)); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(RESULT_QUEUE)); + assertMessage(consumer.receive(3000), BytesMessage.class, payload + "_replyTo"); + consumer.close(); + } finally { + session.close(); + } + } + + @Test + public void testInflowJMS_inout_physical_name() throws Exception { + String payload = "onMessage_inout_physical_name"; + Session session = _hqMixIn.createJMSSession(); + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_INOUT_PHYSICAL_NAME_QUEUE + "_physical")); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(INOUT_REPLY_TO_PHYSICAL_NAME_QUEUE + "_physical")); + assertMessage(consumer.receive(3000), TextMessage.class, payload + "_replyTo"); + consumer.close(); + } finally { + session.close(); + } + } + + @Test + public void testInflowJMS_inout_physical_name_fault() throws Exception { + String payload = "onMessage_inout_physical_name_fault"; + Session session = _hqMixIn.createJMSSession(); + try { + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(INPUT_INOUT_PHYSICAL_NAME_QUEUE + "_physical")); + TextMessage inMsg = session.createTextMessage(); + inMsg.setText(payload); + producer.send(inMsg); + producer.close(); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(INOUT_FAULT_TO_PHYSICAL_NAME_QUEUE + "_physical")); + assertMessage(consumer.receive(3000), TextMessage.class, "org.switchyard.test.jca.JCAJMSFault: " + payload + "_faultTo"); + consumer.close(); + } finally { + session.close(); + } + } + + private void assertMessage(Message msg, Class type, String expect) throws Exception { + Assert.assertNotNull(msg); + Assert.assertTrue("Unexpected message type: " + msg.getClass().getName(), type.isAssignableFrom(msg.getClass())); + if (msg instanceof TextMessage) { + Assert.assertEquals(expect, TextMessage.class.cast(msg).getText()); + } else if (msg instanceof BytesMessage) { + BytesMessage bmsg = BytesMessage.class.cast(msg); + byte[] bytes = new byte[(int) bmsg.getBodyLength()]; + bmsg.readBytes(bytes); + Assert.assertEquals(expect, new String(bytes)); + } else { + Assert.fail("Unexpected message type: " + msg.getClass().getName()); + } + } +} + diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSServiceImpl.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSServiceImpl.java new file mode 100644 index 000000000..87c1f347e --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSServiceImpl.java @@ -0,0 +1,101 @@ +package org.switchyard.test.jca; + +import javax.inject.Inject; + +import org.switchyard.Context; +import org.switchyard.Exchange; +import org.switchyard.Property; +import org.switchyard.Scope; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; +import org.switchyard.component.common.label.PropertyLabel; +import org.switchyard.component.jca.composer.JMSContextMapper; +import org.switchyard.component.jca.endpoint.JMSEndpoint; + +@Service(JCAJMSService.class) +public class JCAJMSServiceImpl implements JCAJMSService { + + @Inject @Reference("JCAJMSStoreResult") + private JCAJMSService _storeResult; + @Inject @Reference("JCAJMSStoreFault") + private JCAJMSService _storeFault; + @Inject + private Context _context; + private int _declaredFaultCount = 0; + private int _undeclaredFaultCount = 0; + + @Override + public void onMessage(String name) { + if (!name.equals("onMessagetest")) { + throw new RuntimeException("expected content is 'onMessagetest' but was '" + name + "'"); + } + final String val = _context.getProperty("testProp").getValue().toString(); + if (!val.equals("testVal")) { + throw new RuntimeException("'testProp' property is '" + val + "' while it should be 'testVal'"); + }; + + Property jmsMessageId = _context.getProperty(JMSContextMapper.HEADER_JMS_MESSAGE_ID); + if (jmsMessageId == null) { + throw new RuntimeException("Couldn't find javax.jms.JMSMessageID context property"); + } + if (!jmsMessageId.hasLabel(PropertyLabel.HEADER.label())) { + throw new RuntimeException("javax.jmsJMSMessageID context property doesn't have HEADER label"); + } + if (jmsMessageId.getValue().toString() == null) { + throw new RuntimeException("javax.jmsJMSMessageID context property has null value"); + }; + + _storeResult.onMessage(name); + } + + @Override + public void onMessage_fault_rollback(String name) { + _storeResult.onMessage(name); + + if (_undeclaredFaultCount < 4) { + _undeclaredFaultCount++; + _storeFault.onMessage("faultmessage"); + throw new RuntimeException("faultmessage"); + } + + } + + @Override + public void onMessage_fault_commit(String name) throws JCAJMSFault { + _storeResult.onMessage(name); + + if (_declaredFaultCount < 4) { + _declaredFaultCount++; + _storeFault.onMessage("faultmessage"); + _context.setProperty(Exchange.ROLLBACK_ON_FAULT, false); + throw new JCAJMSFault("faultmessage"); + } + } + + @Override + public String onMessage_inout(String name) { + return name + "_replyTo"; + } + + @Override + public String onMessage_inout_fault(String name) throws JCAJMSFault { + throw new JCAJMSFault(name + "_faultTo"); + } + + @Override + public String onMessage_inout_context_property(String name) { + _context.setProperty(JMSEndpoint.CONTEXT_PROPERTY_PREFIX + JMSEndpoint.KEY_REPLY_TO, "StoreResultQueue", Scope.EXCHANGE); + _context.setProperty(JMSEndpoint.CONTEXT_PROPERTY_PREFIX + JMSEndpoint.KEY_MESSAGE_TYPE, "Bytes", Scope.EXCHANGE); + return name + "_replyTo"; + } + + @Override + public String onMessage_inout_physical_name(String name) { + return name + "_replyTo"; + } + + @Override + public String onMessage_inout_physical_name_fault(String name) throws JCAJMSFault { + throw new JCAJMSFault(name + "_faultTo"); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSTransactionService.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSTransactionService.java new file mode 100644 index 000000000..6197757d3 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSTransactionService.java @@ -0,0 +1,15 @@ +package org.switchyard.test.jca; + +public interface JCAJMSTransactionService { + public void onMessage(String body); + + public void onMessageText(String body); + + public void onMessageManaged(String body); + + public void onMessageCamel(String body); + + public void onMessageContextProperty(String name) throws Exception; + + public void onMessagePhysicalName(String name); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSTransactionServiceImpl.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSTransactionServiceImpl.java new file mode 100644 index 000000000..e94bc8064 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/JCAJMSTransactionServiceImpl.java @@ -0,0 +1,89 @@ +package org.switchyard.test.jca; + +import javax.inject.Inject; +import javax.naming.InitialContext; +import javax.transaction.Status; +import javax.transaction.UserTransaction; + +import org.jboss.logging.Logger; +import org.switchyard.component.bean.Reference; +import org.switchyard.component.bean.Service; + +@Service(JCAJMSTransactionService.class) +public class JCAJMSTransactionServiceImpl implements JCAJMSTransactionService { + + private Logger _logger = Logger.getLogger(JCAJMSTransactionServiceImpl.class); + + @Inject @Reference + private JCAJMSReferenceService service; + @Inject @Reference("JCAJMSCamelService") + private JCAJMSReferenceService camelService; + + @Override + public void onMessage(String name) { + int txStatus = getTransactionStatus(); + if (txStatus != Status.STATUS_NO_TRANSACTION) { + throw new RuntimeException("Unexpected Transaction Status: " + txStatus); + } + service.onMessage(name); + } + + @Override + public void onMessageText(String name) { + int txStatus = getTransactionStatus(); + if (txStatus != Status.STATUS_NO_TRANSACTION) { + throw new RuntimeException("Unexpected Transaction Status: " + txStatus); + } + service.onMessageText(name); + } + + @Override + public void onMessageManaged(String name) { + int txStatus = getTransactionStatus(); + if (txStatus != Status.STATUS_ACTIVE) { + throw new RuntimeException("Unexpected Transaction Status: " + txStatus); + } + service.onMessage(name); + } + + @Override + public void onMessageCamel(String name) { + int txStatus = getTransactionStatus(); + if (txStatus != Status.STATUS_ACTIVE) { + throw new RuntimeException("Unexpected Transaction Status: " + txStatus); + } + camelService.onMessage(name); + } + + @Override + public void onMessageContextProperty(String name) throws Exception { + int txStatus = getTransactionStatus(); + if (txStatus != Status.STATUS_ACTIVE) { + throw new RuntimeException("Unexpected Transaction Status: " + txStatus); + } + service.onMessageContextProperty(name); + } + + @Override + public void onMessagePhysicalName(String name) { + int txStatus = getTransactionStatus(); + if (txStatus != Status.STATUS_ACTIVE) { + throw new RuntimeException("Unexpected Transaction Status: " + txStatus); + } + service.onMessagePhysicalName(name); + } + + private int getTransactionStatus() { + try { + InitialContext ic = new InitialContext(); + UserTransaction tx = (UserTransaction) ic.lookup("java:jboss/UserTransaction"); + if (tx != null) { + return tx.getStatus(); + } + } catch (Exception e) { + _logger.warn(e); + } + return Status.STATUS_NO_TRANSACTION; + } +} + diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyJMSContextMapper.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyJMSContextMapper.java new file mode 100644 index 000000000..9fb6df009 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyJMSContextMapper.java @@ -0,0 +1,22 @@ +package org.switchyard.test.jca; + +import org.switchyard.Context; +import org.switchyard.Scope; +import org.switchyard.component.jca.composer.JMSBindingData; +import org.switchyard.component.jca.composer.JMSContextMapper; + +public class MyJMSContextMapper extends JMSContextMapper { + + @Override + public void mapFrom(JMSBindingData source, Context context) throws Exception { + super.mapFrom(source, context); + context.setProperty("testProp", "testVal", Scope.EXCHANGE); + } + + @Override + public void mapTo(Context context, JMSBindingData target) throws Exception { + super.mapTo(context, target); + target.getMessage().setStringProperty("testProp", "testVal"); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyJMSMessageComposer.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyJMSMessageComposer.java new file mode 100644 index 000000000..446956c86 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyJMSMessageComposer.java @@ -0,0 +1,22 @@ +package org.switchyard.test.jca; + +import org.switchyard.Exchange; +import org.switchyard.component.jca.composer.JMSBindingData; +import org.switchyard.component.jca.composer.JMSMessageComposer; + +public class MyJMSMessageComposer extends JMSMessageComposer { + + @Override + public org.switchyard.Message compose(JMSBindingData source, Exchange exchange) throws Exception { + org.switchyard.Message msg = super.compose(source, exchange); + msg.setContent(msg.getContent(String.class) + "test"); + return msg; + } + + @Override + public JMSBindingData decompose(Exchange exchange, JMSBindingData target) throws Exception { + exchange.getMessage().setContent(exchange.getMessage().getContent(String.class)+"test"); + return super.decompose(exchange, target); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyStreamableRecordCCIEndpoint.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyStreamableRecordCCIEndpoint.java new file mode 100644 index 000000000..ed0510fc9 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/MyStreamableRecordCCIEndpoint.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca; + +import javax.resource.cci.Record; + +import org.switchyard.Exchange; +import org.switchyard.SwitchYardException; +import org.switchyard.component.common.SynchronousInOutHandler; +import org.switchyard.component.common.composer.MessageComposer; +import org.switchyard.component.common.selector.BaseOperationSelector; +import org.switchyard.component.jca.composer.StreamableRecordBindingData; +import org.switchyard.component.jca.endpoint.CCIEndpoint; +import org.switchyard.component.jca.processor.cci.StreamableRecord; +import org.switchyard.selector.OperationSelector; +import org.w3c.dom.Document; +/** + * Concrete message endpoint class for JCA message inflow using JCA CCI MessageListener interface. + */ +public class MyStreamableRecordCCIEndpoint extends CCIEndpoint { + + private static final long DEFAULT_TIMEOUT = 15000; + private static final String DEFAULT_RECORD_NAME = "StreamableRecord"; + private static final String DEFAULT_DESCRIPTION = "StreamableRecord implementation by " + MyStreamableRecordCCIEndpoint.class.getName(); + + private long _waitTimeout = DEFAULT_TIMEOUT; + private String _recordName = DEFAULT_RECORD_NAME; + private String _description = DEFAULT_DESCRIPTION; + private MessageComposer _composer; + private OperationSelector _selector; + + @Override + public void initialize() { + setServiceReference(getServiceDomain().getServiceReference(getServiceQName())); + _composer = getMessageComposer(StreamableRecordBindingData.class); + _selector = new BaseOperationSelector(getJCABindingModel().getOperationSelector()) { + @Override + protected Document extractDomDocument(StreamableRecordBindingData content) throws Exception { + return null; + } + @Override + protected String extractString(StreamableRecordBindingData content) throws Exception { + return null; + } + }; + } + + @Override + public Record onMessage(Record record) { + SynchronousInOutHandler inOutHandler = new SynchronousInOutHandler(); + StreamableRecord sourceRecord = StreamableRecord.class.cast(record); + try { + StreamableRecordBindingData bindingData = new StreamableRecordBindingData(sourceRecord); + String operation = _selector != null ? _selector.selectOperation(bindingData).getLocalPart() : null; + Exchange exchange = createExchange(operation, inOutHandler); + exchange.send(_composer.compose(bindingData, exchange)); + + exchange = inOutHandler.waitForOut(_waitTimeout); + StreamableRecord returnRecord = new StreamableRecord(); + returnRecord.setRecordName(_recordName); + returnRecord.setRecordShortDescription(_description); + returnRecord.setRecordShortDescription(_description); + return _composer.decompose(exchange, new StreamableRecordBindingData(returnRecord)).getRecord(); + } catch (Exception e) { + throw new SwitchYardException(e); + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/InteractionListener.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/InteractionListener.java new file mode 100644 index 000000000..a65bcbfa3 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/InteractionListener.java @@ -0,0 +1,31 @@ +package org.switchyard.test.jca.mockra; + +import javax.resource.cci.InteractionSpec; +import javax.resource.cci.Record; + +/** + * interaction event listener interface. + * + * @author Tomohisa Igarashi + * + */ +public interface InteractionListener { + /** + * this is invoked from Interaction.execute(InteractionSpec ispec, Record input, Record output). + * + * @param ispec InteractionSpec + * @param input input record + * @param output output record + * @return true if succeeded + */ + public boolean onExecute(InteractionSpec ispec, Record input, Record output); + + /** + * this is invoked from Interaction.execute(InteractionSpec ispec, Record input). + * + * @param ispec InteractionSpec + * @param input input record + * @return output record + */ + public Record onExecute(InteractionSpec ispec, Record input); +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockActivationSpec.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockActivationSpec.java new file mode 100644 index 000000000..8eaa291dd --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockActivationSpec.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import javax.resource.ResourceException; +import javax.resource.spi.ActivationSpec; +import javax.resource.spi.InvalidPropertyException; +import javax.resource.spi.ResourceAdapter; + +import org.apache.log4j.Logger; + +/** + * MockActivationSpec. + * + * @author Tomohisa Igarashi + * + */ +public class MockActivationSpec implements ActivationSpec { + private Logger _logger = Logger.getLogger(MockActivationSpec.class); + private ResourceAdapter _adapter; + + /** + * Constructor. + */ + public MockActivationSpec() { + _logger.debug("instantiate MockResourceAdapter"); + } + + @Override + public ResourceAdapter getResourceAdapter() { + _logger.debug("call getResourceAdapter"); + return _adapter; + } + @Override + public void setResourceAdapter(ResourceAdapter arg0) + throws ResourceException { + _logger.debug("call setResourceAdapter(" + arg0 + ")"); + _adapter = arg0; + } + @Override + public void validate() throws InvalidPropertyException { + _logger.debug("call validate"); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnection.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnection.java new file mode 100644 index 000000000..4689006e7 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnection.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import java.util.List; + +import javax.resource.ResourceException; +import javax.resource.cci.Connection; +import javax.resource.cci.ConnectionMetaData; +import javax.resource.cci.Interaction; +import javax.resource.cci.LocalTransaction; +import javax.resource.cci.ResultSetInfo; + +import org.apache.log4j.Logger; + +/** + * MockConnection. + * + * @author Tomohisa Igarashi + * + */ +public class MockConnection implements Connection { + private Logger _logger = Logger.getLogger(MockConnection.class); + private List _listener; + + /** + * Constructor. + * @param listener InteractionListener. + */ + public MockConnection(List listener) { + _listener = listener; + } + + @Override + public Interaction createInteraction() throws ResourceException { + _logger.debug("call createInteraction()"); + return new MockInteraction(_listener, this); + } + + @Override + public LocalTransaction getLocalTransaction() throws ResourceException { + _logger.debug("call getLocalTransaction()"); + return null; + } + + @Override + public ConnectionMetaData getMetaData() throws ResourceException { + _logger.debug("call getMetaData()"); + return null; + } + + @Override + public ResultSetInfo getResultSetInfo() throws ResourceException { + _logger.debug("call getResultSetInfo()"); + return null; + } + + @Override + public void close() throws ResourceException { + _logger.debug("call close()"); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnectionFactory.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnectionFactory.java new file mode 100644 index 000000000..75f2f3769 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnectionFactory.java @@ -0,0 +1,139 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import javax.naming.NamingException; +import javax.naming.Reference; +import javax.resource.Referenceable; +import javax.resource.ResourceException; +import javax.resource.cci.Connection; +import javax.resource.cci.ConnectionFactory; +import javax.resource.cci.ConnectionSpec; +import javax.resource.cci.RecordFactory; +import javax.resource.cci.ResourceAdapterMetaData; +import javax.resource.spi.ConnectionManager; + +import org.apache.log4j.Logger; + +/** + * MockConnectionFactory. + * + * @author Tomohisa Igarashi + * + */ +public class MockConnectionFactory implements ConnectionFactory, Serializable, Referenceable { + + private static final long serialVersionUID = 1L; + private Logger _logger = Logger.getLogger(MockConnectionFactory.class); + private ConnectionManager _cm; + private Reference _ref; + private List _listener = new ArrayList(); + + /** + * Constructor. + */ + public MockConnectionFactory() { + } + + /** + * Constructor. + * + * @param cm {@link ConnectionManager} + */ + public MockConnectionFactory(ConnectionManager cm) { + _logger.debug("call MockConnectionFactory(" + cm + ")"); + _cm = (ConnectionManager) cm; + _ref = null; + } + @Override + public Connection getConnection() throws ResourceException { + _logger.debug("call getConnection"); + return new MockConnection(_listener); + } + @Override + public Connection getConnection(ConnectionSpec properties) + throws ResourceException { + _logger.debug("call getConnection(" + properties + ")"); + return new MockConnection(_listener); + } + @Override + public RecordFactory getRecordFactory() throws ResourceException { + _logger.debug("call getRecordFactory"); + return new MockRecordFactory(); + } + @Override + public ResourceAdapterMetaData getMetaData() throws ResourceException { + _logger.debug("call getMetaData"); + return new ResourceAdapterMetaData() { + @Override + public String getAdapterVersion() { + return null; + } + @Override + public String getAdapterVendorName() { + return null; + } + @Override + public String getAdapterName() { + return null; + } + @Override + public String getAdapterShortDescription() { + return null; + } + @Override + public String getSpecVersion() { + return null; + } + @Override + public String[] getInteractionSpecsSupported() { + return null; + } + @Override + public boolean supportsExecuteWithInputAndOutputRecord() { + return false; + } + @Override + public boolean supportsExecuteWithInputRecordOnly() { + return false; + } + @Override + public boolean supportsLocalTransactionDemarcation() { + return false; + } + }; + } + @Override + public Reference getReference() throws NamingException { + _logger.debug("call getReference"); + return _ref; + } + @Override + public void setReference(Reference ref) { + _logger.debug("call setReference(" + ref + ")"); + _ref = ref; + } + + /** + * set InteractionListener. + * @param listener InteractionListener + */ + public void setInteractionListener(InteractionListener listener) { + _listener.add(listener); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnectionManager.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnectionManager.java new file mode 100644 index 000000000..f39e4227f --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnectionManager.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import javax.resource.ResourceException; +import javax.resource.spi.ConnectionManager; +import javax.resource.spi.ConnectionRequestInfo; +import javax.resource.spi.ManagedConnectionFactory; + +import org.apache.log4j.Logger; + +/** + * MockConnectionManager. + * + * @author Tomohisa Igarashi + * + */ +public class MockConnectionManager implements ConnectionManager { + + private transient Logger _logger = Logger.getLogger(MockConnectionManager.class); + private static final long serialVersionUID = 1L; + + @Override + public Object allocateConnection(ManagedConnectionFactory arg0, + ConnectionRequestInfo arg1) throws ResourceException { + _logger.debug("call allocateConnection(" + arg0 + ", " + arg1 + ")"); + return arg0.createManagedConnection(null, arg1).getConnection(null, arg1); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockIndexedRecord.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockIndexedRecord.java new file mode 100644 index 000000000..4edc49bce --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockIndexedRecord.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import java.util.ArrayList; + +import javax.resource.cci.IndexedRecord; + +/** + * MockIndexedRecord. + * + * @author Tomohisa Igarashi + * + */ +@SuppressWarnings("rawtypes") +public class MockIndexedRecord extends ArrayList implements IndexedRecord { + + private static final long serialVersionUID = 1341376132007016249L; + private String _recordName; + private String _recordShortDescription; + + @Override + public String getRecordName() { + return _recordName; + } + + @Override + public void setRecordName(String name) { + _recordName = name; + } + + @Override + public void setRecordShortDescription(String description) { + _recordShortDescription = description; + } + + @Override + public String getRecordShortDescription() { + return _recordShortDescription; + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockInteraction.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockInteraction.java new file mode 100644 index 000000000..9be0831c0 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockInteraction.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import java.util.List; + +import javax.resource.ResourceException; +import javax.resource.cci.Connection; +import javax.resource.cci.Interaction; +import javax.resource.cci.InteractionSpec; +import javax.resource.cci.Record; +import javax.resource.cci.ResourceWarning; + +import org.apache.log4j.Logger; + +/** + * MockInteraction. + * + * @author Tomohisa Igarashi + * + */ +public class MockInteraction implements Interaction { + private Logger _logger = Logger.getLogger(MockInteraction.class); + private List _listener; + private Connection _connection; + + /** + * Constructor. + * + * @param listener InteractionListener + */ + public MockInteraction(List listener, Connection conn) { + _listener = listener; + _connection = conn; + } + + @Override + public void close() throws ResourceException { + _logger.debug("call close()"); + } + + @Override + public Connection getConnection() { + _logger.debug("call getConnection()"); + return _connection; + } + + @Override + public boolean execute(InteractionSpec ispec, Record input, Record output) + throws ResourceException { + _logger.debug("call execute(" + ispec + ", " + input + ", " + output + ")"); + boolean result = true; + for (InteractionListener l : _listener) { + result &= l.onExecute(ispec, input, output); + } + return result; + } + + @Override + public Record execute(InteractionSpec ispec, Record input) + throws ResourceException { + _logger.debug("call execute(" + ispec + ", " + input + ")"); + Record output = null; + for (InteractionListener l : _listener) { + output = l.onExecute(ispec, input); + input = output; + } + return output; + } + + @Override + public ResourceWarning getWarnings() throws ResourceException { + _logger.debug("call getWarnings()"); + return null; + } + + @Override + public void clearWarnings() throws ResourceException { + _logger.debug("call clearWarnings()"); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockManagedConnection.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockManagedConnection.java new file mode 100644 index 000000000..5fd7376c2 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockManagedConnection.java @@ -0,0 +1,133 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; + +import javax.resource.ResourceException; +import javax.resource.spi.ConnectionEventListener; +import javax.resource.spi.ConnectionRequestInfo; +import javax.resource.spi.LocalTransaction; +import javax.resource.spi.ManagedConnection; +import javax.resource.spi.ManagedConnectionMetaData; +import javax.security.auth.Subject; +import javax.transaction.xa.XAResource; + +import org.apache.log4j.Logger; + +/** + * MockManagedConnection. + * + * @author Tomohisa Igarashi + * + */ +class MockManagedConnection implements ManagedConnection { + + private Logger _logger = Logger.getLogger(MockManagedConnection.class); + private List _listener = new ArrayList(); + + @Override + public void addConnectionEventListener(ConnectionEventListener arg0) { + _logger.debug("call addConnectionEventListener(" + arg0 + ")"); + _listener.add(arg0); + } + + @Override + public void associateConnection(Object arg0) throws ResourceException { + _logger.debug("call associateConnection(" + arg0 + ")"); + } + + @Override + public void cleanup() throws ResourceException { + _logger.debug("call cleanup"); + } + + @Override + public void destroy() throws ResourceException { + _logger.debug("call destroy"); + } + + @Override + public Object getConnection(Subject arg0, ConnectionRequestInfo arg1) + throws ResourceException { + _logger.debug("call getConnection(" + arg0 + ", " + arg1 + ")"); + return new MockConnection(new ArrayList()); + } + + @Override + public LocalTransaction getLocalTransaction() throws ResourceException { + _logger.debug("call getTransaction"); + return new LocalTransaction() { + @Override + public void begin() throws ResourceException { + } + + @Override + public void commit() throws ResourceException { + } + + @Override + public void rollback() throws ResourceException { + } + }; + } + + @Override + public PrintWriter getLogWriter() throws ResourceException { + _logger.debug("call getLogWriter"); + return null; + } + + @Override + public ManagedConnectionMetaData getMetaData() throws ResourceException { + _logger.debug("call getMetaData"); + return new ManagedConnectionMetaData() { + @Override + public String getEISProductName() throws ResourceException { + return null; + } + @Override + public String getEISProductVersion() throws ResourceException { + return null; + } + @Override + public int getMaxConnections() throws ResourceException { + return 0; + } + @Override + public String getUserName() throws ResourceException { + return null; + } + }; + } + + @Override + public XAResource getXAResource() throws ResourceException { + _logger.debug("call getXAResource"); + return new MockXAResource(); + } + + @Override + public void removeConnectionEventListener(ConnectionEventListener arg0) { + _logger.debug("call removeConnectionEventListener(" + arg0 + ")"); + _listener.remove(arg0); + } + + @Override + public void setLogWriter(PrintWriter arg0) throws ResourceException { + _logger.debug("call setLogWriter(" + arg0 + ")"); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockManagedConnectionFactory.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockManagedConnectionFactory.java new file mode 100644 index 000000000..fdfdeab73 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockManagedConnectionFactory.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import java.io.PrintWriter; +import java.util.Set; + +import javax.resource.ResourceException; +import javax.resource.spi.ConnectionManager; +import javax.resource.spi.ConnectionRequestInfo; +import javax.resource.spi.ManagedConnection; +import javax.resource.spi.ManagedConnectionFactory; +import javax.security.auth.Subject; + +import org.apache.log4j.Logger; + +/** + * MockManagedConnectionFactory. + * + * @author Tomohisa Igarashi + * + */ +public class MockManagedConnectionFactory implements ManagedConnectionFactory { + + private transient Logger _logger = Logger.getLogger(MockManagedConnectionFactory.class); + private static final long serialVersionUID = 1L; + + @Override + public Object createConnectionFactory() throws ResourceException { + _logger.debug("call createConnectionFactory"); + return new MockConnectionFactory(new MockConnectionManager()); + } + + @Override + public Object createConnectionFactory(ConnectionManager arg0) + throws ResourceException { + _logger.debug("call createConnectionFactory(" + arg0 + ")"); + return new MockConnectionFactory(arg0); + } + + @Override + public ManagedConnection createManagedConnection(Subject arg0, + ConnectionRequestInfo arg1) throws ResourceException { + _logger.debug("call createManagedConnection(" + arg0 + ", " + arg1 + ")"); + return new MockManagedConnection(); + } + + @Override + public PrintWriter getLogWriter() throws ResourceException { + _logger.debug("call getLogWriter"); + return null; + } + + @Override + public ManagedConnection matchManagedConnections(Set arg0, + Subject arg1, ConnectionRequestInfo arg2) + throws ResourceException { + _logger.debug("call matchManagedConnections(" + arg0 + ", " + arg1 + ", " + arg2 + ")"); + return null; + } + + @Override + public void setLogWriter(PrintWriter arg0) throws ResourceException { + _logger.debug("call setLogWriter(" + arg0 + ")"); + } + + @Override + public boolean equals(Object obj) { + if (obj != null) { + return obj.equals(this); + } + return false; + } + + @Override + public int hashCode() { + return super.hashCode(); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockMappedRecord.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockMappedRecord.java new file mode 100644 index 000000000..3641efd7e --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockMappedRecord.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import java.util.HashMap; + +import javax.resource.cci.MappedRecord; + +/** + * MockMappedRecord. + * + * @author Tomohisa Igarashi + * + */ +@SuppressWarnings("rawtypes") +public class MockMappedRecord extends HashMap implements MappedRecord { + + private static final long serialVersionUID = 1L; + private String _recordName; + private String _description; + + @Override + public String getRecordName() { + return _recordName; + } + + @Override + public void setRecordName(String name) { + _recordName = name; + } + + @Override + public void setRecordShortDescription(String description) { + _description = description; + } + + @Override + public String getRecordShortDescription() { + return _description; + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockRecordFactory.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockRecordFactory.java new file mode 100644 index 000000000..f2ff327d9 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockRecordFactory.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import javax.resource.ResourceException; +import javax.resource.cci.IndexedRecord; +import javax.resource.cci.MappedRecord; +import javax.resource.cci.RecordFactory; + +/** + * MockRecordFactory. + * + * @author Tomohisa Igarashi + * + */ +public class MockRecordFactory implements RecordFactory { + + @Override + public MappedRecord createMappedRecord(String recordName) throws ResourceException { + MappedRecord rec = new MockMappedRecord(); + rec.setRecordName(recordName); + return rec; + } + + @Override + public IndexedRecord createIndexedRecord(String recordName) throws ResourceException { + IndexedRecord rec = new MockIndexedRecord(); + rec.setRecordName(recordName); + return rec; + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockResourceAdapter.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockResourceAdapter.java new file mode 100644 index 000000000..bc31c04da --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockResourceAdapter.java @@ -0,0 +1,165 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import java.lang.reflect.Method; + +import javax.naming.InitialContext; +import javax.resource.ResourceException; +import javax.resource.cci.MessageListener; +import javax.resource.cci.Record; +import javax.resource.spi.ActivationSpec; +import javax.resource.spi.BootstrapContext; +import javax.resource.spi.ResourceAdapter; +import javax.resource.spi.ResourceAdapterInternalException; +import javax.resource.spi.endpoint.MessageEndpoint; +import javax.resource.spi.endpoint.MessageEndpointFactory; +import javax.transaction.xa.XAResource; + +import org.apache.log4j.Logger; + +/** + * MockResourceAdapter. + * + * @author Tomohisa Igarashi + * + */ +public class MockResourceAdapter implements ResourceAdapter { + + private Logger _logger = Logger.getLogger(MockResourceAdapter.class); + private ActivationSpec _spec = null; + private MessageEndpointFactory _factory = null; + private MessageEndpoint _endpoint = null; + + public MockResourceAdapter() { + try { + InitialContext ic = new InitialContext(); + ic.bind(MockResourceAdapterUtil.JNDI_ADAPTER, this); + _logger.info("Bound to " + MockResourceAdapterUtil.JNDI_ADAPTER); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public void endpointActivation(MessageEndpointFactory arg0, + ActivationSpec arg1) throws ResourceException { + _spec = arg1; + _factory = arg0; + _logger.debug("call endpointActivation(" + arg0 + ", " + arg1 + ")"); + } + + @Override + public void endpointDeactivation(MessageEndpointFactory arg0, + ActivationSpec arg1) { + _logger.debug("call endpointDeactivation(" + arg0 + ", " + arg1 + ")"); + } + + @Override + public XAResource[] getXAResources(ActivationSpec[] arg0) + throws ResourceException { + StringBuffer buffer = new StringBuffer(); + for (ActivationSpec as : arg0) { + buffer.append("[" + as.toString() + "] "); + } + buffer.trimToSize(); + _logger.debug("call getXAResources(" + buffer.toString() + ")"); + return null; + } + + @Override + public void start(BootstrapContext arg0) + throws ResourceAdapterInternalException { + _logger.debug("call start(" + arg0 + ")"); + } + + @Override + public void stop() { + _logger.debug("call stop"); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof MockResourceAdapter) { + return true; + } + return false; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + /** + * fire createEndpoint(). + */ + public void fireCreateEndpoint() { + _logger.debug("call fireCreateEndpoint"); + try { + _endpoint = _factory.createEndpoint(new MockXAResource()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * fire beforeDelivery(). + */ + public void fireBeforeDelivery() { + _logger.debug("call fireBeforeDelivery"); + try { + _endpoint.beforeDelivery(null); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * fire message delivery via {@link MessageListener#onMessage()}. + * + * @param record {@link Record} instance to deliver + * @return returned value + */ + public Record fireDelivery(Record record) { + _logger.debug("call onMessage: record=" + record); + + try { + Method m = MessageListener.class.getMethod("onMessage", new Class[]{Record.class}); + return Record.class.cast(m.invoke(_endpoint, new Object[]{record})); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * fire afterDelivery(). + */ + public void fireAfterDelivery() { + _logger.debug("call fireAfterDelivery"); + try { + _endpoint.afterDelivery(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * fire release(). + */ + public void fireRelease() { + _logger.debug("call fireRelease"); + _endpoint.release(); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockResourceAdapterUtil.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockResourceAdapterUtil.java new file mode 100644 index 000000000..f27e5e281 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockResourceAdapterUtil.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import javax.resource.cci.MessageListener; + +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; +import org.switchyard.common.type.Classes; + +public class MockResourceAdapterUtil { + public static final String IRONJACAMAR_XML = "org/switchyard/test/jca/cci-test-ironjacamar.xml"; + public static final String RESOURCE_ADAPTER_XML = "org/switchyard/test/jca/cci-test-mock-ra.xml"; + public static final String ADAPTER_NAME = "myeis-ra"; + public static final String ADAPTER_ARCHIVE_NAME = ADAPTER_NAME + ".rar"; + public static final String LIB_JAR_NAME = "lib.jar"; + public static final String JNDI_CONNECTION_FACTORY = "java:jboss/MyEISConnectionFactory"; + public static final String JNDI_ADAPTER = "MyEISResourceAdapter"; + public static final String MCF_CLASS = MockManagedConnectionFactory.class.getName(); + + public static ResourceAdapterArchive createMockResourceAdapterArchive() { + JavaArchive ja = ShrinkWrap.create(JavaArchive.class, LIB_JAR_NAME); + ja.addClasses(MessageListener.class, MockActivationSpec.class, MockConnection.class, + MockConnectionFactory.class, MockConnectionManager.class, + MockManagedConnection.class, MockManagedConnectionFactory.class, + MockResourceAdapter.class, MockXAResource.class, InteractionListener.class, + MockInteraction.class, MockRecordFactory.class, MockMappedRecord.class, MockIndexedRecord.class); + try { + return ShrinkWrap.create(ResourceAdapterArchive.class, ADAPTER_ARCHIVE_NAME) + .addAsLibrary(ja) + .setResourceAdapterXML(Classes.getResource(RESOURCE_ADAPTER_XML)) + .addAsManifestResource(IRONJACAMAR_XML, "ironjacamar.xml"); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockXAResource.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockXAResource.java new file mode 100644 index 000000000..94bb690d1 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockXAResource.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.jca.mockra; + +import javax.transaction.xa.XAException; +import javax.transaction.xa.XAResource; +import javax.transaction.xa.Xid; + +import org.apache.log4j.Logger; + +/** + * MockXAResource. + * + * @author Tomohisa Igarashi + * + */ +public class MockXAResource implements XAResource { + private Logger _logger = Logger.getLogger(MockXAResource.class); + + @Override + public void commit(Xid xid, boolean onePhase) throws XAException { + _logger.debug("call commit(" + xid + ", " + onePhase + ")"); + } + + @Override + public void end(Xid xid, int flags) throws XAException { + _logger.debug("call end(" + xid + ", " + flags + ")"); + } + + @Override + public void forget(Xid xid) throws XAException { + _logger.debug("call forget(" + xid + ")"); + } + + @Override + public int getTransactionTimeout() throws XAException { + _logger.debug("call getTransactionTimeout"); + return 0; + } + + @Override + public boolean isSameRM(XAResource xares) throws XAException { + return xares.equals(this); + } + + @Override + public int prepare(Xid xid) throws XAException { + _logger.debug("call prepare(" + xid + ")"); + return 0; + } + + @Override + public Xid[] recover(int flag) throws XAException { + _logger.debug("call recover(" + flag + ")"); + return null; + } + + @Override + public void rollback(Xid xid) throws XAException { + _logger.debug("call rollback(" + xid + ")"); + } + + @Override + public boolean setTransactionTimeout(int seconds) throws XAException { + _logger.debug("call setTransactionTimeout(" + seconds + ")"); + return false; + } + + @Override + public void start(Xid xid, int flags) throws XAException { + _logger.debug("call start(" + xid + ", " + flags + ")"); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BPMServiceQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BPMServiceQuickstartTest.java new file mode 100644 index 000000000..ce28ee8eb --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BPMServiceQuickstartTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +/** + * + * @author Tomohisa Igarashi (C) 2011 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class BPMServiceQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-bpm-service"); + } + + @Test + public void testProcessOrder() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:8080/swydws/ProcessOrder", SOAP_REQUEST); + XMLAssert.assertXpathEvaluatesTo("PO-19839-XYZ", "//orderId", response); + XMLAssert.assertXpathEvaluatesTo("true", "//accepted", response); + XMLAssert.assertXpathEvaluatesTo("Thanks for your order, it has been shipped!", "//status", response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " \n" + + " \n" + + " PO-19839-XYZ\n" + + " cowbell\n" + + " 100\n" + + " \n" + + " \n" + + ""; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BeanServiceQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BeanServiceQuickstartTest.java new file mode 100644 index 000000000..adb3a55ca --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BeanServiceQuickstartTest.java @@ -0,0 +1,124 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.InputStreamReader; +import java.io.StringReader; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.type.Classes; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class BeanServiceQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-bean-service"); + } + + @Test + public void testOrders() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String wsdl = httpMixIn.sendString("http://localhost:8080/quickstart-bean/OrderService?wsdl", "", HTTPMixIn.HTTP_GET); + XMLAssert.assertXMLEqual(new InputStreamReader(Classes.getResourceAsStream("OrderService.wsdl")), new StringReader(wsdl)); + String response = httpMixIn.postString("http://localhost:8080/quickstart-bean/OrderService", SOAP_REQUEST); + XMLAssert.assertXpathEvaluatesTo("PO-19838-XYZ", "//orderAck/orderId", response); + XMLAssert.assertXpathEvaluatesTo("true", "//orderAck/accepted", response); + XMLAssert.assertXpathEvaluatesTo("Order Accepted [intercepted]", "//orderAck/status", response); + } finally { + httpMixIn.uninitialize(); + } + } + + @Test + public void testGatewayRestart(@ArquillianResource ManagementClient client) throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String wsdl = httpMixIn.sendString("http://localhost:8080/quickstart-bean/OrderService?wsdl", "", HTTPMixIn.HTTP_GET); + XMLAssert.assertXMLEqual(new InputStreamReader(Classes.getResourceAsStream("OrderService.wsdl")), new StringReader(wsdl)); + String response = httpMixIn.postString("http://localhost:8080/quickstart-bean/OrderService", SOAP_REQUEST); + XMLAssert.assertXpathEvaluatesTo("PO-19838-XYZ", "//orderAck/orderId", response); + XMLAssert.assertXpathEvaluatesTo("true", "//orderAck/accepted", response); + XMLAssert.assertXpathEvaluatesTo("Order Accepted [intercepted]", "//orderAck/status", response); + + final String namespace = "urn:switchyard-quickstart:bean-service:0.1.0"; + final String application = "orders"; + final String service = "OrderService"; + final String bindingType = "soap"; + final ModelNode operation = new ModelNode(); + operation.get(ModelDescriptionConstants.OP_ADDR).add("subsystem", "switchyard"); + operation.get(ModelDescriptionConstants.NAME).set("_" + service + "_" + bindingType + "_1"); + operation.get("service-name").set(new QName(namespace, service).toString()); + operation.get("application-name").set(new QName(namespace, application).toString()); + + // stop the gateway + operation.get(ModelDescriptionConstants.OP).set("stop-gateway"); + ModelNode result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to stop gateway: " + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + int status = httpMixIn.sendStringAndGetStatus("http://localhost:8080/quickstart-bean/OrderService", + SOAP_REQUEST, HTTPMixIn.HTTP_POST); + Assert.assertEquals("Unexpected status for disabled gateway.", 404, status); + + // restart the gateway + operation.get(ModelDescriptionConstants.OP).set("start-gateway"); + result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to restart gateway" + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + wsdl = httpMixIn.sendString("http://localhost:8080/quickstart-bean/OrderService?wsdl", "", HTTPMixIn.HTTP_GET); + XMLAssert.assertXMLEqual(new InputStreamReader(Classes.getResourceAsStream("OrderService.wsdl")), new StringReader(wsdl)); + response = httpMixIn.postString("http://localhost:8080/quickstart-bean/OrderService", SOAP_REQUEST); + XMLAssert.assertXpathEvaluatesTo("PO-19838-XYZ", "//orderAck/orderId", response); + XMLAssert.assertXpathEvaluatesTo("true", "//orderAck/accepted", response); + XMLAssert.assertXpathEvaluatesTo("Order Accepted [intercepted]", "//orderAck/status", response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " \n" + + " \n" + + " \n" + + " PO-19838-XYZ\n" + + " BUTTER\n" + + " 200\n" + + " \n" + + " \n" + + " \n" + + ""; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceJmsBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceJmsBindingQuickstartTest.java new file mode 100644 index 000000000..5b2da0026 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceJmsBindingQuickstartTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.Message; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +/** + * A testcase for deploy & invoke the bpel-service/jms_binding quickstart on AS7. + * + * @author Tomohisa Igarashi + */ +@RunWith(Arquillian.class) +public class BpelServiceJmsBindingQuickstartTest { + + private static final String REQUEST_QUEUE = "HelloRequestQueue"; + private static final String REPLY_QUEUE = "HelloReplyQueue"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + ResourceDeployer.addQueue(REQUEST_QUEUE); + ResourceDeployer.addQueue(REPLY_QUEUE); + return ArquillianUtil.createJarQSDeployment("switchyard-bpel-jms-binding"); + } + + @Test + public void testJmsBinding() throws Exception { + HornetQMixIn hqMixIn = new HornetQMixIn(false) + .setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + hqMixIn.initialize(); + + Session session = null; + MessageProducer producer = null; + MessageConsumer consumer = null; + try { + session = hqMixIn.createJMSSession(); + producer = session.createProducer(HornetQMixIn.getJMSQueue(REQUEST_QUEUE)); + Message message = hqMixIn.createJMSMessage(INPUT); + producer.send(message); + + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(REPLY_QUEUE)); + message = consumer.receive(3000); + String reply = hqMixIn.readStringFromJMSMessage(message); + SwitchYardTestKit.compareXMLToString(reply, EXPECTED_REPLY); + } finally { + hqMixIn.uninitialize(); + } + } + + @After + public void undeploy() throws IOException { + ResourceDeployer.removeQueue(REQUEST_QUEUE); + ResourceDeployer.removeQueue(REPLY_QUEUE); + } + + private static final String INPUT = "" + + "Tomo" + + ""; + + private static final String EXPECTED_REPLY = "" + + "Hello Tomo" + + ""; + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceLoanApprovalQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceLoanApprovalQuickstartTest.java new file mode 100644 index 000000000..a1afe5364 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceLoanApprovalQuickstartTest.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.custommonkey.xmlunit.NamespaceContext; +import org.custommonkey.xmlunit.SimpleNamespaceContext; +import org.custommonkey.xmlunit.XMLUnit; +import org.custommonkey.xmlunit.XpathEngine; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.w3c.dom.NodeList; + +/** + * + */ +@RunWith(Arquillian.class) +public class BpelServiceLoanApprovalQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-bpel-loan-approval"); + } + + @Test + public void testLoanRequestAccepted() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:8080/loanService/loanService", SOAP_REQUEST_1); + + org.w3c.dom.Document d = XMLUnit.buildControlDocument(response); + java.util.HashMap m = new java.util.HashMap(); + m.put("tns", "http://example.com/loan-approval/loanService/"); + NamespaceContext ctx = new SimpleNamespaceContext(m); + XpathEngine engine = XMLUnit.newXpathEngine(); + engine.setNamespaceContext(ctx); + + NodeList l = engine.getMatchingNodes("//tns:accept", d); + assertEquals(1, l.getLength()); + assertEquals(org.w3c.dom.Node.ELEMENT_NODE, l.item(0).getNodeType()); + + if (!l.item(0).getTextContent().equals("yes")) { + fail("Expecting 'yes'"); + } + } finally { + httpMixIn.uninitialize(); + } + } + + @Test + public void testLoanRequestUnableToHandle() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:8080/loanService/loanService", SOAP_REQUEST_2); + + org.w3c.dom.Document d = XMLUnit.buildControlDocument(response); + java.util.HashMap m = new java.util.HashMap(); + //m.put("tns", "http://example.com/loan-approval/loanService/"); + NamespaceContext ctx = new SimpleNamespaceContext(m); + XpathEngine engine = XMLUnit.newXpathEngine(); + engine.setNamespaceContext(ctx); + + NodeList l = engine.getMatchingNodes("//faultcode", d); + assertEquals(1, l.getLength()); + assertEquals(org.w3c.dom.Node.ELEMENT_NODE, l.item(0).getNodeType()); + + if (!l.item(0).getTextContent().endsWith(":unableToHandleRequest")) { + fail("Expecting 'unableToHandleRequest' fault code"); + } + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST_1 = "\n" + + " \n" + + " \n" + + " \n" + + " Fred\n" + + " Bloggs\n" + + " 100\n" + + " \n" + + " \n" + + ""; + + private static final String SOAP_REQUEST_2 = "\n" + + " \n" + + " \n" + + " \n" + + " Fred\n" + + " Bloggs\n" + + " 11000\n" + + " \n" + + " \n" + + ""; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceSayHelloQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceSayHelloQuickstartTest.java new file mode 100644 index 000000000..65f6fb1c8 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/BpelServiceSayHelloQuickstartTest.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.custommonkey.xmlunit.NamespaceContext; +import org.custommonkey.xmlunit.SimpleNamespaceContext; +import org.custommonkey.xmlunit.XMLUnit; +import org.custommonkey.xmlunit.XpathEngine; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.w3c.dom.NodeList; + +/** + * + */ +@RunWith(Arquillian.class) +public class BpelServiceSayHelloQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-bpel-say-hello"); + } + + @Test + public void testSayHello() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:8080/SayHelloService/SayHelloService", SOAP_REQUEST); + + org.w3c.dom.Document d = XMLUnit.buildControlDocument(response); + java.util.HashMap m = new java.util.HashMap(); + m.put("tns", "http://www.jboss.org/bpel/examples"); + NamespaceContext ctx = new SimpleNamespaceContext(m); + XpathEngine engine = XMLUnit.newXpathEngine(); + engine.setNamespaceContext(ctx); + + NodeList l = engine.getMatchingNodes("//tns:result", d); + assertEquals(1, l.getLength()); + assertEquals(org.w3c.dom.Node.ELEMENT_NODE, l.item(0).getNodeType()); + + if (!l.item(0).getTextContent().equals("Hello Fred")) { + fail("Expecting 'Hello Fred'"); + } + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " \n" + + " \n" + + " \n" + + " Fred\n" + + " \n" + + " \n" + + ""; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelBindingQuickstartTest.java new file mode 100644 index 000000000..6f179c3ec --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelBindingQuickstartTest.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.File; +import java.io.FileWriter; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +/** + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class CamelBindingQuickstartTest { + + private static String DEST_FILE = "target/input/test.txt"; + + @Deployment(testable = true) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-file-binding"); + } + + @Test + public void testDeployment() throws Exception { + File destFile = new File(DEST_FILE); + destFile.getParentFile().mkdirs(); + FileWriter writer = null; + try { + writer = new FileWriter(destFile); + writer.append("Captain Crunch"); + Assert.assertTrue(destFile.exists()); + } finally { + if (writer != null) { + writer.close(); + } + } + // Wait a spell so that the file component polls and picks up the file + while (destFile.exists()) { + Thread.sleep(50); + } + // File should have been picked up + Assert.assertFalse(destFile.exists()); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelCdiBusQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelCdiBusQuickstartTest.java new file mode 100644 index 000000000..2ffcf6550 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelCdiBusQuickstartTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.util.HashMap; +import java.util.Map; + +import org.custommonkey.xmlunit.SimpleNamespaceContext; +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +/** + * Test deployment of bus extension done by custom cdi beans. + */ +@RunWith(Arquillian.class) +public class CamelCdiBusQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-bus-cdi"); + } + + @Test + public void testDeployment() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String response = httpMixIn.postString("http://localhost:8080/quickstart-cdi-bus/OrderService", SOAP_REQUEST); + + Map namespaces = new HashMap(); + namespaces.put("ns", "urn:switchyard-quickstart:cdi-bus:1.0"); + XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); + + XMLAssert.assertXpathEvaluatesTo("PO-19838-XYZ", "//ns:orderAck/orderId", response); + XMLAssert.assertXpathEvaluatesTo("true", "//ns:orderAck/accepted", response); + XMLAssert.assertXpathEvaluatesTo("Order Accepted", "//ns:orderAck/status", response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " " + + " \n" + + " \n" + + " PO-19838-XYZ\n" + + " BUTTER\n" + + " 200\n" + + " \n" + + " \n" + + ""; + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelCxfQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelCxfQuickstartTest.java new file mode 100644 index 000000000..2f79f7731 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelCxfQuickstartTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +/** + * Test deployment of Camel Cxf. + */ +@RunWith(Arquillian.class) +public class CamelCxfQuickstartTest { + + private static final String SWITCHYARD_WEB_SERVICE = "http://localhost:8082/camel-cxf/order/OrderService"; + private static final String SWITCHYARD_REFERENCE_SERVICE = "http://localhost:8083/camel-cxf/warehouse/WarehouseService"; + + private HTTPMixIn _httpMixIn = new HTTPMixIn(); + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-cxf-binding"); + } + + @Ignore("Sporadic failures with JAXBMarshalling") @Test + public void cxfBinding() throws Exception { + _httpMixIn.initialize(); + try { + // goose the reference to workaround deadlock in initialization + _httpMixIn.postString(SWITCHYARD_REFERENCE_SERVICE, REQUEST); + String response = _httpMixIn.postString(SWITCHYARD_WEB_SERVICE, REQUEST); + Assert.assertTrue(response, response.contains("Order Boeing with quantity 10 accepted.")); + } finally { + _httpMixIn.uninitialize(); + } + } + + private static String REQUEST = "" + + " " + + " " + + " Boeing" + + " 10" + + " " + + " " + + ""; + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelHL7QuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelHL7QuickstartTest.java new file mode 100644 index 000000000..9530c375d --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelHL7QuickstartTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.apache.camel.CamelContext; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.hl7.HL7MLLPCodec; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.SimpleRegistry; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +/** + * Test to demonstrate deployment of the HL7 Quickstart. + */ +@RunWith(Arquillian.class) +public class CamelHL7QuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-hl7"); + } + + @Test + public void testDeployment() throws Exception { + SimpleRegistry registry = new SimpleRegistry(); + HL7MLLPCodec codec = new HL7MLLPCodec(); + codec.setCharset("iso-8859-1"); + codec.setConvertLFtoCR(true); + + registry.put("hl7codec", codec); + CamelContext camelContext = null; + ProducerTemplate template = null; + + try { + camelContext = new DefaultCamelContext(registry); + camelContext.start(); + template = camelContext.createProducerTemplate(); + String line1 = "MSH|^~\\&|MYSENDER|MYRECEIVER|MYAPPLICATION||200612211200||QRY^A19|1234|P|2.4"; + String line2 = "QRD|200612211200|R|I|GetPatient|||1^RD|0101701234|DEM||"; + + StringBuilder in = new StringBuilder(); + in.append(line1); + in.append("\r"); + in.append(line2); + + template.requestBody("mina2:tcp://127.0.0.1:8888?sync=true&codec=#hl7codec", in.toString()); + } finally { + if (template != null) { + try { + template.stop(); + } catch (Exception e) { + } + } + if (camelContext != null) { + try { + camelContext.stop(); + } catch (Exception e) { + } + } + } + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelJMSBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelJMSBindingQuickstartTest.java new file mode 100644 index 000000000..03bab39ef --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelJMSBindingQuickstartTest.java @@ -0,0 +1,122 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import javax.jms.Message; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.QueueBrowser; +import javax.jms.Session; +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +@RunWith(Arquillian.class) +public class CamelJMSBindingQuickstartTest { + + private static final String QUEUE = "GreetingServiceQueue"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + ResourceDeployer.addQueue(QUEUE); + return ArquillianUtil.createJarQSDeployment("switchyard-camel-jms-binding"); + } + + @Test + public void testDeployment() throws Exception { + HornetQMixIn hqMixIn = new HornetQMixIn(false) + .setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + hqMixIn.initialize(); + + try { + Session session = hqMixIn.getJMSSession(); + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE)); + Message message = hqMixIn.createJMSMessage("Tomo"); + producer.send(message); + } finally { + hqMixIn.uninitialize(); + ResourceDeployer.removeQueue(QUEUE); + } + } + + @Test + public void testGatewayRestart(@ArquillianResource ManagementClient client) throws Exception { + HornetQMixIn hqMixIn = new HornetQMixIn(false) + .setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + hqMixIn.initialize(); + + try { + Session session = hqMixIn.getJMSSession(); + Queue queue = HornetQMixIn.getJMSQueue(QUEUE); + MessageProducer producer = session.createProducer(queue); + QueueBrowser browser = session.createBrowser(queue); + Message message = hqMixIn.createJMSMessage("Restarter"); + producer.send(message); + Thread.sleep(1000); + Assert.assertFalse(browser.getEnumeration().hasMoreElements()); + + final String namespace = "urn:switchyard-quickstart:camel-jms-binding:0.1.0"; + final String application = "camel-jms-binding"; + final String service = "GreetingService"; + final String bindingType = "jms"; + final ModelNode operation = new ModelNode(); + operation.get(ModelDescriptionConstants.OP_ADDR).add("subsystem", "switchyard"); + operation.get(ModelDescriptionConstants.NAME).set("_" + service + "_" + bindingType + "_1"); + operation.get("service-name").set(new QName(namespace, service).toString()); + operation.get("application-name").set(new QName(namespace, application).toString()); + + // stop the gateway + operation.get(ModelDescriptionConstants.OP).set("stop-gateway"); + ModelNode result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to stop gateway: " + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + message = hqMixIn.createJMSMessage("Stopped"); + producer.send(message); + Thread.sleep(1000); + Assert.assertEquals(message.getJMSMessageID(), + ((Message) browser.getEnumeration().nextElement()).getJMSMessageID()); + + // restart the gateway + operation.get(ModelDescriptionConstants.OP).set("start-gateway"); + result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to restart gateway" + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + message = hqMixIn.createJMSMessage("Restarted"); + producer.send(message); + Thread.sleep(1000); + Assert.assertFalse(browser.getEnumeration().hasMoreElements()); + } finally { + hqMixIn.uninitialize(); + ResourceDeployer.removeQueue(QUEUE); + } + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelJpaBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelJpaBindingQuickstartTest.java new file mode 100644 index 000000000..809cec796 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelJpaBindingQuickstartTest.java @@ -0,0 +1,217 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; + +import javax.naming.InitialContext; +import javax.sql.DataSource; +import javax.xml.namespace.QName; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.RunAsClient; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.junit.InSequence; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class CamelJpaBindingQuickstartTest { + + @Deployment(testable = true) + public static JavaArchive createDeployment() throws IOException { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-jpa-binding"); + } + + private static final String namespace = "urn:switchyard-quickstart:camel-jpa-binding:0.1.0"; + private static final String application = new QName(namespace, "camel-jpa-retrieve-binding").toString(); + private static final String quartzService = new QName(namespace, "PeriodicService").toString(); + private static final String quartzBinding = "_PeriodicService_quartz_1"; + private static final String greetingService = new QName(namespace, "GreetingService").toString(); + private static final String greetingBinding = "_GreetingService_jpa_1"; + private static final String storeReference = new QName(namespace, "StoreReference").toString(); + private static final String storeBinding = "_StoreReference_jpa_1"; + + @ArquillianResource + private ManagementClient _client; + + @Test + @RunAsClient + @InSequence(1) + public void testStopStoreGateway() throws Exception { + // make at least one event is stored + Thread.sleep(6000); + + // stop the store gateway + executeOperation(storeReference, storeBinding, false); + } + + @Test + @InSequence(2) + public void testStoreGatewayStopped(@ArquillianResource InitialContext context) throws Exception { + Connection connection = null; + Statement statement = null; + try { + // make sure at least one event is generated + Thread.sleep(6000); + + final DataSource ds = (DataSource) context.lookup("java:jboss/datasources/ExampleDS"); + connection = ds.getConnection(); + + // verify there are no events to be processed + assertEvents(connection, "StoreReference not disabled.", false); + + // send in a message to make sure the greeting service is still + // running + statement = connection.createStatement(); + statement.execute("INSERT INTO events (sender,receiver,createdAt) values ('John', 'Rambo', NOW())"); + Assert.assertEquals(1, statement.getUpdateCount()); + statement.close(); + statement = null; + + // verify the event was processed + Thread.sleep(1000); + assertEvents(connection, "GreetingService not running.", false); + } finally { + if (statement != null) { + try { + statement.close(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + if (connection != null) { + try { + connection.close(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + } + + @Test + @RunAsClient + @InSequence(3) + public void testRestartStoreGateway() throws Exception { + // stop the processor gateway + executeOperation(greetingService, greetingBinding, false); + + // restart the store gateway + executeOperation(storeReference, storeBinding, true); + } + + @Test + @InSequence(4) + public void testGreetingGatewayStopped(@ArquillianResource InitialContext context) throws Exception { + // make sure at least one event is generated + Thread.sleep(6000); + + assertEvents(context, "GreetingService not stopped or StoreReference not restarted.", true); + } + + @Test + @RunAsClient + @InSequence(5) + public void testStopQuartzGateway() throws Exception { + // stop the quartz gateway + executeOperation(quartzService, quartzBinding, false); + + // start the processor gateway + executeOperation(greetingService, greetingBinding, true); + + // make sure at least one event is generated + Thread.sleep(6000); + + // stop the processor gateway + executeOperation(greetingService, greetingBinding, false); + } + + @Test + @InSequence(6) + public void testQuartzGatewayStopped(@ArquillianResource InitialContext context) throws Exception { + // make sure at least one event is generated + Thread.sleep(6000); + + assertEvents(context, "Quartz gateway not stopped.", false); + } + + private void executeOperation(final String serviceName, final String bindingName, final boolean start) + throws Exception { + final ModelNode operation = new ModelNode(); + operation.get(ModelDescriptionConstants.OP_ADDR).add("subsystem", "switchyard"); + operation.get("application-name").set(application); + if (start) { + operation.get(ModelDescriptionConstants.OP).set("start-gateway"); + } else { + operation.get(ModelDescriptionConstants.OP).set("stop-gateway"); + } + operation.get(ModelDescriptionConstants.NAME).set(bindingName); + operation.get("service-name").set(serviceName); + final ModelNode result = _client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to " + (start ? "start" : "stop") + " gateway: " + result.toString(), + ModelDescriptionConstants.SUCCESS, result.get(ModelDescriptionConstants.OUTCOME).asString()); + } + + private void assertEvents(final InitialContext context, final String message, final boolean expected) + throws Exception { + Connection connection = null; + try { + final DataSource ds = (DataSource) context.lookup("java:jboss/datasources/ExampleDS"); + connection = ds.getConnection(); + assertEvents(connection, message, expected); + } finally { + if (connection != null) { + try { + connection.close(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + } + + private void assertEvents(final Connection connection, final String message, final boolean expected) + throws Exception { + Statement statement = null; + try { + statement = connection.createStatement(); + boolean containsEvents = statement.execute("SELECT * FROM events"); + if (containsEvents) { + final ResultSet rs = statement.getResultSet(); + containsEvents = rs.next(); + rs.close(); + } + Assert.assertEquals(message, expected, containsEvents); + } finally { + if (statement != null) { + try { + statement.close(); + } catch (Exception e) { + e.fillInStackTrace(); + } + } + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelMQTTBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelMQTTBindingQuickstartTest.java new file mode 100644 index 000000000..efe7f3bab --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelMQTTBindingQuickstartTest.java @@ -0,0 +1,99 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.util.concurrent.TimeUnit; + +import org.apache.activemq.broker.BrokerService; +import org.fusesource.mqtt.client.BlockingConnection; +import org.fusesource.mqtt.client.MQTT; +import org.fusesource.mqtt.client.Message; +import org.fusesource.mqtt.client.QoS; +import org.fusesource.mqtt.client.Topic; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class CamelMQTTBindingQuickstartTest { + + private static final String TOPIC_INPUT = "camel/mqtt/test/input"; + private static final String TOPIC_OUTPUT = "camel/mqtt/test/output"; + private static final String MESSAGE_INPUT = "SpongeBob"; + private static final String MESSAGE_OUTPUT = "Hello there " + MESSAGE_INPUT + " :-) "; + private static final String USER_NAME = "karaf"; + private static final String PASSWORD = "karaf"; + + private static BrokerService _broker; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws Exception { + _broker = new BrokerService(); + _broker.setBrokerName("default"); + _broker.setUseJmx(false); + _broker.setPersistent(false); + _broker.addConnector("mqtt://localhost:1883"); + _broker.setUseShutdownHook(false); + _broker.start(); + + return ArquillianUtil.createJarQSDeployment("switchyard-camel-mqtt-binding"); + } + + @Test + public void testDeployment() throws Exception { + BlockingConnection publishConnection = null; + BlockingConnection subscribeConnection = null; + try { + Topic outputTopic = new Topic(TOPIC_OUTPUT, QoS.AT_LEAST_ONCE); + MQTT mqtt = new MQTT(); + mqtt.setUserName(USER_NAME); + mqtt.setPassword(PASSWORD); + subscribeConnection = mqtt.blockingConnection(); + subscribeConnection.connect(); + subscribeConnection.subscribe(new Topic[]{outputTopic}); + + publishConnection = mqtt.blockingConnection(); + publishConnection.connect(); + publishConnection.publish(TOPIC_INPUT, MESSAGE_INPUT.getBytes(), QoS.AT_LEAST_ONCE, false); + + /* Disable for now due to https://issues.jboss.org/browse/SWITCHYARD-2221 + * + Message message = subscribeConnection.receive(1000, TimeUnit.MILLISECONDS); + Assert.assertNotNull("No output message from " + TOPIC_OUTPUT, message); + Assert.assertEquals(MESSAGE_OUTPUT, new String(message.getPayload())); + Assert.assertNull("More than one message received from " + TOPIC_OUTPUT, + subscribeConnection.receive(1000, TimeUnit.MILLISECONDS)); + */ + } finally { + if (publishConnection != null && publishConnection.isConnected()) { + publishConnection.disconnect(); + } + if (subscribeConnection != null && subscribeConnection.isConnected()) { + subscribeConnection.disconnect(); + } + } + } + + @AfterClass + public static void cleanup() throws Exception { + if (_broker != null) { + _broker.stop(); + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelMailBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelMailBindingQuickstartTest.java new file mode 100644 index 000000000..25fb2ca54 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelMailBindingQuickstartTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.jvnet.mock_javamail.Mailbox; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class CamelMailBindingQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + JavaArchive quickstart = ArquillianUtil.createJarQSDeployment("switchyard-camel-mail-binding"); + // copy mock javamail to archive to use mock mail providers instead of real + quickstart.addAsResource(Mailbox.class.getResource("/META-INF/javamail.providers"), + "/META-INF/javamail.providers"); + quickstart.addPackage(Mailbox.class.getPackage()); + return quickstart; + } + + @Test + public void testDeployment() throws Exception { + Assert.assertNotNull("Dummy not null", ""); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelNettyBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelNettyBindingQuickstartTest.java new file mode 100644 index 000000000..170ac2e34 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelNettyBindingQuickstartTest.java @@ -0,0 +1,138 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; +import java.net.Socket; +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManagerFactory; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.as.arquillian.api.ServerSetup; +import org.jboss.as.arquillian.api.ServerSetupTask; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +@ServerSetup(CamelNettyBindingQuickstartTest.SecuritySetupTask.class) +public class CamelNettyBindingQuickstartTest { + + private static String SRC_DIR = System.getProperty("jboss.home") + "/quickstarts/camel-netty-binding"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-netty-binding"); + } + + @Test + public void testTCPSecure() throws Exception { + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(new FileInputStream(new File(SRC_DIR, "users.jks")), "changeit".toCharArray()); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(keystore); + + SSLContext context = SSLContext.getInstance("TLS"); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, "changeit".toCharArray()); + + context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); + + SSLSocketFactory sf = context.getSocketFactory(); + + Socket clientSocket = sf.createSocket("localhost", 3939); + DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream()); + outputStream.write(getClass().getName().getBytes()); + outputStream.flush(); + + Thread.sleep(1000); + + clientSocket.close(); + } + + @Test + public void testTCPUnsecure() throws Exception { + Socket clientSocket = new Socket("localhost", 3939); + DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream()); + outputStream.write(getClass().getName().getBytes()); + Thread.sleep(1000); + clientSocket.close(); + } + + @Test + public void testUDPUnsecure() throws Exception { + MulticastSocket clientSocket = new MulticastSocket(); + InetAddress group = InetAddress.getByName("localhost"); + + byte[] datagramBody = getClass().getName().getBytes(); + DatagramPacket packet = new DatagramPacket(datagramBody, 0, datagramBody.length, group, 3940); + clientSocket.send(packet); + + Thread.sleep(1000); + clientSocket.close(); + } + + public static class SecuritySetupTask implements ServerSetupTask { + + @Override + public void setup(ManagementClient client, String unused) throws Exception { + ModelNode op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "netty-security-cert"); + op.get("cache-type").set("default"); + client.getControllerClient().execute(op); + + op.remove("cache-type"); + op.get("address").add("authentication", "classic"); + ModelNode loginModule = new ModelNode(); + loginModule.get("code").set("org.switchyard.security.login.CertificateLoginModule"); + loginModule.get("flag").set("required"); + loginModule.get("module-options").add("keyStoreLocation", + new File(SRC_DIR, "users.jks").getAbsolutePath()); + loginModule.get("module-options").add("keyStorePassword", "changeit"); + loginModule.get("module-options").add("rolesProperties", + new File(SRC_DIR, "roles.properties").getAbsolutePath()); + op.get("login-modules").add(loginModule); + op.get("operation-headers", "allow-resource-service-restart").set("true"); + client.getControllerClient().execute(op); + + Thread.sleep(1000); + } + + @Override + public void tearDown(ManagementClient client, String unused) throws Exception { + ModelNode op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "netty-security-cert"); + client.getControllerClient().execute(op); + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelQuartzBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelQuartzBindingQuickstartTest.java new file mode 100644 index 000000000..2da6f396c --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelQuartzBindingQuickstartTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class CamelQuartzBindingQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-quartz-binding"); + } + + @Test + public void testDeployment() throws Exception { + Assert.assertNotNull("Dummy not null", ""); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSOAPProxyQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSOAPProxyQuickstartTest.java new file mode 100644 index 000000000..51bcc44de --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSOAPProxyQuickstartTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class CamelSOAPProxyQuickstartTest { + + @Deployment(testable = false, order=1, name="ReverseService") + public static WebArchive createProxyDeployment() throws IOException { + return ArquillianUtil.createWarQSDeployment("switchyard-camel-soap-proxy-reverse-service"); + } + + @Deployment(testable = false, order=2) + public static JavaArchive createDeployment() throws IOException { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-soap-proxy"); + } + + @Test + public void testDeployment() throws Exception { + HTTPMixIn soapMixIn = new HTTPMixIn(); + soapMixIn.initialize(); + + try { + String port = System.getProperty("org.switchyard.component.soap.client.port", "8080"); + // For karaf, the directory will generally be cxf/proxy/ReverseService + String dir = System.getProperty("org.switchyard.component.soap.client.dir", "proxy/ReverseService"); + String url = "http://localhost:" + port + "/" + dir; + String response = soapMixIn.postString(url, XML); + XMLAssert.assertXpathEvaluatesTo("raboof", "//text", response); + } finally { + soapMixIn.uninitialize(); + } + } + + private static final String XML = "" + + "" + + " " + + " " + + " " + + " foobar" + + " " + + " " + + ""; + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSaxonQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSaxonQuickstartTest.java new file mode 100644 index 000000000..52c805e20 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSaxonQuickstartTest.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class CamelSaxonQuickstartTest { + + private static final String URL = "http://localhost:8080/quickstart-camel-saxon/GreetingService"; + + private static final String SOAP_REQUEST = +"" + +" " + +" " + +" Garfield" + +" " + +""; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-saxon"); + } + + @Test + public void testGreeting() throws Exception { + HTTPMixIn soapMixIn = new HTTPMixIn(); + soapMixIn.initialize(); + + try { + int status = soapMixIn.sendStringAndGetStatus(URL, SOAP_REQUEST, HTTPMixIn.HTTP_POST); + Assert.assertEquals("Unexpected status.", 202, status); + } finally { + soapMixIn.uninitialize(); + } + } + + @Test + public void testGatewayRestart(@ArquillianResource ManagementClient client) throws Exception { + HTTPMixIn soapMixIn = new HTTPMixIn(); + soapMixIn.initialize(); + + try { + int status = soapMixIn.sendStringAndGetStatus(URL, SOAP_REQUEST, HTTPMixIn.HTTP_POST); + Assert.assertEquals("Unexpected status.", 202, status); + + final String namespace = "urn:switchyard-quickstart:camel-saxon:0.1.0"; + final String application = "camel-saxon"; + final String service = "GreetingService"; + final String bindingType = "soap"; + final ModelNode operation = new ModelNode(); + operation.get(ModelDescriptionConstants.OP_ADDR).add("subsystem", "switchyard"); + operation.get(ModelDescriptionConstants.NAME).set("_" + service + "_" + bindingType + "_1"); + operation.get("service-name").set(new QName(namespace, service).toString()); + operation.get("application-name").set(new QName(namespace, application).toString()); + + // stop the gateway + operation.get(ModelDescriptionConstants.OP).set("stop-gateway"); + ModelNode result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to stop gateway: " + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + status = soapMixIn.sendStringAndGetStatus(URL, SOAP_REQUEST, HTTPMixIn.HTTP_POST); + Assert.assertEquals("Unexpected status for disabled gateway.", 404, status); + + // restart the gateway + operation.get(ModelDescriptionConstants.OP).set("start-gateway"); + result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to restart gateway" + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + status = soapMixIn.sendStringAndGetStatus(URL, SOAP_REQUEST, HTTPMixIn.HTTP_POST); + Assert.assertEquals("Unexpected status for restarted gateway.", 202, status); + } finally { + soapMixIn.uninitialize(); + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelServiceQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelServiceQuickstartTest.java new file mode 100644 index 000000000..be46f8a92 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelServiceQuickstartTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import javax.xml.namespace.QName; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; +import org.switchyard.test.ArquillianUtil; + +/** + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class CamelServiceQuickstartTest { + + private static final QName SERVICE = new QName( "urn:switchyard-quickstart:camel-service:0.1.0", "JavaDSL"); + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-service"); + } + + @Test + public void testDeployment() throws Exception { + // Create a new remote client invoker + String port = System.getProperty("org.switchyard.component.sca.client.port", "8080"); + RemoteInvoker invoker = new HttpInvoker("http://localhost:" + port + "/switchyard-remote"); + + // Create the request message + RemoteMessage message = new RemoteMessage(); + message.setService(SERVICE).setOperation("acceptMessage").setContent("test"); + + // Invoke the service + invoker.invoke(message); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSqlBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSqlBindingQuickstartTest.java new file mode 100644 index 000000000..63711c638 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/CamelSqlBindingQuickstartTest.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class CamelSqlBindingQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + return ArquillianUtil.createJarQSDeployment("switchyard-camel-sql-binding").addAsManifestResource("test-ds.xml"); + } + + @Test + public void testDeployment() throws Exception { + Assert.assertNotNull("Dummy not null", ""); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/EarDeployQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/EarDeployQuickstartTest.java new file mode 100644 index 000000000..a63d86f18 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/EarDeployQuickstartTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.TextMessage; + +import junit.framework.Assert; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +@RunWith(Arquillian.class) +public class EarDeployQuickstartTest { + + private static final String ORDER_QUEUE_NAME = "EAROrderRequestQueue"; + private static final String ORDERACK_QUEUE_NAME = "EAROrderReplyQueue"; + + @Deployment(testable = false) + public static EnterpriseArchive createDeployment() throws IOException { + return ArquillianUtil.createEarQSDeployment("switchyard-ear-deployment-ear-assembly"); + } + + @Test + public void testDeployment() throws Exception { + HornetQMixIn hqMixIn = new HornetQMixIn(false) + .setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + hqMixIn.initialize(); + + try { + Session session = hqMixIn.getJMSSession(); + // send the request + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(ORDER_QUEUE_NAME)); + Message message = hqMixIn.createJMSMessage(REQUEST); + producer.send(message); + + // wait for a reply + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(ORDERACK_QUEUE_NAME)); + TextMessage reply = (TextMessage)consumer.receive(3000); + Assert.assertNotNull("No reply message received from order-consumer", reply); + Assert.assertTrue("Received message is not an orderAck", reply.getText().contains("orderAck")); + } finally { + hqMixIn.uninitialize(); + } + } + + private static final String REQUEST = + "" + + "" + + "PO-19838-XYZ" + + "BUTTER" + + "200" + + "" + + ""; + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/EarDeploymentTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/EarDeploymentTest.java new file mode 100644 index 000000000..4b07090bf --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/EarDeploymentTest.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +/** + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class EarDeploymentTest { + + private static String VERSION = System.getenv("SWITCHYARD_VERSION"); + + private static String APPLICATION_XML = "\n" + + " \n" + + " switchyard-bean-service-" + VERSION + ".jar\n" + + " \n" + + " \n" + + " switchyard-camel-file-binding-" + VERSION + ".jar\n" + + " \n" + + " \n" + + " switchyard-transform-jaxb-" + VERSION + ".jar\n" + + " \n" + + " \n" + + " switchyard-transform-json-" + VERSION + ".jar\n" + + " \n" + + " \n" + + " switchyard-transform-smooks-" + VERSION + ".jar\n" + + " \n" + + " \n" + + " switchyard-transform-xslt-" + VERSION + ".jar\n" + + " \n" + + ""; + + @Deployment(testable = false) + public static EnterpriseArchive createDeployment() { + return ShrinkWrap + .create(EnterpriseArchive.class) + .setApplicationXML(new StringAsset(APPLICATION_XML)) + .addAsModule(ArquillianUtil.createJarQSDeployment("switchyard-bean-service")) + .addAsModule(ArquillianUtil.createJarQSDeployment("switchyard-camel-file-binding")) + .addAsModule(ArquillianUtil.createJarQSDeployment("switchyard-transform-jaxb")) + .addAsModule(ArquillianUtil.createJarQSDeployment("switchyard-transform-json")) + .addAsModule(ArquillianUtil.createJarQSDeployment("switchyard-transform-smooks")) + .addAsModule(ArquillianUtil.createJarQSDeployment("switchyard-transform-xslt")); + } + + @Test + public void testDeployment() { + Assert.assertNotNull("Dummy not null", ""); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/HttpBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/HttpBindingQuickstartTest.java new file mode 100644 index 000000000..b69344b90 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/HttpBindingQuickstartTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import javax.xml.namespace.QName; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.SwitchYardTestKit; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +@RunWith(Arquillian.class) +public class HttpBindingQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-http-binding"); + } + + @Test + public void quoteService() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + String response = httpMixIn.sendString(BASE_URL + "/quote", "vineyard", HTTPMixIn.HTTP_POST); + Assert.assertEquals("136.5", response); + } finally { + httpMixIn.uninitialize(); + } + } + + @Test + public void gatewayRestart(@ArquillianResource ManagementClient client) throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + String response = httpMixIn.sendString(BASE_URL + "/quote", "vineyard", HTTPMixIn.HTTP_POST); + Assert.assertEquals("136.5", response); + + final String namespace = "urn:switchyard-quickstart:http-binding:1.0"; + final ModelNode operation = new ModelNode(); + operation.get(ModelDescriptionConstants.OP_ADDR).add("subsystem", "switchyard"); + operation.get(ModelDescriptionConstants.NAME).set("_QuoteService_http_1"); + operation.get("service-name").set(new QName(namespace, "QuoteService").toString()); + operation.get("application-name").set(new QName(namespace, "http-binding").toString()); + + // stop the gateway + operation.get(ModelDescriptionConstants.OP).set("stop-gateway"); + ModelNode result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to stop gateway: " + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + Assert.assertEquals(404, + httpMixIn.sendStringAndGetStatus(BASE_URL + "/quote", "vineyard", HTTPMixIn.HTTP_POST)); + + // restart the gateway + operation.get(ModelDescriptionConstants.OP).set("start-gateway"); + result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to restart gateway: " + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + Assert.assertEquals("136.5", httpMixIn.sendString(BASE_URL + "/quote", "vineyard", HTTPMixIn.HTTP_POST)); + } finally { + httpMixIn.uninitialize(); + } + } + + @Test + public void headers() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String response = httpMixIn.sendString(BASE_URL + "/symbol", "headers", HTTPMixIn.HTTP_POST); + Assert.assertTrue("Unexpected response: [" + response + "]", response.toLowerCase().indexOf("content-type=text/xml; charset=utf-8") >= 0); + int status = httpMixIn.sendStringAndGetStatus(BASE_URL + "/symbol", "rum", HTTPMixIn.HTTP_POST); + Assert.assertEquals(404, status); + } finally { + httpMixIn.uninitialize(); + } + } + + @Test + public void requestInfo() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String response = httpMixIn.sendString(BASE_URL + "/symbol", "requestInfo", HTTPMixIn.HTTP_POST); + Assert.assertTrue(response.indexOf("HttpRequestInfo [authType=null, characterEncoding=UTF-8, contentType=text/xml; charset=UTF-8, contextPath=") == 0); + } finally { + httpMixIn.uninitialize(); + } + } + private static final String BASE_URL = "http://localhost:8080/http-binding"; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAInflowHornetQQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAInflowHornetQQuickstartTest.java new file mode 100644 index 000000000..6825f085e --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAInflowHornetQQuickstartTest.java @@ -0,0 +1,134 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; + +import javax.jms.Message; +import javax.jms.MessageProducer; +import javax.jms.Queue; +import javax.jms.QueueBrowser; +import javax.jms.Session; +import javax.jms.TextMessage; +import javax.xml.namespace.QName; + +import junit.framework.Assert; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +@RunWith(Arquillian.class) +public class JCAInflowHornetQQuickstartTest { + + private static final String QUEUE = "JCAInflowGreetingServiceQueue"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + ResourceDeployer.addQueue(QUEUE); + return ArquillianUtil.createJarQSDeployment("switchyard-jca-inflow-hornetq"); + } + + @Test + public void testDeployment() throws Exception { + HornetQMixIn hqMixIn = new HornetQMixIn(false) + .setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + hqMixIn.initialize(); + + try { + Session session = hqMixIn.getJMSSession(); + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE)); + TextMessage message = session.createTextMessage(); + message.setText(PAYLOAD); + producer.send(message); + Thread.sleep(1000); + } finally { + hqMixIn.uninitialize(); + ResourceDeployer.removeQueue(QUEUE); + } + } + + @Test + public void testGatewayRestart(@ArquillianResource ManagementClient client) throws Exception { + HornetQMixIn hqMixIn = new HornetQMixIn(false) + .setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + hqMixIn.initialize(); + + try { + Session session = hqMixIn.getJMSSession(); + Queue queue = HornetQMixIn.getJMSQueue(QUEUE); + MessageProducer producer = session.createProducer(queue); + QueueBrowser browser = session.createBrowser(queue); + TextMessage message = session.createTextMessage(); + message.setText(PAYLOAD); + producer.send(message); + Thread.sleep(1000); + Assert.assertFalse(browser.getEnumeration().hasMoreElements()); + + final String namespace = "urn:switchyard-quickstart:jca-inflow-hornetq:0.1.0"; + final String application = "jca-inflow-hornetq"; + final String service = "GreetingService"; + final String bindingType = "jca"; + final ModelNode operation = new ModelNode(); + operation.get(ModelDescriptionConstants.OP_ADDR).add("subsystem", "switchyard"); + operation.get(ModelDescriptionConstants.NAME).set("_" + service + "_" + bindingType + "_1"); + operation.get("service-name").set(new QName(namespace, service).toString()); + operation.get("application-name").set(new QName(namespace, application).toString()); + + // stop the gateway + operation.get(ModelDescriptionConstants.OP).set("stop-gateway"); + ModelNode result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to stop gateway: " + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + message = session.createTextMessage(); + message.setText(PAYLOAD); + producer.send(message); + Thread.sleep(1000); + Assert.assertEquals(message.getJMSMessageID(), + ((Message) browser.getEnumeration().nextElement()).getJMSMessageID()); + + // restart the gateway + operation.get(ModelDescriptionConstants.OP).set("start-gateway"); + result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to restart gateway" + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + message = session.createTextMessage(); + message.setText(PAYLOAD); + producer.send(message); + Thread.sleep(1000); + Assert.assertFalse(browser.getEnumeration().hasMoreElements()); + } finally { + hqMixIn.uninitialize(); + ResourceDeployer.removeQueue(QUEUE); + } + } + + private static final String PAYLOAD = "\n" + + "\n" + + " Fernando\n" + + " spanish\n" + + "\n"; + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAOutboundHornetQQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAOutboundHornetQQuickstartTest.java new file mode 100644 index 000000000..6be51b174 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/JCAOutboundHornetQQuickstartTest.java @@ -0,0 +1,92 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.jms.BytesMessage; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +@RunWith(Arquillian.class) +public class JCAOutboundHornetQQuickstartTest { + + private static final String ORDER_QUEUE = "OrderQueue"; + private static final String SHIPPING_QUEUE = "ShippingQueue"; + private static final String FILLING_STOCK_QUEUE = "FillingStockQueue"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + ResourceDeployer.addQueue(ORDER_QUEUE); + ResourceDeployer.addQueue(SHIPPING_QUEUE); + ResourceDeployer.addQueue(FILLING_STOCK_QUEUE); + return ArquillianUtil.createJarQSDeployment("switchyard-jca-outbound-hornetq"); + } + + @Test + public void testDeployment() throws Exception { + HornetQMixIn hqMixIn = new HornetQMixIn(false) + .setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + hqMixIn.initialize(); + String[] orders = {"BREAD", "PIZZA", "JAM", "POTATO", "MILK", "JAM"}; + + try { + Session session = hqMixIn.getJMSSession(); + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(ORDER_QUEUE)); + for (String order : orders) { + BytesMessage message = session.createBytesMessage(); + message.writeBytes(order.getBytes()); + producer.send(message); + } + session = hqMixIn.createJMSSession(); + + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(SHIPPING_QUEUE)); + List expectedShippingOrders = new ArrayList(Arrays.asList("BREAD", "JAM", "MILK", "JAM")); + Message msg = null; + while ((msg = consumer.receive(1000)) != null) { + Assert.assertTrue(expectedShippingOrders.remove(hqMixIn.readStringFromJMSMessage(msg))); + } + Assert.assertEquals(0, expectedShippingOrders.size()); + + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(FILLING_STOCK_QUEUE)); + List expectedFillingStockOrders = new ArrayList(Arrays.asList("PIZZA", "POTATO")); + while ((msg = consumer.receive(1000)) != null) { + Assert.assertTrue(expectedFillingStockOrders.remove(hqMixIn.readStringFromJMSMessage(msg))); + } + Assert.assertEquals(0, expectedFillingStockOrders.size()); + } finally { + hqMixIn.uninitialize(); + ResourceDeployer.removeQueue(ORDER_QUEUE); + ResourceDeployer.removeQueue(SHIPPING_QUEUE); + ResourceDeployer.removeQueue(FILLING_STOCK_QUEUE); + } + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RemoteInvokerQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RemoteInvokerQuickstartTest.java new file mode 100644 index 000000000..e86d7fd8a --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RemoteInvokerQuickstartTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import javax.xml.namespace.QName; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.quickstarts.remoteinvoker.Application; +import org.switchyard.quickstarts.remoteinvoker.Car; +import org.switchyard.quickstarts.remoteinvoker.Deal; +import org.switchyard.quickstarts.remoteinvoker.Offer; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class RemoteInvokerQuickstartTest { + + private static final QName SERVICE = + new QName("urn:com.example.switchyard:switchyard-quickstart-remote-invoker:1.0", "Dealer"); + private static final String URL = "http://localhost:8080/switchyard-remote"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-remote-invoker"); + } + + @Test + public void testOffer() throws Exception { + + RemoteInvoker invoker = new HttpInvoker(URL); + Application app = new Application(); + app.setName("Magesh"); + app.setCreditScore(812); + Car car = new Car(); + car.setPrice(9600); + Offer offer = new Offer(); + offer.setApplication(app); + offer.setCar(car); + offer.setAmount(9000); + + RemoteMessage message = new RemoteMessage(); + message.setService(SERVICE) + .setOperation("offer") + .setContent(offer); + + // Invoke the service + RemoteMessage reply = invoker.invoke(message); + Deal deal = (Deal)reply.getContent(); + Assert.assertTrue(deal.isAccepted()); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RestBindingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RestBindingQuickstartTest.java new file mode 100644 index 000000000..a206b5516 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RestBindingQuickstartTest.java @@ -0,0 +1,228 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import javax.xml.namespace.QName; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.SwitchYardTestKit; + +@RunWith(Arquillian.class) +public class RestBindingQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-rest-binding"); + } + + @Test + public void testOrders(@ArquillianResource ManagementClient client) throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + // Create our inventory + String response = httpMixIn.sendString(BASE_URL + "/inventory/create", "", HTTPMixIn.HTTP_OPTIONS); + Assert.assertEquals(SUCCESS, response); + + // Create an order + response = httpMixIn.sendString(BASE_URL + "/order", "", HTTPMixIn.HTTP_POST); + SwitchYardTestKit.compareXMLToString(response, ORDER); + + // Add a new item or update order + response = httpMixIn.sendString(BASE_URL + "/order/item", ORDER1, HTTPMixIn.HTTP_PUT); + Assert.assertEquals(SUCCESS, response); + + // Add some more items or update order + response = httpMixIn.sendString(BASE_URL + "/order/item", ORDER2, HTTPMixIn.HTTP_PUT); + Assert.assertEquals(SUCCESS, response); + + // Look at our order + response = httpMixIn.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET); + SwitchYardTestKit.compareXMLToString(response, ORDER3); + + // Delete the first item + response = httpMixIn.sendString(BASE_URL + "/order/1:1", "", HTTPMixIn.HTTP_DELETE); + Assert.assertEquals(SUCCESS, response); + + // Try to delete item with wrong composite ID + int status = httpMixIn.sendStringAndGetStatus(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_DELETE); + Assert.assertEquals(400, status); + + // Look at our order + response = httpMixIn.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET); + SwitchYardTestKit.compareXMLToString(response, ORDER4); + + // Update item descriptions in our inventory + response = httpMixIn.sendString(BASE_URL + "/inventory/update", "", HTTPMixIn.HTTP_OPTIONS); + Assert.assertEquals(SUCCESS, response); + + // Look at our order + response = httpMixIn.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET); + SwitchYardTestKit.compareXMLToString(response, ORDER5); + + // Look at non existing order + status = httpMixIn.sendStringAndGetStatus(BASE_URL + "/order/" + Integer.MAX_VALUE, "", HTTPMixIn.HTTP_GET); + Assert.assertEquals(404, status); + + // Get item + status = httpMixIn.sendStringAndGetStatus(BASE_URL + "/warehouse/get/26", "", HTTPMixIn.HTTP_GET); + Assert.assertEquals(404, status); + + // Destroy our inventory + response = httpMixIn.sendString(BASE_URL + "/inventory/remove", "", HTTPMixIn.HTTP_OPTIONS); + Assert.assertEquals(SUCCESS, response); + + // Create our inventory + response = httpMixIn.sendString(BASE_URL + "/inventory/create", "", HTTPMixIn.HTTP_OPTIONS); + Assert.assertEquals(SUCCESS, response); + + // Look at our order + response = httpMixIn.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET); + SwitchYardTestKit.compareXMLToString(response, ORDER4); + + final String namespace = "urn:switchyard-quickstart:resteasy-binding:1.0"; + final ModelNode operation = new ModelNode(); + operation.get(ModelDescriptionConstants.OP_ADDR).add("subsystem", "switchyard"); + operation.get(ModelDescriptionConstants.NAME).set("_OrderService_rest_1"); + operation.get("service-name").set(new QName(namespace, "OrderService").toString()); + operation.get("application-name").set(new QName(namespace, "OrderService").toString()); + + // stop the gateway + operation.get(ModelDescriptionConstants.OP).set("stop-gateway"); + ModelNode result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to stop gateway: " + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + // Update item descriptions in our inventory, should fail + Assert.assertEquals(404, + httpMixIn.sendStringAndGetStatus(BASE_URL + "/inventory/update", "", HTTPMixIn.HTTP_OPTIONS)); + + // restart the gateway + operation.get(ModelDescriptionConstants.OP).set("start-gateway"); + result = client.getControllerClient().execute(operation); + Assert.assertEquals("Failed to restart gateway: " + result.toString(), ModelDescriptionConstants.SUCCESS, + result.get(ModelDescriptionConstants.OUTCOME).asString()); + + // Look at our order. if this fails, the item descriptions were + // updated or the gateway didn't restart. + response = httpMixIn.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET); + SwitchYardTestKit.compareXMLToString(response, ORDER4); + + // Destroy our inventory + response = httpMixIn.sendString(BASE_URL + "/inventory/remove", "", HTTPMixIn.HTTP_OPTIONS); + Assert.assertEquals(SUCCESS, response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String BASE_URL = "http://localhost:8080/rest-binding"; + private static final String SUCCESS = "SUCCESS"; + private static final String ORDER = "" + + " 1" + + ""; + private static final String ORDER1 = "" + + " 1" + + " " + + " " + + " 1" + + " " + + " 10" + + " " + + ""; + private static final String ORDER2 = "" + + " 1" + + " " + + " " + + " 3" + + " " + + " 5" + + " " + + " " + + " " + + " 4" + + " " + + " 3" + + " " + + ""; + private static final String ORDER3 = "" + + " 1" + + " " + + " " + + " 1" + + " Hydrogen Atom - No, we are not kidding!" + + " " + + " 10" + + " " + + " " + + " " + + " 3" + + " Einstein's Bust - Talks about your future :)" + + " " + + " 5" + + " " + + " " + + " " + + " 4" + + " Time Machine" + + " " + + " 3" + + " " + + ""; + private static final String ORDER4 = "" + + " 1" + + " " + + " " + + " 3" + + " Einstein's Bust - Talks about your future :)" + + " " + + " 5" + + " " + + " " + + " " + + " 4" + + " Time Machine" + + " " + + " 3" + + " " + + ""; + private static final String ORDER5 = "" + + " 1" + + " " + + " " + + " 3" + + " Theory of relativity" + + " " + + " 5" + + " " + + " " + + " " + + " 4" + + " Coffee Maker" + + " " + + " 3" + + " " + + ""; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesCamelCBRQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesCamelCBRQuickstartTest.java new file mode 100644 index 000000000..1cd99f08d --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesCamelCBRQuickstartTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +/** + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class RulesCamelCBRQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-rules-camel-cbr"); + } + + @Test + public void testDeployment() { + // Only testing that deployment is successful at this point. + Assert.assertTrue(true); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewContainerQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewContainerQuickstartTest.java new file mode 100644 index 000000000..fb3bdf9b2 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewContainerQuickstartTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +/** + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class RulesInterviewContainerQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-rules-interview-container"); + } + + @Test + public void testVerifyPass() throws Exception { + RulesInterviewQuickstartTest.doTestVerify("rules-interview-container", true); + } + + @Test + public void testVerifyFail() throws Exception { + RulesInterviewQuickstartTest.doTestVerify("rules-interview-container", false); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewDTableQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewDTableQuickstartTest.java new file mode 100644 index 000000000..0a2127864 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewDTableQuickstartTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +/** + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class RulesInterviewDTableQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-rules-interview-dtable"); + } + + @Test + public void testVerifyPass() throws Exception { + RulesInterviewQuickstartTest.doTestVerify("rules-interview-dtable", true); + } + + @Test + public void testVerifyFail() throws Exception { + RulesInterviewQuickstartTest.doTestVerify("rules-interview-dtable", false); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewQuickstartTest.java new file mode 100644 index 000000000..e35fb7a62 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/RulesInterviewQuickstartTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +/** + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class RulesInterviewQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-rules-interview"); + } + + @Test + public void testVerifyPass() throws Exception { + doTestVerify("rules-interview", true); + } + + @Test + public void testVerifyFail() throws Exception { + doTestVerify("rules-interview", false); + } + + static final void doTestVerify(String context, boolean pass) throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String request = getSoapRequest(context, pass); + String response = httpMixIn.postString("http://localhost:8080/" + context + "/Interview", request); + XMLAssert.assertXpathEvaluatesTo(String.valueOf(pass), "//return", response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String getSoapRequest(String context, boolean pass) { + return + "" + + "" + + "" + + "" + + "" + + "" + (pass ? 20 : 16) + "" + + "" + (pass ? "Twenty" : "Sixteen") + "" + + "" + + "" + + "" + + ""; + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapAddressingQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapAddressingQuickstartTest.java new file mode 100644 index 000000000..7849bcf1b --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapAddressingQuickstartTest.java @@ -0,0 +1,109 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; + +import org.custommonkey.xmlunit.XMLUnit; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +/* + * WS-A test. + */ +@RunWith(Arquillian.class) +public class SoapAddressingQuickstartTest { + + private static final String SWITCHYARD_WEB_SERVICE = "http://localhost:8080/soap-addressing/order/OrderService"; + + private HTTPMixIn _httpMixIn = new HTTPMixIn(); + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-soap-addressing"); + } + + @Test + public void addressingError() throws Exception { + _httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String response = _httpMixIn.postString(SWITCHYARD_WEB_SERVICE, REQUEST); + Assert.assertTrue(response.contains("MessageAddressingHeaderRequired")); + Assert.assertTrue(response.contains("A required header representing a Message Addressing Property is not present")); + } finally { + _httpMixIn.uninitialize(); + } + } + + @Test + public void addressingReplyTo() throws Exception { + _httpMixIn.initialize(); + try { + File testFile = new File("/tmp/test.txt"); + if (testFile.exists()) { + testFile.delete(); + } + String response = _httpMixIn.postString(SWITCHYARD_WEB_SERVICE, REQUEST2); + Assert.assertTrue(response.contains("urn:switchyard-quickstart:soap-addressing:1.0:OrderService:orderResponse")); + Assert.assertTrue(response.contains("uuid:3d3fcbbb-fd43-4118-b40e-62577894f39a")); + Assert.assertTrue(response.contains("Thank you for your order. You should hear back from our WarehouseService shortly!")); + // Wait for the actual response from WarehouseService + int timeout = 0; + while (!testFile.exists()) { + Thread.sleep(100); + timeout += 100; + if (timeout == 5000) { + break; + } + } + BufferedReader stream = new BufferedReader(new FileReader(testFile)); + String text = stream.readLine(); + stream.close(); + Assert.assertEquals("Order Boeing with quantity 10 accepted.", text); + } finally { + _httpMixIn.uninitialize(); + } + } + + private static String REQUEST = "" + + " " + + " " + + " Boeing" + + " 10" + + " " + + " " + + ""; + + private static String REQUEST2 = "" + + " " + + " uuid:3d3fcbbb-fd43-4118-b40e-62577894f39a" + + " urn:switchyard-quickstart:soap-addressing:1.0:OrderService:orderRequest" + + " " + + " " + + " " + + " Boeing" + + " 10" + + " " + + " " + + ""; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapAttachmentQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapAttachmentQuickstartTest.java new file mode 100644 index 000000000..ab68ad520 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapAttachmentQuickstartTest.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map; +import java.util.Iterator; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.jws.WebService; +import javax.xml.namespace.QName; +import javax.xml.soap.AttachmentPart; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPBodyElement; +import javax.xml.soap.SOAPConnection; +import javax.xml.soap.SOAPConnectionFactory; +import javax.xml.soap.SOAPConstants; +import javax.xml.soap.SOAPElement; +import javax.xml.soap.SOAPMessage; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +/* + * Huge attachment test without any heap space error. + */ +@RunWith(Arquillian.class) +public class SoapAttachmentQuickstartTest { + + private static final String SWITCHYARD_WEB_SERVICE = "http://localhost:8080/soap-attachment/ImageServiceService"; + + static int size = 13000000; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-soap-attachment"); + } + + @Test + public void imageService() throws Exception { + SOAPMessage response = sendMessage(); + Assert.assertTrue(response.getAttachments().hasNext()); + } + + public SOAPMessage sendMessage() throws Exception { + SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); + + SOAPConnection connection = conFactory.createConnection(); + MessageFactory msgFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage msg = msgFactory.createMessage(); + SOAPBodyElement bodyElement = msg.getSOAPBody().addBodyElement(new QName("urn:switchyard-quickstart:soap-attachment:1.0", "echoImage")); + bodyElement.addTextNode("cid:switchyard.png"); + + // CXF does not set content-type. + msg.getMimeHeaders().addHeader("Content-Type", "multipart/related; type=\"text/xml\"; start=\"\""); + msg.getSOAPPart().setContentId(""); + + AttachmentPart ap = msg.createAttachmentPart(); + ap.setDataHandler(new DataHandler(new StreamDataSource())); + ap.setContentId(""); + msg.addAttachmentPart(ap); + + return connection.call(msg, new URL(SWITCHYARD_WEB_SERVICE)); + } + + private static class StreamDataSource implements DataSource { + + public InputStream getInputStream() throws IOException { + return new InputStream() { + int count; + + @Override + public int read() throws IOException { + if (count < size) { + count++; + return 'M'; + } else { + return -1; + } + } + }; + } + + public OutputStream getOutputStream() throws IOException { + return null; + } + + public String getContentType() { + return "image/png"; + } + + public String getName() { + return "junk"; + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapBindingRpcQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapBindingRpcQuickstartTest.java new file mode 100644 index 000000000..15a228ed3 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapBindingRpcQuickstartTest.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class SoapBindingRpcQuickstartTest { + + private static final String SWITCHYARD_WEB_SERVICE = "http://localhost:8080/soap-binding-rpc/HelloWorldWSService"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-soap-binding-rpc"); + } + + @Test + public void helloWorldService() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String replyMsg = httpMixIn.postString(SWITCHYARD_WEB_SERVICE, REQUEST); + XMLAssert.assertXMLEqual(RESPONSE, replyMsg); + int status = httpMixIn.sendStringAndGetStatus(SWITCHYARD_WEB_SERVICE, REQUEST2, HTTPMixIn.HTTP_POST); + Assert.assertEquals(500, status); + } finally { + httpMixIn.uninitialize(); + } + } + + private static String REQUEST = "" + + " " + + " " + + " SwitchYard" + + " English" + + " " + + " " + + ""; + + private static String REQUEST2 = "" + + " " + + " " + + " 500" + + " English" + + " " + + " " + + ""; + + private static String RESPONSE = "" + + "" + + " " + + " " + + " Hello World Greeting for 'SwitchYard' in English on a Sunday!" + + " " + + " " + + ""; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapMtomQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapMtomQuickstartTest.java new file mode 100644 index 000000000..199fb1ec3 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/SoapMtomQuickstartTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.soap.AttachmentPart; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPBodyElement; +import javax.xml.soap.SOAPConnection; +import javax.xml.soap.SOAPConnectionFactory; +import javax.xml.soap.SOAPConstants; +import javax.xml.soap.SOAPMessage; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.soap.util.SOAPUtil; +import org.switchyard.test.ArquillianUtil; + +/* + * MTOM/XOP test. + */ +@RunWith(Arquillian.class) +public class SoapMtomQuickstartTest { + + private static final String SWITCHYARD_WEB_SERVICE = "http://localhost:8080/soap-mtom/ImageServiceService"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-soap-mtom"); + } + + @Test + public void imageService() throws Exception { + SOAPMessage response = sendMessage(); + XMLAssert.assertXMLEqual(RESPONSE, XMLHelper.toString(response.getSOAPPart().getDocumentElement())); + Assert.assertTrue(response.getAttachments().hasNext()); + AttachmentPart attachment = (AttachmentPart)response.getAttachments().next(); + Assert.assertNotNull(attachment); + Assert.assertEquals("image/jpeg", attachment.getContentType()); + /* this assertion appears to be platform-dependent + Assert.assertEquals(16384, attachment.getSize()); + */ + } + + public SOAPMessage sendMessage() throws Exception { + SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); + + SOAPConnection connection = conFactory.createConnection(); + MessageFactory msgFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage msg = msgFactory.createMessage(); + SOAPBodyElement bodyElement = msg.getSOAPBody().addBodyElement(new QName("urn:switchyard-quickstart:soap-mtom:1.0", "image")); + bodyElement.setTextContent(imageData); + + return connection.call(msg, new URL(SWITCHYARD_WEB_SERVICE)); + } + + private static String imageData = "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwg" + + "JC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyM" + + "jIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAQABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAA" + + "AAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRV" + + "S0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJi" + + "pKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8Q" + + "AHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhc" + + "RMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN" + + "0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6" + + "Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDFs0162zJdeLvEepNFcxW0ywahLFDDKTyrsWLlSeAwC5wcHPTRbxbrd3r" + + "994UfVbiJA8trDdwXEwkRo8hX3b9zcrzk89z1qjDoXi6W5i1nStG1KC8uI83dnc28iLIQRvB3/LsLYwpbdgAjkcJP4" + + "I8S2fjE6yul3osBdi4JaFpZQrNkrtjBLMMkZAxxngVtotjHV77n/9k="; + + private static String RESPONSE = "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformDozerQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformDozerQuickstartTest.java new file mode 100644 index 000000000..6a74a7d85 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformDozerQuickstartTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import javax.xml.namespace.QName; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.quickstarts.transform.dozer.Order; +import org.switchyard.quickstarts.transform.dozer.OrderAck; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; +import org.switchyard.test.ArquillianUtil; + +/** + * switchyard-transform-dozer deployment test + */ +@RunWith(Arquillian.class) +public class TransformDozerQuickstartTest { + + private static final QName SERVICE = new QName( "urn:switchyard-quickstart:transform-dozer:0.1.0", "OrderService"); + private static final String URL = "http://localhost:8080/switchyard-remote"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-transform-dozer"); + } + + @Test + public void testDeployment() throws Exception { + RemoteInvoker invoker = new HttpInvoker(URL); + + // Create request payload + Order order = new Order(); + order.setItem("Turkey"); + order.setQuantity(1); + + // Create the request message + RemoteMessage message = new RemoteMessage(); + message.setService(SERVICE).setOperation("submitOrder").setContent(order); + + // Invoke the service + RemoteMessage reply = invoker.invoke(message); + System.out.println(">>>>> " + reply.getContent().toString()); + OrderAck orderAck = (OrderAck) reply.getContent(); + Assert.assertEquals(true, orderAck.isAccepted()); + Assert.assertEquals("Order Accepted", orderAck.getStatusDescription()); + Assert.assertEquals("PO-19838-XYZ", orderAck.getOrderId()); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformJsonQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformJsonQuickstartTest.java new file mode 100644 index 000000000..b89121cfc --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformJsonQuickstartTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import javax.xml.namespace.QName; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.quickstarts.transform.json.Order; +import org.switchyard.quickstarts.transform.json.OrderAck; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; +import org.switchyard.test.ArquillianUtil; + +/** + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class TransformJsonQuickstartTest { + + private static final QName SERVICE = new QName("urn:switchyard-quickstart:transform-json:0.1.0", "OrderService"); + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-transform-json"); + } + + @Test + public void testDeployment() throws Exception { + String port = System.getProperty("org.switchyard.component.sca.client.port", "8080"); + RemoteInvoker invoker = new HttpInvoker("http://localhost:" + port + "/switchyard-remote"); + + // Create request payload + Order order = new Order(); + order.setItemId("Turkey"); + order.setOrderId("Xmas Dinner"); + order.setQuantity(1); + + // Create the request message + RemoteMessage message = new RemoteMessage(); + message.setService(SERVICE).setOperation("submitOrder").setContent(order); + + // Invoke the service + RemoteMessage reply = invoker.invoke(message); + Assert.assertFalse(reply.isFault()); + OrderAck orderAck = (OrderAck) reply.getContent(); + Assert.assertTrue(orderAck.isAccepted()); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformSmooksQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformSmooksQuickstartTest.java new file mode 100644 index 000000000..f88bba530 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/TransformSmooksQuickstartTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +/** + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class TransformSmooksQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-transform-smooks"); + } + + @Test + public void testDeployment() throws Exception { + HTTPMixIn soapMixIn = new HTTPMixIn(); + soapMixIn.initialize(); + + try { + String port = System.getProperty("org.switchyard.component.soap.client.port", "8080"); + String url = "http://localhost:" + port + "/quickstart-transform-smooks/OrderService"; + String response = soapMixIn.postString(url, XML); + XMLAssert.assertXpathEvaluatesTo("PO-19838-XYZ", "//orderId", response); + XMLAssert.assertXpathEvaluatesTo("true", "//accepted", response); + XMLAssert.assertXpathEvaluatesTo("Order Accepted", "//status", response); + } finally { + soapMixIn.uninitialize(); + } + } + + private static final String XML = "" + + "" + + " " + + " " + + " " + + " PO-19838-XYZ" + + " BUTTER" + + " 200" + + " " + + " " + + ""; + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/ValidateXmlQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/ValidateXmlQuickstartTest.java new file mode 100644 index 000000000..8afdb1816 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/ValidateXmlQuickstartTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +/** + * + * @author Tomohisa Igarashi + */ +@RunWith(Arquillian.class) +public class ValidateXmlQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarQSDeployment("switchyard-validate-xml"); + } + + @Test + public void testOrders() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:8080/quickstart-validate-xml/OrderService", SOAP_REQUEST); + Assert.assertTrue(response.contains("Invalid content was found starting with element 'invalid-element'. No child element is expected at this point.")); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " \n" + + " \n" + + " PO-19838-XYZ\n" + + " BUTTER\n" + + " 200\n" + + " This element is not allowed by XML Schema.\n" + + " \n" + + " \n" + + ""; + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/HelpDeskDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/HelpDeskDemoQuickstartTest.java new file mode 100644 index 000000000..75b10e27b --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/HelpDeskDemoQuickstartTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import junit.framework.Assert; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; + +/** + * The helpdesk demo quickstart test. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@RunWith(Arquillian.class) +public class HelpDeskDemoQuickstartTest { + + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ArquillianUtil.createWarDemoDeployment("switchyard-demo-helpdesk"); + } + + @Test + public void test() throws Exception { + // Only testing that deployment is successful at this point. + Assert.assertTrue(true); + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/LibraryDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/LibraryDemoQuickstartTest.java new file mode 100644 index 000000000..5e73e6103 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/LibraryDemoQuickstartTest.java @@ -0,0 +1,68 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; + +@RunWith(Arquillian.class) +public class LibraryDemoQuickstartTest { + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarDemoDeployment("switchyard-demo-library"); + } + + @Test + public void testProcessOrder() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + suggestion(httpMixIn, 1); + loan(httpMixIn, 2); + loan(httpMixIn, 3); + loan(httpMixIn,4); + loan(httpMixIn, 5); + suggestion(httpMixIn, 6); + loan(httpMixIn, 7); + loan(httpMixIn, 8); + loan(httpMixIn,9); + } finally { + httpMixIn.uninitialize(); + } + } + + private void suggestion(HTTPMixIn httpMixIn, int interaction) throws Exception { + String actual = httpMixIn.postString("http://localhost:8080/suggestion/SuggestionService", xml("request", interaction)); + String expected = xml("response", interaction); + XMLAssert.assertXMLEqual(expected, actual); + } + + private void loan(HTTPMixIn httpMixIn, int interaction) throws Exception { + String actual = httpMixIn.postString("http://localhost:8080/loan/LoanService", xml("request", interaction)); + String expected = xml("response", interaction); + XMLAssert.assertXMLEqual(expected, actual); + } + + private String xml(String direction, int interaction) throws Exception { + return new StringPuller().pull("org/switchyard/test/quickstarts/demo/library/soap-" + direction + "-" + interaction + ".xml", getClass()); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/OrdersDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/OrdersDemoQuickstartTest.java new file mode 100644 index 000000000..d0595503a --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/OrdersDemoQuickstartTest.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.custommonkey.xmlunit.XMLAssert; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.xml.sax.SAXException; + +import java.io.IOException; + +import junit.framework.Assert; + +/** + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + * @author tom.fennelly@gmail.com + */ +@RunWith(Arquillian.class) +public class OrdersDemoQuickstartTest { + + @Deployment(testable = false) + public static WebArchive createDeployment() { + return ArquillianUtil.createWarDemoDeployment("switchyard-demo-orders"); + } + + @Test + public void testOrders() throws Exception { + // Only testing that deployment is successful at this point. The web service + // endpoint is tested as part of the bean-service quickstart + Assert.assertTrue(true); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityBasicDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityBasicDemoQuickstartTest.java new file mode 100644 index 000000000..bef7cd3d4 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityBasicDemoQuickstartTest.java @@ -0,0 +1,114 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.as.arquillian.api.ServerSetup; +import org.jboss.as.arquillian.api.ServerSetupTask; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.codec.Base64; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +/** + * The policy-security-basic demo quickstart test. + * + * @author David Ward <dward@jboss.org> © 2012 Red + * Hat Inc. + */ +@RunWith(Arquillian.class) +@ServerSetup(PolicySecurityBasicDemoQuickstartTest.SSLSocketBindingSetupTask.class) +public class PolicySecurityBasicDemoQuickstartTest { + + private static String SRC_DIR = System.getProperty("jboss.home") + "/quickstarts/demos/policy-security-basic"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarDemoDeployment("switchyard-demo-policy-security-basic"); + } + + @Test + public void testUnsecure() throws Exception { + String response = invokeWorkService("http", 8080, "policy-security-basic", null, null); + Assert.assertTrue(response.toLowerCase().contains("fault")); + } + + @Test + public void testConfidentialSecure() throws Exception { + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(new FileInputStream(new File(SRC_DIR, "connector.jks")), "changeit".toCharArray()); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(keystore); + + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, "changeit".toCharArray()); + + SSLContext sslcontext = SSLContext.getInstance("TLS"); + sslcontext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); + + String response = invokeWorkService("https", 8443, "policy-security-basic", new String[] {"kermit", + "the-frog-1" }, sslcontext); + XMLAssert.assertXpathEvaluatesTo("true", "//received", response); + } + + private String invokeWorkService(String scheme, int port, String context, String[] userPass, SSLContext sslContext) + throws Exception { + String soapRequest = new StringPuller().pull(new File(SRC_DIR, "src/test/resources/xml/soap-request.xml")).replaceAll("WORK_CMD", "CMD-" + System.currentTimeMillis()); + HTTPMixIn http = new HTTPMixIn(sslContext); + if (userPass != null && userPass.length == 2) { + http.setRequestHeader("Authorization", "Basic " + Base64.encodeFromString(userPass[0] + ":" + userPass[1])); + } + http.initialize(); + try { + String endpoint = String.format("%s://localhost:%s/%s/WorkService", scheme, port, context); + return http.postString(endpoint, soapRequest); + } finally { + http.uninitialize(); + } + } + + public static class SSLSocketBindingSetupTask implements ServerSetupTask { + + @Override + public void setup(ManagementClient client, String unused) throws Exception { + ResourceDeployer.setupSSL(client, new File(SRC_DIR, "connector.jks").getAbsolutePath(), "changeit"); + + Thread.sleep(1000); + } + + @Override + public void tearDown(ManagementClient client, String unused) throws Exception { + ResourceDeployer.tearDownSSL(client); + } + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityCertDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityCertDemoQuickstartTest.java new file mode 100644 index 000000000..6e9894886 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityCertDemoQuickstartTest.java @@ -0,0 +1,141 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.as.arquillian.api.ServerSetup; +import org.jboss.as.arquillian.api.ServerSetupTask; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +/** + * The policy-security-cert demo quickstart test. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@RunWith(Arquillian.class) +@ServerSetup(PolicySecurityCertDemoQuickstartTest.SSLSocketBindingSetupTask.class) +public class PolicySecurityCertDemoQuickstartTest { + + private static String SRC_DIR = System.getProperty("jboss.home") + "/quickstarts/demos/policy-security-cert"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarDemoDeployment("switchyard-demo-policy-security-cert"); + } + + @Test + public void testUnsecure() throws Exception { + String response = invokeWorkService("http", 8080, "policy-security-cert", null, null); + Assert.assertTrue(response.toLowerCase().contains("fault")); + } + + @Test + public void testConfidentialSecure() throws Exception { + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(new FileInputStream(new File(SRC_DIR, "connector.jks")), "changeit".toCharArray()); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(keystore); + + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, "changeit".toCharArray()); + + SSLContext sslcontext = SSLContext.getInstance("TLS"); + sslcontext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); + + String response = invokeWorkService("https", 8443, "policy-security-cert", + new StringPuller().pull(new File(SRC_DIR, "src/test/resources/xml/BinarySecurityToken.xml")), sslcontext); + XMLAssert.assertXpathEvaluatesTo("true", "//received", response); + } + + private String invokeWorkService(String scheme, int port, String context, String binarySecurityToken, SSLContext sslContext) throws Exception { + String soapRequest = new StringPuller().pull(new File(SRC_DIR, "src/test/resources/xml/soap-request.xml")) + .replaceAll("WORK_CMD", "CMD-" + System.currentTimeMillis()); + if (binarySecurityToken != null) { + soapRequest = soapRequest.replaceFirst("", binarySecurityToken); + } + HTTPMixIn http = new HTTPMixIn(sslContext); + http.initialize(); + try { + String endpoint = String.format("%s://localhost:%s/%s/WorkService", scheme, port, context); + return http.postString(endpoint, soapRequest); + } finally { + http.uninitialize(); + } + } + + public static class SSLSocketBindingSetupTask implements ServerSetupTask { + + @Override + public void setup(ManagementClient client, String unused) throws Exception { + ResourceDeployer.setupSSL(client, new File(SRC_DIR, "connector.jks").getAbsolutePath(), "changeit"); + + ModelNode op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "policy-security-cert"); + op.get("cache-type").set("default"); + client.getControllerClient().execute(op); + + ModelNode loginModule = new ModelNode(); + loginModule.get("code").set("org.switchyard.security.login.CertificateLoginModule"); + loginModule.get("flag").set("required"); + loginModule.get("module-options").add("keyStoreLocation", + new File(SRC_DIR, "users.jks").getAbsolutePath()); + loginModule.get("module-options").add("keyStorePassword", "changeit"); + loginModule.get("module-options").add("rolesProperties", + new File(SRC_DIR, "roles.properties").getAbsolutePath()); + op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "policy-security-cert"); + op.get("address").add("authentication", "classic"); + op.get("login-modules").add(loginModule); + op.get("operation-headers", "allow-resource-service-restart").set("true"); + client.getControllerClient().execute(op); + + Thread.sleep(1000); + } + + @Override + public void tearDown(ManagementClient client, String unused) throws Exception { + ResourceDeployer.tearDownSSL(client); + + ModelNode op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "policy-security-cert"); + client.getControllerClient().execute(op); + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecuritySamlDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecuritySamlDemoQuickstartTest.java new file mode 100644 index 000000000..b121baff5 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecuritySamlDemoQuickstartTest.java @@ -0,0 +1,195 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; +import java.util.zip.ZipFile; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.as.arquillian.api.ServerSetup; +import org.jboss.as.arquillian.api.ServerSetupTask; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.dmr.ModelNode; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.importer.ZipImporter; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.picketlink.identity.federation.api.wstrust.WSTrustClient; +import org.picketlink.identity.federation.api.wstrust.WSTrustClient.SecurityInfo; +import org.picketlink.identity.federation.core.wstrust.plugins.saml.SAMLUtil; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.quickstarts.util.ResourceDeployer; +import org.w3c.dom.Element; + +/** + * The policy-security-saml demo quickstart test. + * + * @author David Ward <dward@jboss.org> © 2012 Red Hat Inc. + */ +@RunWith(Arquillian.class) +@ServerSetup(PolicySecuritySamlDemoQuickstartTest.SSLSocketBindingSetupTask.class) +public class PolicySecuritySamlDemoQuickstartTest { + + private static String SRC_DIR = System.getProperty("jboss.home") + "/quickstarts/demos/policy-security-saml"; + + @Deployment(testable = false, order = 1, name = "picketlink-sts") + public static WebArchive createPicketlinkSTSWar() throws Exception { + File artifactFile = new File(SRC_DIR, "picketlink-sts.war"); + + if (!artifactFile.isFile()) { + Assert.fail("Failed to resolve artifact '" + + artifactFile + + "'. The artifact must be declared as a dependency in your POM, thereby making it available in your local repository."); + } + + return ShrinkWrap.create(ZipImporter.class, artifactFile.getName()).importFrom(new ZipFile(artifactFile)) + .as(WebArchive.class); + } + + @Deployment(testable = false, order = 2) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarDemoDeployment("switchyard-demo-policy-security-saml"); + } + + @Test + public void testUnsecure() throws Exception { + String response = invokeWorkService("http", 8080, "policy-security-saml", null, null); + Assert.assertTrue(response.toLowerCase().contains("fault")); + } + + @Test + public void testConfidentialSecure() throws Exception { + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(new FileInputStream(new File(SRC_DIR, "connector.jks")), "changeit".toCharArray()); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(keystore); + + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, "changeit".toCharArray()); + + SSLContext sslcontext = SSLContext.getInstance("TLS"); + sslcontext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); + + String response = invokeWorkService("https", 8443, "policy-security-saml", getAssertion(), sslcontext); + XMLAssert.assertXpathEvaluatesTo("true", "//received", response); + } + + private String invokeWorkService(String scheme, int port, String context, Element assertion, SSLContext sslContext) + throws Exception { + String soapRequest = new StringPuller().pull(new File(SRC_DIR, "src/test/resources/xml/soap-request.xml")).replaceAll("WORK_CMD", "CMD-" + System.currentTimeMillis()); + if (assertion != null) { + soapRequest = soapRequest.replaceFirst("", XMLHelper.toString(assertion)); + } + HTTPMixIn http = new HTTPMixIn(sslContext); + http.initialize(); + try { + String endpoint = String.format("%s://localhost:%s/%s/WorkService", scheme, port, context); + return http.postString(endpoint, soapRequest); + } finally { + http.uninitialize(); + } + } + + private Element getAssertion() throws Exception { + WSTrustClient client = new WSTrustClient("PicketLinkSTS", "PicketLinkSTSPort", + "http://localhost:8080/picketlink-sts/PicketLinkSTS", new SecurityInfo("admin", "admin")); + return client.issueToken(SAMLUtil.SAML2_TOKEN_TYPE); + } + + public static class SSLSocketBindingSetupTask implements ServerSetupTask { + + @Override + public void setup(ManagementClient client, String unused) throws Exception { + ResourceDeployer.setupSSL(client, new File(SRC_DIR, "connector.jks").getAbsolutePath(), "changeit"); + + ModelNode op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "picketlink-sts"); + op.get("cache-type").set("default"); + client.getControllerClient().execute(op); + + ModelNode loginModule = new ModelNode(); + loginModule.get("code").set("UsersRoles"); + loginModule.get("flag").set("required"); + loginModule.get("module-options").add("usersProperties", "users.properties"); + loginModule.get("module-options").add("rolesProperties", "roles.properties"); + op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "picketlink-sts"); + op.get("address").add("authentication", "classic"); + op.get("login-modules").add(loginModule); + op.get("operation-headers", "allow-resource-service-restart").set("true"); + client.getControllerClient().execute(op); + + op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "saml-validate-token"); + op.get("cache-type").set("default"); + client.getControllerClient().execute(op); + + loginModule = new ModelNode(); + loginModule.get("code") + .set("org.picketlink.identity.federation.core.wstrust.auth.STSValidatingLoginModule"); + loginModule.get("flag").set("required"); + loginModule.get("module-options").add("configFile", + new File(SRC_DIR, "sts-client.properties").getAbsolutePath()); + loginModule.get("module-options").add("useOptionsCredentials", true); + op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "saml-validate-token"); + op.get("address").add("authentication", "classic"); + op.get("login-modules").add(loginModule); + op.get("operation-headers", "allow-resource-service-restart").set("true"); + client.getControllerClient().execute(op); + + Thread.sleep(1000); + } + + @Override + public void tearDown(ManagementClient client, String unused) throws Exception { + ResourceDeployer.tearDownSSL(client); + + ModelNode op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "picketlink-sts"); + client.getControllerClient().execute(op); + + op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("subsystem", "security"); + op.get("address").add("security-domain", "saml-validate-token"); + client.getControllerClient().execute(op); + } + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityWssSignencryptDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityWssSignencryptDemoQuickstartTest.java new file mode 100644 index 000000000..f7ff5d388 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityWssSignencryptDemoQuickstartTest.java @@ -0,0 +1,127 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.as.arquillian.api.ServerSetup; +import org.jboss.as.arquillian.api.ServerSetupTask; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +/** + * The policy-security-wss-signencrypt demo quickstart test. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@RunWith(Arquillian.class) +@ServerSetup(PolicySecurityWssSignencryptDemoQuickstartTest.SSLSocketBindingSetupTask.class) +public class PolicySecurityWssSignencryptDemoQuickstartTest { + + private static String SRC_DIR = System.getProperty("jboss.home") + "/quickstarts/demos/policy-security-wss-signencrypt"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarDemoDeployment("switchyard-demo-policy-security-wss-signencrypt"); + } + + @Test + public void testUnsecure() throws Exception { + String response = invokeWorkService("http", 8080, "policy-security-wss-signencrypt", false, null); + XMLAssert.assertXpathExists("//faultcode", response); + } + + @Test + public void testConfidential() throws Exception { + String response = invokeWorkService("http", 8080, "policy-security-wss-signencrypt", true, null); + XMLAssert.assertXpathNotExists("//faultcode", response); + } + + @Test + public void testConfidentialSecure() throws Exception { + String response = invokeWorkService("https", 8443, "policy-security-wss-signencrypt", true, setupSSLContext()); + XMLAssert.assertXpathNotExists("//faultcode", response); + } + + @Test + public void testSecure() throws Exception { + String response = invokeWorkService("https", 8443, "policy-security-wss-signencrypt", false, setupSSLContext()); + XMLAssert.assertXpathExists("//faultcode", response); + } + + private SSLContext setupSSLContext() throws Exception { + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(new FileInputStream(new File(SRC_DIR, "connector.jks")), "changeit".toCharArray()); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(keystore); + + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, "changeit".toCharArray()); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); + + return sslContext; + } + + private String invokeWorkService(String scheme, int port, String context, boolean signencrypt, SSLContext sslContext) throws Exception { + String soapRequest; + if (signencrypt) { + soapRequest = new StringPuller().pull(new File(SRC_DIR, "src/test/resources/xml/secure-request.xml")); + } else { + soapRequest = new StringPuller().pull(new File(SRC_DIR, "src/test/resources/xml/insecure-request.xml")) + .replaceAll("WORK_CMD", "CMD-" + System.currentTimeMillis()); + } + HTTPMixIn http = new HTTPMixIn(sslContext); + http.initialize(); + try { + String endpoint = String.format("%s://localhost:%s/%s/WorkService", scheme, port, context); + return http.postString(endpoint, soapRequest); + } finally { + http.uninitialize(); + } + } + + public static class SSLSocketBindingSetupTask implements ServerSetupTask { + + @Override + public void setup(ManagementClient client, String unused) throws Exception { + ResourceDeployer.setupSSL(client, new File(SRC_DIR, "connector.jks").getAbsolutePath(), "changeit"); + + Thread.sleep(1000); + } + + @Override + public void tearDown(ManagementClient client, String unused) throws Exception { + ResourceDeployer.tearDownSSL(client); + } + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityWssUsernameDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityWssUsernameDemoQuickstartTest.java new file mode 100644 index 000000000..62d09de08 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicySecurityWssUsernameDemoQuickstartTest.java @@ -0,0 +1,123 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +import org.custommonkey.xmlunit.XMLAssert; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.as.arquillian.api.ServerSetup; +import org.jboss.as.arquillian.api.ServerSetupTask; +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +/** + * The policy-security-wss-username demo quickstart test. + * + * @author David Ward <dward@jboss.org> © 2013 Red Hat Inc. + */ +@RunWith(Arquillian.class) +@ServerSetup(PolicySecurityWssUsernameDemoQuickstartTest.SSLSocketBindingSetupTask.class) +public class PolicySecurityWssUsernameDemoQuickstartTest { + + private static String SRC_DIR = System.getProperty("jboss.home") + "/quickstarts/demos/policy-security-wss-username"; + + @Deployment(testable = false) + public static JavaArchive createDeployment() { + return ArquillianUtil.createJarDemoDeployment("switchyard-demo-policy-security-wss-username"); + } + + @Test + public void testConfidentialAuthentication() throws Exception { + String response = invokeWorkService("https", 8443, "policy-security-wss-username", "kermit", setupSSLContext()); + XMLAssert.assertXpathEvaluatesTo("true", "//received", response); + } + + @Test + public void testConfidentialAuthenticationFail() throws Exception { + String response = invokeWorkService("https", 8443, "policy-security-wss-username", "misspiggy", setupSSLContext()); + XMLAssert.assertXpathExists("//faultcode", response); + } + + @Test + public void testAuthentication() throws Exception { + String response = invokeWorkService("http", 8080, "policy-security-wss-username", "kermit", null); + XMLAssert.assertXpathExists("//faultcode", response); + } + + @Test + public void testAuthenticationFail() throws Exception { + String response = invokeWorkService("http", 8080, "policy-security-wss-username", "misspiggy", null); + XMLAssert.assertXpathExists("//faultcode", response); + } + + private SSLContext setupSSLContext() throws Exception { + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(new FileInputStream(new File(SRC_DIR, "connector.jks")), "changeit".toCharArray()); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(keystore); + + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, "changeit".toCharArray()); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); + + return sslContext; + } + + private String invokeWorkService(String scheme, int port, String context, String username, SSLContext sslContext) throws Exception { + String soapRequest = new StringPuller().pull(new File(SRC_DIR, "src/test/resources/xml/soap-request.xml")) + .replaceAll("WORK_CMD", "CMD-" + System.currentTimeMillis()); + HTTPMixIn http = new HTTPMixIn(sslContext); + soapRequest = soapRequest.replaceFirst("", username); + http.initialize(); + try { + String endpoint = String.format("%s://localhost:%s/%s/WorkService", scheme, port, context); + return http.postString(endpoint, soapRequest); + } finally { + http.uninitialize(); + } + } + + public static class SSLSocketBindingSetupTask implements ServerSetupTask { + + @Override + public void setup(ManagementClient client, String unused) throws Exception { + ResourceDeployer.setupSSL(client, new File(SRC_DIR, "connector.jks").getAbsolutePath(), "changeit"); + + Thread.sleep(1000); + } + + @Override + public void tearDown(ManagementClient client, String unused) throws Exception { + ResourceDeployer.tearDownSSL(client); + } + } + +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicyTransactionDemoQuickstartTest.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicyTransactionDemoQuickstartTest.java new file mode 100644 index 000000000..cccc6785c --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/demo/PolicyTransactionDemoQuickstartTest.java @@ -0,0 +1,200 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.demo; + +import java.io.IOException; + +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.TextMessage; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.test.ArquillianUtil; +import org.switchyard.component.test.mixins.hornetq.HornetQMixIn; +import org.switchyard.test.quickstarts.util.ResourceDeployer; + +/** + * The policy-transaction demo quickstart test. + */ +@RunWith(Arquillian.class) +public class PolicyTransactionDemoQuickstartTest { + + private static final String QUEUE_IN = "policyQSTransacted"; + private static final String QUEUE_IN_NOTX = "policyQSNonTransacted"; + private static final String QUEUE_OUT_A = "queueA"; + private static final String QUEUE_OUT_B = "queueB"; + private static final String QUEUE_OUT_C = "queueC"; + + private HornetQMixIn _hqMixIn; + + @Deployment(testable = false) + public static JavaArchive createDeployment() throws IOException { + System.out.println(ResourceDeployer.addQueue(QUEUE_IN)); + System.out.println(ResourceDeployer.addQueue(QUEUE_IN_NOTX)); + System.out.println(ResourceDeployer.addQueue(QUEUE_OUT_A)); + System.out.println(ResourceDeployer.addQueue(QUEUE_OUT_B)); + System.out.println(ResourceDeployer.addQueue(QUEUE_OUT_C)); + System.out.println(ResourceDeployer.addPooledConnectionFactory("hornetq-ra-in", true, "java:/JmsXAIn")); + System.out.println(ResourceDeployer.addPooledConnectionFactory("hornetq-ra-out-a", true, "java:/JmsXAOutA")); + System.out.println(ResourceDeployer.addPooledConnectionFactory("hornetq-ra-out-b", true, "java:/JmsXAOutB")); + System.out.println(ResourceDeployer.addPooledConnectionFactory("hornetq-ra-out-c", true, "java:/JmsXAOutC")); + return ArquillianUtil.createJarDemoDeployment("switchyard-demo-policy-transaction"); + } + + @Before + public void before() throws Exception { + _hqMixIn = new HornetQMixIn(false) + .setUser(ResourceDeployer.USER) + .setPassword(ResourceDeployer.PASSWD); + _hqMixIn.initialize(); + cleanupQueues(_hqMixIn); + } + + @After + public void after() throws Exception { + cleanupQueues(_hqMixIn); + _hqMixIn.uninitialize(); + } + + public void cleanupQueues(HornetQMixIn mixin) { + Session session = mixin.createJMSSession(); + try { + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_IN)); + while(consumer.receive(1000) != null) {} + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_A)); + while(consumer.receive(1000) != null) {} + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_B)); + while(consumer.receive(1000) != null) {} + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_C)); + while(consumer.receive(1000) != null) {} + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + session.close(); + } catch (Exception e) { /* ignore */ } + } + } + + @AfterClass + public static void afterClass() throws Exception { + System.out.println(ResourceDeployer.removeQueue(QUEUE_IN)); + System.out.println(ResourceDeployer.removeQueue(QUEUE_IN_NOTX)); + System.out.println(ResourceDeployer.removeQueue(QUEUE_OUT_A)); + System.out.println(ResourceDeployer.removeQueue(QUEUE_OUT_B)); + System.out.println(ResourceDeployer.removeQueue(QUEUE_OUT_C)); + System.out.println(ResourceDeployer.removePooledConnectionFactory("hornetq-ra-in")); + System.out.println(ResourceDeployer.removePooledConnectionFactory("hornetq-ra-out-a")); + System.out.println(ResourceDeployer.removePooledConnectionFactory("hornetq-ra-out-b")); + System.out.println(ResourceDeployer.removePooledConnectionFactory("hornetq-ra-out-c")); + } + + @Test + public void testRollbackA() throws Exception { + String command = "rollback.A"; + + Session session = _hqMixIn.createJMSSession(); + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE_IN)); + Message message = _hqMixIn.createJMSMessage(command); + producer.send(message); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_A)); + TextMessage msg = TextMessage.class.cast(consumer.receive(30000)); + Assert.assertEquals(command, msg.getText()); + Assert.assertNull(consumer.receive(1000)); + + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_B)); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + Assert.assertNull(consumer.receive(1000)); + + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_C)); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + Assert.assertNull(consumer.receive(1000)); + session.close(); + } + + @Test + public void testRollbackB() throws Exception { + String command = "rollback.B"; + + Session session = _hqMixIn.createJMSSession(); + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE_IN)); + Message message = _hqMixIn.createJMSMessage(command); + producer.send(message); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_A)); + TextMessage msg = TextMessage.class.cast(consumer.receive(30000)); + Assert.assertEquals(command, msg.getText()); + Assert.assertNull(consumer.receive(1000)); + + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_B)); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + Assert.assertNull(consumer.receive(1000)); + + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_C)); + msg = TextMessage.class.cast(consumer.receive(10000)); + Assert.assertEquals(command, msg.getText()); + Assert.assertNull(consumer.receive(1000)); + session.close(); + } + + @Test + public void testNonTransacted() throws Exception { + String command = "rollback.A"; + + Session session = _hqMixIn.createJMSSession(); + MessageProducer producer = session.createProducer(HornetQMixIn.getJMSQueue(QUEUE_IN_NOTX)); + Message message = _hqMixIn.createJMSMessage(command); + producer.send(message); + session.close(); + + session = _hqMixIn.createJMSSession(); + MessageConsumer consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_A)); + Assert.assertNull(consumer.receive(1000)); + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_B)); + Assert.assertNull(consumer.receive(1000)); + consumer = session.createConsumer(HornetQMixIn.getJMSQueue(QUEUE_OUT_C)); + Assert.assertNull(consumer.receive(1000)); + session.close(); + } +} diff --git a/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/util/ResourceDeployer.java b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/util/ResourceDeployer.java new file mode 100644 index 000000000..707ee38f3 --- /dev/null +++ b/release/jboss-as7/tests/src/test/java/org/switchyard/test/quickstarts/util/ResourceDeployer.java @@ -0,0 +1,211 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.test.quickstarts.util; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.jboss.as.arquillian.container.ManagementClient; +import org.jboss.as.controller.client.ModelControllerClient; +import org.jboss.dmr.ModelNode; + +/** + * ResouceDeployer is capable to deploy different types of resources + * to a running JBoss AS7 server. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + * @author Daniel Bevenius + * + */ +public class ResourceDeployer { + + public static final String DEFAULT_HOST = "localhost"; + public static final int DEFAULT_PORT = 9999; + public static final String USER = "guest"; + public static final String PASSWD = "Guestp123!"; + + private ResourceDeployer() { + } + + public static ModelNode addQueue(final String host, final int port, final String queueName, final String jndiName) throws IOException { + final ModelControllerClient client = createClient(host, port); + try { + final ModelNode op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "messaging"); + op.get("address").add("hornetq-server", "default"); + op.get("address").add("jms-queue", queueName); + op.get("entries").add(jndiName) + .add("java:jboss/exported/jms/" + jndiName); + op.get("durable").set(false); + + return client.execute(op); + } finally { + client.close(); + } + } + + public static ModelNode addQueue(final String host, final int port, final String queueName) throws IOException { + return addQueue(host, port, queueName, queueName); + } + + public static ModelNode addQueue(final String queueName) throws IOException { + return addQueue(DEFAULT_HOST, DEFAULT_PORT, queueName, queueName); + } + + public static ModelNode addQueue(final String queueName, final String jndiName) throws IOException { + return addQueue(DEFAULT_HOST, DEFAULT_PORT, queueName, jndiName); + } + + public static ModelNode removeQueue(final String host, final int port, final String queueName) throws IOException { + final ModelControllerClient client = createClient(host, port); + try { + final ModelNode op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("subsystem", "messaging"); + op.get("address").add("hornetq-server", "default"); + op.get("address").add("jms-queue", queueName); + return client.execute(op); + } finally { + client.close(); + } + } + + public static ModelNode removeQueue(final String queueName) throws IOException { + return addQueue(DEFAULT_HOST, DEFAULT_PORT, queueName); + } + + public static ModelNode addPooledConnectionFactory(final String host, final int port, final String cfName, final boolean xa, final String jndiName) throws IOException { + final ModelControllerClient client = createClient(host, port); + try { + final ModelNode op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "messaging"); + op.get("address").add("hornetq-server", "default"); + op.get("address").add("pooled-connection-factory", cfName); + op.get("transaction").set(xa ? "xa" : "local"); + op.get("connector").set("in-vm", ""); + op.get("entries").add(jndiName); + return client.execute(op); + } finally { + client.close(); + } + } + + public static ModelNode addPooledConnectionFactory(final String cfName, final boolean xa, final String jndiName) throws IOException { + return addPooledConnectionFactory(DEFAULT_HOST, DEFAULT_PORT, cfName, xa, jndiName); + } + + public static ModelNode removePooledConnectionFactory(final String host, final int port, final String cfName) throws IOException { + final ModelControllerClient client = createClient(host, port); + try { + final ModelNode op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("subsystem", "messaging"); + op.get("address").add("hornetq-server", "default"); + op.get("address").add("pooled-connection-factory", cfName); + return client.execute(op); + } finally { + client.close(); + } + } + + public static ModelNode removePooledConnectionFactory(final String cfName) throws IOException { + return removePooledConnectionFactory(DEFAULT_HOST, DEFAULT_PORT, cfName); + } + + public static void setupSSL(ManagementClient client, String keystorePath, String keystorePassword) throws Exception { + // EAP + ModelNode op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "web"); + op.get("address").add("connector", "https"); + op.get("socket-binding").set("https"); + op.get("scheme").set("https"); + op.get("protocol").set("HTTP/1.1"); + op.get("secure").set("true"); + op.get("enabled").set("true"); + op.get("enable-lookups").set("false"); + op.get("operation-headers", "allow-resource-service-restart").set("true"); + client.getControllerClient().execute(op); + + op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "web"); + op.get("address").add("connector", "https"); + op.get("address").add("ssl", "configuration"); + op.get("name").set("https"); + op.get("password").set(keystorePassword); + op.get("certificate-key-file").set(keystorePath); + op.get("operation-headers", "allow-resource-service-restart").set("true"); + client.getControllerClient().execute(op); + + // WildFly + op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("core-service", "management"); + op.get("address").add("security-realm", "SslRealm"); + client.getControllerClient().execute(op); + + op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("core-service", "management"); + op.get("address").add("security-realm", "SslRealm"); + op.get("address").add("server-identity", "ssl"); + op.get("keystore-password").set(keystorePassword); + op.get("keystore-path").set(keystorePath); + op.get("operation-headers", "allow-resource-service-restart").set("true"); + client.getControllerClient().execute(op); + + op = new ModelNode(); + op.get("operation").set("add"); + op.get("address").add("subsystem", "undertow"); + op.get("address").add("server", "default-server"); + op.get("address").add("https-listener", "default-https"); + op.get("socket-binding").set("https"); + op.get("security-realm").set("SslRealm"); + op.get("operation-headers", "allow-resource-service-restart").set("true"); + client.getControllerClient().execute(op); + } + + public static void tearDownSSL(ManagementClient client) throws Exception { + // EAP + ModelNode op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("subsystem", "web"); + op.get("address").add("connector", "https"); + client.getControllerClient().execute(op); + + // WildFly + op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("subsystem", "undertow"); + op.get("address").add("server", "default-server"); + op.get("address").add("https-listener", "https"); + client.getControllerClient().execute(op); + + op = new ModelNode(); + op.get("operation").set("remove"); + op.get("address").add("core-service", "management"); + op.get("address").add("security-realm", "SslRealm"); + client.getControllerClient().execute(op); + } + + private static ModelControllerClient createClient(final String host, final int port) throws UnknownHostException { + return ModelControllerClient.Factory.create(InetAddress.getByName(host), port); + } + +} diff --git a/release/jboss-as7/tests/src/test/resources/OrderService.wsdl b/release/jboss-as7/tests/src/test/resources/OrderService.wsdl new file mode 100644 index 000000000..fb2291246 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/OrderService.wsdl @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/tests/src/test/resources/application-roles.properties b/release/jboss-as7/tests/src/test/resources/application-roles.properties new file mode 100644 index 000000000..3b67dec93 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/application-roles.properties @@ -0,0 +1,22 @@ +# +# Properties declaration of users roles for the realm 'ApplicationRealm' which is the default realm +# for application services on a new installation. +# +# This includes the following protocols: remote ejb, remote jndi, web, remote jms +# +# Users can be added to this properties file at any time, updates after the server has started +# will be automatically detected. +# +# The format of this file is as follows: - +# +# A utility script is provided which can be executed from the bin folder to add the users: - +# - Linux +# bin/add-user.sh +# +# - Windows +# bin\add-user.bat +# +# The following illustrates how an admin user could be defined. +# +guest=guest +kermit=friend diff --git a/release/jboss-as7/tests/src/test/resources/application-users.properties b/release/jboss-as7/tests/src/test/resources/application-users.properties new file mode 100644 index 000000000..fd1b947ca --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/application-users.properties @@ -0,0 +1,25 @@ +# +# Properties declaration of users for the realm 'ApplicationRealm' which is the default realm +# for application services on a new installation. +# +# This includes the following protocols: remote ejb, remote jndi, web, remote jms +# +# Users can be added to this properties file at any time, updates after the server has started +# will be automatically detected. +# +# The format of this realm is as follows: - +# +# A utility script is provided which can be executed from the bin folder to add the users: - +# - Linux +# bin/add-user.sh +# +# - Windows +# bin\add-user.bat +# The following illustrates how an admin user could be defined, this +# is for illustration only and does not correspond to a usable password. +# +guest=7e6f3cab30beb8eaaa6aed0db5598842 +# +#$REALM_NAME=ApplicationRealm$ This line is used by the add-user utility to identify the realm name already used in this file. +# +kermit=a2fd9c14cb4e8bd101140eee75743542 diff --git a/release/jboss-as7/tests/src/test/resources/cxf.xml b/release/jboss-as7/tests/src/test/resources/cxf.xml new file mode 100644 index 000000000..8b2355a23 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/cxf.xml @@ -0,0 +1,17 @@ + + + + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-app-deployment-structure.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-app-deployment-structure.xml new file mode 100644 index 000000000..e2baf7515 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-app-deployment-structure.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-ironjacamar.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-ironjacamar.xml new file mode 100644 index 000000000..ca1587b00 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-ironjacamar.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-mock-ra.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-mock-ra.xml new file mode 100644 index 000000000..61a696c0b --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/cci-test-mock-ra.xml @@ -0,0 +1,38 @@ + + + + Mock resource adapter + SwitchYard + resource-adapter + 1.0 + + org.switchyard.test.jca.mockra.MockResourceAdapter + + + + org.switchyard.test.jca.mockra.MockManagedConnectionFactory + javax.resource.cci.ConnectionFactory + org.switchyard.test.jca.mockra.MockConnectionFactory + javax.resource.cci.Connection + org.switchyard.test.jca.mockra.MockConnection + + + false + + + + + + javax.resource.cci.MessageListener + + org.switchyard.test.jca.mockra.MockActivationSpec + + someProp + + + + + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-cci-jndi.properties b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-cci-jndi.properties new file mode 100644 index 000000000..326401c96 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-cci-jndi.properties @@ -0,0 +1 @@ +java.naming.factory.initial=org.jboss.as.naming.InitialContextFactory diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-jms-destination-jndi.properties b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-jms-destination-jndi.properties new file mode 100644 index 000000000..326401c96 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-jms-destination-jndi.properties @@ -0,0 +1 @@ +java.naming.factory.initial=org.jboss.as.naming.InitialContextFactory diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-jms-jndi.properties b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-jms-jndi.properties new file mode 100644 index 000000000..326401c96 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/outbound-jms-jndi.properties @@ -0,0 +1 @@ +java.naming.factory.initial=org.jboss.as.naming.InitialContextFactory diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-inbound-cci-test.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-inbound-cci-test.xml new file mode 100644 index 000000000..23c36eddf --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-inbound-cci-test.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + javax.resource.cci.MessageListener + + + + true + + + + + + + + + + + + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-inbound-jms-test.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-inbound-jms-test.xml new file mode 100644 index 000000000..b00887724 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-inbound-jms-test.xml @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + javax.jms.MessageListener + + true + + + + + + + + + + + + + javax.jms.MessageListener + + + + + + + true + + + + + + + + + + + + + javax.jms.MessageListener + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-cci-stream-test.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-cci-stream-test.xml new file mode 100644 index 000000000..675191519 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-cci-stream-test.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + javax.resource.cci.MessageListener + + + + true + + + + +  + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-cci-test.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-cci-test.xml new file mode 100644 index 000000000..36fdfecbc --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-cci-test.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + javax.resource.cci.MessageListener + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-jms-camel-test-route.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-jms-camel-test-route.xml new file mode 100644 index 000000000..9033818e7 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-jms-camel-test-route.xml @@ -0,0 +1,21 @@ + + + + + + jmscorrelation-${in.body} + + + \ No newline at end of file diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-jms-test.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-jms-test.xml new file mode 100644 index 000000000..6114e5910 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/jca/switchyard-outbound-jms-test.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + javax.jms.MessageListener + + true + + + + + + + + + + + + + javax.jms.MessageListener + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-1.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-1.xml new file mode 100644 index 000000000..5874f277a --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-1.xml @@ -0,0 +1,3 @@ + + Zombie + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-2.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-2.xml new file mode 100644 index 000000000..af3ca2956 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-2.xml @@ -0,0 +1,3 @@ + + 978-0-307-35193-7 + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-3.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-3.xml new file mode 100644 index 000000000..af3ca2956 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-3.xml @@ -0,0 +1,3 @@ + + 978-0-307-35193-7 + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-4.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-4.xml new file mode 100644 index 000000000..7a9086141 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-4.xml @@ -0,0 +1,8 @@ +1 + + 1 + + 978-0-307-35193-7 + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-5.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-5.xml new file mode 100644 index 000000000..af3ca2956 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-5.xml @@ -0,0 +1,3 @@ + + 978-0-307-35193-7 + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-6.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-6.xml new file mode 100644 index 000000000..5874f277a --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-6.xml @@ -0,0 +1,3 @@ + + Zombie + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-7.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-7.xml new file mode 100644 index 000000000..c547c239f --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-7.xml @@ -0,0 +1,3 @@ + + 978-1-4000-5-80-2 + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-8.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-8.xml new file mode 100644 index 000000000..156402e7b --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-8.xml @@ -0,0 +1,8 @@ +3 + + 3 + + 978-0-307-35193-7 + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-9.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-9.xml new file mode 100644 index 000000000..23749b87e --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-request-9.xml @@ -0,0 +1,8 @@ +4 + + 4 + + 978-1-4000-5-80-2 + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-1.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-1.xml new file mode 100644 index 000000000..883df89df --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-1.xml @@ -0,0 +1,9 @@ + + + + 978-0-307-35193-7 + World War Z + An Oral History of the Zombie War + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-2.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-2.xml new file mode 100644 index 000000000..909a9e052 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-2.xml @@ -0,0 +1,12 @@ +1 + + 1 + true + Happy reading! Remaining copies: 0 + + 978-0-307-35193-7 + World War Z + An Oral History of the Zombie War + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-3.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-3.xml new file mode 100644 index 000000000..2532f1210 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-3.xml @@ -0,0 +1,7 @@ +2 + + 2 + false + Book has no copies available. + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-4.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-4.xml new file mode 100644 index 000000000..f565d7cf2 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-4.xml @@ -0,0 +1,3 @@ +1 + true + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-5.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-5.xml new file mode 100644 index 000000000..03d64005b --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-5.xml @@ -0,0 +1,12 @@ +3 + + 3 + true + Happy reading! Remaining copies: 0 + + 978-0-307-35193-7 + World War Z + An Oral History of the Zombie War + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-6.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-6.xml new file mode 100644 index 000000000..3dc78d93c --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-6.xml @@ -0,0 +1,9 @@ + + + + 978-1-4000-5-80-2 + The Zombie Survival Guide + Complete Protection from the Living Dead + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-7.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-7.xml new file mode 100644 index 000000000..6292ed484 --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-7.xml @@ -0,0 +1,12 @@ +4 + + 4 + true + Happy reading! Remaining copies: 5 + + 978-1-4000-5-80-2 + The Zombie Survival Guide + Complete Protection from the Living Dead + + + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-8.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-8.xml new file mode 100644 index 000000000..67d8932ea --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-8.xml @@ -0,0 +1,3 @@ +3 + true + diff --git a/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-9.xml b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-9.xml new file mode 100644 index 000000000..4f3e1ffdb --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/org/switchyard/test/quickstarts/demo/library/soap-response-9.xml @@ -0,0 +1,3 @@ +4 + true + diff --git a/release/jboss-as7/tests/src/test/resources/test-ds.xml b/release/jboss-as7/tests/src/test/resources/test-ds.xml new file mode 100644 index 000000000..534f423fa --- /dev/null +++ b/release/jboss-as7/tests/src/test/resources/test-ds.xml @@ -0,0 +1,12 @@ + + + + jdbc:h2:tcp://localhost/h2db;DB_CLOSE_DELAY=-1 + h2 + + + sa + + + + \ No newline at end of file diff --git a/release/jboss-as7/wildfly/bundle/assembly.xml b/release/jboss-as7/wildfly/bundle/assembly.xml new file mode 100644 index 000000000..7d0bb5f18 --- /dev/null +++ b/release/jboss-as7/wildfly/bundle/assembly.xml @@ -0,0 +1,38 @@ + + + + switchyard-wildfly-bundle + false + + zip + + + + + + ${staging.jboss.dir} + ${distro.root.dir} + 644 + 755 + + + xsl + ${distro.root.dir}/xsl + + + + diff --git a/release/jboss-as7/wildfly/bundle/pom.xml b/release/jboss-as7/wildfly/bundle/pom.xml new file mode 100644 index 000000000..655313836 --- /dev/null +++ b/release/jboss-as7/wildfly/bundle/pom.xml @@ -0,0 +1,150 @@ + + + + + org.switchyard + switchyard-wildfly-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-wildfly-bundle + pom + SwitchYard: WildFly Bundle + SwitchYard WildFly Bundle + + ${project.build.directory}/jboss-switchyard + ${staging.dir}/jboss-as-${version.org.jboss.as} + / + ${project.build.directory}${distro.root.dir} + + + + org.switchyard + switchyard-release-distribution + + + + + + maven-dependency-plugin + + + install-as7-bpms-layer + generate-sources + + unpack + + + + + org.kie + kie-eap-distributions-bpms-layer + ${version.org.kie} + zip + + + modules/layers.conf + ${staging.jboss.dir} + + + + install-as7-modules + generate-sources + + unpack + + + + + org.switchyard + switchyard-wildfly-modules + zip + ${project.version} + + + ${staging.jboss.dir} + + + + install-quickstarts + generate-sources + + unpack + + + + + org.switchyard.quickstarts + switchyard-quickstart-distro + zip + ${project.version} + + + demos/webapp-deploy/** + camel-amqp-binding/** + ${staging.jboss.dir}/quickstarts + + + + install-distribution-files + generate-sources + + unpack + + + + + org.switchyard + switchyard-release-distribution + jar + ${project.version} + + + ${staging.jboss.dir} + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + generate-test-resources + + single + + + false + switchyard-wildfly-bundle + + ${basedir}/assembly.xml + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + diff --git a/release/jboss-as7/wildfly/bundle/xsl/domain.xsl b/release/jboss-as7/wildfly/bundle/xsl/domain.xsl new file mode 100644 index 000000000..d18ff691f --- /dev/null +++ b/release/jboss-as7/wildfly/bundle/xsl/domain.xsl @@ -0,0 +1,197 @@ + + + + + + + + + + + + + + + + urn:jboss:domain:switchyard switchyard.xsd + + + + + + + + + + + + + + + + + + + :18001 + + + + + :18001 + + + + + + + + + + + + + + + + + + + + + + + cluster + + + + + + + + + + + + + + + + + + + + + + + + + + + :18001 + + + + + :18001 + + + + + + + + + + + + + + + + + + + + + + switchyard + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + switchyard + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/bundle/xsl/standalone-ha.xsl b/release/jboss-as7/wildfly/bundle/xsl/standalone-ha.xsl new file mode 100644 index 000000000..c1674a878 --- /dev/null +++ b/release/jboss-as7/wildfly/bundle/xsl/standalone-ha.xsl @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + switchyard + + + + diff --git a/release/jboss-as7/wildfly/bundle/xsl/standalone.xsl b/release/jboss-as7/wildfly/bundle/xsl/standalone.xsl new file mode 100644 index 000000000..54637adfa --- /dev/null +++ b/release/jboss-as7/wildfly/bundle/xsl/standalone.xsl @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + urn:jboss:domain:switchyard switchyard.xsd + + + + + + + + + + + + + + + + + + + + + :18001 + + + + + + + + + + + + + + + + + + + + + + + + cluster + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/dist/assembly.xml b/release/jboss-as7/wildfly/dist/assembly.xml new file mode 100644 index 000000000..3d3d3a88e --- /dev/null +++ b/release/jboss-as7/wildfly/dist/assembly.xml @@ -0,0 +1,33 @@ + + SwitchYard + false + + zip + + + + + ${staging.jboss.dir} + + *.txt + standalone/**/standalone*.xml + domain/**/domain*.xml + modules/system/layers/bpms/** + modules/system/layers/soa/** + modules/layers.conf + quickstarts/** + + + quickstarts/demos/webapp-deploy/** + quickstarts/bpel-xts-subordinate-wsba/** + quickstarts/bpel-xts-wsat/** + standalone/configuration/standalone_xml_history/** + + 644 + 755 + ${distro.root.dir} + + + diff --git a/release/jboss-as7/wildfly/dist/pom.xml b/release/jboss-as7/wildfly/dist/pom.xml new file mode 100644 index 000000000..ee20220b5 --- /dev/null +++ b/release/jboss-as7/wildfly/dist/pom.xml @@ -0,0 +1,394 @@ + + + + + org.switchyard + switchyard-wildfly-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-wildfly-dist + jar + SwitchYard: Wildfly Distribution + SwitchYard Wildfly Distribution + + ${project.build.directory}/jboss-switchyard + wildfly-${version.wildfly} + ${staging.dir}/${wildfly.dir} + ${staging.dir}/configs + switchyard-${project.version}-WildFly + / + /switchyard-wildfly-installer-${version.distro} + ${staging.jboss.dir} + ${distro.file}.zip + + + + org.switchyard + switchyard-wildfly-bundle + zip + + + org.wildfly + wildfly-dist + zip + + + org.jboss.arquillian.junit + arquillian-junit-container + test + + + org.jboss.arquillian.container + arquillian-container-test-api + test + + + org.jboss.arquillian.protocol + arquillian-protocol-servlet + test + + + org.jboss.shrinkwrap.descriptors + shrinkwrap-descriptors-impl-javaee + test + + + org.wildfly + wildfly-arquillian-container-managed + test + + + org.wildfly + wildfly-arquillian-common + test + + + + org.jboss.ws.cxf + jbossws-cxf-client + test + + + org.jboss.ws.cxf + jbossws-cxf-factories + test + + + org.jboss.ws.cxf + jbossws-cxf-transports-httpserver + test + + + org.apache.cxf + cxf-rt-core + test + + + org.apache.cxf + cxf-rt-frontend-simple + test + + + org.apache.cxf + cxf-rt-frontend-jaxws + test + + + org.apache.cxf + cxf-rt-bindings-soap + test + + + org.apache.cxf + cxf-rt-bindings-xml + test + + + org.apache.cxf + cxf-rt-databinding-jaxb + test + + + org.apache.camel + camel-hl7 + test + + + org.apache.camel + camel-mina2 + test + + + org.apache.ws.xmlschema + xmlschema-core + test + + + org.picketlink + picketlink-federation + test + + + + + + src/test/resources + true + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + maven-dependency-plugin + + + stage-jboss + generate-sources + + unpack + + + + + org.wildfly + wildfly-dist + zip + + + ${staging.dir} + + + + stage-jboss-configs + generate-sources + + unpack + + + + + org.wildfly + wildfly-dist + zip + true + + + ${wildfly.dir}/standalone/configuration/standalone.xml, ${wildfly.dir}/standalone/configuration/standalone-full.xml, ${wildfly.dir}/standalone/configuration/standalone.xml, ${wildfly.dir}/standalone/configuration/standalone-ha.xml, ${wildfly.dir}/standalone/configuration/standalone.xml, ${wildfly.dir}/standalone/configuration/standalone-full-ha.xml,${wildfly.dir}/domain/configuration/domain.xml + ${staging.configs.dir} + + + + unpack-bundle + generate-sources + + unpack + + + + + org.switchyard + switchyard-wildfly-bundle + zip + ${project.version} + + + ${staging.jboss.dir} + + + + unpack-tests + process-test-classes + + unpack + + + + + org.switchyard + switchyard-as7-tests + test-jar + ${project.version} + + + application-roles.properties, application-users.properties + ${project.build.testOutputDirectory} + + + + unpack-users + process-test-classes + + unpack + + + + + org.switchyard + switchyard-as7-tests + test-jar + ${project.version} + + + application-roles.properties, application-users.properties + ${staging.jboss.dir}/standalone/configuration + + + + + + org.codehaus.mojo + xml-maven-plugin + + + generate-sources + + transform + + + + + true + + + ${staging.configs.dir}/${wildfly.dir}/standalone/configuration + + standalone.xml + standalone-ha.xml + standalone-full-ha.xml + standalone-full.xml + + ${staging.jboss.dir}/standalone/configuration + ${staging.jboss.dir}/xsl/standalone.xsl + + + ${staging.jboss.dir}/standalone/configuration + + standalone-ha.xml + standalone-full-ha.xml + + ${staging.jboss.dir}/standalone/configuration + ${staging.jboss.dir}/xsl/standalone-ha.xsl + + + ${staging.configs.dir}/${wildfly.dir}/domain/configuration + + domain.xml + + ${staging.jboss.dir}/domain/configuration + ${staging.jboss.dir}/xsl/domain.xsl + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + assembly-dist + generate-sources + + single + + + false + ${distro.file} + + ${basedir}/assembly.xml + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + -Xms512m -Xmx512m + always + + ${wildfly.home} + ${project.version} + + + jboss + org.jboss.logmanager.LogManager + ${wildfly.home} + ${wildfly.home}/modules + -Xms256m -Xmx1024m -XX:MaxPermSize=512m + + false + + **/*$* + + + + + + + + default + + + !wildfly.home + + + + ${switchyard.wildfly.home} + + + + manual + + + wildfly.home + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + prepare + process-test-resources + + + + + + + + + run + + + + + + + + + diff --git a/release/jboss-as7/wildfly/dist/src/test/resources/arquillian.xml b/release/jboss-as7/wildfly/dist/src/test/resources/arquillian.xml new file mode 100644 index 000000000..21b42424e --- /dev/null +++ b/release/jboss-as7/wildfly/dist/src/test/resources/arquillian.xml @@ -0,0 +1,17 @@ + + + + + + + + + ../../../../test-classes/standalone-test.xml + + + + \ No newline at end of file diff --git a/release/jboss-as7/wildfly/dist/src/test/resources/standalone-test.xml b/release/jboss-as7/wildfly/dist/src/test/resources/standalone-test.xml new file mode 100644 index 000000000..69b273ad3 --- /dev/null +++ b/release/jboss-as7/wildfly/dist/src/test/resources/standalone-test.xml @@ -0,0 +1,668 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + h2 + + sa + sa + + + + + org.h2.jdbcx.JdbcDataSource + + + + + + + + + false + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + 102400 + 2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jms.queue.DLQ + jms.queue.ExpiryQueue + 0 + 10485760 + 2097152 + PAGE + 10 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + ${jboss.bind.address:127.0.0.1} + + + + + + + + + + + + + + + + + :18001 + + + + + + + :18001 + + + + + + + + + + + + + + + + + + + + + + + + + cluster + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/extension/pom.xml b/release/jboss-as7/wildfly/extension/pom.xml new file mode 100644 index 000000000..98bd5dfcc --- /dev/null +++ b/release/jboss-as7/wildfly/extension/pom.xml @@ -0,0 +1,347 @@ + + + + + org.switchyard + switchyard-wildfly-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-deploy-wildfly + jar + SwitchYard: WildFly Extension + SwitchYard WildFly Extension and Subsystem + + ${project.build.directory}/dependency/jboss-as7/java + ${project.build.directory}/dependency/jboss-as7/resources + + + + org.wildfly + wildfly-web-common + + + org.wildfly + wildfly-undertow + + + org.wildfly + wildfly-weld + + + org.switchyard + switchyard-admin + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-security + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-http + + + org.switchyard.components + switchyard-component-jca + + + org.switchyard.components + switchyard-component-resteasy + + + org.switchyard.components + switchyard-component-sca + + + org.switchyard.components + switchyard-component-soap + + + + log4j + log4j + + + org.apache.camel + camel-core + + + org.apache.cxf + cxf-api + + + org.apache.cxf + cxf-rt-frontend-jaxws + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.cxf + cxf-rt-ws-addr + + + org.apache.cxf + cxf-rt-ws-policy + + + org.apache.cxf + cxf-rt-ws-security + provided + + + org.apache.neethi + neethi + + + org.apache.ws.security + wss4j + provided + + + org.hibernate + hibernate-core + + + org.hibernate + hibernate-entitymanager + + + org.infinispan + infinispan-core + + + org.jboss + jboss-dmr + + + org.wildfly + wildfly-clustering-infinispan + + + org.wildfly + wildfly-controller + + + org.wildfly + wildfly-ee + + + org.wildfly + wildfly-logging + + + org.wildfly + wildfly-naming + + + org.wildfly + wildfly-network + + + org.wildfly + wildfly-server + + + org.wildfly + wildfly-weld + + + org.jboss + jboss-vfs + + + org.jboss + staxmapper + + + org.jboss.com.sun.httpserver + httpserver + + + org.jboss.ironjacamar + ironjacamar-core-api + + + org.jboss.logging + jboss-logging + + + org.jboss.logging + jboss-logging-annotations + + + org.jboss.logging + jboss-logging-processor + + + org.jboss.metadata + jboss-metadata-common + + + org.jboss.metadata + jboss-metadata-ear + + + org.jboss.metadata + jboss-metadata-web + + + org.jboss.modules + jboss-modules + + + org.jboss.msc + jboss-msc + + + org.jboss.resteasy + resteasy-jaxrs + + + org.jboss.ws + jbossws-spi + + + org.jboss.ws.cxf + jbossws-cxf-server + provided + + + org.jboss.ws.cxf + jbossws-cxf-transports-httpserver + provided + + + org.jboss.ws.projects + jaxws-jboss-httpserver-httpspi + + + org.picketbox + picketbox + provided + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + stage-common-sources + generate-sources + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-common-sources-dir + generate-sources + + add-source + + + + ${common.sources.dir} + + + + + add-common-resources-dir + generate-sources + + add-resource + + + + + ${common.resources.dir} + + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/ejb/EntityManagerImpl.java b/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/ejb/EntityManagerImpl.java new file mode 100644 index 000000000..bb3a83cf1 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/ejb/EntityManagerImpl.java @@ -0,0 +1,14 @@ +package org.hibernate.ejb; + +import java.util.Map; +import javax.persistence.PersistenceContextType; +import javax.persistence.SynchronizationType; +import javax.persistence.spi.PersistenceUnitTransactionType; +import org.hibernate.jpa.internal.EntityManagerFactoryImpl; + +public class EntityManagerImpl extends org.hibernate.jpa.internal.EntityManagerImpl { + + public EntityManagerImpl(EntityManagerFactoryImpl entityManagerFactory, PersistenceContextType pcType, SynchronizationType synchronizationType, PersistenceUnitTransactionType transactionType, boolean discardOnClose, Class sessionInterceptorClass, Map properties) { + super(entityManagerFactory, pcType, synchronizationType, transactionType, discardOnClose, sessionInterceptorClass, properties); + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/service/jdbc/connections/spi/ConnectionProvider.java b/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/service/jdbc/connections/spi/ConnectionProvider.java new file mode 100644 index 000000000..a4db9ead2 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/service/jdbc/connections/spi/ConnectionProvider.java @@ -0,0 +1,4 @@ +package org.hibernate.service.jdbc.connections.spi; + +public abstract interface ConnectionProvider extends org.hibernate.engine.jdbc.connections.spi.ConnectionProvider { +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/service/jta/platform/internal/AbstractJtaPlatform.java b/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/service/jta/platform/internal/AbstractJtaPlatform.java new file mode 100644 index 000000000..e4a830785 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/hibernate/service/jta/platform/internal/AbstractJtaPlatform.java @@ -0,0 +1,4 @@ +package org.hibernate.service.jta.platform.internal; + +public abstract class AbstractJtaPlatform extends org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform { +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleAdd.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleAdd.java new file mode 100644 index 000000000..7bbd9a13a --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/SwitchYardModuleAdd.java @@ -0,0 +1,117 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.jboss.as.controller.AbstractAddStepHandler; +import org.jboss.as.controller.OperationContext; +import org.jboss.as.controller.OperationFailedException; +import org.jboss.as.controller.PathAddress; +import org.jboss.as.controller.ServiceVerificationHandler; +import org.jboss.as.controller.descriptions.ModelDescriptionConstants; +import org.jboss.as.controller.registry.Resource; +import org.jboss.as.server.AbstractDeploymentChainStep; +import org.jboss.as.server.DeploymentProcessorTarget; +import org.jboss.as.server.deployment.Phase; +//import org.jboss.as.web.WebSubsystemServices; +import org.jboss.dmr.ModelNode; +import org.jboss.jca.core.spi.rar.ResourceAdapterRepository; +import org.jboss.logging.Logger; +import org.jboss.msc.service.ServiceBuilder; +import org.jboss.msc.service.ServiceController; +import org.jboss.msc.service.ServiceController.Mode; +import org.jboss.msc.service.ServiceName; +import org.switchyard.as7.extension.deployment.SwitchYardModuleDependencyProcessor; +import org.switchyard.as7.extension.services.SwitchYardComponentService; +import org.switchyard.as7.extension.services.SwitchYardInjectorService; +import org.switchyard.deploy.Component; + +/** + * The SwitchYard subsystem's module add update handler. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class SwitchYardModuleAdd extends AbstractAddStepHandler { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + // TODO use ConnectorServices.RA_REPOSITORY_SERVICE instead once JBoss AS is updated to 7.1.1 or later + //private static final ServiceName RA_REPOSITORY_SERVICE_NAME = ConnectorServices.RA_REPOSITORY_SERVICE; + private static final ServiceName RA_REPOSITORY_SERVICE_NAME = ServiceName.JBOSS.append("rarepository"); + + static final SwitchYardModuleAdd INSTANCE = new SwitchYardModuleAdd(); + + /** + * Global component names. + */ + private static List _componentNames = new ArrayList(); + + /** + * Global priority. + */ + public static int _priority = 0x4005; + + private SwitchYardModuleAdd() { + + } + + /** + * Get the list of configured component names. + * + * @return the list of components + */ + public static List getComponentNames() { + return _componentNames; + } + + @Override + protected void populateModel(final ModelNode operation, final Resource resource) { + final ModelNode model = resource.getModel(); + + populateModel(operation, model); + } + + @Override + protected void populateModel(ModelNode operation, ModelNode subModel) { + subModel.get(CommonAttributes.IMPLCLASS).set(operation.get(CommonAttributes.IMPLCLASS)); + if (operation.hasDefined(CommonAttributes.PROPERTIES)) { + subModel.get(CommonAttributes.PROPERTIES).set(operation.get(CommonAttributes.PROPERTIES)); + } + } + + @Override + protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model, + ServiceVerificationHandler verificationHandler, List> newControllers) throws OperationFailedException { + final String moduleId = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.ADDRESS)).getLastElement().getValue(); + _componentNames.add(moduleId); + + context.addStep(new AbstractDeploymentChainStep() { + protected void execute(DeploymentProcessorTarget processorTarget) { + processorTarget.addDeploymentProcessor(SwitchYardExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, _priority++, new SwitchYardModuleDependencyProcessor(moduleId)); + } + }, OperationContext.Stage.RUNTIME); + + final SwitchYardComponentService componentService = new SwitchYardComponentService(moduleId, model); + final ServiceBuilder componentServiceBuilder = context.getServiceTarget().addService(SwitchYardComponentService.SERVICE_NAME.append(moduleId), componentService); + componentServiceBuilder.addDependency(SwitchYardInjectorService.SERVICE_NAME, Map.class, componentService.getInjectedValues()) + .addDependency(RA_REPOSITORY_SERVICE_NAME, ResourceAdapterRepository.class, componentService.getResourceAdapterRepository()); + //componentServiceBuilder.addDependency(WebSubsystemServices.JBOSS_WEB); + componentServiceBuilder.setInitialMode(Mode.ACTIVE); + newControllers.add(componentServiceBuilder.install()); + } + +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/WebResource.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/WebResource.java new file mode 100644 index 000000000..18034ac43 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/WebResource.java @@ -0,0 +1,113 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension; + +import java.util.ArrayList; +import java.util.List; + +import org.jboss.as.web.host.WebDeploymentBuilder; +import org.jboss.as.web.host.WebDeploymentController; +import org.switchyard.component.common.Endpoint; + +/** + * A Web endpoint. + * + * @author Magesh Kumar B (C) 2014 Red Hat Inc. + */ +public class WebResource { + + private WebDeploymentBuilder _deployment; + private WebDeploymentController _handle; + private List _endpoints = new ArrayList(); + private Boolean _started = false; + + /** + * Sets the started boolean. + * @param started Set endpoint started or not + */ + public void setStarted(Boolean started) { + _started = started; + } + + /** + * Sets the deployment associated with this HTTP endpoint. + * @return The WebDeploymentBuilder + */ + public WebDeploymentBuilder getDeployment() { + return _deployment; + } + + /** + * Sets the deployment associated with this HTTP endpoint. + * @param deployment The WebDeploymentBuilder + */ + public void setDeployment(WebDeploymentBuilder deployment) { + _deployment = deployment; + } + + /** + * Sets the handle associated with this HTTP endpoint. + * @return The WebDeploymentController + */ + public WebDeploymentController getHandle() { + return _handle; + } + + /** + * Sets the handle associated with this HTTP endpoint. + * @param handle The WebDeploymentController + */ + public void setHandle(WebDeploymentController handle) { + _handle = handle; + } + + /** + * Starts the web context. + * @param endpoint endpoint + */ + public void start(Endpoint endpoint) { + if (!_started) { + try { + if (_handle != null) { + _handle.create(); + _handle.start(); + } + } catch (Exception e) { + throw ExtensionMessages.MESSAGES.unableToStartContext(_deployment.getContextRoot(), e); + } + _started = true; + } + _endpoints.add(endpoint); + } + + /** + * Stops the web context. + * @param endpoint endpoint + */ + public void stop(Endpoint endpoint) { + _endpoints.remove(endpoint); + if (_endpoints.isEmpty()) { + try { + if (_handle != null) { + _handle.stop(); + _handle.destroy(); + } + } catch (Exception e) { + ExtensionLogger.ROOT_LOGGER.unableToDestroyWebContext(_deployment.getContextRoot(), e); + } + _started = false; + } + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/cluster/RemoteEndpointListener.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/cluster/RemoteEndpointListener.java new file mode 100644 index 000000000..17f302139 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/cluster/RemoteEndpointListener.java @@ -0,0 +1,198 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.cluster; + +import java.io.File; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.jboss.as.network.SocketBinding; +import org.jboss.as.server.ServerEnvironment; +import org.jboss.as.web.host.ServletBuilder; +import org.jboss.as.web.host.WebDeploymentBuilder; +import org.jboss.as.web.host.WebDeploymentController; +import org.jboss.as.web.host.WebHost; +import org.jboss.logging.Logger; +import org.jboss.msc.value.InjectedValue; +import org.switchyard.ServiceDomain; +import org.switchyard.as7.extension.ExtensionLogger; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.util.ServerUtil; +import org.switchyard.component.sca.RemoteEndpointPublisher; +import org.switchyard.component.sca.SwitchYardRemotingServlet; +import org.wildfly.extension.undertow.HttpListenerService; +import org.wildfly.extension.undertow.HttpsListenerService; +import org.wildfly.extension.undertow.ListenerService; + +/** + * Publishes standalone HTTP endpoint. + */ +public class RemoteEndpointListener implements RemoteEndpointPublisher { + + private static final String SERVER_TEMP_DIR = System.getProperty(ServerEnvironment.SERVER_TEMP_DIR); + private static final String SERVLET_NAME = "SwitchYardRemotingServlet"; + + private static Logger _log = Logger.getLogger(RemoteEndpointListener.class); + + private String _contextName; + private WebDeploymentController _handle; + private Map _services = new ConcurrentHashMap(); + private boolean _disableRemoteTransaction = false; + + private boolean _started; + + /** + * Constructor. + */ + public RemoteEndpointListener() { + } + + @Override + public void init(String context) { + _contextName = context; + } + + @Override + public synchronized void start() throws Exception { + // If the remote listener is already started, just return. + if (_started) { + return; + } + + WebHost host = ServerUtil.getDefaultHost(); + WebDeploymentBuilder deployment = new WebDeploymentBuilder(); + ServletBuilder servletBuilder = new ServletBuilder(); + try { + deployment.setContextRoot(_contextName); + File docBase = new File(SERVER_TEMP_DIR, _contextName); + if (!docBase.exists()) { + if (!docBase.mkdirs()) { + throw ExtensionMessages.MESSAGES.unableToCreateTempDirectory(docBase.getPath()); + } + } + deployment.setDocumentRoot(docBase); + deployment.setClassLoader(Thread.currentThread().getContextClassLoader()); + + List urlPatterns = new ArrayList(); + urlPatterns.add("/*"); + servletBuilder.addUrlMappings(urlPatterns); + + servletBuilder.setServletName(SERVLET_NAME); + servletBuilder.setServletClass(SwitchYardRemotingServlet.class); + servletBuilder.setForceInit(true); + + SwitchYardRemotingServlet remotingServlet = new SwitchYardRemotingServlet(); + remotingServlet.setEndpointPublisher(this); + servletBuilder.setServlet(remotingServlet); + deployment.addServlet(servletBuilder); + + _handle = host.addWebDeployment(deployment); + _handle.create(); + _handle.start(); + _started = true; + _log.info("Published Remote Service Endpoint " + _contextName); + } catch (Exception e) { + throw ExtensionMessages.MESSAGES.unableToStartContext(_contextName, e); + } + } + + @Override + public synchronized void stop() throws Exception { + if (_handle != null) { + try { + _handle.stop(); + _handle.destroy(); + _log.info("Destroyed HTTP context " + _contextName); + _started = false; + } catch (Exception e) { + ExtensionLogger.ROOT_LOGGER.unableToDestroyWebContext(_contextName, e); + } + } + } + + /** + * Return the address. + * + * @return An address string + */ + public String getAddress() { + String schema = "http"; + String hostAddress = "127.0.0.1"; + int port = 8080; + + ListenerService listener = ServerUtil.getDefaultListener(); + if (listener != null) { + if (listener instanceof HttpsListenerService) { + schema = "https"; + } else if (listener instanceof HttpListenerService) { + schema = "http"; + } else { + ExtensionLogger.ROOT_LOGGER.defaultListenerIsNotHttpListener(listener.getClass().getName()); + schema = "http"; + } + + InjectedValue inject = listener.getBinding(); + if (inject != null) { + SocketBinding binding = inject.getValue(); + InetAddress address = binding.getAddress(); + hostAddress = address.getHostAddress(); + port = binding.getAbsolutePort(); + }else { + Set aliases = ServerUtil.getDefaultHostAliases(); + if (aliases != null && !aliases.isEmpty()) { + hostAddress = aliases.iterator().next(); + } + ExtensionLogger.ROOT_LOGGER.noSocketBindingDefinitionFound(hostAddress, Integer.toString(port)); + } + } else { + ExtensionLogger.ROOT_LOGGER.noDefaultListenerDefined(schema, hostAddress, Integer.toString(port)); + } + + return schema + "://" + hostAddress + ":" + port + "/" + _contextName; + } + + @Override + public void addService(QName serviceName, ServiceDomain domain) { + _services.put(serviceName, domain); + } + + @Override + public void removeService(QName serviceName, ServiceDomain domain) { + _services.remove(serviceName); + } + + @Override + public ServiceDomain getDomain(QName serviceName) { + return _services.get(serviceName); + } + + @Override + public RemoteEndpointPublisher setDisableRemoteTransaction(boolean disable) { + _disableRemoteTransaction = disable; + return this; + } + + @Override + public boolean isDisableRemoteTransaction() { + return _disableRemoteTransaction; + } + +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardCdiIntegrationProcessor.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardCdiIntegrationProcessor.java new file mode 100644 index 000000000..384c2f81c --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardCdiIntegrationProcessor.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import org.apache.log4j.Logger; +import org.jboss.as.ee.weld.WeldDeploymentMarker; +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.as.weld.deployment.WeldPortableExtensions; +import org.jboss.modules.Module; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; + +/** + * Deployment processor that installs the SwitchYard CDI extension. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardCdiIntegrationProcessor implements DeploymentUnitProcessor { + + private static final String SWITCHYARD_CDI_EXTENSION = "org.switchyard.component.bean.SwitchYardCDIServiceDiscovery"; + private static final String DELTASPIKE_CDI_EXTENSION = "org.apache.deltaspike.core.api.provider.BeanManagerProvider"; + + private static Logger _logger = Logger.getLogger(SwitchYardCdiIntegrationProcessor.class); + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#deploy(org.jboss.as.server.deployment.DeploymentPhaseContext) + */ + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + if (!SwitchYardDeploymentMarker.isSwitchYardDeployment(deploymentUnit)) { + return; + } + + if (WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) { + // Add the Weld portable extension + final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent(); + synchronized (parent) { + checkExtension(SWITCHYARD_CDI_EXTENSION, deploymentUnit, parent); + checkExtension(DELTASPIKE_CDI_EXTENSION, deploymentUnit, parent); + } + } else { + _logger.debug("SwitchYard Application for deployment unit '" + deploymentUnit.getName() + "' does not appear to contain CDI Beans " + + "(no META-INF/beans.xml file in unit). Not attaching SwitchYard CDI Discovery Extension to deployment."); + } + } + + private void checkExtension(final String extensionName, DeploymentUnit deploymentUnit, DeploymentUnit parent) throws DeploymentUnitProcessingException { + final Module module = deploymentUnit.getAttachment(Attachments.MODULE); + Class extensionClass = null; + try { + extensionClass = module.getClassLoader().loadClass(extensionName); + } catch (ClassNotFoundException cnfe) { + throw new DeploymentUnitProcessingException(cnfe); + } + if (extensionClass != null) { + WeldPortableExtensions extensions = WeldPortableExtensions.getPortableExtensions(deploymentUnit); + extensions.tryRegisterExtension(extensionClass, deploymentUnit); + } else { + throw ExtensionMessages.MESSAGES.extensionNotfound(extensionName); + } + } + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#undeploy(org.jboss.as.server.deployment.DeploymentUnit) + */ + @Override + public void undeploy(DeploymentUnit context) { + } + +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeployment.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeployment.java new file mode 100644 index 000000000..fb9097ec5 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeployment.java @@ -0,0 +1,261 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.namespace.QName; + +import org.jboss.as.controller.PathElement; +import org.jboss.as.naming.context.NamespaceContextSelector; +import org.jboss.as.server.deployment.AttachmentKey; +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.dmr.ModelNode; +import org.jboss.modules.Module; +import org.jboss.msc.service.ServiceController; +import org.switchyard.ServiceDomain; +import org.switchyard.admin.Application; +import org.switchyard.admin.base.BaseSwitchYard; +import org.switchyard.as7.extension.SwitchYardExtension; +import org.switchyard.as7.extension.SwitchYardModelConstants; +import org.switchyard.as7.extension.WebResource; +import org.switchyard.as7.extension.admin.ModelNodeCreationUtil; +import org.switchyard.as7.extension.camel.JBossThreadPoolFactory; +import org.switchyard.as7.extension.services.SwitchYardAdminService; +import org.switchyard.common.camel.SwitchYardCamelContext; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.ActivatorLoader; +import org.switchyard.deploy.Component; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.internal.Deployment; + +/** + * Represents a single AS7 deployment containing a SwitchYard application. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardDeployment { + + /** The attachment key. */ + public static final AttachmentKey ATTACHMENT_KEY = AttachmentKey + .create(SwitchYardDeployment.class); + + private static final Map> WEBRESOURCESMAP = new ConcurrentHashMap>(); + + private final DeploymentUnit _deployUnit; + private SwitchYardDeploymentState _deploymentState; + private Deployment _deployment; + private ServiceDomainManager _domainManager; + private ServiceDomain _appServiceDomain; + private NamespaceContextSelector _contextSelector; + + /** + * Add a WebResource. + * + * @param domain The ServiceDomain + * @param resource The WebResource to add + */ + public static final void addResource(ServiceDomain domain, WebResource resource) { + Map resources = WEBRESOURCESMAP.get(domain); + if (resources == null) { + resources = new ConcurrentHashMap(); + } + resources.put(resource.getDeployment().getContextRoot(), resource); + WEBRESOURCESMAP.put(domain, resources); + } + + /** + * Get a WebResource. + * + * @param domain The ServiceDomain + * @param context The contextPath + * @return The WebResource + */ + public static final WebResource getResource(ServiceDomain domain, String context) { + WebResource resource = null; + Map resources = WEBRESOURCESMAP.get(domain); + if (resources != null) { + resource = resources.get(context); + } + return resource; + } + + /** + * Creates a new SwitchYard deployment. + * + * @param deploymentUnit deployment reference + * @param config switchyard configuration + * @param domainManager Service Domain Manager instance. + */ + public SwitchYardDeployment(final DeploymentUnit deploymentUnit, final SwitchYardModel config, ServiceDomainManager domainManager) { + _deployUnit = deploymentUnit; + _deployment = new Deployment(config); + _domainManager = domainManager; + } + + /** + * Create the application. + */ + public void create() { + } + + /** + * Destroy the application. + */ + public void destroy() { + } + + /** + * Set by SwitchYardService before start() is called to allow the namespace + * context to be set for any threads created in the application. + * @param contextSelector NamespaceContextSelector + */ + public void setNamespaceContextSelector(NamespaceContextSelector contextSelector) { + _contextSelector = contextSelector; + } + + /** + * Start the application. + * + * @param components the list of components + */ + public void start(final List components) { + final Module module = _deployUnit.getAttachment(Attachments.MODULE); + ClassLoader origCL = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(module.getClassLoader()); + setDeploymentState(SwitchYardDeploymentState.INITIALIZING); + + _appServiceDomain = _domainManager.createDomain(getName(_deployment.getConfig()), _deployment.getConfig()); + + // Override the default Camel ThreadPoolFactory to allow for naming + // context to be set on any threads created within Camel + SwitchYardCamelContext camelCtx = (SwitchYardCamelContext) + _appServiceDomain.getProperty(SwitchYardCamelContext.CAMEL_CONTEXT_PROPERTY); + camelCtx.getExecutorServiceManager().setThreadPoolFactory( + new JBossThreadPoolFactory(_contextSelector)); + + List activators = ActivatorLoader.createActivators( + _appServiceDomain, components, _deployment.getActivationTypes()); + _deployment.init(_appServiceDomain, activators); + setDeploymentState(SwitchYardDeploymentState.STARTING); + _deployment.start(); + setDeploymentState(SwitchYardDeploymentState.STARTED); + registerManagementNodes(); + } finally { + Thread.currentThread().setContextClassLoader(origCL); + } + } + + /** + * Stop the application. + */ + public void stop() { + ClassLoader origCL = Thread.currentThread().getContextClassLoader(); + try { + final Module module = _deployUnit.getAttachment(Attachments.MODULE); + Thread.currentThread().setContextClassLoader(module.getClassLoader()); + if (_deploymentState == SwitchYardDeploymentState.STARTED) { + _deployment.stop(); + setDeploymentState(SwitchYardDeploymentState.STOPPED); + unregisterManagementNodes(); + } + if (_deploymentState == SwitchYardDeploymentState.STARTING + || _deploymentState == SwitchYardDeploymentState.STOPPED) { + _deployment.destroy(); + setDeploymentState(SwitchYardDeploymentState.DESTROYED); + } + } finally { + Thread.currentThread().setContextClassLoader(origCL); + } + } + + /** + * Set the deployment state. + * + * @param deploymentState the deployment state + */ + public void setDeploymentState(SwitchYardDeploymentState deploymentState) { + this._deploymentState = deploymentState; + } + + /** + * Get the deployment state. + * + * @return DeploymentState + */ + public SwitchYardDeploymentState getDeploymentState() { + return _deploymentState; + } + + /** + * Get the application domain. + * + * @return ServiceDomain + */ + public ServiceDomain getDomain() { + return _appServiceDomain; + } + + private void registerManagementNodes() { + QName applicationName = _deployment.getName(); + if (applicationName == null) { + return; + } + + ServiceController adminService = _deployUnit.getServiceRegistry().getService( + SwitchYardAdminService.SERVICE_NAME); + if (adminService == null) { + return; + } + + BaseSwitchYard switchYard = BaseSwitchYard.class.cast(adminService.getValue()); + if (switchYard == null) { + return; + } + + ModelNode deployNode = _deployUnit.createDeploymentSubModel(SwitchYardExtension.SUBSYSTEM_NAME, + PathElement.pathElement(SwitchYardModelConstants.APPLICATION, applicationName.toString())); + + Application application = switchYard.getApplication(applicationName); + if (application == null) { + return; + } + deployNode.set(ModelNodeCreationUtil.createApplicationNode(application)); + } + + private void unregisterManagementNodes() { + QName applicationName = _deployment.getName(); + if (applicationName == null) { + return; + } + _deployUnit.createDeploymentSubModel(SwitchYardExtension.SUBSYSTEM_NAME, + PathElement.pathElement(SwitchYardModelConstants.APPLICATION, applicationName.toString())).clear(); + } + + private QName getName(SwitchYardModel config) { + if (config == null) { + return null; + } + QName name = config.getQName(); + if (name == null && config.getComposite() != null) { + name = config.getComposite().getQName(); + } + return name; + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentProcessor.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentProcessor.java new file mode 100644 index 000000000..664b8b272 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardDeploymentProcessor.java @@ -0,0 +1,206 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import java.util.HashSet; +import java.util.Set; + +import org.jboss.as.clustering.infinispan.subsystem.CacheService; +import org.jboss.as.connector.util.ConnectorServices; +import org.jboss.as.ee.component.EEModuleDescription; +import org.jboss.as.ee.weld.WeldDeploymentMarker; +import org.jboss.as.naming.context.NamespaceContextSelector; +import org.jboss.as.naming.deployment.JndiNamingDependencyProcessor; +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.as.web.host.WebHost; +import org.jboss.as.weld.WeldStartService; +import org.jboss.as.weld.services.BeanManagerService; +import org.jboss.logging.Logger; +import org.jboss.metadata.ear.spec.EarMetaData; +import org.jboss.modules.Module; +import org.jboss.msc.service.ServiceBuilder; +import org.jboss.msc.service.ServiceBuilder.DependencyType; +import org.jboss.msc.service.ServiceController.Mode; +import org.jboss.msc.service.ServiceName; +import org.jboss.msc.service.ServiceTarget; +import org.jboss.msc.value.ImmediateValue; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; +import org.switchyard.as7.extension.SwitchYardModuleAdd; +import org.switchyard.as7.extension.services.SwitchYardComponentService; +import org.switchyard.as7.extension.services.SwitchYardService; +import org.switchyard.as7.extension.services.SwitchYardServiceDomainManagerService; +import org.switchyard.component.jca.config.model.InboundConnectionModel; +import org.switchyard.component.jca.config.model.JCABindingModel; +import org.switchyard.component.jca.config.model.OutboundConnectionModel; +import org.switchyard.component.jca.config.model.ResourceAdapterModel; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.CompositeModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.deploy.Component; +import org.switchyard.deploy.ServiceDomainManager; + +/** + * Deployment processor that installs the SwitchYard service and all other dependent services. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + */ +public class SwitchYardDeploymentProcessor implements DeploymentUnitProcessor { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + + /** + * Construct SwitchYard deployment processor with a list of component modules. + */ + public SwitchYardDeploymentProcessor() { + } + + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + if (!SwitchYardDeploymentMarker.isSwitchYardDeployment(deploymentUnit)) { + return; + } + final DeploymentUnit parent = deploymentUnit.getParent(); + Boolean initializeInOrder = false; + if (parent != null) { + final EarMetaData earConfig = deploymentUnit.getParent().getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA); + if (earConfig != null) { + initializeInOrder = earConfig.getInitializeInOrder(); + } + } + doDeploy(phaseContext, deploymentUnit, initializeInOrder); + } + + private void doDeploy(DeploymentPhaseContext phaseContext, final DeploymentUnit deploymentUnit, final Boolean initializeInOrder) { + LOG.info("Deploying SwitchYard application '" + deploymentUnit.getName() + "'"); + + ServiceDomainManager domainManager = + (ServiceDomainManager) phaseContext.getServiceRegistry().getRequiredService(SwitchYardServiceDomainManagerService.SERVICE_NAME).getService().getValue(); + + final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); + SwitchYardMetaData metaData = deploymentUnit.getAttachment(SwitchYardMetaData.ATTACHMENT_KEY); + SwitchYardDeployment deployment = new SwitchYardDeployment(deploymentUnit, metaData.getSwitchYardModel(), domainManager); + SwitchYardService container = new SwitchYardService(deployment); + final ServiceName switchyardServiceName = deploymentUnit.getServiceName().append(SwitchYardService.SERVICE_NAME); + final ServiceBuilder switchyardServiceBuilder = serviceTarget.addService(switchyardServiceName, container); + for (String componentName : SwitchYardModuleAdd.getComponentNames()) { + switchyardServiceBuilder.addDependency(SwitchYardComponentService.SERVICE_NAME.append(componentName), Component.class, container.getComponent()); + } + // ensure naming context is fully initialized before we start + switchyardServiceBuilder.addDependency(JndiNamingDependencyProcessor.serviceName(deploymentUnit)); + + final EEModuleDescription moduleDescription = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION); + if (moduleDescription != null) { + container.getNamespaceSelector().setValue(new ImmediateValue(moduleDescription.getNamespaceContextSelector())); + } + + // Only add a dependency on the Weld BeanManager if the deployment has beans (i.e. Weld Metadata)... + if (WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit)) { + final ServiceName beanManagerServiceName = deploymentUnit.getServiceName().append(BeanManagerService.NAME); + switchyardServiceBuilder.addDependency(beanManagerServiceName); + if (deploymentUnit.getParent() == null) { + final ServiceName weldStartServiceName = deploymentUnit.getServiceName().append(WeldStartService.SERVICE_NAME); + switchyardServiceBuilder.addDependency(weldStartServiceName); + } else { + final ServiceName weldStartServiceName = deploymentUnit.getParent().getServiceName().append(WeldStartService.SERVICE_NAME); + switchyardServiceBuilder.addDependency(weldStartServiceName); + } + } + + // Add WebHostService dependency + switchyardServiceBuilder.addDependency(WebHost.SERVICE_NAME.append("default-host")); + + // Collect all the resource adapters referenced from SwitchYard configuration + Set resourceAdapters = new HashSet(); + ClassLoader origCl = Thread.currentThread().getContextClassLoader(); + try { + final Module module = deploymentUnit.getAttachment(Attachments.MODULE); + Thread.currentThread().setContextClassLoader(module.getClassLoader()); + CompositeModel composite = metaData.getSwitchYardModel().getComposite(); + if (composite != null) { + for (CompositeServiceModel service : composite.getServices()) { + for (BindingModel binding : service.getBindings()) { + if (binding instanceof JCABindingModel) { + JCABindingModel jcabinding = JCABindingModel.class.cast(binding); + InboundConnectionModel ic = jcabinding.getInboundConnection(); + if (ic != null) { + ResourceAdapterModel ra = ic.getResourceAdapter(); + if (ra != null && ra.getName() != null && !ra.getName().isEmpty()) { + resourceAdapters.add(ra.getName()); + } + } + } + } + } + for (CompositeReferenceModel reference : composite.getReferences()) { + for (BindingModel binding : reference.getBindings()) { + if (binding instanceof JCABindingModel) { + JCABindingModel jcabinding = JCABindingModel.class.cast(binding); + OutboundConnectionModel oc = jcabinding.getOutboundConnection(); + if (oc != null) { + ResourceAdapterModel ra = oc.getResourceAdapter(); + if (ra != null && ra.getName() != null && !ra.getName().isEmpty()) { + resourceAdapters.add(ra.getName()); + } + } + } + } + } + } else { + LOG.info("A composite element is missing from the switchyard.xml"); + } + } finally { + Thread.currentThread().setContextClassLoader(origCl); + } + for (String raName : resourceAdapters) { + switchyardServiceBuilder.addDependency(ConnectorServices.RESOURCE_ADAPTER_SERVICE_PREFIX + .append(stripDotRarSuffix(raName))); + } + + // Add dependency in the order defined in ear config + if (initializeInOrder) { + final DeploymentUnit parent = deploymentUnit.getParent(); + ServiceName previousServiceName = parent.getAttachment(SwitchYardMetaData.SERVICENAME_ATTACHMENT_KEY); + if (previousServiceName != null) { + switchyardServiceBuilder.addDependency(previousServiceName); + } + parent.putAttachment(SwitchYardMetaData.SERVICENAME_ATTACHMENT_KEY, switchyardServiceName); + } + + switchyardServiceBuilder.addDependency(DependencyType.OPTIONAL, CacheService.getServiceName("cluster", null)); + + switchyardServiceBuilder.setInitialMode(Mode.ACTIVE); + switchyardServiceBuilder.install(); + } + + private String stripDotRarSuffix(final String raName) { + if (raName == null) { + return null; + } + if (raName.endsWith(".rar")) { + return raName.substring(0, raName.indexOf(".rar")); + } + return raName; + } + + @Override + public void undeploy(DeploymentUnit deploymentUnit) { + } + +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardModuleDependencyProcessor.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardModuleDependencyProcessor.java new file mode 100644 index 000000000..8c60be7a4 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/deployment/SwitchYardModuleDependencyProcessor.java @@ -0,0 +1,93 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.as7.extension.deployment; + +import org.jboss.as.ee.weld.WeldDeploymentMarker; +import org.jboss.as.server.deployment.Attachments; +import org.jboss.as.server.deployment.DeploymentPhaseContext; +import org.jboss.as.server.deployment.DeploymentUnit; +import org.jboss.as.server.deployment.DeploymentUnitProcessingException; +import org.jboss.as.server.deployment.DeploymentUnitProcessor; +import org.jboss.as.server.deployment.module.ModuleDependency; +import org.jboss.as.server.deployment.module.ModuleSpecification; +import org.jboss.metadata.ear.spec.EarMetaData; +import org.jboss.modules.Module; +import org.jboss.modules.ModuleIdentifier; +import org.jboss.modules.ModuleLoader; +import org.jboss.modules.filter.PathFilter; +import org.jboss.modules.filter.PathFilters; +import org.switchyard.as7.extension.SwitchYardDeploymentMarker; + +/** + * DU processor which adds a module dependency for modules needed for SwitchYard deployments. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class SwitchYardModuleDependencyProcessor implements DeploymentUnitProcessor { + + private static final PathFilter META_INF_FILTER = PathFilters.isChildOf("META-INF"); + private static final ModuleIdentifier SWITCHYARD_BEAN_ID = ModuleIdentifier.create("org.switchyard.component.bean"); + + private String _moduleId; + + /** + * Construct SwitchYard module dependency processor. + * + * @param moduleId The module identifier + */ + public SwitchYardModuleDependencyProcessor(String moduleId) { + _moduleId = moduleId; + } + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#deploy(org.jboss.as.server.deployment.DeploymentPhaseContext) + */ + @Override + public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { + final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); + ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION); + if (!SwitchYardDeploymentMarker.isSwitchYardDeployment(deploymentUnit)) { + return; + } + + ModuleLoader moduleLoader = Module.getBootModuleLoader(); + ModuleDependency dep = new ModuleDependency(moduleLoader, ModuleIdentifier.fromString(_moduleId), false, false, true, false); + dep.addImportFilter(META_INF_FILTER, true); + moduleSpecification.addSystemDependency(dep); + + if (WeldDeploymentMarker.isPartOfWeldDeployment(deploymentUnit) && (deploymentUnit.getParent() != null)) { + final EarMetaData earConfig = deploymentUnit.getParent().getAttachment(org.jboss.as.ee.structure.Attachments.EAR_METADATA); + if (earConfig != null) { + final ModuleIdentifier beanComponent = deploymentUnit.getParent().getAttachment(SwitchYardMetaData.BEAN_COMPONENT_ATTACHMENT_KEY); + if (beanComponent == null) { + moduleLoader = Module.getBootModuleLoader(); + moduleSpecification = deploymentUnit.getParent().getAttachment(Attachments.MODULE_SPECIFICATION); + dep = new ModuleDependency(moduleLoader, SWITCHYARD_BEAN_ID, false, false, true, false); + dep.addImportFilter(META_INF_FILTER, true); + moduleSpecification.addSystemDependency(dep); + deploymentUnit.getParent().putAttachment(SwitchYardMetaData.BEAN_COMPONENT_ATTACHMENT_KEY, SWITCHYARD_BEAN_ID); + } + } + } + } + + + /* (non-Javadoc) + * @see org.jboss.as.server.deployment.DeploymentUnitProcessor#undeploy(org.jboss.as.server.deployment.DeploymentUnit) + */ + @Override + public void undeploy(DeploymentUnit deploymentUnit) { + } + +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpoint.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpoint.java new file mode 100644 index 000000000..1a48375a0 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpoint.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.http; + +import org.switchyard.as7.extension.WebResource; +import org.switchyard.component.common.Endpoint; + +/** + * A JBossWeb HTTP endpoint. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JBossWebEndpoint implements Endpoint { + + private WebResource _resource; + + /** + * Gets the WebResource associated with this endpoint. + * @return The WebResource + */ + public WebResource getWebResource() { + return _resource; + } + + /** + * Sets the WebResource associated with this endpoint. + * @param resource The resource + */ + public void setWebResource(WebResource resource) { + _resource = resource; + } + + @Override + public void start() { + _resource.start(this); + } + + @Override + public void stop() { + _resource.stop(this); + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpointPublisher.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpointPublisher.java new file mode 100644 index 000000000..6308cadce --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/http/JBossWebEndpointPublisher.java @@ -0,0 +1,98 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.http; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + + +import org.jboss.as.server.ServerEnvironment; +import org.jboss.as.web.host.ServletBuilder; +import org.jboss.as.web.host.WebDeploymentBuilder; +import org.jboss.as.web.host.WebDeploymentController; +import org.jboss.as.web.host.WebHost; +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.WebResource; +import org.switchyard.as7.extension.deployment.SwitchYardDeployment; +import org.switchyard.as7.extension.util.ServerUtil; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.http.InboundHandler; +import org.switchyard.component.http.HttpGatewayServlet; +import org.switchyard.component.http.endpoint.EndpointPublisher; + +/** + * Publishes standalone HTTP endpoint. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JBossWebEndpointPublisher implements EndpointPublisher { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + private static final String SERVER_TEMP_DIR = System.getProperty(ServerEnvironment.SERVER_TEMP_DIR); + private static final String SERVLET_NAME = "HttpGatewayServlet"; + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, String context, InboundHandler handler) throws Exception { + + WebResource resource = SwitchYardDeployment.getResource(domain, context); + if (resource == null) { + WebHost host = ServerUtil.getDefaultHost(); + WebDeploymentBuilder deployment = new WebDeploymentBuilder(); + WebDeploymentController handle = null; + ServletBuilder servletBuilder = new ServletBuilder(); + try { + deployment.setContextRoot(context); + File docBase = new File(SERVER_TEMP_DIR, context); + if (!docBase.exists()) { + if (!docBase.mkdirs()) { + throw ExtensionMessages.MESSAGES.unableToCreateTempDirectory(docBase.getPath()); + } + } + deployment.setDocumentRoot(docBase); + deployment.setClassLoader(Thread.currentThread().getContextClassLoader()); + + List urlPatterns = new ArrayList(); + urlPatterns.add("/*"); + servletBuilder.addUrlMappings(urlPatterns); + + HttpGatewayServlet servlet = new HttpGatewayServlet(); + servlet.setHandler(handler); + servletBuilder.setServletName(SERVLET_NAME); + servletBuilder.setServletClass(HttpGatewayServlet.class); + servletBuilder.setForceInit(true); + servletBuilder.setServlet(servlet); + deployment.addServlet(servletBuilder); + + handle = host.addWebDeployment(deployment); + } catch (Exception e) { + throw ExtensionMessages.MESSAGES.unableToStartContext(context, e); + } + resource = new WebResource(); + resource.setHandle(handle); + resource.setDeployment(deployment); + SwitchYardDeployment.addResource(domain, resource); + } else if ((resource.getDeployment() != null) && !(resource.getDeployment().getServlets().get(0).getServlet() instanceof HttpGatewayServlet)) { + throw ExtensionMessages.MESSAGES.contextAlreadyExists(context); + } + JBossWebEndpoint endpoint = new JBossWebEndpoint(); + endpoint.setWebResource(resource); + return endpoint; + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResource.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResource.java new file mode 100644 index 000000000..dae2b31e2 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResource.java @@ -0,0 +1,76 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.resteasy; + +import java.util.ArrayList; +import java.util.List; + +import org.switchyard.as7.extension.WebResource; +import org.switchyard.component.common.Endpoint; + +/** + * A standalone RESTEasy resource. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyResource implements Endpoint { + + private List _instances = new ArrayList(); + private WebResource _resource; + + /** + * Gets the list of instances associated with this resource deployment. + * @return The List of instances + */ + public List getInstances() { + return _instances; + } + + /** + * Sets the list of instances associated with this resource deployment. + * @param instances The List of instances + */ + public void setInstances(List instances) { + _instances = instances; + } + + /** + * Gets the WebResource associated with this resource deployment. + * @return The WebResource + */ + public WebResource getWebResource() { + return _resource; + } + + /** + * Sets the WebResource associated with this resource deployment. + * @param resource The resource + */ + public void setWebResource(WebResource resource) { + _resource = resource; + } + + @Override + public void start() { + _resource.start(this); + ((RESTEasyServlet)_resource.getDeployment().getServlets().get(0).getServlet()).addInstances(getInstances()); + } + + @Override + public void stop() { + ((RESTEasyServlet)_resource.getDeployment().getServlets().get(0).getServlet()).removeInstances(getInstances()); + _resource.stop(this); + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResourcePublisher.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResourcePublisher.java new file mode 100644 index 000000000..3b6c7b004 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyResourcePublisher.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.resteasy; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.jboss.as.server.ServerEnvironment; +import org.jboss.as.web.host.ServletBuilder; +import org.jboss.as.web.host.WebDeploymentBuilder; +import org.jboss.as.web.host.WebDeploymentController; +import org.jboss.as.web.host.WebHost; +import org.jboss.logging.Logger; +import org.switchyard.ServiceDomain; +import org.switchyard.as7.extension.ExtensionMessages; +import org.switchyard.as7.extension.WebResource; +import org.switchyard.as7.extension.deployment.SwitchYardDeployment; +import org.switchyard.as7.extension.util.ServerUtil; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.resteasy.resource.ResourcePublisher; + +/** + * Creates a RESTEasy resource on WildFly. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class RESTEasyResourcePublisher implements ResourcePublisher { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + private static final String SERVER_TEMP_DIR = System.getProperty(ServerEnvironment.SERVER_TEMP_DIR); + private static final String SERVLET_NAME = "RestEasy"; + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, String context, List instances, Map contextParams) throws Exception { + WebResource resource = SwitchYardDeployment.getResource(domain, context); + if (resource == null) { + WebHost host = ServerUtil.getDefaultHost(); + WebDeploymentBuilder deployment = new WebDeploymentBuilder(); + WebDeploymentController handle = null; + ServletBuilder servletBuilder = new ServletBuilder(); + try { + deployment.setContextRoot(context); + File docBase = new File(SERVER_TEMP_DIR, context); + if (!docBase.exists()) { + if (!docBase.mkdirs()) { + throw ExtensionMessages.MESSAGES.unableToCreateTempDirectory(docBase.getPath()); + } + } + deployment.setDocumentRoot(docBase); + deployment.setClassLoader(Thread.currentThread().getContextClassLoader()); + + List urlPatterns = new ArrayList(); + urlPatterns.add("/*"); + servletBuilder.addUrlMappings(urlPatterns); + + RESTEasyServlet servlet = new RESTEasyServlet(); + servletBuilder.setServletName(SERVLET_NAME); + servletBuilder.setServletClass(RESTEasyServlet.class); + servletBuilder.setForceInit(true); + servletBuilder.addInitParam("resteasy.servlet.context.deployment", "true"); + if (contextParams != null) { + for (Map.Entry cp : contextParams.entrySet()) { + servletBuilder.addInitParam(cp.getKey(), cp.getValue()); + } + } + servletBuilder.setServlet(servlet); + deployment.addServlet(servletBuilder); + + handle = host.addWebDeployment(deployment); + } catch (Exception e) { + throw ExtensionMessages.MESSAGES.unableToStartContext(context, e); + } + resource = new WebResource(); + resource.setHandle(handle); + resource.setDeployment(deployment); + SwitchYardDeployment.addResource(domain, resource); + } else if ((resource.getDeployment() != null) && !(resource.getDeployment().getServlets().get(0).getServlet() instanceof RESTEasyServlet)) { + throw ExtensionMessages.MESSAGES.contextAlreadyExists(context); + } + RESTEasyResource endpoint = new RESTEasyResource(); + endpoint.setInstances(instances); + endpoint.setWebResource(resource); + return endpoint; + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyServlet.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyServlet.java new file mode 100644 index 000000000..2eec0ab49 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyServlet.java @@ -0,0 +1,84 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.resteasy; + +import java.io.IOException; +import java.util.List; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.jboss.logging.Logger; +import org.jboss.resteasy.spi.Registry; +import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher; + +/** + * A RESTEasy servlet dispatcher. + * + * @author Magesh Kumar B (C) 2014 Red Hat Inc. + */ +public class RESTEasyServlet extends HttpServletDispatcher { + + private static final Logger LOG = Logger.getLogger("org.switchyard"); + private Registry _registry; + + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + ServletContext servletContext = servletConfig.getServletContext(); + _registry = (Registry)servletContext.getAttribute(Registry.class.getName()); + } + + @Override + public void destroy() { + //_deployment.stop(); + } + + @Override + protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { + super.service(new RESTEasyServletRequest(httpServletRequest), httpServletResponse); + } + + /** + * Register instances associated with this resource deployment. + * @param instances The List of instances + */ + public void addInstances(List instances) { + // Add as singleton instance + for (Object instance : instances) { + _registry.addSingletonResource(instance); + if (LOG.isTraceEnabled()) { + LOG.trace("Registering instance of " + instance.getClass()); + } + } + } + + /** + * Unregister instances associated with this resource deployment. + * @param instances The List of instances + */ + public void removeInstances(List instances) { + // Add as singleton instance + for (Object instance : instances) { + _registry.removeRegistrations(instance.getClass()); + if (LOG.isTraceEnabled()) { + LOG.trace("Unregistering instance of " + instance.getClass()); + } + } + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyServletRequest.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyServletRequest.java new file mode 100644 index 000000000..d08579240 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/resteasy/RESTEasyServletRequest.java @@ -0,0 +1,406 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.resteasy; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.AsyncContext; +import javax.servlet.DispatcherType; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpUpgradeHandler; +import javax.servlet.http.Part; + +/** + * A RESTEasy servlet request wrapper to fix contextPath. + * + * @author Magesh Kumar B (C) 2014 Red Hat Inc. + */ +public class RESTEasyServletRequest implements HttpServletRequest { + + private HttpServletRequest _wrapper; + + /** + * Constructor. + * @param wrapper the request to be wrapped + */ + public RESTEasyServletRequest(HttpServletRequest wrapper) { + _wrapper = wrapper; + } + + @Override + public String getHeader(final String name) { + return _wrapper.getHeader(name); + } + + @Override + public Enumeration getHeaderNames() { + return _wrapper.getHeaderNames(); + } + + @Override + public String getMethod() { + return _wrapper.getMethod(); + } + + @Override + public String getPathInfo() { + return _wrapper.getPathInfo(); + } + + @Override + public String getQueryString() { + return _wrapper.getQueryString(); + } + + @Override + public String getRequestURI() { + return _wrapper.getRequestURI(); + } + + @Override + public String getContextPath() { + String contextPath = _wrapper.getContextPath(); + if (contextPath != null && !contextPath.equals("") && !contextPath.startsWith("/")) { + contextPath = "/" + contextPath; + } + return contextPath; + } + + @Override + public HttpSession getSession(boolean arg0) { + return _wrapper.getSession(arg0); + } + + @Override + public String getContentType() { + return _wrapper.getContentType(); + } + + @Override + public ServletInputStream getInputStream() throws IOException { + return _wrapper.getInputStream(); + } + + @Override + public String getParameter(final String name) { + return _wrapper.getParameter(name); + } + + @Override + public Principal getUserPrincipal() { + return _wrapper.getUserPrincipal(); + } + + @Override + public boolean isUserInRole(final String name) { + return _wrapper.isUserInRole(name); + } + + @Override + public String getAuthType() { + return _wrapper.getAuthType(); + } + + @Override + public Cookie[] getCookies() { + return _wrapper.getCookies(); + } + + @Override + public long getDateHeader(String name) { + return _wrapper.getDateHeader(name); + } + + @Override + public Enumeration getHeaders(final String name) { + return _wrapper.getHeaders(name); + } + + @Override + public int getIntHeader(String name) { + return _wrapper.getIntHeader(name); + } + + @Override + public StringBuffer getRequestURL() { + return _wrapper.getRequestURL(); + } + + @Override + public String getPathTranslated() { + return _wrapper.getPathTranslated(); + } + + @Override + public String getRemoteUser() { + return _wrapper.getRemoteUser(); + } + + @Override + public String getRequestedSessionId() { + return _wrapper.getRequestedSessionId(); + } + + @Override + public String getServletPath() { + return _wrapper.getServletPath(); + } + + @Override + public HttpSession getSession() { + return _wrapper.getSession(); + } + + @Override + public boolean isRequestedSessionIdFromCookie() { + return _wrapper.isRequestedSessionIdFromCookie(); + } + + @Override + public boolean isRequestedSessionIdFromURL() { + return _wrapper.isRequestedSessionIdFromURL(); + } + + @Override + public boolean isRequestedSessionIdFromUrl() { + return _wrapper.isRequestedSessionIdFromUrl(); + } + + @Override + public boolean isRequestedSessionIdValid() { + return _wrapper.isRequestedSessionIdValid(); + } + + @Override + public Enumeration getAttributeNames() { + return _wrapper.getAttributeNames(); + } + + @Override + public String getCharacterEncoding() { + return _wrapper.getCharacterEncoding(); + } + + @Override + public int getContentLength() { + return _wrapper.getContentLength(); + } + + @Override + public Locale getLocale() { + return _wrapper.getLocale(); + } + + @Override + public Enumeration getLocales() { + return _wrapper.getLocales(); + } + + @Override + public Map getParameterMap() { + return _wrapper.getParameterMap(); + } + + @Override + public Enumeration getParameterNames() { + return _wrapper.getParameterNames(); + } + + @Override + public String[] getParameterValues(String arg0) { + return _wrapper.getParameterValues(arg0); + } + + @Override + public String getProtocol() { + return _wrapper.getProtocol(); + } + + @Override + public BufferedReader getReader() throws IOException { + return _wrapper.getReader(); + } + + @Override + public String getRealPath(String arg0) { + return _wrapper.getRealPath(arg0); + } + + @Override + public String getRemoteAddr() { + return _wrapper.getRemoteAddr(); + } + + @Override + public String getRemoteHost() { + return _wrapper.getRemoteHost(); + } + + @Override + public long getContentLengthLong() { + return _wrapper.getContentLengthLong(); + } + + @Override + public ServletContext getServletContext() { + return _wrapper.getServletContext(); + } + + @Override + public AsyncContext startAsync() throws IllegalStateException { + return _wrapper.startAsync(); + } + + @Override + public AsyncContext startAsync(final ServletRequest servletRequest, final ServletResponse servletResponse) throws IllegalStateException { + return _wrapper.startAsync(servletRequest, servletResponse); + } + + @Override + public boolean isAsyncStarted() { + return _wrapper.isAsyncStarted(); + } + + @Override + public boolean isAsyncSupported() { + return _wrapper.isAsyncSupported(); + } + + @Override + public AsyncContext getAsyncContext() { + return _wrapper.getAsyncContext(); + } + + @Override + public RequestDispatcher getRequestDispatcher(String arg0) { + return _wrapper.getRequestDispatcher(arg0); + } + + @Override + public String getScheme() { + return _wrapper.getScheme(); + } + + @Override + public String getServerName() { + return _wrapper.getServerName(); + } + + @Override + public int getServerPort() { + return _wrapper.getServerPort(); + } + + @Override + public boolean isSecure() { + return _wrapper.isSecure(); + } + + @Override + public void removeAttribute(String arg0) { + _wrapper.removeAttribute(arg0); + } + + @Override + public void setAttribute(String arg0, Object arg1) { + _wrapper.setAttribute(arg0, arg1); + } + + @Override + public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { + _wrapper.setCharacterEncoding(arg0); + } + + @Override + public Object getAttribute(String arg0) { + return _wrapper.getAttribute(arg0); + } + + @Override + public String getLocalAddr() { + return _wrapper.getLocalAddr(); + } + + @Override + public String getLocalName() { + return _wrapper.getLocalName(); + } + + @Override + public int getLocalPort() { + return _wrapper.getLocalPort(); + } + + @Override + public int getRemotePort() { + return _wrapper.getRemotePort(); + } + + @Override + public String changeSessionId() { + return _wrapper.changeSessionId(); + } + + @Override + public DispatcherType getDispatcherType() { + return _wrapper.getDispatcherType(); + } + + @Override + public boolean authenticate(final HttpServletResponse response) throws IOException, ServletException { + return _wrapper.authenticate(response); + } + + @Override + public void login(final String username, final String password) throws ServletException { + _wrapper.login(username, password); + } + + @Override + public void logout() throws ServletException { + _wrapper.logout(); + } + + @Override + public Collection getParts() throws IOException, ServletException { + return _wrapper.getParts(); + } + + @Override + public Part getPart(final String name) throws IOException, ServletException { + return _wrapper.getPart(name); + } + + @Override + public T upgrade(final Class handlerClass) throws IOException, ServletException { + return _wrapper.upgrade(handlerClass); + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/util/ServerUtil.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/util/ServerUtil.java new file mode 100644 index 000000000..9bdd85fd5 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/util/ServerUtil.java @@ -0,0 +1,119 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.util; + +import java.util.Set; + +import org.jboss.as.server.deployment.AttachmentKey; +import org.jboss.as.web.host.WebHost; +import org.jboss.metadata.web.jboss.JBossWebMetaData; +import org.jboss.msc.service.ServiceController; +import org.jboss.msc.service.ServiceRegistry; +import org.wildfly.extension.undertow.Host; +import org.wildfly.extension.undertow.ListenerService; +import org.wildfly.extension.undertow.Server; +import org.wildfly.extension.undertow.UndertowService; + +/** + * Utility class for AS7 related functions. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public final class ServerUtil { + + /** + * The attachment key for web.xml. + */ + public static final AttachmentKey JBOSSWEB_METADATA_KEY = AttachmentKey.create(JBossWebMetaData.class); + + private static ServiceRegistry _registry; + private static String _host = "default-host"; + private static String _server = "default-server"; + private static String _listener = "default"; + + private ServerUtil() { + } + + /** + * Set the JBoss container's Service Registry. + * @param registry the ServiceRegistry + */ + public static void setRegistry(ServiceRegistry registry) { + _registry = registry; + } + + /** + * Get the JBoss container's Service Registry. + * @return the ServiceRegistry + */ + public static ServiceRegistry getRegistry() { + return _registry; + } + + /** + * Set the JBoss container's Host Name. + * @param host the name of the host + */ + public static void setHostName(String host) { + _host = host; + } + + /** + * Get the JBoss container's Host Name. + * @return the name of the host + */ + public static String getHostName() { + return _host; + } + + /** + * Get the JBoss container's WebHost. + * @return the WebHost + */ + public static WebHost getDefaultHost() { + ServiceController service = (ServiceController)_registry.getService(WebHost.SERVICE_NAME.append(_host)); + return service != null ? service.getValue() : null; + } + + /** + * Get the JBoss container's DefaultConnector. + * @return the DefaultConnector + */ + public static ListenerService getDefaultListener() { + ServiceController service = (ServiceController)_registry.getService(UndertowService.SERVER.append(_server)); + if (service != null) { + Server server = service.getValue(); + for (ListenerService listener : server.getListeners()) { + if (listener.getName().equals(_listener)) { + return listener; + } + } + } + return null; + } + + public static Set getDefaultHostAliases() { + ServiceController service = (ServiceController)_registry.getService(UndertowService.SERVER.append(_server)); + if (service != null) { + Server server = service.getValue(); + for(Host host : server.getHosts()) { + if (host.getName().equals(server.getDefaultHost())) { + return host.getAllAliases(); + } + } + } + return null; + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpoint.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpoint.java new file mode 100644 index 000000000..4bd4ebc31 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpoint.java @@ -0,0 +1,192 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.ws; + +import java.net.URL; +import java.util.Map; +import java.util.ServiceLoader; + +import javax.xml.ws.WebServiceException; + +import org.jboss.as.security.plugins.SecurityDomainContext; +import org.jboss.as.webservices.security.SecurityDomainContextAdaptor; +import org.jboss.logging.Logger; +import org.jboss.as.web.host.ServletBuilder; +import org.jboss.as.web.host.WebDeploymentBuilder; +import org.jboss.as.web.host.WebDeploymentController; +import org.jboss.wsf.spi.classloading.ClassLoaderProvider; +import org.jboss.wsf.spi.deployment.WSFServlet; +import org.jboss.wsf.spi.metadata.webservices.JBossWebservicesFactory; +import org.jboss.wsf.spi.metadata.webservices.JBossWebservicesMetaData; +import org.jboss.wsf.spi.metadata.webservices.WebservicesMetaData; +import org.jboss.wsf.spi.publish.Context; +import org.jboss.wsf.spi.publish.EndpointPublisher; +import org.jboss.wsf.spi.publish.EndpointPublisherFactory; +import org.switchyard.ServiceDomain; +import org.switchyard.as7.extension.WebResource; +import org.switchyard.as7.extension.deployment.SwitchYardDeployment; +import org.switchyard.common.type.Classes; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.WebServicePublishException; +import org.switchyard.component.soap.config.model.EndpointConfigModel; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.endpoint.BaseWebService; + +/** + * Wrapper for JBossWS endpoints. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JBossWSEndpoint implements Endpoint { + + private static final Logger LOGGER = Logger.getLogger("org.switchyard"); + + private static final String HOST = "default-host"; + private static final EndpointPublisherFactory FACTORY; + + private EndpointPublisher _publisher; + private Context _context; + + private WebResource _resource; + + /** + * Construct a JBossWS endpoint on default host. + * @throws Exception If a publisher could not be created + */ + public JBossWSEndpoint() throws Exception { + _publisher = FACTORY.newEndpointPublisher(HOST); + } + + /** + * Construct a JBossWS endpoint on specified host. + * @param host The host on which the pubhlisher should created + * @throws Exception if a publisher could not be created + */ + public JBossWSEndpoint(String host) throws Exception { + _publisher = FACTORY.newEndpointPublisher(host); + } + + /** + * {@inheritDoc} + */ + public void publish(ServiceDomain domain, String contextRoot, Map urlPatternToClassNameMap, WebservicesMetaData wsMetadata, SOAPBindingModel bindingModel, InboundHandler handler) throws Exception { + EndpointConfigModel epcModel = bindingModel.getEndpointConfig(); + JBossWebservicesMetaData jbwsMetadata = null; + if (epcModel != null) { + String configFile = epcModel.getConfigFile(); + if (configFile != null) { + URL jbwsURL = Classes.getResource(configFile, getClass()); + try { + JBossWebservicesFactory factory = new JBossWebservicesFactory(jbwsURL); + jbwsMetadata = factory.load(jbwsURL); + } catch (WebServiceException e) { + if (LOGGER.isDebugEnabled()) { + LOGGER.error("Unable to load jboss-webservices metadata", e); + } + jbwsMetadata = new JBossWebservicesMetaData(jbwsURL); + jbwsMetadata.setConfigFile(configFile); + } + } + String configName = epcModel.getConfigName(); + if (configName != null) { + if (jbwsMetadata == null) { + jbwsMetadata = new JBossWebservicesMetaData(null); + } + jbwsMetadata.setConfigName(configName); + } + } + ClassLoader tccl = Classes.getTCCL(); + _context = _publisher.publish(contextRoot, tccl, urlPatternToClassNameMap, wsMetadata, jbwsMetadata); + for (org.jboss.wsf.spi.deployment.Endpoint ep : _context.getEndpoints()) { + BaseWebService wsProvider = (BaseWebService)ep.getInstanceProvider().getInstance(BaseWebService.class.getName()).getValue(); + wsProvider.setInvocationClassLoader(tccl); + // Hook the handler + wsProvider.setConsumer(handler); + // Hook the interceptors + Interceptors.addInterceptors(ep, bindingModel, tccl); + // Set the security domain + ep.setSecurityDomainContext(new SwitchYardSecurityDomainContext( + domain.getServiceSecurity(bindingModel.getService().getComponentService().getSecurity()).getSecurityDomain(), + ep.getSecurityDomainContext())); + } + WebResource resource = SwitchYardDeployment.getResource(domain, contextRoot); + if (resource == null) { + resource = new WebResource(); + resource.setStarted(true); + WebDeploymentController handle = _context.getEndpoints().get(0).getService().getDeployment().getAttachment(WebDeploymentController.class); + resource.setHandle(handle); + WebDeploymentBuilder deployment = new WebDeploymentBuilder(); + deployment.setContextRoot(contextRoot); + ServletBuilder servlet = new ServletBuilder(); + servlet.setServletClass(WSFServlet.class); + deployment.addServlet(servlet); + resource.setDeployment(deployment); // A dummy deployment builder + SwitchYardDeployment.addResource(domain, resource); + } + setWebResource(resource); + } + + /** + * Stop and destroy context. + */ + public void stopContext() { + if (_context != null && _publisher != null) { + try { + //undeploy endpoints + _publisher.destroy(_context); + } catch (Exception e) { + LOGGER.error(e); + } + } + } + + /** + * Gets the WebResource associated with this endpoint. + * @return The WebResource + */ + public WebResource getWebResource() { + return _resource; + } + + /** + * Sets the WebResource associated with this endpoint. + * @param resource The resource + */ + public void setWebResource(WebResource resource) { + _resource = resource; + } + + @Override + public void start() { + _resource.start(this); + } + + @Override + public void stop() { + // The stopcontext ensures that the context is destroyed, so no need to do this + // _resource.stop(this); + stopContext(); + } + + static { + try { + ClassLoader loader = ClassLoaderProvider.getDefaultProvider().getWebServiceSubsystemClassLoader(); + FACTORY = ServiceLoader.load(EndpointPublisherFactory.class, loader).iterator().next(); + } catch (Exception e) { + throw new WebServicePublishException(e); + } + } +} diff --git a/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpointPublisher.java b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpointPublisher.java new file mode 100644 index 000000000..82bbf94e4 --- /dev/null +++ b/release/jboss-as7/wildfly/extension/src/main/java/org/switchyard/as7/extension/ws/JBossWSEndpointPublisher.java @@ -0,0 +1,97 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.as7.extension.ws; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.ws.WebServiceFeature; +import javax.xml.ws.soap.AddressingFeature; +import javax.xml.ws.soap.MTOMFeature; + +import org.jboss.logging.Logger; +import org.jboss.wsf.spi.metadata.webservices.PortComponentMetaData; +import org.jboss.wsf.spi.metadata.webservices.WebserviceDescriptionMetaData; +import org.jboss.wsf.spi.metadata.webservices.WebservicesMetaData; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.WebServicePublishException; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.endpoint.AbstractEndpointPublisher; + +/** + * Handles publishing of Webservice Endpoints on JBossWS stack. + * + * @author Magesh Kumar B (C) 2012 Red Hat Inc. + */ +public class JBossWSEndpointPublisher extends AbstractEndpointPublisher { + + private static final Logger LOGGER = Logger.getLogger("org.switchyard"); + + private static final String SEI = "org.switchyard.component.soap.endpoint.BaseWebService"; + private static final String RESPONSE_STATUS_HANDLER = "ResponseStatusHandler"; + + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, final SOAPBindingModel config, final String bindingId, final InboundHandler handler, WebServiceFeature... features) { + JBossWSEndpoint wsEndpoint = null; + try { + initialize(config); + Map map = new HashMap(); + map.put("/" + config.getPort().getServiceName(), SEI); + + WebservicesMetaData wsMetadata = new WebservicesMetaData(); + WebserviceDescriptionMetaData wsDescMetaData = new WebserviceDescriptionMetaData(wsMetadata); + wsDescMetaData.setWsdlFile(getWsdlLocation()); + PortComponentMetaData portComponent = new PortComponentMetaData(wsDescMetaData); + portComponent.setPortComponentName(config.getServiceName() + + ":" + config.getPort().getServiceQName().getLocalPart() + + ":" + config.getPort().getPortQName().getLocalPart()); //unique ID + portComponent.setServiceEndpointInterface(SEI); + portComponent.setWsdlPort(config.getPort().getPortQName()); + portComponent.setWsdlService(config.getPort().getServiceQName()); + // Should be the WSDL's service name and not the SwitchYard config's service name + portComponent.setServletLink(config.getPort().getServiceQName().getLocalPart()); + + for (WebServiceFeature feature : features) { + if (feature instanceof AddressingFeature) { + AddressingFeature addrFeature = (AddressingFeature)feature; + portComponent.setAddressingEnabled(addrFeature.isEnabled()); + portComponent.setAddressingRequired(addrFeature.isRequired()); + LOGGER.info("Addressing [enabled = " + addrFeature.isEnabled() + ", required = " + addrFeature.isRequired() + "]"); + } else if (feature instanceof MTOMFeature) { + MTOMFeature mtom = (MTOMFeature)feature; + portComponent.setMtomEnabled(mtom.isEnabled()); + portComponent.setMtomThreshold(mtom.getThreshold()); + LOGGER.info("MTOM [enabled = " + mtom.isEnabled() + ", threshold = " + mtom.getThreshold() + "]"); + } + } + wsDescMetaData.addPortComponent(portComponent); + wsMetadata.addWebserviceDescription(wsDescMetaData); + + wsEndpoint = new JBossWSEndpoint(); + if (config.getContextPath() != null) { + wsEndpoint.publish(domain, getContextRoot(), map, wsMetadata, config, handler); + } else { + wsEndpoint.publish(domain, getContextPath(), map, wsMetadata, config, handler); + } + } catch (Exception e) { + throw new WebServicePublishException(e); + } + return wsEndpoint; + } +} diff --git a/release/jboss-as7/wildfly/installer/assembly.xml b/release/jboss-as7/wildfly/installer/assembly.xml new file mode 100644 index 000000000..618d7b70e --- /dev/null +++ b/release/jboss-as7/wildfly/installer/assembly.xml @@ -0,0 +1,68 @@ + + + + SwitchyardWildFlyInstaller + false + + zip + + + + + true + scripts/installer.properties + installer.properties + ${installer.root.dir} + + + scripts/installer.ant.xml + build.xml + ${installer.root.dir}/ + + + ${bundle.dir}/xsl/standalone.xsl + ${installer.root.dir}/res + + + ${bundle.dir}/xsl/standalone-ha.xsl + ${installer.root.dir}/res + + + ${bundle.dir}/xsl/domain.xsl + ${installer.root.dir}/res + + + + + + docs + ${installer.root.dir} + + + + + + false + + org.switchyard:switchyard-wildfly-bundle + + ${installer.root.dir}/res + switchyard-wildfly-bundle.zip + + + + diff --git a/release/jboss-as7/wildfly/installer/docs/LICENSE-2.0.txt b/release/jboss-as7/wildfly/installer/docs/LICENSE-2.0.txt new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/release/jboss-as7/wildfly/installer/docs/LICENSE-2.0.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/release/jboss-as7/wildfly/installer/docs/README.txt b/release/jboss-as7/wildfly/installer/docs/README.txt new file mode 100644 index 000000000..e1357301d --- /dev/null +++ b/release/jboss-as7/wildfly/installer/docs/README.txt @@ -0,0 +1,29 @@ +SwitchYard WildFly Standalone Installer +========================================= + +Installing Runtime +------------------ +This package contains resources for installing SwitchYard into a +JBoss Enterprise Application Platform installation. + +Prerequisites: + 1. Java Runtime + 2. Fully installed Ant available on the command line execution PATH. + 3. A WildFly installation. + +Instructions: + 1. Open a terminal command prompt. + 2. Change directory into the root of the bundle. + 3. Execute command "ant". + +This script will ask you for the path to the WildFly distribution and will +install all the necessary files required to run SwitchYard applications on +WildFly including the set of quickstart example applications. + +Installing BPEL Console - Coming soon +----------------------- +Instructions: + 1. Execute command "ant install-bpel-console" + +The script will ask for the location of your WildFly install where the console server and webapp will be deployed. + diff --git a/release/jboss-as7/wildfly/installer/pom.xml b/release/jboss-as7/wildfly/installer/pom.xml new file mode 100644 index 000000000..047202913 --- /dev/null +++ b/release/jboss-as7/wildfly/installer/pom.xml @@ -0,0 +1,96 @@ + + + + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../../../pom.xml + + 4.0.0 + switchyard-wildfly-installer + pom + SwitchYard: WildFly Installer + SwitchYard WildFly Installer + + ${project.build.directory}/bundle + /switchyard-wildfly-installer-${version.distro} + + + + org.switchyard + switchyard-wildfly-bundle + zip + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + maven-dependency-plugin + + + install-switchyard + generate-sources + + unpack + + + + + org.switchyard + switchyard-wildfly-bundle + zip + ${project.version} + xsl/* + + + ${bundle.dir} + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + assembly-installer + generate-test-resources + + single + + + false + switchyard-wildfly-installer + + ${basedir}/assembly.xml + + + 493 + + + + + + + + diff --git a/release/jboss-as7/wildfly/installer/scripts/installer.ant.xml b/release/jboss-as7/wildfly/installer/scripts/installer.ant.xml new file mode 100644 index 000000000..c841f697b --- /dev/null +++ b/release/jboss-as7/wildfly/installer/scripts/installer.ant.xml @@ -0,0 +1,211 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Downloading SwitchYard Tools Bundle ... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/installer/scripts/installer.properties b/release/jboss-as7/wildfly/installer/scripts/installer.properties new file mode 100644 index 000000000..453a4782a --- /dev/null +++ b/release/jboss-as7/wildfly/installer/scripts/installer.properties @@ -0,0 +1,18 @@ +# Project version of the installer +project.version=${project.version} +as.version=${version.wildfly} +tools.version=2.0 + +# Update this property if you would like to use a different version of the +# SwitchYard tools. +switchyard.tools.url=http://downloads.jboss.org/switchyard/releases/v2.0.Final/switchyard-tools-2.0.0.Final.zip + +# For nightly builds, we use the following setting : +# (Please remove before release) +#switchyard.tools.url=https://hudson.jboss.org/hudson/job/SwitchYard-Release/lastSuccessfulBuild/artifact/tools/dist/target/switchyard-tools.zip + +# Directory that the AS zip has unzipped into +unzipped.dir=wildfly-8.0.0.Final + +# Product name +container.name=WildFly diff --git a/release/jboss-as7/wildfly/modules/README b/release/jboss-as7/wildfly/modules/README new file mode 100644 index 000000000..e8f7b0c3b --- /dev/null +++ b/release/jboss-as7/wildfly/modules/README @@ -0,0 +1,29 @@ +SwitchYard AS7 Deployment stuff +=============================== +1. Extract the contents of build/target/switchyard.deployer.zip to JBoss AS7 root directory +2. Edit standalone.xml or domain.xml according to the configuration used and add the following + + + ... + + + + ... + + +3. To add a component extract the contents of components/{component}/build/target/switchyard.deployer.zip to JBoss AS7 root directory +4. Add the component modules + + + + + + + + + +5. Deploy m1app +6. Test with soapUI client diff --git a/release/jboss-as7/wildfly/modules/assembly.xml b/release/jboss-as7/wildfly/modules/assembly.xml new file mode 100644 index 000000000..ba01c6c49 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/assembly.xml @@ -0,0 +1,50 @@ + + + + + WildFly + false + + zip + + + + + ${project.build.directory}/modules + /modules + + system/layers/soa/org/switchyard/main/*.* + system/layers/soa/org/switchyard/component/bpel/main/module.xml + system/layers/soa/org/switchyard/component/common/knowledge/main/module.xml + system/layers/soa/org/jboss/as/console/eap/*.* + + + + + + + + + src/main/resources/switchyard/core/assembly-component.xml + src/main/resources/switchyard/components/bpel/assembly-component.xml + src/main/resources/switchyard/components/common/knowledge/assembly-component.xml + src/main/resources/switchyard/console/assembly-component.xml + src/main/resources/external/jboss/as/osgi/jta/assembly-component.xml + src/main/resources/external/jboss/netty/assembly-component.xml + + + diff --git a/release/jboss-as7/wildfly/modules/pom.xml b/release/jboss-as7/wildfly/modules/pom.xml new file mode 100644 index 000000000..79521b65a --- /dev/null +++ b/release/jboss-as7/wildfly/modules/pom.xml @@ -0,0 +1,107 @@ + + + + + org.switchyard + switchyard-wildfly-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-wildfly-modules + SwitchYard: WildFly Modules + SwitchYard WildFly Modules + + + + org.apache.maven.plugins + maven-resources-plugin + + + false + + ${*} + + + + + maven-dependency-plugin + + + stage-modules + generate-sources + + unpack + + + + + org.switchyard + switchyard-as7-modules + ${project.version} + zip + + + **/layers/base/** + ${project.build.directory} + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + package + + single + + + false + switchyard.wildfly.deployer + + ${basedir}/assembly.xml + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + org.switchyard + switchyard-deploy-wildfly + + + org.switchyard.console + switchyard-console-application + resources + + + io.netty + netty + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/as/osgi/jta/assembly-component.xml b/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/as/osgi/jta/assembly-component.xml new file mode 100644 index 000000000..b8bc317b1 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/as/osgi/jta/assembly-component.xml @@ -0,0 +1,27 @@ + + + + + + src/main/resources/external/jboss/as/osgi/jta/module.xml + /modules/system/layers/soa/org/jboss/as/osgi/jta/main + true + + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/as/osgi/jta/module.xml b/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/as/osgi/jta/module.xml new file mode 100644 index 000000000..157b43885 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/as/osgi/jta/module.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/netty/assembly-component.xml b/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/netty/assembly-component.xml new file mode 100644 index 000000000..78928bd80 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/netty/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/external/jboss/netty/module.xml + /modules/system/layers/soa/org/jboss/netty/main + true + + + + + /modules/system/layers/soa/org/jboss/netty/main + + io.netty:netty + + ${artifact.artifactId}-${artifact.baseVersion}.${artifact.extension} + false + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/netty/module.xml b/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/netty/module.xml new file mode 100644 index 000000000..0542e19e5 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/external/jboss/netty/module.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/README.md b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/README.md new file mode 100644 index 000000000..885d6ebd8 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/README.md @@ -0,0 +1 @@ +Only SwitchYard modules (no external) should be located in this folder. \ No newline at end of file diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/bpel/assembly-component.xml b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/bpel/assembly-component.xml new file mode 100644 index 000000000..fcc6d224d --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/bpel/assembly-component.xml @@ -0,0 +1,28 @@ + + + + + + + src/main/resources/switchyard/components/bpel/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/bpel/main + true + + + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/bpel/resources/module.xml b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/bpel/resources/module.xml new file mode 100644 index 000000000..213d68a9f --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/bpel/resources/module.xml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/common/knowledge/assembly-component.xml b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/common/knowledge/assembly-component.xml new file mode 100644 index 000000000..43d2906ad --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/common/knowledge/assembly-component.xml @@ -0,0 +1,26 @@ + + + + + + src/main/resources/switchyard/components/common/knowledge/resources/module.xml + /modules/system/layers/soa/org/switchyard/component/common/knowledge/main + true + + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/common/knowledge/resources/module.xml b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/common/knowledge/resources/module.xml new file mode 100644 index 000000000..4576810a9 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/components/common/knowledge/resources/module.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/console/assembly-component.xml b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/console/assembly-component.xml new file mode 100644 index 000000000..191375c01 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/console/assembly-component.xml @@ -0,0 +1,36 @@ + + + + + + src/main/resources/switchyard/console/resources/module.xml + /modules/system/layers/soa/org/jboss/as/console/main + true + + + + + + false + + org.switchyard.console:switchyard-console-application:jar:resources + + /modules/system/layers/soa/org/jboss/as/console/main + ${artifact.artifactId}-${artifact.classifier}.${artifact.extension} + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/console/resources/module.xml b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/console/resources/module.xml new file mode 100644 index 000000000..076a0c5b6 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/console/resources/module.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/core/assembly-component.xml b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/core/assembly-component.xml new file mode 100644 index 000000000..a4d5bcb0a --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/core/assembly-component.xml @@ -0,0 +1,35 @@ + + + + + + src/main/resources/switchyard/core/module.xml + /modules/system/layers/soa/org/switchyard/main + true + + + + + false + + org.switchyard:switchyard-deploy-wildfly + + /modules/system/layers/soa/org/switchyard/main + ${artifact.artifactId}-${project.version}.${artifact.extension} + + + + diff --git a/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/core/module.xml b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/core/module.xml new file mode 100644 index 000000000..09224cd89 --- /dev/null +++ b/release/jboss-as7/wildfly/modules/src/main/resources/switchyard/core/module.xml @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/jboss-as7/wildfly/pom.xml b/release/jboss-as7/wildfly/pom.xml new file mode 100644 index 000000000..f9097f91b --- /dev/null +++ b/release/jboss-as7/wildfly/pom.xml @@ -0,0 +1,73 @@ + + + + + org.switchyard + switchyard-container-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-wildfly-parent + pom + SwitchYard: Wildfly Standalone Parent + SwitchYard Wildfly Standalone Parent + + 8.0.0.Final + + 3.6.6.Final + + + + extension + modules + bundle + + installer + dist + + + + + org.wildfly + wildfly-parent + pom + import + ${version.wildfly} + + + org.wildfly + wildfly-dist + zip + ${version.wildfly} + + + io.netty + netty + ${version.io.netty} + + + org.apache.httpcomponents + httpclient + ${version.org.apache.httpcomponents.httpclient} + + + org.apache.httpcomponents + httpcore + ${version.org.apache.httpcomponents.httpcore} + + + + diff --git a/release/karaf/bpel/pom.xml b/release/karaf/bpel/pom.xml new file mode 100644 index 000000000..517ce84ca --- /dev/null +++ b/release/karaf/bpel/pom.xml @@ -0,0 +1,243 @@ + + + + + org.switchyard.karaf + switchyard-karaf-parent + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-karaf-bpel + bundle + SwitchYard: BPEL Component Bundle for Karaf + OSGi bundle packaging for the SwitchYard BPEL component + + + org.switchyard.component.bpel.*;version="${switchyard.osgi.version}";-noimport:=true, + org.riftsaw.*;version="${version.riftsaw.engine}";-noimport:=true, + org.jboss.soa.bpel.*;version="${version.riftsaw.engine}";-noimport:=true, + org.wso2.carbon.bpel.ui.*;version="${version.riftsaw.engine}";-noimport:=true, + org.jboss.bpm.console.*;version="${version.riftsaw.console}";-noimport:=true, + org.apache.ode.*;version="${version.riftsaw.ode}";-noimport:=true, + org.jboss.bpm.monitor.*;version="${version.activity.monitor.model}";-noimport:=true + + version="[$(version;==;${version.net.sourceforge.saxon}),$(version;=+;${version.net.sourceforge.saxon}))" + + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + javax.persistence, + org.hibernate.*, + org.hibernate.proxy, + javassist.util.proxy, + org.osgi.framework, + org.h2, + org.apache.xmlbeans.impl.schema, + com.ibm.wsdl, + com.ibm.wsdl.extensions, + com.ibm.wsdl.extensions.http, + com.ibm.wsdl.extensions.mime, + com.ibm.wsdl.extensions.schema, + com.ibm.wsdl.extensions.soap, + com.ibm.wsdl.extensions.soap12, + com.ibm.wsdl.factory, + com.ibm.wsdl.util, + net.sf.saxon.*;${switchyard.osgi.import.bpel.saxon.version}, + !org.jboss.logmanager.*, + !org.jboss.vfs.*, + !org.jboss.as.*, + !org.jboss.msc.*, + !javax.resource.spi, + !org.apache.axiom.*, + !org.apache.commons.httpclient.*, + !org.apache.geronimo.connector.*, + !org.tranql.*, + !org.apache.log4j.helpers, + !org.jboss.errai.bus.server.annotations.*, + * + + *;inline=**.xml;groupId=!org.osgi;scope=compile,*;groupId=!org.osgi;scope=compile + + + + org.switchyard + switchyard-api + provided + + + org.switchyard.components + switchyard-component-bpel + + + * + * + + + + + org.riftsaw + engine + + + org.jboss.soa.bpel + riftsaw-agents + + + org.jboss.soa.bpel + riftsaw-bpel-api + + + org.jboss.soa.bpel + riftsaw-bpel-compiler + + + org.jboss.soa.bpel + riftsaw-bpel-dao + + + org.jboss.soa.bpel + riftsaw-bpel-epr + + + org.jboss.soa.bpel + riftsaw-bpel-obj + + + org.jboss.soa.bpel + riftsaw-bpel-ql + + + org.jboss.soa.bpel + riftsaw-bpel-runtime + + + org.jboss.soa.bpel + riftsaw-bpel-schemas + + + org.jboss.soa.bpel + riftsaw-bpel-store + + + org.jboss.soa.bpel + riftsaw-dao-jpa + + + org.jboss.soa.bpel + riftsaw-dao-jpa-hibernate + + + org.jboss.soa.bpel + riftsaw-jacob + + + org.jboss.soa.bpel + riftsaw-scheduler-simple + + + org.jboss.soa.bpel + riftsaw-utils + + + org.jboss.bpm + activity-monitor-model + + + + org.jboss.bpm + gwt-console-rpc + + + org.jboss.bpm + gwt-console-server-integration + + + org.riftsaw.console + riftsaw-bpaf + + + org.riftsaw.console + riftsaw-bpel2svg + + + org.riftsaw.console + riftsaw-console-integration + + + org.switchyard.karaf + switchyard-karaf-deploy + provided + + + org.jboss.logging + jboss-logging + + + + org.osgi + org.osgi.core + provided + + + org.osgi + org.osgi.compendium + provided + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + false + + + + org.apache.felix + maven-bundle-plugin + + + <_exportcontents> + org.switchyard.component.bpel.*;version="${switchyard.osgi.version}";-noimport:=true, + org.riftsaw.engine;version="${version.riftsaw.engine}";-noimport:=true + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + attach-artifacts + package + + attach-artifact + + + + + target/classes/bpel.properties + properties + riftsaw + + + + + + + + + diff --git a/release/karaf/bpel/progress.txt b/release/karaf/bpel/progress.txt new file mode 100644 index 000000000..faa44b8d6 --- /dev/null +++ b/release/karaf/bpel/progress.txt @@ -0,0 +1,28 @@ +Progress to date: +OpenJPA is easiest to configure, but fails because custom sequence +(bpel_sequence) can't be used for AUTO fields. + +Hibernate has all sorts of problems. Most successful solution is to use +"unmanaged" mode, looking up the persistence provider and manually creating +the EMF after injecting the relevant hibernate.* properties from the +bpel.properties file. "Managed" mode requires the datasource be defined +within the persistence.xml file. The environment also needs to define +hibernate.dialect or the EMF generation fails. Hibernate is also very sensitive +to the install (yes, install) order of the bundles. hibernate-osgi must be +installed after the bpel bundle for managed persistence to work at all. + +If one of the above "works" initialization fails because +BPELEngineImpl.RegisterServicesIntoJNDI() requires org.jboss.msc classes (!!!). + +Short of it: +BPELEngineImpl will need to be reconstructed to remove platform dependencies. +The deploy() methods will also need to be modified to support accessing files +from bundles (as opposed to file://). + +Console hooks need to be reimplemented accordingly, as they all reference +BPELEngineFactory.getEngine() (static). This should be rewritten to support +injecting an engine instance (that might even be created through blueprint). + +I'm sure there are other areas where code is looking for things with specific +JNDI names, which are pretty much guaranteed not to exist in osgi (e.g. +anything with java:). diff --git a/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/BPELEngineFactory.java b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/BPELEngineFactory.java new file mode 100644 index 000000000..a5cd33cd6 --- /dev/null +++ b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/BPELEngineFactory.java @@ -0,0 +1,93 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.osgi; + +import java.io.File; +import java.io.IOException; +import java.util.Properties; + +import javax.transaction.TransactionManager; + +import org.osgi.framework.Bundle; +import org.osgi.framework.FrameworkUtil; +import org.riftsaw.engine.BPELEngine; +import org.riftsaw.engine.ServiceLocator; +import org.riftsaw.engine.internal.BPELEngineImpl; +import org.riftsaw.engine.internal.DeploymentManager; + +/** + * Simple class for creating BPELEngine beans through blueprint. + */ +public class BPELEngineFactory { + + private ServiceLocator _serviceLocator; + private Properties _configuration; + private TransactionManager _transactionManager; + + /** + * @return a new BPELEngine instance + * @throws Exception if something goes awry + */ + public BPELEngine createEngine() throws Exception { + final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + final BPELEngineImpl engine = new BPELEngineImpl(); + engine.setTransactionManager(_transactionManager); + engine.setDeploymentManager(createDeploymentManager()); + engine.init(_serviceLocator, _configuration); + return engine; + } finally { + Thread.currentThread().setContextClassLoader(oldLoader); + } + } + + /** + * @param serviceLocator service locator to use for new engines + */ + public void setServiceLocator(ServiceLocator serviceLocator) { + _serviceLocator = serviceLocator; + } + + /** + * @param configuration configuration to use for new engines + */ + public void setConfiguration(Properties configuration) { + _configuration = configuration; + } + + /** + * @param transactionManager transaction manager to use for new engines + */ + public void setTransactionManager(TransactionManager transactionManager) { + _transactionManager = transactionManager; + } + + private DeploymentManager createDeploymentManager() throws IOException { + final DeploymentManager manager = new DeploymentManager(); + manager.setDeploymentFolder(getDeploymentsDirectory().getCanonicalPath()); + return manager; + } + + private File getDeploymentsDirectory() { + final Bundle bundle = FrameworkUtil.getBundle(getClass()); + final File dataDirectory = bundle.getDataFile(""); + final File deploymentsDirectory = new File(dataDirectory, "deployments"); + if (!deploymentsDirectory.exists()) { + deploymentsDirectory.mkdir(); + deploymentsDirectory.deleteOnExit(); + } + return deploymentsDirectory; + } +} diff --git a/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/BPELOSGiComponent.java b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/BPELOSGiComponent.java new file mode 100644 index 000000000..9e56ff90b --- /dev/null +++ b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/BPELOSGiComponent.java @@ -0,0 +1,70 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.osgi; + +import java.util.Properties; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.riftsaw.engine.BPELEngine; +import org.riftsaw.engine.ServiceLocator; +import org.switchyard.component.bpel.deploy.BPELComponent; + +/** + * BPELOSGiComponent + *

+ * Replaces BPELEngine creation with OSGi service lookup. + */ +public class BPELOSGiComponent extends BPELComponent { + + /** + * Create a new BPELOSGiComponent. + */ + public BPELOSGiComponent() { + super(new BPELEngineInstanceImpl()); + } + + private static final class BPELEngineInstanceImpl implements BPELEngineInstance { + private BPELEngine _engine; + private ServiceReference _serviceReference; + + @Override + public void init(ServiceLocator serviceLocator, Properties config) { + } + + @Override + public synchronized BPELEngine getBPELEngine() throws Exception { + if (_engine == null) { + Bundle thisBundle = FrameworkUtil.getBundle(getClass()); + BundleContext context = thisBundle.getBundleContext(); + _serviceReference = context.getServiceReference(BPELEngine.class); + _engine = context.getService(_serviceReference); + } + return _engine; + } + + @Override + public void dispose() throws Exception { + if (_engine != null) { + Bundle thisBundle = FrameworkUtil.getBundle(getClass()); + BundleContext context = thisBundle.getBundleContext(); + context.ungetService(_serviceReference); + _serviceReference = null; + _engine = null; + } + } + } +} diff --git a/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/ODEEntityManagerFactoryService.java b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/ODEEntityManagerFactoryService.java new file mode 100644 index 000000000..9e5e7bf72 --- /dev/null +++ b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/ODEEntityManagerFactoryService.java @@ -0,0 +1,73 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.osgi; + +import java.util.Collection; + +import javax.persistence.EntityManagerFactory; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; + +/** + * Provides access to the ode.emf registered by the BPEL engine. + */ +public class ODEEntityManagerFactoryService { + + private ServiceReference _reference; + private EntityManagerFactory _service; + + /** + * Create a new ODEEntityManagerFactoryService. + */ + public ODEEntityManagerFactoryService() { + } + + /** + * @return the ODE EMF + * @throws Exception if something goes awry + */ + public synchronized EntityManagerFactory getOdeEmf() throws Exception { + if (_service == null) { + final Bundle bundle = FrameworkUtil.getBundle(getClass()); + final BundleContext context = bundle.getBundleContext(); + final Collection> references = context.getServiceReferences( + EntityManagerFactory.class, "(ode.emf=*)"); + if (references.size() == 0) { + throw new RuntimeException("Could not locate ode.emf."); + } + // if (references.size() > 1) { + // TODO: warn??? + // } + _reference = references.iterator().next(); + _service = context.getService(_reference); + } + return _service; + } + + /** + * Cleaup after ourselves. + */ + public synchronized void dispose() { + if (_reference != null) { + final Bundle bundle = FrameworkUtil.getBundle(getClass()); + final BundleContext context = bundle.getBundleContext(); + context.ungetService(_reference); + _reference = null; + _service = null; + } + } +} diff --git a/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/RiftsawBPELOSGiExchangeHandler.java b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/RiftsawBPELOSGiExchangeHandler.java new file mode 100644 index 000000000..eba3b545c --- /dev/null +++ b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/RiftsawBPELOSGiExchangeHandler.java @@ -0,0 +1,123 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.osgi; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.channels.ReadableByteChannel; +import java.util.Enumeration; + +import org.jboss.logging.Logger; +import org.osgi.framework.Bundle; +import org.switchyard.ServiceDomain; +import org.switchyard.component.bpel.riftsaw.RiftsawBPELExchangeHandler; +import org.switchyard.deploy.osgi.internal.SwitchYardContainerImpl; + +/** + * Specialized for use in OSGi environments. + */ +public class RiftsawBPELOSGiExchangeHandler extends RiftsawBPELExchangeHandler { + + private static final Logger LOG = Logger.getLogger(RiftsawBPELOSGiExchangeHandler.class); + + private final ServiceDomain _domain; + + protected RiftsawBPELOSGiExchangeHandler(ServiceDomain domain) { + super(domain); + _domain = domain; + } + + @Override + protected File getDeployment() throws Exception { + final Bundle applicationBundle = getApplicationBundle(); + final Enumeration deploymentEntries = applicationBundle.findEntries("/", "deploy.xml", false); + if (deploymentEntries.hasMoreElements()) { + return expandDeployment(applicationBundle, deploymentEntries.nextElement()); + } + throw new Exception("Bundle does not contain deploy.xml file: " + applicationBundle.getSymbolicName()); + } + + @Override + protected String getDeploymentName() throws Exception { + return getApplicationBundle().getSymbolicName(); + } + + private Bundle getApplicationBundle() throws Exception { + return (Bundle) _domain.getProperty(SwitchYardContainerImpl.SWITCHYARD_DEPLOYMENT_BUNDLE); + } + + private File expandDeployment(Bundle applicationBundle, URL deployXmlUrl) throws IOException { + final File rootDirectory = getDataDirectory(applicationBundle); + copyFile(deployXmlUrl, rootDirectory); + final Enumeration bpelFiles = applicationBundle.findEntries("/", "*.bpel*", true); + if (bpelFiles != null) { + while (bpelFiles.hasMoreElements()) { + copyFile(bpelFiles.nextElement(), rootDirectory); + } + } + return rootDirectory; + } + + private void copyFile(URL source, File rootDirectory) throws IOException { + final File destination = new File(rootDirectory, source.getPath()); + if (!destination.getName().matches(".+\\.bpel(-\\d+)?") && !"deploy.xml".equals(destination.getName())) { + LOG.warnf("Skipping file copy for \"%s\", not a *.bpel or deploy.xml file.", destination.getName()); + return; + } + destination.getParentFile().mkdirs(); + + ReadableByteChannel input = null; + FileChannel output = null; + try { + final ByteBuffer buffer = ByteBuffer.allocate(0x100000); + input = Channels.newChannel(source.openStream()); + output = new FileOutputStream(destination).getChannel(); + while (input.read(buffer) > 0) { + buffer.flip(); + output.write(buffer); + buffer.clear(); + } + } finally { + if (input != null) { + try { + input.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + if (output != null) { + try { + output.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + private File getDataDirectory(final Bundle bundle) { + final File dataDirectory = bundle.getDataFile(""); + final File deploymentsDirectory = new File(dataDirectory, "bpel"); + if (!deploymentsDirectory.exists()) { + deploymentsDirectory.mkdirs(); + deploymentsDirectory.deleteOnExit(); + } + return deploymentsDirectory; + } +} diff --git a/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/RiftsawBPELOSGiExchangeHandlerFactory.java b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/RiftsawBPELOSGiExchangeHandlerFactory.java new file mode 100644 index 000000000..a8c1a1e42 --- /dev/null +++ b/release/karaf/bpel/src/main/java/org/switchyard/component/bpel/osgi/RiftsawBPELOSGiExchangeHandlerFactory.java @@ -0,0 +1,28 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.component.bpel.osgi; + +import org.switchyard.ServiceDomain; +import org.switchyard.component.bpel.exchange.BPELExchangeHandler; +import org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory; + +/** + * Creates BPELExchangeHandler objects for use in an OSGi environment. + */ +public class RiftsawBPELOSGiExchangeHandlerFactory extends BPELExchangeHandlerFactory { + @Override + public BPELExchangeHandler newBPELExchangeHandler(ServiceDomain serviceDomain) { + return new RiftsawBPELOSGiExchangeHandler(serviceDomain); + } +} diff --git a/release/karaf/bpel/src/main/resources/META-INF/services/org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory b/release/karaf/bpel/src/main/resources/META-INF/services/org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory new file mode 100644 index 000000000..a4d0d6529 --- /dev/null +++ b/release/karaf/bpel/src/main/resources/META-INF/services/org.switchyard.component.bpel.exchange.BPELExchangeHandlerFactory @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.bpel.osgi.RiftsawBPELOSGiExchangeHandlerFactory diff --git a/release/karaf/bpel/src/main/resources/META-INF/services/org.switchyard.deploy.Component b/release/karaf/bpel/src/main/resources/META-INF/services/org.switchyard.deploy.Component new file mode 100644 index 000000000..e84d00956 --- /dev/null +++ b/release/karaf/bpel/src/main/resources/META-INF/services/org.switchyard.deploy.Component @@ -0,0 +1,12 @@ +# Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +org.switchyard.component.bpel.osgi.BPELOSGiComponent diff --git a/release/karaf/bpel/src/main/resources/OSGI-INF/blueprint/bpel-engine.xml b/release/karaf/bpel/src/main/resources/OSGI-INF/blueprint/bpel-engine.xml new file mode 100644 index 000000000..e81b8ff0f --- /dev/null +++ b/release/karaf/bpel/src/main/resources/OSGI-INF/blueprint/bpel-engine.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/karaf/bpel/src/main/resources/bpel.properties b/release/karaf/bpel/src/main/resources/bpel.properties new file mode 100644 index 000000000..f62ff6a27 --- /dev/null +++ b/release/karaf/bpel/src/main/resources/bpel.properties @@ -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. +# + +## bpel Configuration Properties + +bpel.dao.factory=org.riftsaw.engine.osgi.BpelDAOConnectionFactoryImpl +bpel.dao.factory.store=org.riftsaw.engine.osgi.ConfStoreDAOConnectionFactoryImpl +bpel.dao.factory.scheduler=org.riftsaw.engine.osgi.SchedulerDAOConnectionFactoryImpl +# need to look at integrating infinispan into osgi +#bpel.cache.provider=org.riftsaw.engine.internal.InfinispanCacheProvider +bpel.cache.provider=org.apache.ode.il.cache.DefaultCacheProvider + +# initialized through osgi blueprint +#bpel.tx.factory.class = org.riftsaw.engine.jboss.JBossTransactionFactory + +#bpel.db.mode=EMBEDDED +bpel.db.mode=EXTERNAL +db.emb.create=false +#bpel.db.ext.dataSource=java:BPELDB +bpel.db.ext.dataSource=osgi:service/jdbc/RiftsawDS + +# all hibernate specific properties + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.hbm2ddl.auto=none +hibernate.current_session_context_class=jta +hibernate.show_sql=false +hibernate.connection.isolation=2 +hibernate.jdbc.batch_size=20 + +jta.UserTransaction=UserTransaction + +ode.persistence=hibernate + +# +# Comma separated list of BPEL event listeners. +# BPAFLogAdapter is used to store BPEL events for historic analysis. +# +bpel.event.listeners=org.jboss.soa.bpel.console.bpaf.BPAFLogAdapter +#bpel.event.listeners= + +# Property used to configure whether ODE should store the BPEL events in its default location +# (Set to false, as RiftSaw uses the BPEL events stored by the BPAFLogAdapter) +persist.bpel.events = false + +# Determines if even top level transaction based ODE invokes should bypass the scheduler +# If false, then top level invokes will be scheduled, but subsequent nested invokes (to +# external services in same thread) will be directly invoked instead of via the scheduler. +# NOTE: Currently disabled, as the mechanism bypasses the mex.timeout guard and also has +# issues when dealing with correlation, where messages are received out of order. +#bpel.invoke.immediate=false + +#Configure the scheduler node name +bpel.riftsaw.node.name=riftsaw-scheduler-node + +#Configure the cache name from the infinispan module for the ProcessConf cache +bpel.cache-name=cluster diff --git a/release/karaf/commands/pom.xml b/release/karaf/commands/pom.xml new file mode 100644 index 000000000..57e3ee1c0 --- /dev/null +++ b/release/karaf/commands/pom.xml @@ -0,0 +1,88 @@ + + + + 4.0.0 + + org.switchyard.karaf + switchyard-karaf-parent + 2.1.0-SNAPSHOT + + switchyard-karaf-commands + bundle + SwitchYard: Karaf Commands + Commands for running Switchyard on Karaf + http://switchyard.org + + + + org.apache.felix.service.command, + org.apache.felix.gogo.commands, + org.apache.karaf.shell.console, + org.osgi.framework, + org.switchyard.deploy, + org.switchyard.deploy.osgi, + org.switchyard.admin, + * + + + org.switchyard.deploy.karaf + + + + + + org.switchyard + switchyard-admin + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-deploy + + + org.switchyard.karaf + switchyard-karaf-deploy + + + org.apache.karaf.shell + org.apache.karaf.shell.console + + + org.eclipse.osgi + org.eclipse.osgi + + + + + org.apache.karaf + org.apache.karaf.util + + + org.osgi + org.osgi.core + + + diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/AbstractSwitchYardServiceCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/AbstractSwitchYardServiceCommand.java new file mode 100644 index 000000000..6ea56991c --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/AbstractSwitchYardServiceCommand.java @@ -0,0 +1,77 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.osgi.framework.ServiceReference; +import org.switchyard.admin.SwitchYard; + +/** + * Provides utility methods used by commands referencing the SwitchYard admin + * service. + */ +public abstract class AbstractSwitchYardServiceCommand extends OsgiCommandSupport { + + @Override + protected final Object doExecute() throws Exception { + final ServiceReference serviceReference = getBundleContext().getServiceReference(SwitchYard.class); + if (serviceReference == null) { + System.out.println("SwitchYard admin service is unavailable."); + return null; + } + try { + final SwitchYard switchYard = getBundleContext().getService(serviceReference); + if (switchYard == null) { + System.out.println("SwitchYard admin service is unavailable."); + return null; + } + return doExecute(switchYard); + } finally { + getBundleContext().ungetService(serviceReference); + } + } + + protected abstract Object doExecute(SwitchYard switchYard) throws Exception; + + /** + * Aggregates the patterns in the list into a patterns[0]|patterns[1]|... + * + * @param patterns list of patterns + * @return a compiled Pattern + */ + protected Pattern compilePattern(List patterns, boolean isRegex) { + if (patterns == null || patterns.size() == 0) { + patterns = Collections.singletonList(".*"); + isRegex = true; + } + final StringBuffer regex = new StringBuffer(); + for (String name : patterns) { + if (!isRegex) { + regex.append("\\Q"); + } + regex.append(name); + if (!isRegex) { + regex.append("\\E"); + } + regex.append('|'); + } + regex.deleteCharAt(regex.length() - 1); + return Pattern.compile(regex.toString()); + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ApplicationNameCompleter.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ApplicationNameCompleter.java new file mode 100644 index 000000000..824b64969 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ApplicationNameCompleter.java @@ -0,0 +1,47 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; + +import org.apache.karaf.shell.console.Completer; +import org.apache.karaf.shell.console.completer.StringsCompleter; +import org.switchyard.admin.Application; +import org.switchyard.admin.SwitchYard; + +/** + * Generates completion set for Application arguments. + */ +public class ApplicationNameCompleter implements Completer { + + private SwitchYard _switchYard; + + @Override + public int complete(String buffer, int cursor, List candidates) { + final StringsCompleter delegate = new StringsCompleter(); + final List applications = _switchYard.getApplications(); + for (Application application : applications) { + delegate.getStrings().add(application.getName().toString()); + } + return delegate.complete(buffer, cursor, candidates); + } + + /** + * @param switchYard the SwitchYard admin service + */ + public void setSwitchYard(SwitchYard switchYard) { + _switchYard = switchYard; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ArtifactCompleter.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ArtifactCompleter.java new file mode 100644 index 000000000..b2a1bd617 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ArtifactCompleter.java @@ -0,0 +1,88 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.Arrays; +import java.util.List; + +import org.apache.felix.service.command.CommandSession; +import org.apache.karaf.shell.console.Completer; +import org.apache.karaf.shell.console.completer.ArgumentCompleter; +import org.apache.karaf.shell.console.completer.StringsCompleter; +import org.apache.karaf.shell.console.jline.CommandSessionHolder; +import org.switchyard.admin.Application; +import org.switchyard.admin.SwitchYard; +import org.switchyard.config.model.switchyard.ArtifactModel; + +/** + * Generates completion set for artifact arguments. + */ +public class ArtifactCompleter implements Completer { + + private SwitchYard _switchYard; + + @Override + public int complete(String buffer, int cursor, List candidates) { + final StringsCompleter delegate = new StringsCompleter(); + final UsesArtifactCommand.SearchType type = getType(); + for (Application application : _switchYard.getApplications()) { + if (application.getConfig().getArtifacts() == null) { + continue; + } + for (ArtifactModel artifact : application.getConfig().getArtifacts().getArtifacts()) { + switch (type) { + case name: + delegate.getStrings().add(artifact.getName()); + break; + case url: + delegate.getStrings().add(artifact.getURL()); + break; + } + } + } + return delegate.complete(buffer, cursor, candidates); + } + + /** + * @param switchYard the SwitchYard admin service + */ + public void setSwitchYard(SwitchYard switchYard) { + _switchYard = switchYard; + } + + private UsesArtifactCommand.SearchType getType() { + final CommandSession session = CommandSessionHolder.getSession(); + if (session == null) { + return null; + } + final ArgumentCompleter.ArgumentList argList = (ArgumentCompleter.ArgumentList) session + .get(ArgumentCompleter.ARGUMENTS_LIST); + if (argList == null || argList.getArguments() == null || argList.getArguments().length == 0) { + return null; + } + final List arguments = Arrays.asList(argList.getArguments()); + int argumentOffset = 1; // command is first argument + for (int index = 0, count = arguments.size(); index < count; ++index) { + if (arguments.get(index).startsWith("-")) { + argumentOffset = index; + } + } + // XXX: assuming the last option does not accept a value here + if (argumentOffset < arguments.size()) { + return UsesArtifactCommand.SearchType.valueOf(arguments.get(argumentOffset)); + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/BindingNameCompleter.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/BindingNameCompleter.java new file mode 100644 index 000000000..3f7ec6df7 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/BindingNameCompleter.java @@ -0,0 +1,85 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.Arrays; +import java.util.List; + +import javax.xml.namespace.QName; + +import org.apache.felix.service.command.CommandSession; +import org.apache.karaf.shell.console.Completer; +import org.apache.karaf.shell.console.completer.ArgumentCompleter; +import org.apache.karaf.shell.console.completer.StringsCompleter; +import org.apache.karaf.shell.console.jline.CommandSessionHolder; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Generates completion set for Application arguments. + */ +public class BindingNameCompleter implements Completer { + + private SwitchYard _switchYard; + + @Override + public int complete(String buffer, int cursor, List candidates) { + final StringsCompleter delegate = new StringsCompleter(); + final CommandSession session = CommandSessionHolder.getSession(); + if (session == null) { + return delegate.complete(buffer, cursor, candidates); + } + final ArgumentCompleter.ArgumentList argList = (ArgumentCompleter.ArgumentList) session + .get(ArgumentCompleter.ARGUMENTS_LIST); + if (argList == null || argList.getArguments() == null || argList.getArguments().length == 4) { + return delegate.complete(buffer, cursor, candidates); + } + final List arguments = Arrays.asList(argList.getArguments()); + final Application application = _switchYard.getApplication(QName.valueOf(arguments.get(2))); + if (application == null) { + return delegate.complete(buffer, cursor, candidates); + } + final QName serviceOrReferenceName = QName.valueOf(arguments.get(3)); + final Service service = application.getService(serviceOrReferenceName); + if (service == null) { + final Reference reference = application.getReference(serviceOrReferenceName); + if (reference == null) { + return delegate.complete(buffer, cursor, candidates); + } + for (Binding binding : reference.getGateways()) { + if (binding.getName() != null) { + delegate.getStrings().add(binding.getName()); + } + } + } else { + for (Binding binding : service.getGateways()) { + if (binding.getName() != null) { + delegate.getStrings().add(binding.getName()); + } + } + } + return delegate.complete(buffer, cursor, candidates); + } + + /** + * @param switchYard the SwitchYard admin service + */ + public void setSwitchYard(SwitchYard switchYard) { + _switchYard = switchYard; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ComponentList.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ComponentList.java new file mode 100644 index 000000000..e822a01d4 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ComponentList.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.felix.gogo.commands.Command; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.osgi.framework.ServiceReference; +import org.switchyard.deploy.Component; + +/** + * Shell commands for components. + */ +@Command(scope = "switchyard", name = "component-list", description = "List switchyard components.") +public class ComponentList extends OsgiCommandSupport { + + public static final String SWITCHYARD_TYPES = "switchyard.types"; + + @Override + protected Object doExecute() throws Exception { + Collection> refs = + getBundleContext().getServiceReferences( + Component.class, "(" + SWITCHYARD_TYPES + "=*)"); + if (refs != null) { + Set types = new TreeSet(); + for (ServiceReference ref : refs) { + types.addAll(getTypes(ref.getProperty(SWITCHYARD_TYPES))); + } + for (String type : types) { + System.out.println(type); + } + } + return null; + } + + private static List getTypes(Object ns) { + if (ns == null) { + throw new IllegalArgumentException("Component service does not have an associated " + + SWITCHYARD_TYPES + " property defined"); + } else if (ns instanceof String[]) { + return Arrays.asList((String[]) ns); + } else if (ns instanceof URI) { + return Collections.singletonList(ns.toString()); + } else if (ns instanceof String) { + return Collections.singletonList((String) ns); + } else if (ns instanceof Collection) { + Collection col = (Collection) ns; + List types = new ArrayList(col.size()); + for (Object o : col) { + types.add(o.toString()); + } + return types; + } else if (ns instanceof Object[]) { + Object[] array = (Object[]) ns; + List types = new ArrayList(array.length); + for (Object o : array) { + types.add(o.toString()); + } + return types; + } else { + throw new IllegalArgumentException("Component service has an associated " + + SWITCHYARD_TYPES + " property defined which can not be converted to an array of String"); + } + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/DeploymentList.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/DeploymentList.java new file mode 100644 index 000000000..da974ab96 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/DeploymentList.java @@ -0,0 +1,142 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import org.apache.felix.gogo.commands.Command; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.osgi.framework.ServiceRegistration; +import org.switchyard.deploy.osgi.SwitchYardEvent; +import org.switchyard.deploy.osgi.SwitchYardListener; + +import java.io.PrintStream; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Shell commands for deployments. + */ +@Command(scope = "switchyard", name = "deployment-list", description = "List switchyard deployments.") +public class DeploymentList extends OsgiCommandSupport { + + + private static final String ID_COLUMN_LABEL = "Id"; + private static final String NAME_COLUMN_LABEL = "Name"; + private static final String STATUS_COLUMN_LABEL = "Status"; + private static final int DEFAULT_FORMAT_BUFFER_LENGTH = 24; + private static final String DEFAULT_FIELD_PREAMBLE = "[ "; + private static final String DEFAULT_FIELD_POSTAMBLE = " ]"; + private static final String DEFAULT_HEADER_PREAMBLE = " "; + private static final String DEFAULT_HEADER_POSTAMBLE = " "; + private static final int DEFAULT_COLUMN_WIDTH_INCREMENT = 0; + private static final int MAX_COLUMN_WIDTH = Integer.MAX_VALUE; + + private final List _events = new CopyOnWriteArrayList(); + + @Override + protected Object doExecute() throws Exception { + SwitchYardListener listener = new SwitchYardListener() { + @Override + public void switchyardEvent(SwitchYardEvent event) { + _events.add(event); + } + }; + ServiceRegistration reg = getBundleContext().registerService(SwitchYardListener.class, listener, null); + reg.unregister(); + + if (!_events.isEmpty()) { + final Map columnWidths = computeColumnWidths(_events); + final String headerFormat = buildFormatString(columnWidths, true); + final String rowFormat = buildFormatString(columnWidths, false); + final PrintStream out = System.out; + + out.println(String.format(headerFormat, ID_COLUMN_LABEL, NAME_COLUMN_LABEL, STATUS_COLUMN_LABEL)); + for (SwitchYardEvent event : _events) { + out.println(String.format(rowFormat, getId(event), getName(event), getStatus(event))); + } + } + return null; + } + + private static Map computeColumnWidths(final Iterable events) throws Exception { + if (events == null) { + throw new IllegalArgumentException("Unable to determine column widths from null Iterable"); + } else { + int maxIdLen = 0; + int maxNameLen = 0; + int maxStatusLen = 0; + + for (final SwitchYardEvent event : events) { + maxIdLen = java.lang.Math.max(maxIdLen, getId(event).length()); + maxNameLen = java.lang.Math.max(maxNameLen, getName(event).length()); + maxStatusLen = java.lang.Math.max(maxStatusLen, getStatus(event).length()); + } + + final Map retval = new Hashtable(3); + retval.put(ID_COLUMN_LABEL, maxIdLen); + retval.put(NAME_COLUMN_LABEL, maxNameLen); + retval.put(STATUS_COLUMN_LABEL, maxStatusLen); + + return retval; + } + } + + private static String getId(SwitchYardEvent event) { + return Long.toString(event.getBundle().getBundleId()); + } + + private static String getName(SwitchYardEvent event) { + return event.getBundle().getSymbolicName(); + } + + private static String getStatus(SwitchYardEvent event) { + switch (event.getType()) { + case SwitchYardEvent.CREATING: return "Creating"; + case SwitchYardEvent.GRACE_PERIOD: return "Grace Period"; + case SwitchYardEvent.CREATED: return "Created"; + case SwitchYardEvent.DESTROYING: return "Destroying"; + case SwitchYardEvent.DESTROYED: return "Destroyed"; + case SwitchYardEvent.FAILURE: return "Failure"; + default: return "Unknown"; + } + } + + private static String buildFormatString(final Map columnWidths, final boolean isHeader) { + final String fieldPreamble; + final String fieldPostamble; + final int columnWidthIncrement; + + if (isHeader) { + fieldPreamble = DEFAULT_HEADER_PREAMBLE; + fieldPostamble = DEFAULT_HEADER_POSTAMBLE; + } else { + fieldPreamble = DEFAULT_FIELD_PREAMBLE; + fieldPostamble = DEFAULT_FIELD_POSTAMBLE; + } + columnWidthIncrement = DEFAULT_COLUMN_WIDTH_INCREMENT; + + final int idLen = java.lang.Math.min(columnWidths.get(ID_COLUMN_LABEL) + columnWidthIncrement, MAX_COLUMN_WIDTH); + final int nameLen = java.lang.Math.min(columnWidths.get(NAME_COLUMN_LABEL) + columnWidthIncrement, MAX_COLUMN_WIDTH); + final int statusLen = java.lang.Math.min(columnWidths.get(STATUS_COLUMN_LABEL) + columnWidthIncrement, MAX_COLUMN_WIDTH); + + final StringBuilder retval = new StringBuilder(DEFAULT_FORMAT_BUFFER_LENGTH); + retval.append(fieldPreamble).append("%-").append(idLen).append('.').append(idLen).append('s').append(fieldPostamble).append(' '); + retval.append(fieldPreamble).append("%-").append(nameLen).append('.').append(nameLen).append('s').append(fieldPostamble).append(' '); + retval.append(fieldPreamble).append("%-").append(statusLen).append('.').append(statusLen).append('s').append(fieldPostamble).append(' '); + + return retval.toString(); + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/GatewayCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/GatewayCommand.java new file mode 100644 index 000000000..479a3fcbe --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/GatewayCommand.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import javax.xml.namespace.QName; + +import org.apache.felix.gogo.commands.Argument; +import org.apache.felix.gogo.commands.Command; +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for uses-artifact. + */ +@Command(scope = "switchyard", name = "gateway", description = "Perform an operation on a gateway.") +public class GatewayCommand extends AbstractSwitchYardServiceCommand { + + /** + * Specifies the type: start, stop. + */ + public static enum OperationType { + /** start operation. */ + start, + /** stop operation. */ + stop; + } + + @Argument(index = 0, name = "operation", description = "Specifies the operation type [start | stop].", required = true) + private OperationType _operation; + + @Argument(index = 1, name = "application", description = "Specifies the name of the application containing the binding.", required = true) + private String _application; + + @Argument(index = 2, name = "service", description = "Specifies the name of the service containing the binding.", required = true) + private String _service; + + @Argument(index = 3, name = "binding", description = "Specifies the name of the binding.", required = true) + private String _binding; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Application application = switchYard.getApplication(QName.valueOf(_application)); + if (application == null) { + System.err.println("Could not locate application: " + _application); + return null; + } + final Binding binding; + final QName serviceName = QName.valueOf(_service); + final Service service = application.getService(serviceName); + if (service == null) { + final Reference reference = application.getReference(serviceName); + if (reference == null) { + System.err.println("Could not locate service or reference: " + _service); + return null; + } + binding = reference.getGateway(_binding); + } else { + binding = service.getGateway(_binding); + } + if (binding == null) { + System.err.println("Could not locate binding: " + _binding); + return null; + } + switch (_operation) { + case start: + binding.start(); + break; + case stop: + binding.stop(); + break; + + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/GetVersionCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/GetVersionCommand.java new file mode 100644 index 000000000..fc3523e53 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/GetVersionCommand.java @@ -0,0 +1,31 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import org.apache.felix.gogo.commands.Command; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for get-version. + */ +@Command(scope = "switchyard", name = "get-version", description = "Returns the version installed on the system.") +public class GetVersionCommand extends AbstractSwitchYardServiceCommand { + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + System.out.println("SwitchYard runtime version: " + switchYard.getVersion()); + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListApplicationsCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListApplicationsCommand.java new file mode 100644 index 000000000..75eb18355 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListApplicationsCommand.java @@ -0,0 +1,35 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import org.apache.felix.gogo.commands.Command; +import org.switchyard.admin.Application; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for list-applications. + */ +@Command(scope = "switchyard", name = "list-applications", description = "Returns a list of all SwitchYard applications deployed on the system.") +public class ListApplicationsCommand extends AbstractSwitchYardServiceCommand { + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + System.out.println(" SwitchYard Applications "); + for (Application application : switchYard.getApplications()) { + System.out.println(String.format("[ %s ]", application.getName())); + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListReferencesCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListReferencesCommand.java new file mode 100644 index 000000000..1582bb5ab --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListReferencesCommand.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.felix.gogo.commands.Argument; +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.Reference; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for list-references. + */ +@Command(scope = "switchyard", name = "list-references", description = "Returns a list of SwitchYard references used by application(s) deployed on the system.") +public class ListReferencesCommand extends AbstractSwitchYardServiceCommand { + + @Argument(index = 0, name = "application", description = "If specified, only service references for the named applications are returned.", multiValued = true) + private List _applicationNames; + + @Option(name = "--regex", description = "If specified, treat the application name(s) as a regular expression.") + private boolean _regex; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Pattern pattern = compilePattern(_applicationNames, _regex); + for (Application application : switchYard.getApplications()) { + final String applicationName = String.valueOf(application.getName()); + final Matcher matcher = pattern.matcher(applicationName); + if (matcher.find()) { + System.out.println(String.format(" SwitchYard References: %s ", applicationName)); + for (Reference reference : application.getReferences()) { + System.out.println(String.format("[ %s ]", reference.getName())); + } + } + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListServicesCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListServicesCommand.java new file mode 100644 index 000000000..c9d3b7f2c --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ListServicesCommand.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.felix.gogo.commands.Argument; +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for list-references. + */ +@Command(scope = "switchyard", name = "list-services", description = "Returns a list of SwitchYard services used by application(s) deployed on the system.") +public class ListServicesCommand extends AbstractSwitchYardServiceCommand { + + @Argument(index = 0, name = "application", description = "If specified, only services for the named application are returned.", multiValued = true) + private List _applicationNames; + + @Option(name = "--regex", description = "If specified, treat the application name(s) as a regular expression.") + private boolean _regex; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Pattern pattern = compilePattern(_applicationNames, _regex); + for (Application application : switchYard.getApplications()) { + final String applicationName = String.valueOf(application.getName()); + final Matcher matcher = pattern.matcher(applicationName); + if (matcher.find()) { + System.out.println(String.format(" SwitchYard References: %s ", applicationName)); + for (Service service : application.getServices()) { + System.out.println(String.format("[ %s ]", service.getName())); + } + } + } + return null; + } +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/NamespaceList.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/NamespaceList.java new file mode 100644 index 000000000..e0368cf9b --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/NamespaceList.java @@ -0,0 +1,101 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.felix.gogo.commands.Command; +import org.apache.karaf.shell.console.OsgiCommandSupport; +import org.osgi.framework.ServiceReference; +import org.switchyard.deploy.osgi.NamespaceHandler; + +/** + * Shell commands for namespaces. + */ +@Command(scope = "switchyard", name = "namespace-list", description = "List switchyard namespaces.") +public class NamespaceList extends OsgiCommandSupport { + + @Override + protected Object doExecute() throws Exception { + Collection> refs = + getBundleContext().getServiceReferences( + NamespaceHandler.class, "(" + NamespaceHandler.NAMESPACES + "=*)"); + if (refs != null) { + Set namespaces = new TreeSet(); + for (ServiceReference ref : refs) { + namespaces.addAll(getNamespaces(ref.getProperty(NamespaceHandler.NAMESPACES))); + } + for (URI namespace : namespaces) { + System.out.println(namespace.toString()); + } + } + return null; + } + + private static List getNamespaces(Object ns) { + if (ns == null) { + throw new IllegalArgumentException("NamespaceHandler service does not have an associated " + + NamespaceHandler.NAMESPACES + " property defined"); + } else if (ns instanceof URI[]) { + return Arrays.asList((URI[]) ns); + } else if (ns instanceof URI) { + return Collections.singletonList((URI) ns); + } else if (ns instanceof String) { + return Collections.singletonList(URI.create((String) ns)); + } else if (ns instanceof String[]) { + String[] strings = (String[]) ns; + List namespaces = new ArrayList(strings.length); + for (String string : strings) { + namespaces.add(URI.create(string)); + } + return namespaces; + } else if (ns instanceof Collection) { + Collection col = (Collection) ns; + List namespaces = new ArrayList(col.size()); + for (Object o : col) { + namespaces.add(toURI(o)); + } + return namespaces; + } else if (ns instanceof Object[]) { + Object[] array = (Object[]) ns; + List namespaces = new ArrayList(array.length); + for (Object o : array) { + namespaces.add(toURI(o)); + } + return namespaces; + } else { + throw new IllegalArgumentException("NamespaceHandler service has an associated " + + NamespaceHandler.NAMESPACES + " property defined which can not be converted to an array of URI"); + } + } + + private static URI toURI(Object o) { + if (o instanceof URI) { + return (URI) o; + } else if (o instanceof String) { + return URI.create((String) o); + } else { + throw new IllegalArgumentException("NamespaceHandler service has an associated " + + NamespaceHandler.NAMESPACES + " property defined which can not be converted to an array of URI"); + } + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/PrintUtil.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/PrintUtil.java new file mode 100644 index 000000000..78fa09ae2 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/PrintUtil.java @@ -0,0 +1,935 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.switchyard.admin.Application; +import org.switchyard.admin.Binding; +import org.switchyard.admin.ComponentReference; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.MessageMetrics; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.ServiceOperation; +import org.switchyard.admin.Throttling; +import org.switchyard.admin.Transformer; +import org.switchyard.admin.Validator; +import org.switchyard.config.model.switchyard.ArtifactModel; + +/** + * PrintUtil + * + * Utility class for creating text output for + * {@link org.switchyard.admin.SwitchYard} admin objects. + */ +final public class PrintUtil { + + private static final String INTERFACE = "interface"; + private static final String TYPE = "type"; + private static final String APPLICATION = "application"; + private static final String COMPONENT_SERVICES = "componentServices"; + private static final String CONFIGURATION = "configuration"; + private static final String FROM = "from"; + private static final String IMPLEMENTATION = "implementation"; + private static final String IMPLEMENTATION_CONFIGURATION = "implementationConfiguration"; + private static final String GATEWAYS = "gateways"; + private static final String OPERATIONS = "operations"; + private static final String PROPERTIES = "properties"; + private static final String PROMOTED_REFERENCE = "promotedReference"; + private static final String PROMOTED_SERVICE = "promotedService"; + private static final String REFERENCES = "references"; + private static final String SERVICES = "services"; + private static final String STATE = "state"; + private static final String THROTTLING = "throttling"; + private static final String TO = "to"; + private static final String TRANSFORMERS = "transformers"; + private static final String ARTIFACTS = "artifacts"; + private static final String URL = "url"; + private static final String VALIDATORS = "validators"; + private static final String SUCCESS_COUNT = "successCount"; + private static final String FAULT_COUNT = "faultCount"; + private static final String TOTAL_COUNT = "totalCount"; + private static final String AVERAGE_TIME = "averageTime"; + private static final String MIN_TIME = "minTime"; + private static final String MAX_TIME = "maxTime"; + private static final String TOTAL_TIME = "totalTime"; + private static final String ENABLED = "enabled"; + private static final String MAX_REQUESTS = "maxRequests"; + private static final String TIME_PERIOD = "timePeriod"; + + /** + * Creates output tree for the {@link Application}. The tree has the form:
+ *

+     *  "name" = [
+     *      "services" = [
+     *          "name" = [
+     *              "application" = "name"
+     *              "interface" = "interfaceName"
+     *              "promotedService" = "promotedServiceName"
+     *              "gateways" = [
+     *                  "name" = [
+     *                      "type" = "typeName"
+     *                      "configuration" = "<?binding.foo ..."
+     *                  ]
+     *                  ...
+     *              ]
+     *          ]
+     *          ...
+     *      ]
+     *      "references" = [
+     *          "name" = [
+     *              "application" = "name"
+     *              "interface" = "interfaceName"
+     *              "promotedReference" = "promotedReferenceName"
+     *              "gateways" = [
+     *                  "name" = [
+     *                      "type" = "typeName"
+     *                      "configuration" = "<?binding.foo ..."
+     *                  ]
+     *                  ...
+     *              ]
+     *          ]
+     *          ...
+     *      ]
+     *      "componentServices" = [
+     *          "name" = [
+     *              "application" = "name"
+     *              "interface" = "interfaceName"
+     *              "implementation" = "implementationTypeName"
+     *              "references" = [
+     *                  "name" = "interfaceName"
+     *                  ...
+     *              ]
+     *          ]
+     *          ...
+     *      ]
+     *      "transformers" = [
+     *          [
+     *              "from" = "fromType"
+     *              "to" = "toType"
+     *              "type" = "transformerType"
+     *          ]
+     *          ...
+     *      ]
+     *      "artifacts" = [
+     *          "name" = "urlType"
+     *          ...
+     *      ]
+     *      "validators" = [
+     *          "name" = "XML"
+     *      ]
+     *      "properties" = [
+     *          "key" = "value",
+     *      ]
+     *  ]
+     * 
+ * + * @param application the {@link Application} used to populate the node. + * @return text + */ + public static String printApplication(Application application) { + final StringBuffer applicationNode = new StringBuffer(); + int indentLevel = 0; + applicationNode.append(indent(indentLevel)).append(application.getName()).append(" = [\n"); + + ++indentLevel; + + applicationNode.append(indent(indentLevel)).append(SERVICES).append(" = [\n"); + ++indentLevel; + for (Service service : application.getServices()) { + applicationNode.append(printService(service, indentLevel)); + } + --indentLevel; + applicationNode.append(indent(indentLevel)).append("]\n"); + + applicationNode.append(indent(indentLevel)).append(REFERENCES).append(" = [\n"); + ++indentLevel; + for (Reference reference : application.getReferences()) { + applicationNode.append(printReference(reference, indentLevel)); + } + --indentLevel; + applicationNode.append(indent(indentLevel)).append("]\n"); + + applicationNode.append(indent(indentLevel)).append(COMPONENT_SERVICES).append(" = [\n"); + ++indentLevel; + for (ComponentService componentService : application.getComponentServices()) { + applicationNode.append(printComopnentService(componentService, indentLevel)); + } + --indentLevel; + applicationNode.append(indent(indentLevel)).append("]\n"); + + applicationNode.append(indent(indentLevel)).append(TRANSFORMERS).append(" = [\n"); + ++indentLevel; + for (Transformer transformer : application.getTransformers()) { + applicationNode.append(indent(indentLevel)).append("[\n"); + ++indentLevel; + applicationNode.append(printTransformer(transformer, indentLevel)); + --indentLevel; + applicationNode.append(indent(indentLevel)).append("]\n"); + } + + if (application.getConfig().getArtifacts() != null) { + applicationNode.append(indent(indentLevel)).append(ARTIFACTS).append(" = [\n"); + ++indentLevel; + for (ArtifactModel artifact : application.getConfig().getArtifacts().getArtifacts()) { + applicationNode.append(printArtifact(artifact, indentLevel)); + } + --indentLevel; + applicationNode.append(indent(indentLevel)).append("]\n"); + } + + if (application.getValidators() != null) { + applicationNode.append(indent(indentLevel)).append(VALIDATORS).append(" = [\n"); + ++indentLevel; + for (Validator validator : application.getValidators()) { + applicationNode.append(printValidator(validator, indentLevel)); + } + --indentLevel; + applicationNode.append(indent(indentLevel)).append("]\n"); + } + + if (application.getProperties() != null) { + applicationNode.append(indent(indentLevel)).append(PROPERTIES).append(" = [\n"); + ++indentLevel; + for (Map.Entry property : application.getProperties().entrySet()) { + applicationNode.append(indent(indentLevel)).append(property.getKey()).append(" = ") + .append(property.getValue()); + applicationNode.append("\n"); + } + --indentLevel; + applicationNode.append(indent(indentLevel)).append("]\n"); + } + + --indentLevel; + applicationNode.append(indent(indentLevel)).append("]\n"); + + return applicationNode.toString(); + } + + /** + * Creates text tree from the {@link Reference}. The tree has the form:
+ *
+     *  "name" = [
+     *      "application" = "name"
+     *      "interface" = "interfaceName"
+     *      "promotedReference" = "promotedReferenceName"
+     *      "gateways" = [
+     *          name = [
+     *              "type" = "typeName"
+     *              "configuration" = "<?binding.foo ..."
+     *          ]
+     *          ...
+     *      ]
+     *  ]
+     * 
+ * + * @param reference the {@link Reference} used to populate the node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printReference(Reference reference, int indentLevel) { + final StringBuffer referenceNode = new StringBuffer(); + + referenceNode.append(indent(indentLevel)).append(reference.getName().toString()).append(" = [\n"); + + ++indentLevel; + + referenceNode.append(indent(indentLevel)).append(APPLICATION).append(" = ") + .append(reference.getApplication().getName().toString()); + referenceNode.append("\n"); + + String interfaceName = reference.getInterface(); + if (interfaceName != null) { + referenceNode.append(indent(indentLevel)).append(INTERFACE).append(" = ").append(interfaceName); + referenceNode.append("\n"); + } + + String promotedReference = reference.getPromotedReference(); + if (promotedReference != null) { + referenceNode.append(indent(indentLevel)).append(PROMOTED_REFERENCE).append(" = ") + .append(promotedReference); + referenceNode.append("\n"); + } + + referenceNode.append(indent(indentLevel)).append(GATEWAYS).append(" = [\n"); + ++indentLevel; + for (Binding gateway : reference.getGateways()) { + referenceNode.append(createGateway(gateway, indentLevel)); + } + --indentLevel; + referenceNode.append(indent(indentLevel)).append("]\n"); + + --indentLevel; + referenceNode.append(indent(indentLevel)).append("]\n"); + + return referenceNode.toString(); + } + + /** + * Creates text tree from the {@link Service}. The tree has the form:
+ *
+     *  "name" = [
+     *      "application" = "name"
+     *      "interface" = "interfaceName"
+     *      "promotedService" = "promotedServiceName"
+     *      "gateways" = [
+     *          name = [
+     *              "type" = "typeName"
+     *              "configuration" = "<?binding.foo ..."
+     *          ]
+     *          ...
+     *      ]
+     *      "throttling" = [
+     *          "enabled" = "true"
+     *          "maxRequests" = "maxRequests"
+     *          "timePeriod" = "timePeriod"
+     *      ]
+     *  ]
+     * 
+ * + * @param service the {@link Service} used to populate the node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printService(Service service, int indentLevel) { + final StringBuffer serviceNode = new StringBuffer(); + + serviceNode.append(indent(indentLevel)).append(service.getName()).append(" = [\n"); + + ++indentLevel; + + serviceNode.append(indent(indentLevel)).append(APPLICATION).append(" = ") + .append(service.getApplication().getName().toString()); + serviceNode.append("\n"); + + String interfaceName = service.getInterface(); + if (interfaceName != null) { + serviceNode.append(indent(indentLevel)).append(INTERFACE).append(" = ").append(interfaceName); + serviceNode.append("\n"); + } + + ComponentService promotedService = service.getPromotedService(); + if (promotedService != null) { + serviceNode.append(indent(indentLevel)).append(PROMOTED_SERVICE).append(" = ") + .append(promotedService.getName().toString()); + serviceNode.append("\n"); + } + + serviceNode.append(indent(indentLevel)).append(GATEWAYS).append(" = [\n"); + ++indentLevel; + for (Binding gateway : service.getGateways()) { + serviceNode.append(createGateway(gateway, indentLevel)); + } + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + serviceNode.append(printThrottlingTo(service.getThrottling(), indentLevel)); + + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + return serviceNode.toString(); + } + + /** + * Creates text tree from the {@link ComponentService}. The tree has the + * form:
+ *
+     *  "name" = [
+     *      "application" = "name"
+     *      "interface" = "interfaceName"
+     *      "implementation" = "implementationTypeName"
+     *      "references" = [
+     *          "name" = [
+     *              "interface" = "interfaceName"
+     *          ]
+     *          ...
+     *      ]
+     *  ]
+     * 
+ * + * @param service the {@link ComponentService} used to populate the node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printComopnentService(ComponentService service, int indentLevel) { + final StringBuffer serviceNode = new StringBuffer(); + + serviceNode.append(indent(indentLevel)).append(service.getName()).append(" = [\n"); + + ++indentLevel; + + serviceNode.append(indent(indentLevel)).append(APPLICATION).append(" = ") + .append(service.getApplication().getName().toString()); + serviceNode.append("\n"); + + String interfaceName = service.getInterface(); + if (interfaceName != null) { + serviceNode.append(indent(indentLevel)).append(INTERFACE).append(" = ").append(interfaceName); + serviceNode.append("\n"); + } + + String implementation = service.getImplementation(); + if (implementation != null) { + serviceNode.append(indent(indentLevel)).append(IMPLEMENTATION).append(" = ").append(implementation); + serviceNode.append("\n"); + } + + String implementationConfiguration = service.getImplementationConfiguration(); + if (implementationConfiguration != null) { + serviceNode.append(indent(indentLevel)).append(IMPLEMENTATION_CONFIGURATION).append(" = ") + .append(implementationConfiguration); + serviceNode.append("\n"); + } + + serviceNode.append(indent(indentLevel)).append(REFERENCES).append(" = [\n"); + ++indentLevel; + for (ComponentReference reference : service.getReferences()) { + serviceNode.append(printComponentReference(reference, indentLevel)); + } + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + return serviceNode.toString(); + } + + /** + * Creates text tree from the {@link Service}. The tree has the form:
+ *
+     *  "name" = [
+     *      "type" = "typeName"
+     *      "configuration" = "<?binding.foo ..."
+     *      "state" = "STARTED"
+     *  ]
+     * 
+ * + * @param binding the {@link Binding} used to populate the node. + * @param indentLevel the beginning indentLevel + * @return text + */ + public static String createGateway(Binding binding, int indentLevel) { + StringBuffer gatewayNode = new StringBuffer(); + + gatewayNode.append(indent(indentLevel)).append(binding.getName()).append(" = [\n"); + + ++indentLevel; + + if (binding.getType() != null) { + gatewayNode.append(indent(indentLevel)).append(TYPE).append(" = ").append(binding.getType()); + gatewayNode.append("\n"); + } + + if (binding.getConfiguration() != null) { + gatewayNode.append(indent(indentLevel)).append(CONFIGURATION).append(" = ") + .append(binding.getConfiguration()); + gatewayNode.append("\n"); + } + + gatewayNode.append(indent(indentLevel)).append(STATE).append(" = ").append(binding.getState().toString()); + gatewayNode.append("\n"); + + --indentLevel; + gatewayNode.append(indent(indentLevel)).append("]\n"); + + return gatewayNode.toString(); + } + + /** + * Creates text tree from the {@link ComponentReference}. The tree has the + * form:
+ *
+     *  "name" = [
+     *      "interface" = "interfaceName"
+     *  ]
+     * 
+ * + * @param reference the {@link ComponentReference} used to populate the + * node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printComponentReference(ComponentReference reference, int indentLevel) { + final StringBuffer referenceNode = new StringBuffer(); + + referenceNode.append(indent(indentLevel)).append(reference.getName().toString()).append(" = [\n"); + + ++indentLevel; + referenceNode.append(indent(indentLevel)).append(INTERFACE).append(" = ").append(reference.getInterface()) + .append("\n"); + + --indentLevel; + referenceNode.append(indent(indentLevel)).append("]\n"); + + return referenceNode.toString(); + } + + /** + * Creates text tree from the {@link Transformer}. The tree has the form:
+ *
+     *      "from" = "fromType",
+     *      "to" = "toType",
+     *      "type" = "transformerType",
+     * 
+ * + * @param transformation the {@link Transformer} used to populate the node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printTransformer(Transformer transformation, int indentLevel) { + final StringBuffer transformationNode = new StringBuffer(); + + if (transformation.getFrom() != null) { + transformationNode.append(indent(indentLevel)).append(FROM).append(" = ") + .append(transformation.getFrom().toString()); + transformationNode.append("\n"); + } + + if (transformation.getTo() != null) { + transformationNode.append(indent(indentLevel)).append(TO).append(" = ") + .append(transformation.getTo().toString()); + transformationNode.append("\n"); + } + + if (transformation.getType() != null) { + transformationNode.append(indent(indentLevel)).append(TYPE).append(" = ").append(transformation.getType()); + transformationNode.append("\n"); + } + + return transformationNode.toString(); + } + + /** + * Creates text tree from the {@link ArtifactModel}. The tree has the form:
+ *
+     *  "name" = [
+     *      "url" = "urlType"
+     *  ]
+     * 
+ * + * @param artifact the {@link ArtifactModel} used to populate the node. + * @param indentLevel the beginning indent level; + * @return text + */ + public static String printArtifact(ArtifactModel artifact, int indentLevel) { + final StringBuffer artifactNode = new StringBuffer(); + artifactNode.append(indent(indentLevel)).append(artifact.getName()).append(" = [\n"); + + ++indentLevel; + artifactNode.append(indent(indentLevel)).append(URL).append(" = ").append(artifact.getURL()).append("\n"); + --indentLevel; + + artifactNode.append("]\n"); + + return artifactNode.toString(); + } + + /** + * Creates text tree from the validtors. The tree has the form:
+ *
+     *  "name" = [
+     *      "type" = "XML"
+     *  ]
+     * 
+ * + * @param validator the {@link Validator} used to populate the node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printValidator(Validator validator, int indentLevel) { + final StringBuffer validatorNode = new StringBuffer(); + validatorNode.append(indent(indentLevel)).append(validator.getName().toString()).append(" = [\n"); + + ++indentLevel; + validatorNode.append(indent(indentLevel)).append(TYPE).append(" = ").append(validator.getType()).append("\n"); + --indentLevel; + + validatorNode.append(indent(indentLevel)).append("]\n"); + + return validatorNode.toString(); + } + + /** + * Adds metrics to an existing node from the {@link MessageMetrics}. The + * tree has the form:
+ *
+     *      "successCount" = "successCount",
+     *      "faultCount" = "faultCount",
+     *      "totalCount" = "totalCount",
+     *      "averageTime" = "averageTime",
+     *      "minTime" = "minTime",
+     *      "maxTime" = "maxTime",
+     *      "totalTime" = "totalTime"
+     * 
+ * + * @param metrics the metrics to add to the node + * @param indentLevel the indent level + * @return text + */ + public static String addMetricsToNode(MessageMetrics metrics, int indentLevel) { + final StringBuffer metricsNode = new StringBuffer(); + metricsNode.append(indent(indentLevel)).append(SUCCESS_COUNT).append(" = ").append(metrics.getSuccessCount()) + .append("\n"); + metricsNode.append(indent(indentLevel)).append(FAULT_COUNT).append(" = ").append(metrics.getFaultCount()) + .append("\n"); + metricsNode.append(indent(indentLevel)).append(TOTAL_COUNT).append(" = ").append(metrics.getTotalCount()) + .append("\n"); + metricsNode.append(indent(indentLevel)).append(AVERAGE_TIME).append(" = ") + .append(BigDecimal.valueOf(metrics.getAverageProcessingTime())).append("\n"); + metricsNode.append(indent(indentLevel)).append(MIN_TIME).append(" = ").append(metrics.getMinProcessingTime()) + .append("\n"); + metricsNode.append(indent(indentLevel)).append(MAX_TIME).append(" = ").append(metrics.getMaxProcessingTime()) + .append("\n"); + metricsNode.append(indent(indentLevel)).append(TOTAL_TIME).append(" = ") + .append(metrics.getTotalProcessingTime()).append("\n"); + + return metricsNode.toString(); + } + + /** + * Creates text tree from the {@link Reference} for metrics. The tree has + * the form:
+ *
+     *  "name" = [
+     *      "successCount" = "successCount"
+     *      "faultCount" = "faultCount"
+     *      "totalCount" = "totalCount"
+     *      "averageTime" = "averageTime"
+     *      "minTime" = "minTime"
+     *      "maxTime" = "maxTime"
+     *      "totalTime" = "totalTime"
+     *      "gateways" = [
+     *          "name" = [
+     *              "type" = "bindingType",
+     *               "successCount" = "successCount",
+     *               "faultCount" = "faultCount",
+     *               "totalCount" = "totalCount",
+     *               "averageTime" = "averageTime",
+     *               "minTime" = "minTime",
+     *               "maxTime" = "maxTime",
+     *               "totalTime" = "totalTime",
+     *          ]
+     *          ...
+     *      ]
+     *      "operations" = [
+     *          "name" = [
+     *               "successCount" = "successCount"
+     *               "faultCount" = "faultCount"
+     *               "totalCount" = "totalCount"
+     *               "averageTime" = "averageTime"
+     *               "minTime" = "minTime"
+     *               "maxTime" = "maxTime"
+     *               "totalTime" = "totalTime"
+     *          ]
+     *          ...
+     *      ]
+     *  ]
+     * 
+ * + * @param reference the {@link Reference} used to populate the node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printReferenceMetrics(Reference reference, int indentLevel) { + final StringBuffer referenceNode = new StringBuffer(); + + referenceNode.append(indent(indentLevel)).append(reference.getName().toString()).append(" = [\n"); + + ++indentLevel; + + referenceNode.append(addMetricsToNode(reference.getMessageMetrics(), indentLevel)); + + referenceNode.append(indent(indentLevel)).append(GATEWAYS).append(" = [\n"); + ++indentLevel; + for (Binding gateway : reference.getGateways()) { + referenceNode.append(indent(indentLevel)).append(gateway.getName()).append(" = [\n"); + ++indentLevel; + referenceNode.append(indent(indentLevel)).append(TYPE).append(" = ").append(gateway.getType()).append("\n"); + referenceNode.append(addMetricsToNode(gateway.getMessageMetrics(), indentLevel)); + --indentLevel; + referenceNode.append(indent(indentLevel)).append("]\n"); + } + --indentLevel; + referenceNode.append(indent(indentLevel)).append("]\n"); + + referenceNode.append(indent(indentLevel)).append(OPERATIONS).append(" = [\n"); + ++indentLevel; + for (ServiceOperation operation : reference.getServiceOperations()) { + referenceNode.append(indent(indentLevel)).append(operation.getName()).append(" = [\n"); + ++indentLevel; + referenceNode.append(addMetricsToNode(operation.getMessageMetrics(), indentLevel)); + --indentLevel; + referenceNode.append(indent(indentLevel)).append("]\n"); + } + --indentLevel; + referenceNode.append(indent(indentLevel)).append("]\n"); + + --indentLevel; + referenceNode.append(indent(indentLevel)).append("]\n"); + + return referenceNode.toString(); + } + + /** + * Creates text tree from the {@link Service} for metrics. The tree has the + * form:
+ *
+     *  "name" = [
+     *      "successCount" = "successCount"
+     *      "faultCount" = "faultCount"
+     *      "totalCount" = "totalCount"
+     *      "averageTime" = "averageTime"
+     *      "minTime" = "minTime"
+     *      "maxTime" = "maxTime"
+     *      "totalTime" = "totalTime"
+     *      "operations" = [
+     *          "name" = [
+     *               "successCount" = "successCount"
+     *               "faultCount" = "faultCount"
+     *               "totalCount" = "totalCount"
+     *               "averageTime" = "averageTime"
+     *               "minTime" = "minTime"
+     *               "maxTime" = "maxTime"
+     *               "totalTime" = "totalTime"
+     *          ]
+     *          ...
+     *      ]
+     *      "references" = [
+     *          "name" = [
+     *               "successCount" = "successCount"
+     *               "faultCount" = "faultCount"
+     *               "totalCount" = "totalCount"
+     *               "averageTime" = "averageTime"
+     *               "minTime" = "minTime"
+     *               "maxTime" = "maxTime"
+     *               "totalTime" = "totalTime"
+     *          ]
+     *          ...
+     *      ]
+     *      "gateways" = [
+     *          "name" = [
+     *              "type" = "bindingType"
+     *               "successCount" = "successCount"
+     *               "faultCount" = "faultCount"
+     *               "totalCount" = "totalCount"
+     *               "averageTime" = "averageTime"
+     *               "minTime" = "minTime"
+     *               "maxTime" = "maxTime"
+     *               "totalTime" = "totalTime"
+     *          ]
+     *          ...
+     *      ]
+     * 
+ * + * @param service the {@link Service} used to populate the node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printServiceMetrics(Service service, int indentLevel) { + final StringBuffer serviceNode = new StringBuffer(); + + serviceNode.append(indent(indentLevel)).append(service.getName().toString()).append(" = [\n"); + + ++indentLevel; + + serviceNode.append(addMetricsToNode(service.getMessageMetrics(), indentLevel)); + + serviceNode.append(indent(indentLevel)).append(OPERATIONS).append(" = [\n"); + ++indentLevel; + for (ServiceOperation operation : service.getPromotedService().getServiceOperations()) { + serviceNode.append(indent(indentLevel)).append(operation.getName()).append(" = [\n"); + ++indentLevel; + serviceNode.append(addMetricsToNode(operation.getMessageMetrics(), indentLevel)); + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + } + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + serviceNode.append(indent(indentLevel)).append(REFERENCES).append(" = [\n"); + ++indentLevel; + for (ComponentReference reference : service.getPromotedService().getReferences()) { + serviceNode.append(indent(indentLevel)).append(reference.getName()).append(" = [\n"); + ++indentLevel; + serviceNode.append(addMetricsToNode(reference.getMessageMetrics(), indentLevel)); + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + } + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + serviceNode.append(indent(indentLevel)).append(GATEWAYS).append(" = [\n"); + ++indentLevel; + for (Binding gateway : service.getGateways()) { + serviceNode.append(indent(indentLevel)).append(gateway.getName()).append(" = [\n"); + ++indentLevel; + serviceNode.append(indent(indentLevel)).append(TYPE).append(" = ").append(gateway.getType()).append("\n"); + serviceNode.append(addMetricsToNode(gateway.getMessageMetrics(), indentLevel)); + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + } + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + return serviceNode.toString(); + } + + /** + * Creates text tree from the {@link ComponentService} for metrics. The tree + * has the form:
+ *
+     *      "name" = "serviceName",
+     *      "application" = "name",
+     *      "successCount" = "successCount",
+     *      "faultCount" = "faultCount",
+     *      "totalCount" = "totalCount",
+     *      "averageTime" = "averageTime",
+     *      "minTime" = "minTime",
+     *      "maxTime" = "maxTime",
+     *      "totalTime" = "totalTime",
+     *      "operations" = [
+     *          {
+     *              "name" = "operationName",
+     *               "successCount" = "successCount",
+     *               "faultCount" = "faultCount",
+     *               "totalCount" = "totalCount",
+     *               "averageTime" = "averageTime",
+     *               "minTime" = "minTime",
+     *               "maxTime" = "maxTime",
+     *               "totalTime" = "totalTime",
+     *          },
+     *          ...
+     *      ],
+     *      "references" = [
+     *          {
+     *              "name" = "referenceName",
+     *               "successCount" = "successCount",
+     *               "faultCount" = "faultCount",
+     *               "totalCount" = "totalCount",
+     *               "averageTime" = "averageTime",
+     *               "minTime" = "minTime",
+     *               "maxTime" = "maxTime",
+     *               "totalTime" = "totalTime",
+     *          },
+     *          ...
+     *      ]
+     * 
+ * + * @param componentService the {@link Service} used to populate the node. + * @param indentLevel the beginning indent level + * @return text + */ + public static String printComponentServiceMetrics(ComponentService componentService, int indentLevel) { + final StringBuffer serviceNode = new StringBuffer(); + + serviceNode.append(indent(indentLevel)).append(componentService.getName().toString()).append(" = [\n"); + + ++indentLevel; + + serviceNode.append(addMetricsToNode(componentService.getMessageMetrics(), indentLevel)); + + serviceNode.append(indent(indentLevel)).append(OPERATIONS).append(" = [\n"); + ++indentLevel; + for (ServiceOperation operation : componentService.getServiceOperations()) { + serviceNode.append(indent(indentLevel)).append(operation.getName()).append(" = [\n"); + ++indentLevel; + serviceNode.append(addMetricsToNode(operation.getMessageMetrics(), indentLevel)); + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + } + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + serviceNode.append(indent(indentLevel)).append(REFERENCES).append(" = [\n"); + ++indentLevel; + for (ComponentReference reference : componentService.getReferences()) { + serviceNode.append(indent(indentLevel)).append(reference.getName()).append(" = [\n"); + ++indentLevel; + serviceNode.append(addMetricsToNode(reference.getMessageMetrics(), indentLevel)); + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + } + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + --indentLevel; + serviceNode.append(indent(indentLevel)).append("]\n"); + + return serviceNode.toString(); + } + + /** + * Creates a new node from the {@link Throttling}. The tree has the form:
+ *
+     *      "throttling" = [
+     *          "enabled" = "true"
+     *          "maxRequests" = "maxRequests"
+     *          "timePeriod" = "timePeriod"
+     *      ]
+     * 
+ * + * @param throttling the throttling configuration to add to the node + * @param indentLevel the beginning indent level + * @return text + */ + public static String printThrottlingTo(Throttling throttling, int indentLevel) { + if (throttling == null) { + return ""; + } + final StringBuffer throttlingNode = new StringBuffer(); + + throttlingNode.append(indent(indentLevel)).append(THROTTLING).append(" = [\n"); + + ++indentLevel; + + throttlingNode.append(indent(indentLevel)).append(ENABLED).append(" = ").append(throttling.isEnabled()) + .append("\n"); + throttlingNode.append(indent(indentLevel)).append(MAX_REQUESTS).append(" = ") + .append(throttling.getMaxRequests()).append("\n"); + throttlingNode.append(indent(indentLevel)).append(TIME_PERIOD).append(" = ").append(throttling.getTimePeriod()) + .append("\n"); + + --indentLevel; + + throttlingNode.append(indent(indentLevel)).append("]\n"); + + return throttlingNode.toString(); + } + + private static final List INDENT = new ArrayList(); + + private static synchronized String indent(int indentLevel) { + while (INDENT.size() <= indentLevel) { + final StringBuffer indent = new StringBuffer(); + for (int i = 0, size = 4 * INDENT.size(); i <= size; ++i) { + indent.append(' '); + } + INDENT.add(indent.toString()); + } + return INDENT.get(indentLevel); + } + + private PrintUtil() { + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadApplicationCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadApplicationCommand.java new file mode 100644 index 000000000..6999750b3 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadApplicationCommand.java @@ -0,0 +1,50 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.felix.gogo.commands.Argument; +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for read-application. + */ +@Command(scope = "switchyard", name = "read-application", description = "Returns a details about a SwitchYard application deployed on the system.") +public class ReadApplicationCommand extends AbstractSwitchYardServiceCommand { + + @Argument(index = 0, name = "name", description = "If specified, only details for the named application are returned.", multiValued = true) + private List _applicationNames; + + @Option(name = "--regex", description = "If specified, treat the application name(s) as a regular expression.") + private boolean _regex; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Pattern pattern = compilePattern(_applicationNames, _regex); + for (Application application : switchYard.getApplications()) { + final String applicationName = String.valueOf(application.getName()); + final Matcher matcher = pattern.matcher(applicationName); + if (matcher.find()) { + System.out.println(PrintUtil.printApplication(application)); + } + } + return null; + } +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadReferenceCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadReferenceCommand.java new file mode 100644 index 000000000..8a1d88e92 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadReferenceCommand.java @@ -0,0 +1,62 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.Reference; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for read-references. + */ +@Command(scope = "switchyard", name = "read-reference", description = "Returns a details about a SwitchYard reference deployed on the system.") +public class ReadReferenceCommand extends AbstractSwitchYardServiceCommand { + + @Option(name = "--application", aliases = "-a", description = "If specified, only details for the named application are returned.", multiValued = true) + private List _applicationNames; + @Option(name = "--reference", aliases = "-r", description = "If specified, only details for the named reference are returned.", multiValued = true) + private List _referenceNames; + @Option(name = "--regex", description = "If specified, treat the name(s) as a regular expression.") + private boolean _regex; + + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Pattern applicationPattern = compilePattern(_applicationNames, _regex); + final Pattern referencePattern = compilePattern(_referenceNames, _regex); + for (Application application : switchYard.getApplications()) { + final String applicationName = application.getName().toString(); + final Matcher applicationMatcher = applicationPattern.matcher(applicationName); + if (applicationMatcher.find()) { + System.out.println(application.getName() + " = ["); + for (Reference reference : application.getReferences()) { + final String referenceName = reference.getName().toString(); + final Matcher referenceMatcher = referencePattern.matcher(referenceName); + if (referenceMatcher.find()) { + System.out.println(PrintUtil.printReference(reference, 1)); + } + } + System.out.println("]"); + } + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadServiceCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadServiceCommand.java new file mode 100644 index 000000000..09ebff824 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReadServiceCommand.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for list-service. + */ +@Command(scope = "switchyard", name = "read-service", description = "Returns a details about a SwitchYard service deployed on the system.") +public class ReadServiceCommand extends AbstractSwitchYardServiceCommand { + + @Option(name = "--application", aliases = "-a", description = "If specified, only details for the named application are returned.", multiValued = true) + private List _applicationNames; + @Option(name = "--service", aliases = "-s", description = "If specified, only details for the named service are returned.", multiValued = true) + private List _serviceNames; + @Option(name = "--regex", description = "If specified, treat the name(s) as a regular expression.") + private boolean _regex; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Pattern applicationPattern = compilePattern(_applicationNames, _regex); + final Pattern servicePattern = compilePattern(_serviceNames, _regex); + for (Application application : switchYard.getApplications()) { + final String applicationName = application.getName().toString(); + final Matcher applicationMatcher = applicationPattern.matcher(applicationName); + if (applicationMatcher.find()) { + System.out.println(application.getName() + " = ["); + for (Service service : application.getServices()) { + final String serviceName = service.getName().toString(); + final Matcher serviceMatcher = servicePattern.matcher(serviceName); + if (serviceMatcher.find()) { + System.out.println(PrintUtil.printService(service, 1)); + } + } + System.out.println("]"); + } + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReferenceNameCompleter.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReferenceNameCompleter.java new file mode 100644 index 000000000..c00d39293 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ReferenceNameCompleter.java @@ -0,0 +1,137 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.felix.service.command.CommandSession; +import org.apache.karaf.shell.console.Completer; +import org.apache.karaf.shell.console.completer.ArgumentCompleter; +import org.apache.karaf.shell.console.completer.StringsCompleter; +import org.apache.karaf.shell.console.jline.CommandSessionHolder; +import org.switchyard.admin.Application; +import org.switchyard.admin.Reference; +import org.switchyard.admin.SwitchYard; + +/** + * Generates completion set for Application arguments. + */ +public class ReferenceNameCompleter implements Completer { + + private SwitchYard _switchYard; + private Integer _applicationArgumentIndex; + private String[] _applicationOptions; + + @Override + public int complete(String buffer, int cursor, List candidates) { + final StringsCompleter delegate = new StringsCompleter(); + final Pattern applicationNamePattern = getApplicationNamePattern(); + final List applications = _switchYard.getApplications(); + for (Application application : applications) { + if (applicationNamePattern.matcher(application.getName().toString()).find()) { + for (Reference reference : application.getReferences()) { + delegate.getStrings().add(reference.getName().toString()); + } + } + } + return delegate.complete(buffer, cursor, candidates); + } + + /** + * @param switchYard the SwitchYard admin service + */ + public void setSwitchYard(SwitchYard switchYard) { + _switchYard = switchYard; + } + + /** + * @param applicationArgumentIndex the index for the application argument + */ + public void setApplicationArgumentIndex(Integer applicationArgumentIndex) { + _applicationArgumentIndex = applicationArgumentIndex; + } + + /** + * @param applicationOptions option strings for application name + */ + public void setApplicationOptions(String[] applicationOptions) { + _applicationOptions = applicationOptions; + } + + private Pattern getApplicationNamePattern() { + final CommandSession session = CommandSessionHolder.getSession(); + if (session == null) { + return compilePattern(null, false); + } + final ArgumentCompleter.ArgumentList argList = (ArgumentCompleter.ArgumentList) session + .get(ArgumentCompleter.ARGUMENTS_LIST); + if (argList == null || argList.getArguments() == null || argList.getArguments().length == 0) { + return compilePattern(null, false); + } + final List arguments = Arrays.asList(argList.getArguments()); + boolean isRegex = arguments.indexOf("--regex") > 0; + if (_applicationArgumentIndex == null) { + if (_applicationOptions == null || _applicationOptions.length == 0) { + return compilePattern(null, false); + } + for (String option : _applicationOptions) { + final int index = arguments.indexOf(option); + if (index >= 0) { + if (arguments.size() - 1 > index) { + // XXX: do we need to worry about commas delimiting a + // list? + return compilePattern(Collections.singletonList(arguments.get(index + 1)), isRegex); + } + } + } + } else { + int argumentOffset = 1; // command is first argument + for (int index = 0, count = arguments.size(); index < count; ++index) { + if (arguments.get(index).startsWith("-")) { + argumentOffset = index; + } + } + // XXX: assuming the last option does not accept a value here + if (_applicationArgumentIndex + argumentOffset < arguments.size()) { + return compilePattern( + Collections.singletonList(arguments.get(_applicationArgumentIndex + argumentOffset)), isRegex); + } + } + return compilePattern(null, false); + } + + private Pattern compilePattern(List patterns, boolean isRegex) { + if (patterns == null || patterns.size() == 0) { + patterns = Collections.singletonList(".*"); + isRegex = true; + } + final StringBuffer regex = new StringBuffer(); + for (String name : patterns) { + if (!isRegex) { + regex.append("\\Q"); + } + regex.append(name); + if (!isRegex) { + regex.append("\\E"); + } + regex.append('|'); + } + regex.deleteCharAt(regex.length() - 1); + return Pattern.compile(regex.toString()); + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ResetMetricsCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ResetMetricsCommand.java new file mode 100644 index 000000000..41d6ecab3 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ResetMetricsCommand.java @@ -0,0 +1,110 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.felix.gogo.commands.Argument; +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for uses-artifact. + */ +@Command(scope = "switchyard", name = "reset-metrics", description = "Reset metrics for the specified service/reference/application service.") +public class ResetMetricsCommand extends AbstractSwitchYardServiceCommand { + + /** + * Specifies the type: services, references, application or all. + */ + public static enum SearchType { + /** service metrics. */ + service() { + @Override + public void resetMetrics(Pattern pattern, SwitchYard switchYard) { + for (Service service : switchYard.getServices()) { + if (pattern.matcher(service.getName().toString()).find()) { + service.resetMessageMetrics(); + } + } + } + }, + /** reference metrics. */ + reference() { + @Override + public void resetMetrics(Pattern pattern, SwitchYard switchYard) { + for (Reference reference : switchYard.getReferences()) { + if (pattern.matcher(reference.getName().toString()).find()) { + reference.resetMessageMetrics(); + } + } + } + }, + /** application metrics. */ + application() { + @Override + public void resetMetrics(Pattern pattern, SwitchYard switchYard) { + for (Application application : switchYard.getApplications()) { + if (pattern.matcher(application.getName().toString()).find()) { + for (Service service : application.getServices()) { + service.resetMessageMetrics(); + } + for (Reference reference : application.getReferences()) { + reference.resetMessageMetrics(); + } + for (ComponentService service : application.getComponentServices()) { + service.resetMessageMetrics(); + } + } + } + } + }, + /** all metrics. */ + all() { + @Override + public void resetMetrics(Pattern pattern, SwitchYard switchYard) { + switchYard.resetMessageMetrics(); + } + }; + + /** + * @param pattern the pattern + * @param switchYard the SwitchYard admin service + */ + public abstract void resetMetrics(Pattern pattern, SwitchYard switchYard); + } + + @Argument(index = 0, name = "type", description = "Specifies the type [service | reference | application | all] of metrics to reset.", required = true) + private SearchType _type; + + @Argument(index = 1, name = "patterns", description = "Specifies the search pattern to use.", multiValued = true) + private List _patterns; + + @Option(name = "--regex", description = "If specified, treat the pattern(s) as a regular expression.") + private boolean _regex; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Pattern pattern = compilePattern(_patterns, _regex); + _type.resetMetrics(pattern, switchYard); + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ResetMetricsPatternCompleter.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ResetMetricsPatternCompleter.java new file mode 100644 index 000000000..277762774 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ResetMetricsPatternCompleter.java @@ -0,0 +1,92 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.Arrays; +import java.util.List; + +import org.apache.felix.service.command.CommandSession; +import org.apache.karaf.shell.console.Completer; +import org.apache.karaf.shell.console.completer.ArgumentCompleter; +import org.apache.karaf.shell.console.completer.StringsCompleter; +import org.apache.karaf.shell.console.jline.CommandSessionHolder; +import org.switchyard.admin.Application; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Generates completion set for Application arguments. + */ +public class ResetMetricsPatternCompleter implements Completer { + + private SwitchYard _switchYard; + + @Override + public int complete(String buffer, int cursor, List candidates) { + final StringsCompleter delegate = new StringsCompleter(); + final ResetMetricsCommand.SearchType type = getType(); + switch (type) { + case application: + for (Application application : _switchYard.getApplications()) { + delegate.getStrings().add(application.getName().toString()); + } + break; + case service: + for (Service service : _switchYard.getServices()) { + delegate.getStrings().add(service.getName().toString()); + } + break; + case reference: + for (Reference reference : _switchYard.getReferences()) { + delegate.getStrings().add(reference.getName().toString()); + } + break; + default: + break; + } + return delegate.complete(buffer, cursor, candidates); + } + + /** + * @param switchYard the SwitchYard admin service + */ + public void setSwitchYard(SwitchYard switchYard) { + _switchYard = switchYard; + } + + private ResetMetricsCommand.SearchType getType() { + final CommandSession session = CommandSessionHolder.getSession(); + if (session == null) { + return null; + } + final ArgumentCompleter.ArgumentList argList = (ArgumentCompleter.ArgumentList) session + .get(ArgumentCompleter.ARGUMENTS_LIST); + if (argList == null || argList.getArguments() == null || argList.getArguments().length == 0) { + return null; + } + final List arguments = Arrays.asList(argList.getArguments()); + int argumentOffset = 1; // command is first argument + for (int index = 0, count = arguments.size(); index < count; ++index) { + if (arguments.get(index).startsWith("-")) { + argumentOffset = index; + } + } + if (argumentOffset < arguments.size()) { + return ResetMetricsCommand.SearchType.valueOf(arguments.get(argumentOffset)); + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ServiceNameCompleter.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ServiceNameCompleter.java new file mode 100644 index 000000000..08ad3a2f9 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ServiceNameCompleter.java @@ -0,0 +1,154 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; + +import org.apache.felix.service.command.CommandSession; +import org.apache.karaf.shell.console.Completer; +import org.apache.karaf.shell.console.completer.ArgumentCompleter; +import org.apache.karaf.shell.console.completer.StringsCompleter; +import org.apache.karaf.shell.console.jline.CommandSessionHolder; +import org.switchyard.admin.Application; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Generates completion set for Application arguments. + */ +public class ServiceNameCompleter implements Completer { + + private SwitchYard _switchYard; + private Integer _applicationArgumentIndex; + private String[] _applicationOptions; + private Set _optionsWithParameters = Collections.emptySet(); + + @Override + public int complete(String buffer, int cursor, List candidates) { + final StringsCompleter delegate = new StringsCompleter(); + final Pattern applicationNamePattern = getApplicationNamePattern(); + final List applications = _switchYard.getApplications(); + for (Application application : applications) { + if (applicationNamePattern.matcher(application.getName().toString()).find()) { + for (Service service : application.getServices()) { + delegate.getStrings().add(service.getName().toString()); + } + } + } + return delegate.complete(buffer, cursor, candidates); + } + + /** + * @param switchYard the SwitchYard admin service + */ + public void setSwitchYard(SwitchYard switchYard) { + _switchYard = switchYard; + } + + /** + * @param applicationArgumentIndex the index for the application argument + */ + public void setApplicationArgumentIndex(Integer applicationArgumentIndex) { + _applicationArgumentIndex = applicationArgumentIndex; + } + + /** + * @param applicationOptions option strings for application name + */ + public void setApplicationOptions(String[] applicationOptions) { + _applicationOptions = applicationOptions; + } + + /** + * @param optionsWithParameters option strings which require parameters + */ + public void setOptionsWithParameters(String[] optionsWithParameters) { + if (optionsWithParameters == null) { + _optionsWithParameters = Collections.emptySet(); + } else { + _optionsWithParameters = new HashSet(Arrays.asList(optionsWithParameters)); + } + } + + private Pattern getApplicationNamePattern() { + final CommandSession session = CommandSessionHolder.getSession(); + if (session == null) { + return compilePattern(null, false); + } + final ArgumentCompleter.ArgumentList argList = (ArgumentCompleter.ArgumentList) session + .get(ArgumentCompleter.ARGUMENTS_LIST); + if (argList == null || argList.getArguments() == null || argList.getArguments().length == 0) { + return compilePattern(null, false); + } + final List arguments = Arrays.asList(argList.getArguments()); + boolean isRegex = arguments.indexOf("--regex") > 0; + if (_applicationArgumentIndex == null) { + if (_applicationOptions == null || _applicationOptions.length == 0) { + return compilePattern(null, false); + } + for (String option : _applicationOptions) { + final int index = arguments.indexOf(option); + if (index >= 0) { + if (arguments.size() - 1 > index) { + // XXX: do we need to worry about commas delimiting a + // list? + return compilePattern(Collections.singletonList(arguments.get(index + 1)), isRegex); + } + } + } + } else { + int argumentOffset = 1; // command is first argument + for (int index = 0, count = arguments.size(); index < count; ++index) { + if (arguments.get(index).startsWith("-")) { + argumentOffset = index; + if (_optionsWithParameters.contains(arguments.get(index))) { + ++argumentOffset; + } + } + } + // XXX: assuming the last option does not accept a value here + if (_applicationArgumentIndex + argumentOffset < arguments.size()) { + return compilePattern( + Collections.singletonList(arguments.get(_applicationArgumentIndex + argumentOffset)), isRegex); + } + } + return compilePattern(null, false); + } + + private Pattern compilePattern(List patterns, boolean isRegex) { + if (patterns == null || patterns.size() == 0) { + patterns = Collections.singletonList(".*"); + isRegex = true; + } + final StringBuffer regex = new StringBuffer(); + for (String name : patterns) { + if (!isRegex) { + regex.append("\\Q"); + } + regex.append(name); + if (!isRegex) { + regex.append("\\E"); + } + regex.append('|'); + } + regex.deleteCharAt(regex.length() - 1); + return Pattern.compile(regex.toString()); + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ServiceReferenceNameCompleter.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ServiceReferenceNameCompleter.java new file mode 100644 index 000000000..aa7201464 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ServiceReferenceNameCompleter.java @@ -0,0 +1,141 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.regex.Pattern; + +import org.apache.felix.service.command.CommandSession; +import org.apache.karaf.shell.console.Completer; +import org.apache.karaf.shell.console.completer.ArgumentCompleter; +import org.apache.karaf.shell.console.completer.StringsCompleter; +import org.apache.karaf.shell.console.jline.CommandSessionHolder; +import org.switchyard.admin.Application; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Generates completion set for Application arguments. + */ +public class ServiceReferenceNameCompleter implements Completer { + + private SwitchYard _switchYard; + private Integer _applicationArgumentIndex; + private String[] _applicationOptions; + + @Override + public int complete(String buffer, int cursor, List candidates) { + final StringsCompleter delegate = new StringsCompleter(); + final Pattern applicationNamePattern = getApplicationNamePattern(); + final List applications = _switchYard.getApplications(); + for (Application application : applications) { + if (applicationNamePattern.matcher(application.getName().toString()).find()) { + for (Service service : application.getServices()) { + delegate.getStrings().add(service.getName().toString()); + } + for (Reference reference : application.getReferences()) { + delegate.getStrings().add(reference.getName().toString()); + } + } + } + return delegate.complete(buffer, cursor, candidates); + } + + /** + * @param switchYard the SwitchYard admin service + */ + public void setSwitchYard(SwitchYard switchYard) { + _switchYard = switchYard; + } + + /** + * @param applicationArgumentIndex the index for the application argument + */ + public void setApplicationArgumentIndex(Integer applicationArgumentIndex) { + _applicationArgumentIndex = applicationArgumentIndex; + } + + /** + * @param applicationOptions option strings for application name + */ + public void setApplicationOptions(String[] applicationOptions) { + _applicationOptions = applicationOptions; + } + + private Pattern getApplicationNamePattern() { + final CommandSession session = CommandSessionHolder.getSession(); + if (session == null) { + return compilePattern(null, false); + } + final ArgumentCompleter.ArgumentList argList = (ArgumentCompleter.ArgumentList) session + .get(ArgumentCompleter.ARGUMENTS_LIST); + if (argList == null || argList.getArguments() == null || argList.getArguments().length == 0) { + return compilePattern(null, false); + } + final List arguments = Arrays.asList(argList.getArguments()); + boolean isRegex = arguments.indexOf("--regex") > 0; + if (_applicationArgumentIndex == null) { + if (_applicationOptions == null || _applicationOptions.length == 0) { + return compilePattern(null, false); + } + for (String option : _applicationOptions) { + final int index = arguments.indexOf(option); + if (index >= 0) { + if (arguments.size() - 1 > index) { + // XXX: do we need to worry about commas delimiting a + // list? + return compilePattern(Collections.singletonList(arguments.get(index + 1)), isRegex); + } + } + } + } else { + int argumentOffset = 1; // command is first argument + for (int index = 0, count = arguments.size(); index < count; ++index) { + if (arguments.get(index).startsWith("-")) { + argumentOffset = index; + } + } + // XXX: assuming the last option does not accept a value here + if (_applicationArgumentIndex + argumentOffset < arguments.size()) { + return compilePattern( + Collections.singletonList(arguments.get(_applicationArgumentIndex + argumentOffset)), isRegex); + } + } + return compilePattern(null, false); + } + + private Pattern compilePattern(List patterns, boolean isRegex) { + if (patterns == null || patterns.size() == 0) { + patterns = Collections.singletonList(".*"); + isRegex = true; + } + final StringBuffer regex = new StringBuffer(); + for (String name : patterns) { + if (!isRegex) { + regex.append("\\Q"); + } + regex.append(name); + if (!isRegex) { + regex.append("\\E"); + } + regex.append('|'); + } + regex.deleteCharAt(regex.length() - 1); + return Pattern.compile(regex.toString()); + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ShowMetricsCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ShowMetricsCommand.java new file mode 100644 index 000000000..4bc3c496a --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ShowMetricsCommand.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.felix.gogo.commands.Argument; +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for uses-artifact. + */ +@Command(scope = "switchyard", name = "show-metrics", description = "Displays metrics for the specified service/reference/component service.") +public class ShowMetricsCommand extends AbstractSwitchYardServiceCommand { + + /** + * Specifies the search type: services, references or component services. + */ + public static enum SearchType { + /** show services. */ + service() { + @Override + public void printMetrics(Pattern pattern, Application application) { + boolean printHeader = true; + for (Service service : application.getServices()) { + final Matcher matcher = pattern.matcher(service.getName().toString()); + if (matcher.find()) { + if (printHeader) { + System.out.println(application.getName() + " = ["); + printHeader = false; + } + System.out.println(PrintUtil.printServiceMetrics(service, 1)); + } + } + if (!printHeader) { + System.out.println("]"); + } + }; + }, + /** show references. */ + reference() { + @Override + public void printMetrics(Pattern pattern, Application application) { + boolean printHeader = true; + for (Reference reference : application.getReferences()) { + final Matcher matcher = pattern.matcher(reference.getName().toString()); + if (matcher.find()) { + if (printHeader) { + System.out.println(application.getName() + " = ["); + printHeader = false; + } + System.out.println(PrintUtil.printReferenceMetrics(reference, 1)); + } + } + if (!printHeader) { + System.out.println("]"); + } + }; + }, + /** show component services. */ + component() { + @Override + public void printMetrics(Pattern pattern, Application application) { + boolean printHeader = true; + for (ComponentService service : application.getComponentServices()) { + final Matcher matcher = pattern.matcher(service.getName().toString()); + if (matcher.find()) { + if (printHeader) { + System.out.println(application.getName() + " = ["); + printHeader = false; + } + System.out.println(PrintUtil.printComponentServiceMetrics(service, 1)); + } + } + if (!printHeader) { + System.out.println("]"); + } + }; + }, + /** show system. */ + system() { + @Override + public void printMetrics(Pattern pattern, Application application) { + }; + }; + + /** + * @param pattern the pattern + * @param application the application to scan + */ + public abstract void printMetrics(Pattern pattern, Application application); + } + + @Argument(index = 0, name = "type", description = "Specifies the search type [service | reference | component | system].", required = true) + private SearchType _type; + + @Argument(index = 1, name = "patterns", description = "Specifies the search pattern to use.", multiValued = true) + private List _patterns; + + @Option(name = "--regex", description = "If specified, treat the pattern(s) as a regular expression.") + private boolean _regex; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + if (_type == SearchType.system) { + System.out.println(PrintUtil.addMetricsToNode(switchYard.getMessageMetrics(), 1)); + } else { + final Pattern pattern = compilePattern(_patterns, _regex); + for (Application application : switchYard.getApplications()) { + _type.printMetrics(pattern, application); + } + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ShowMetricsPatternCompleter.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ShowMetricsPatternCompleter.java new file mode 100644 index 000000000..2e45b9dfb --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/ShowMetricsPatternCompleter.java @@ -0,0 +1,95 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.Arrays; +import java.util.List; + +import org.apache.felix.service.command.CommandSession; +import org.apache.karaf.shell.console.Completer; +import org.apache.karaf.shell.console.completer.ArgumentCompleter; +import org.apache.karaf.shell.console.completer.StringsCompleter; +import org.apache.karaf.shell.console.jline.CommandSessionHolder; +import org.switchyard.admin.Application; +import org.switchyard.admin.ComponentService; +import org.switchyard.admin.Reference; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Generates completion set for Application arguments. + */ +public class ShowMetricsPatternCompleter implements Completer { + + private SwitchYard _switchYard; + + @Override + public int complete(String buffer, int cursor, List candidates) { + final StringsCompleter delegate = new StringsCompleter(); + final ShowMetricsCommand.SearchType type = getType(); + switch (type) { + case service: + for (Service service : _switchYard.getServices()) { + delegate.getStrings().add(service.getName().toString()); + } + break; + case reference: + for (Reference reference : _switchYard.getReferences()) { + delegate.getStrings().add(reference.getName().toString()); + } + break; + case component: + for (Application application : _switchYard.getApplications()) { + for (ComponentService service : application.getComponentServices()) { + delegate.getStrings().add(service.getName().toString()); + } + } + break; + default: + break; + } + return delegate.complete(buffer, cursor, candidates); + } + + /** + * @param switchYard the SwitchYard admin service + */ + public void setSwitchYard(SwitchYard switchYard) { + _switchYard = switchYard; + } + + private ShowMetricsCommand.SearchType getType() { + final CommandSession session = CommandSessionHolder.getSession(); + if (session == null) { + return null; + } + final ArgumentCompleter.ArgumentList argList = (ArgumentCompleter.ArgumentList) session + .get(ArgumentCompleter.ARGUMENTS_LIST); + if (argList == null || argList.getArguments() == null || argList.getArguments().length == 0) { + return null; + } + final List arguments = Arrays.asList(argList.getArguments()); + int argumentOffset = 1; // command is first argument + for (int index = 0, count = arguments.size(); index < count; ++index) { + if (arguments.get(index).startsWith("-")) { + argumentOffset = index; + } + } + if (argumentOffset < arguments.size()) { + return ShowMetricsCommand.SearchType.valueOf(arguments.get(argumentOffset)); + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/UpdateThrottlingCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/UpdateThrottlingCommand.java new file mode 100644 index 000000000..065ca9953 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/UpdateThrottlingCommand.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import javax.xml.namespace.QName; + +import org.apache.felix.gogo.commands.Argument; +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.Service; +import org.switchyard.admin.SwitchYard; + +/** + * Shell command for uses-artifact. + */ +@Command(scope = "switchyard", name = "throttling", description = "Update throttling settings on a service.") +public class UpdateThrottlingCommand extends AbstractSwitchYardServiceCommand { + + /** + * Specifies the type: enable, disable. + */ + public static enum OperationType { + /** enable operation. */ + enable, + /** disable operation. */ + disable; + } + + @Argument(index = 0, name = "operation", description = "Specifies the operation type [enable | disable].", required = true) + private OperationType _operation; + + @Argument(index = 1, name = "application", description = "Specifies the name of the application containing the binding.", required = true) + private String _application; + + @Argument(index = 2, name = "service", description = "Specifies the name of the service containing the binding.", required = true) + private String _service; + + @Option(name = "--maxRequests", description = "The maximum number of requests per period.") + private Integer _maxRequests; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Application application = switchYard.getApplication(QName.valueOf(_application)); + if (application == null) { + System.err.println("Could not locate application: " + _application); + return null; + } + final QName serviceName = QName.valueOf(_service); + final Service service = application.getService(serviceName); + if (service == null) { + System.err.println("Could not locate service: " + _service); + return null; + } + service.getThrottling().update(_operation == OperationType.enable, _maxRequests); + return null; + } + +} diff --git a/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/UsesArtifactCommand.java b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/UsesArtifactCommand.java new file mode 100644 index 000000000..8ef7c79f7 --- /dev/null +++ b/release/karaf/commands/src/main/java/org/switchyard/deploy/karaf/UsesArtifactCommand.java @@ -0,0 +1,95 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.karaf; + +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.felix.gogo.commands.Argument; +import org.apache.felix.gogo.commands.Command; +import org.apache.felix.gogo.commands.Option; +import org.switchyard.admin.Application; +import org.switchyard.admin.SwitchYard; +import org.switchyard.config.model.switchyard.ArtifactModel; + +/** + * Shell command for uses-artifact. + */ +@Command(scope = "switchyard", name = "uses-artifact", description = "Returns a list of all SwitchYard applications referencing the specified artifact.") +public class UsesArtifactCommand extends AbstractSwitchYardServiceCommand { + + /** + * Specifies the search type: by name or by url. + */ + public static enum SearchType { + /** by name. */ + name() { + @Override + public boolean matches(Pattern pattern, ArtifactModel artifact) { + final Matcher matcher = pattern.matcher(artifact.getName()); + return matcher.find(); + }; + }, + /** by url. */ + url() { + @Override + public boolean matches(Pattern pattern, ArtifactModel artifact) { + final Matcher matcher = pattern.matcher(artifact.getURL()); + return matcher.find(); + }; + }; + + /** + * @param pattern the pattern + * @param artifact the artifact + * @return true if the artifact matches the pattern + */ + public abstract boolean matches(Pattern pattern, ArtifactModel artifact); + } + + @Argument(index = 0, name = "type", description = "Specifies the search type [name | url].", required = true) + private SearchType _type; + + @Argument(index = 1, name = "patterns", description = "Specifies the search pattern to use.", multiValued = true) + private List _patterns; + + @Option(name = "--regex", description = "If specified, treat the pattern(s) as a regular expression.") + private boolean _regex; + + @Override + protected Object doExecute(final SwitchYard switchYard) throws Exception { + final Pattern pattern = compilePattern(_patterns, _regex); + for (Application application : switchYard.getApplications()) { + if (application.getConfig().getArtifacts() == null) { + continue; + } + boolean printHeader = true; + for (ArtifactModel artifact : application.getConfig().getArtifacts().getArtifacts()) { + if (_type.matches(pattern, artifact)) { + if (printHeader) { + System.out.println(application.getName() + " = ["); + printHeader = false; + } + System.out.println(PrintUtil.printArtifact(artifact, 1)); + } + } + if (!printHeader) { + System.out.println("]"); + } + } + return null; + } + +} diff --git a/release/karaf/commands/src/main/resources/OSGI-INF/blueprint/switchyard-commands.xml b/release/karaf/commands/src/main/resources/OSGI-INF/blueprint/switchyard-commands.xml new file mode 100644 index 000000000..629c36f79 --- /dev/null +++ b/release/karaf/commands/src/main/resources/OSGI-INF/blueprint/switchyard-commands.xml @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --application + -a + + + + + + + + + + + + + + + + --application + -a + + + + + + + + + + + + + + name + url + + + + + + + + + + + + + + + service + reference + component + system + + + + + + + + + + + + + + + service + reference + application + all + + + + + + + + + + + + + + + start + stop + + + + + + + + + + + + + + + + + + + + enable + disable + + + + + + + + + + --maxRequests + + + + + + + + \ No newline at end of file diff --git a/release/karaf/deploy/pom.xml b/release/karaf/deploy/pom.xml new file mode 100644 index 000000000..e508dc432 --- /dev/null +++ b/release/karaf/deploy/pom.xml @@ -0,0 +1,151 @@ + + + + 4.0.0 + + org.switchyard.karaf + switchyard-karaf-parent + 2.1.0-SNAPSHOT + + switchyard-karaf-deploy + bundle + SwitchYard: Karaf Deployer + Karaf-Based Deployer + http://switchyard.org + + org.switchyard.deploy.osgi.internal.SwitchYardExtender + + org.switchyard.deploy.osgi + + + org.switchyard.deploy.osgi*, + org.apache.camel.core.osgi* + + + org.switchyard.admin.*;${switchyard.osgi.import.switchyard.version}, + !org.osgi.service;org.switchyard.admin.*;${switchyard.osgi.import.switchyard.version}, + org.switchyard.component.soap.*;${switchyard.osgi.import.switchyard.version};resolution:="optional", + org.switchyard.component.*;${switchyard.osgi.import.switchyard.version};resolution:="optional", + org.apache.cxf.*;resolution:="optional", + org.switchyard.*;${switchyard.osgi.import.switchyard.version}, + * + + org.switchyard.admin.SwitchYard + true + + + + + org.osgi + org.osgi.core + + + org.osgi + org.osgi.compendium + + + org.switchyard + switchyard-admin + + + org.switchyard + switchyard-api + + + org.switchyard + switchyard-bus-camel + + + org.switchyard + switchyard-common + + + org.switchyard + switchyard-common-camel + + + org.switchyard + switchyard-config + + + org.switchyard + switchyard-deploy + + + org.switchyard + switchyard-runtime + + + org.switchyard + switchyard-security + + + org.switchyard + switchyard-transform + + + org.switchyard.components + switchyard-component-common + + + org.switchyard.components + switchyard-component-soap + + + org.apache.cxf + * + + + + + + org.jboss.spec.javax.servlet + jboss-servlet-api_2.5_spec + provided + + + org.apache.camel + camel-core + + + org.apache.camel + camel-core-osgi + + + org.apache.cxf + cxf-core + + + org.apache.cxf + cxf-rt-bindings-soap + + + org.apache.cxf + cxf-rt-frontend-jaxws + + + org.apache.cxf + cxf-rt-ws-addr + + + org.apache.karaf.features + org.apache.karaf.features.core + + + org.slf4j + slf4j-api + + + diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/ComponentRegistry.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/ComponentRegistry.java new file mode 100644 index 000000000..641b32ba7 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/ComponentRegistry.java @@ -0,0 +1,63 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi; + +import org.switchyard.deploy.Component; + +/** + * ComponentRegistry. + */ +public interface ComponentRegistry { + + Component getComponent(String type); + + /** + * Add a new Listener to be called when namespace handlers are registerd or unregistered. + * @param listener the listener to register + */ + void addListener(Listener listener); + + /** + * Remove a previously registered Listener. + * @param listener the listener to unregister + */ + void removeListener(Listener listener); + + /** + * Destroy this registry. + */ + void destroy(); + + /** + * Interface used to listen to registered or unregistered namespace handlers. + * @see ComponentRegistry#addListener(org.switchyard.deploy.osgi.ComponentRegistry.Listener) + * @see ComponentRegistry#removeListener(org.switchyard.deploy.osgi.ComponentRegistry.Listener) + */ + public interface Listener { + + /** + * Called when a Component has been registered for the specified type. + * @param type the component activation type + */ + void componentRegistered(String type); + + /** + * Called when a Component has been unregistered for the specified type. + * @param type the component activation type + */ + void componentUnregistered(String type); + + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/EventConstants.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/EventConstants.java new file mode 100644 index 000000000..00cd5e0b7 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/EventConstants.java @@ -0,0 +1,147 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi; + +/** + * EventConstants. + */ +public class EventConstants { + + private EventConstants() { + // non-instantiable class + } + + /** + * The type of the event that has been issued. This property is of type + * Integer and can take one of the values defined in + * {@link SwitchYardEvent}. + */ + public static final String TYPE = "type"; + + /** + * The SwitchyardEvent object that caused this event. This + * property is of type {@link SwitchYardEvent}. + */ + public static final String EVENT = "event"; + + /** + * The time the event was created. This property is of type + * Long. + */ + public static final String TIMESTAMP = "timestamp"; + + /** + * The Switchyard bundle associated with this event. This property is of type + * Bundle. + */ + public static final String BUNDLE = "bundle"; + + /** + * The bundle id of the Switchyard bundle associated with this event. This + * property is of type Long. + */ + public static final String BUNDLE_ID = "bundle.id"; + + /** + * The bundle symbolic name of the Switchyard bundle associated with this + * event. This property is of type String. + */ + public static final String BUNDLE_SYMBOLICNAME = "bundle.symbolicName"; + + /** + * The bundle version of the Switchyard bundle associated with this event. + * This property is of type Version. + */ + public static final String BUNDLE_VERSION = "bundle.version"; + + /** + * The Switchyard extender bundle that is generating this event. This + * property is of type Bundle. + */ + public static final String EXTENDER_BUNDLE = "extender.bundle"; + + /** + * The bundle id of the Switchyard extender bundle that is generating this + * event. This property is of type Long. + */ + public static final String EXTENDER_BUNDLE_ID = "extender.bundle.id"; + + /** + * The bundle symbolic of the Switchyard extender bundle that is generating + * this event. This property is of type String. + */ + public static final String EXTENDER_BUNDLE_SYMBOLICNAME = "extender.bundle.symbolicName"; + + /** + * The bundle version of the Switchyard extender bundle that is generating + * this event. This property is of type Version. + */ + public static final String EXTENDER_BUNDLE_VERSION = "extender.bundle.version"; + + /** + * The filters identifying the missing dependencies that caused this event + * for a {@link SwitchYardEvent#FAILURE FAILURE} or + * {@link SwitchYardEvent#GRACE_PERIOD GRACE_PERIOD}. This property type is an + * array of String. + */ + public static final String DEPENDENCIES = "dependencies"; + + /** + * The cause for a {@link SwitchYardEvent#FAILURE FAILURE} event. This + * property is of type Throwable. + */ + public static final String CAUSE = "cause"; + + /** + * Topic prefix for all events issued by the Switchyard Container. + */ + public static final String TOPIC_SWITCHYARD_EVENTS = "org/switchyard/container"; + + /** + * Topic for Switchyard Container CREATING events. + */ + public static final String TOPIC_CREATING = TOPIC_SWITCHYARD_EVENTS + + "/CREATING"; + + /** + * Topic for Switchyard Container CREATED events. + */ + public static final String TOPIC_CREATED = TOPIC_SWITCHYARD_EVENTS + + "/CREATED"; + + /** + * Topic for Switchyard Container DESTROYING events. + */ + public static final String TOPIC_DESTROYING = TOPIC_SWITCHYARD_EVENTS + + "/DESTROYING"; + + /** + * Topic for Switchyard Container DESTROYED events. + */ + public static final String TOPIC_DESTROYED = TOPIC_SWITCHYARD_EVENTS + + "/DESTROYED"; + + /** + * Topic for Switchyard Container FAILURE events. + */ + public static final String TOPIC_FAILURE = TOPIC_SWITCHYARD_EVENTS + + "/FAILURE"; + + /** + * Topic for Switchyard Container GRACE_PERIOD events. + */ + public static final String TOPIC_GRACE_PERIOD = TOPIC_SWITCHYARD_EVENTS + + "/GRACE_PERIOD"; + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandler.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandler.java new file mode 100644 index 000000000..bd9cd99b1 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandler.java @@ -0,0 +1,52 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi; + +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Marshaller; + +import java.net.URL; +import java.util.Set; + +/** + * NamespaceHandler. + */ +public interface NamespaceHandler { + + /** + * Key for namespace value used by a namespace handler. + */ + public static final String NAMESPACES = "switchyard.namespaces"; + + /** + * Return the schema location for the given namespace. + * @param namespace namespace + * @return schema location + */ + URL getSchemaLocation(String namespace); + + /** + * Create a config marshaller for the specified namespace. + * @param namespace namespace + * @param descriptor config descriptor + * @return marshaller instance + */ + Marshaller createMarshaller(String namespace, Descriptor descriptor); + + /** + * Returns the set of marshaller classes used by this handler. + * @return set of marshaller classes used by this handler. + */ + Set getManagedClasses(); +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandlerRegistry.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandlerRegistry.java new file mode 100644 index 000000000..afe479869 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandlerRegistry.java @@ -0,0 +1,38 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi; + +import org.osgi.framework.Bundle; + +import java.net.URI; +import java.util.Set; + +/** + * Registry of NamespaceHandler. + */ +public interface NamespaceHandlerRegistry { + + /** + * Retrieve the NamespaceHandler for the specified URI. + * @param uri the namespace identifying the namespace handler + * @param bundle the blueprint bundle to be checked for class space consistency + * @return a set of registered NamespaceHandlers compatible with the class space of the given bundle + */ + NamespaceHandlerSet getNamespaceHandlers(Set uri, Bundle bundle); + + /** + * Destroy this registry. + */ + void destroy(); +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandlerSet.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandlerSet.java new file mode 100644 index 000000000..8e28cb3f5 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/NamespaceHandlerSet.java @@ -0,0 +1,89 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi; + +import java.io.IOException; +import java.net.URI; +import java.util.Set; + +import javax.xml.validation.Schema; + +import org.xml.sax.SAXException; + +/** + * Interface used to managed a set of namespace handlers. + */ +public interface NamespaceHandlerSet { + + /** + * Retrieve the set of namespaces used by handlers. + * @return set of namespaces + */ + Set getNamespaces(); + + boolean isComplete(); + + /** + * Retrieve the NamespaceHandler to use for the given namespace. + * @param namespace namespace + * @return the NamespaceHandler to use or null if none is available at this time + */ + NamespaceHandler getNamespaceHandler(URI namespace); + + /** + * Obtain a schema to validate the XML for the given list of namespaces. + * @return the schema to use to validate the XML + * @throws IOException failed to load schema + * @throws SAXException failed to parse schema + */ + Schema getSchema() throws SAXException, IOException; + + /** + * Add a new Listener to be called when namespace handlers are registerd or unregistered. + * @param listener the listener to register + */ + void addListener(Listener listener); + + /** + * Remove a previously registered Listener. + * @param listener the listener to unregister + */ + void removeListener(Listener listener); + + /** + * Destroy this handler set. + */ + void destroy(); + + /** + * Interface used to listen to registered or unregistered namespace handlers. + * @see NamespaceHandlerSet#addListener(org.switchyard.deploy.osgi.NamespaceHandlerSet.Listener) + * @see NamespaceHandlerSet#removeListener(org.switchyard.deploy.osgi.NamespaceHandlerSet.Listener) + */ + public interface Listener { + + /** + * Called when a NamespaceHandler has been registered for the specified URI. + * @param uri the URI of the newly registered namespace handler + */ + void namespaceHandlerRegistered(URI uri); + + /** + * Called when a NamespaceHandler has been unregistered for the specified URI. + * @param uri the URI of the newly unregistered namespace handler + */ + void namespaceHandlerUnregistered(URI uri); + + } +} \ No newline at end of file diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardContainer.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardContainer.java new file mode 100644 index 000000000..5efff7945 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardContainer.java @@ -0,0 +1,21 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi; + +/** + * Marker interface for SwitchYard container. + */ +public interface SwitchYardContainer { + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardEvent.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardEvent.java new file mode 100644 index 000000000..5d7511f18 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardEvent.java @@ -0,0 +1,286 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi; + +import org.osgi.framework.Bundle; + +/** + * SwitchyardEvent. + */ +public class SwitchYardEvent { + + /** CREATING. */ + public static final int CREATING = 1; + /** CREATED. */ + public static final int CREATED = 2; + /** DESTROYING. */ + public static final int DESTROYING = 3; + /** DESTROYED. */ + public static final int DESTROYED = 4; + /** FAILURE. */ + public static final int FAILURE = 5; + /** GRACE_PERIOD. */ + public static final int GRACE_PERIOD = 6; + + private final int _type; + /** + * The time when the event occurred. + * + * @see #getTimestamp() + */ + private final long _timestamp; + /** + * The Switchyard bundle. + * + * @see #getBundle() + */ + private final Bundle _bundle; + /** + * The Switchyard extender bundle. + * + * @see #getExtenderBundle() + */ + private final Bundle _extenderBundle; + /** + * An array containing filters identifying the missing dependencies. Must + * not be null when the event type requires it. + * + * @see #getDependencies() + */ + private final String[] _dependencies; + /** + * Cause of the failure. + * + * @see #getCause() + */ + private final Throwable _cause; + /** + * Indicate if this event is a replay event or not. + * + * @see #isReplay() + */ + private final boolean _replay; + + /** + * Create a simple SwitchyardEvent object. + * + * @param type The type of this event. + * @param bundle The Switchyard bundle associated with this event. This + * parameter must not be null. + * @param extenderBundle The Switchyard extender bundle that is generating + * this event. This parameter must not be null. + */ + public SwitchYardEvent(int type, Bundle bundle, Bundle extenderBundle) { + this(type, bundle, extenderBundle, null, null); + } + + /** + * Create a SwitchyardEvent object associated with a set of + * dependencies. + * + * @param type The type of this event. + * @param bundle The Switchyard bundle associated with this event. This + * parameter must not be null. + * @param extenderBundle The Switchyard extender bundle that is generating + * this event. This parameter must not be null. + * @param dependencies An array of String filters for each + * dependency associated with this event. Must be a non-empty array + * for event types {@link #FAILURE}, {@link #GRACE_PERIOD}. + * Must be null for other event types. + */ + public SwitchYardEvent(int type, Bundle bundle, Bundle extenderBundle, + String[] dependencies) { + this(type, bundle, extenderBundle, dependencies, null); + } + + /** + * Create a SwitchyardEvent object associated with a failure + * cause. + * + * @param type The type of this event. + * @param bundle The Switchyard bundle associated with this event. This + * parameter must not be null. + * @param extenderBundle The Switchyard extender bundle that is generating + * this event. This parameter must not be null. + * @param cause A Throwable object describing the root cause of + * the event. May be null. + */ + public SwitchYardEvent(int type, Bundle bundle, Bundle extenderBundle, + Throwable cause) { + this(type, bundle, extenderBundle, null, cause); + } + + /** + * Create a SwitchyardEvent object associated with a failure + * cause and a set of dependencies. + * + * @param type The type of this event. + * @param bundle The Switchyard bundle associated with this event. This + * parameter must not be null. + * @param extenderBundle The Switchyard extender bundle that is generating + * this event. This parameter must not be null. + * @param dependencies An array of String filters for each + * dependency associated with this event. Must be a non-empty array + * for event type {@link #GRACE_PERIOD}. It + * is optional for {@link #FAILURE} event types. + * Must be null for other event types. + * @param cause A Throwable object describing the root cause of + * this event. May be null. + */ + public SwitchYardEvent(int type, Bundle bundle, Bundle extenderBundle, + String[] dependencies, Throwable cause) { + _type = type; + _timestamp = System.currentTimeMillis(); + _bundle = bundle; + _extenderBundle = extenderBundle; + _dependencies = dependencies == null ? null + : (String[]) dependencies.clone();; + _cause = cause; + _replay = false; + if (bundle == null) { + throw new NullPointerException("bundle must not be null"); + } + if (extenderBundle == null) { + throw new NullPointerException("extenderBundle must not be null"); + } + switch (type) { + case GRACE_PERIOD : + if (dependencies == null) { + throw new NullPointerException( + "dependencies must not be null"); + } + if (dependencies.length == 0) { + throw new IllegalArgumentException( + "dependencies must not be length zero"); + } + break; + case FAILURE : + // not all FAILURE events have a dependency list, but if there + // is one, it must be non-empty. + if (dependencies != null) { + if (dependencies.length == 0) { + throw new IllegalArgumentException( + "dependencies must not be length zero"); + } + } + break; + default : + if (dependencies != null) { + throw new IllegalArgumentException( + "dependencies must be null"); + } + break; + } + } + + /** + * Create a new SwitchyardEvent from the specified + * SwitchyardEvent. The timestamp property will be + * copied from the original event and only the replay property will be + * overridden with the given value. + * + * @param event The original SwitchyardEvent to copy. Must not + * be null. + * @param replay true if this event should be used as a replay + * event. + */ + public SwitchYardEvent(SwitchYardEvent event, boolean replay) { + _type = event._type; + _timestamp = event._timestamp; + _bundle = event._bundle; + _extenderBundle = event._extenderBundle; + _dependencies = event._dependencies; + _cause = event._cause; + _replay = replay; + } + + /** + * Return the type of this event. + *

+ * The type values are: + *

    + *
  • {@link #CREATING}
  • + *
  • {@link #CREATED}
  • + *
  • {@link #DESTROYING}
  • + *
  • {@link #DESTROYED}
  • + *
  • {@link #FAILURE}
  • + *
  • {@link #GRACE_PERIOD}
  • + *
+ * + * @return The type of this event. + */ + public int getType() { + return _type; + } + + /** + * Return the time at which this event was created. + * + * @return The time at which this event was created. + */ + public long getTimestamp() { + return _timestamp; + } + + /** + * Return the Blueprint bundle associated with this event. + * + * @return The Blueprint bundle associated with this event. + */ + public Bundle getBundle() { + return _bundle; + } + + /** + * Return the Blueprint extender bundle that is generating this event. + * + * @return The Blueprint extender bundle that is generating this event. + */ + public Bundle getExtenderBundle() { + return _extenderBundle; + } + + /** + * Return the filters identifying the missing dependencies that caused this + * event. + * + * @return The filters identifying the missing dependencies that caused this + * event if the event type is one of + * {@link #GRACE_PERIOD} or {@link #FAILURE} or null + * for the other event types. + */ + public String[] getDependencies() { + return _dependencies == null ? null : (String[]) _dependencies.clone(); + } + + /** + * Return the cause for this {@link #FAILURE} event. + * + * @return The cause of the failure for this event. May be null + * . + */ + public Throwable getCause() { + return _cause; + } + + /** + * Return whether this event is a replay event. + * + * @return true if this event is a replay event and + * false otherwise. + */ + public boolean isReplay() { + return _replay; + } +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardListener.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardListener.java new file mode 100644 index 000000000..43dba9bdf --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/SwitchYardListener.java @@ -0,0 +1,28 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi; + +/** + * Listens for SwitchYard events. + */ +public interface SwitchYardListener { + + /** + * Receives notifications of a SwitchYard Event. + * + * Implementers should quickly process the event and return. + * @param event The {@link SwitchYardEvent}. + */ + void switchyardEvent(SwitchYardEvent event); +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/AbstractExtender.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/AbstractExtender.java new file mode 100644 index 000000000..92c6a0f22 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/AbstractExtender.java @@ -0,0 +1,344 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.base; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.Constants; +import org.osgi.framework.SynchronousBundleListener; +import org.osgi.util.tracker.BundleTracker; +import org.osgi.util.tracker.BundleTrackerCustomizer; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; + +/** + * Base class to write bundle extenders. + * This extender tracks started bundles (or starting if they have a lazy activation + * policy) and will create an {@link Extension} for each of them to manage it. + * + * The extender will handle all concurrency and synchronization issues, see + * {@link Extension} for more information about the additional constraints. + * + * The extender guarantee that all extensions will be stopped synchronously with + * the STOPPING event of a given bundle and that all extensions will be stopped + * before the extender bundle is stopped. + * + */ +public abstract class AbstractExtender implements BundleActivator, BundleTrackerCustomizer, SynchronousBundleListener { + + private final ConcurrentMap _extensions = new ConcurrentHashMap(); + private final ConcurrentMap _destroying = new ConcurrentHashMap(); + private volatile boolean _stopping; + + private boolean _synchronous; + private boolean _preemptiveShutdown; + private BundleContext _context; + private ExecutorService _executors; + private BundleTracker _tracker; + + /** + * Check if the extender is synchronous or not. + * If the flag is set, the extender will start the extension synchronously + * with the bundle being tracked or started. Else, the starting of the + * extension will be delegated to a thread pool. + * + * @return if the extender is synchronous + */ + public boolean isSynchronous() { + return _synchronous; + } + + /** + * Check if the extender performs a preemptive shutdown + * of all extensions when the framework is being stopped. + * The default behavior is to wait for the framework to stop + * the bundles and stop the extension at that time. + * + * @return if the extender use a preemptive shutdown + */ + public boolean isPreemptiveShutdown() { + return _preemptiveShutdown; + } + + /** + * Retrieve the bundle context for extensions. + * @return bundle context + */ + public BundleContext getBundleContext() { + return _context; + } + + /** + * Retrieve ExecutorService. + * @return ExecutorService + */ + public ExecutorService getExecutors() { + return _executors; + } + + /** + * Indicates whether extensions should be started in the calling thread. + * @param synchronous true for sync, false otherwise + */ + public void setSynchronous(boolean synchronous) { + _synchronous = synchronous; + } + + /** + * Specify whether extensions are subject to preemptive shutdown. + * @param preemptiveShutdown true for preemptiveShutdown + */ + public void setPreemptiveShutdown(boolean preemptiveShutdown) { + _preemptiveShutdown = preemptiveShutdown; + } + + @Override + public void start(BundleContext context) throws Exception { + _context = context; + _context.addBundleListener(this); + _tracker = new BundleTracker(_context, Bundle.ACTIVE | Bundle.STARTING, this); + if (!_synchronous) { + _executors = createExecutor(); + } + doStart(); + } + + @Override + public void stop(BundleContext context) throws Exception { + _stopping = true; + while (!_extensions.isEmpty()) { + Collection toDestroy = chooseBundlesToDestroy(_extensions.keySet()); + if (toDestroy == null || toDestroy.isEmpty()) { + toDestroy = new ArrayList(_extensions.keySet()); + } + for (Bundle bundle : toDestroy) { + destroyExtension(bundle); + } + } + doStop(); + if (_executors != null) { + _executors.shutdown(); + try { + _executors.awaitTermination(60, TimeUnit.SECONDS); + } catch (InterruptedException e) { + // Ignore + e.getMessage(); + } + _executors = null; + } + } + + public void bundleChanged(BundleEvent event) { + Bundle bundle = event.getBundle(); + if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) { + // The bundle is not in STARTING or ACTIVE state anymore + // so destroy the context. Ignore our own bundle since it + // needs to kick the orderly shutdown. + if (bundle != _context.getBundle()) { + destroyExtension(bundle); + } + } + } + + @Override + public Bundle addingBundle(Bundle bundle, BundleEvent event) { + modifiedBundle(bundle, event, bundle); + return bundle; + } + + @Override + public void modifiedBundle(Bundle bundle, BundleEvent event, Bundle object) { + // If the bundle being stopped is the system bundle, + // do an orderly shutdown of all blueprint contexts now + // so that service usage can actually be useful + if (bundle.getBundleId() == 0 && bundle.getState() == Bundle.STOPPING) { + if (_preemptiveShutdown) { + try { + stop(_context); + } catch (Exception e) { + error("Error while performing preemptive shutdown", e); + } + return; + } + } + if (bundle.getState() != Bundle.ACTIVE && bundle.getState() != Bundle.STARTING) { + // The bundle is not in STARTING or ACTIVE state anymore + // so destroy the context. Ignore our own bundle since it + // needs to kick the orderly shutdown and not unregister the namespaces. + if (bundle != _context.getBundle()) { + destroyExtension(bundle); + } + return; + } + // Do not track bundles given we are stopping + if (_stopping) { + return; + } + // For starting bundles, ensure, it's a lazy activation, + // else we'll wait for the bundle to become ACTIVE + if (bundle.getState() == Bundle.STARTING) { + String activationPolicyHeader = (String) bundle.getHeaders().get(Constants.BUNDLE_ACTIVATIONPOLICY); + if (activationPolicyHeader == null || !activationPolicyHeader.startsWith(Constants.ACTIVATION_LAZY)) { + // Do not track this bundle yet + return; + } + } + createExtension(bundle); + } + + @Override + public void removedBundle(Bundle bundle, BundleEvent event, Bundle object) { + // Nothing to do + destroyExtension(bundle); + } + + + protected void doStart() throws Exception { + startTracking(); + } + + protected void doStop() throws Exception { + stopTracking(); + } + + protected void startTracking() { + _tracker.open(); + } + + protected void stopTracking() { + _tracker.close(); + } + + /** + * Create the executor used to start extensions asynchronously. + * + * @return an + */ + protected ExecutorService createExecutor() { + return Executors.newScheduledThreadPool(3); + } + + /** + * + * @param bundles + * @return + */ + protected Collection chooseBundlesToDestroy(Set bundles) { + return null; + } + + /** + * Create the extension for the given bundle, or null if the bundle is not to be extended. + * + * @param bundle the bundle to extend + * @return + * @throws Exception + */ + protected abstract Extension doCreateExtension(Bundle bundle) throws Exception; + + protected abstract void debug(Bundle bundle, String msg); + protected abstract void warn(Bundle bundle, String msg, Throwable t); + protected abstract void error(String msg, Throwable t); + + private void createExtension(final Bundle bundle) { + try { + BundleContext bundleContext = bundle.getBundleContext(); + if (bundleContext == null) { + // The bundle has been stopped in the mean time + return; + } + final Extension extension = doCreateExtension(bundle); + if (extension == null) { + // This bundle is not to be extended + return; + } + synchronized (_extensions) { + if (_extensions.putIfAbsent(bundle, extension) != null) { + return; + } + } + if (_synchronous) { + debug(bundle, "Starting extension synchronously"); + extension.start(); + } else { + debug(bundle, "Scheduling asynchronous start of extension"); + getExecutors().submit(new Runnable() { + public void run() { + try { + extension.start(); + } catch (Throwable t) { + warn(bundle, "Error starting extension", t); + } + } + }); + } + } catch (Throwable t) { + warn(bundle, "Error while creating extension", t); + } + } + + private void destroyExtension(final Bundle bundle) { + FutureTask future; + synchronized (_extensions) { + debug(bundle, "Starting destruction process"); + future = _destroying.get(bundle); + if (future == null) { + final Extension extension = _extensions.remove(bundle); + if (extension != null) { + debug(bundle, "Scheduling extension destruction"); + future = new FutureTask(new Runnable() { + public void run() { + debug(bundle, "Destroying extension"); + try { + extension.destroy(); + } catch (Throwable t) { + warn(bundle, "Error while destroying extension", t); + } finally { + debug(bundle, "Finished destroying extension"); + synchronized (_extensions) { + _destroying.remove(bundle); + } + } + } + }, null); + _destroying.put(bundle, future); + } else { + debug(bundle, "Not an extended bundle or destruction of extension already finished"); + } + } else { + debug(bundle, "Destruction already scheduled"); + } + } + if (future != null) { + try { + debug(bundle, "Waiting for extension destruction"); + future.run(); + future.get(); + } catch (Throwable t) { + warn(bundle, "Error while destroying extension", t); + } + } + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/CompoundExtension.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/CompoundExtension.java new file mode 100644 index 000000000..6e5fb7f19 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/CompoundExtension.java @@ -0,0 +1,50 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.base; + +import org.osgi.framework.Bundle; + +import java.util.List; + +/** + * CompoundExtension. + */ +public class CompoundExtension extends SimpleExtension { + + final List _extensions; + + /** + * Create a new CompoundExtension. + * @param bundle bundle + * @param extensions extensions + */ + public CompoundExtension(Bundle bundle, List extensions) { + super(bundle); + _extensions = extensions; + } + + @Override + protected void doStart() throws Exception { + for (Extension extension : _extensions) { + extension.start(); + } + } + + @Override + protected void doDestroy() throws Exception { + for (Extension extension : _extensions) { + extension.destroy(); + } + } +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/Extension.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/Extension.java new file mode 100644 index 000000000..99e374903 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/Extension.java @@ -0,0 +1,36 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.base; + +/** + * A simple interface used by the extender to manage extensions. + */ +public interface Extension { + + /** + * Start this extension. Starting and stopping of the extension + * should be synchronized. + * @throws Exception failed + */ + void start() throws Exception; + + /** + * Destroy should be synchronous and only return when the extension + * has been fully destroyed. In addition it must be synchronized with + * start, because start() and destroy() can be called concurrently. + * @throws Exception failed + */ + void destroy() throws Exception; + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/SimpleExtension.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/SimpleExtension.java new file mode 100644 index 000000000..73f68af4c --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/base/SimpleExtension.java @@ -0,0 +1,97 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.base; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * SimpleExtension. + */ +public abstract class SimpleExtension implements Extension { + + protected final Bundle _bundle; + protected final BundleContext _bundleContext; + protected final AtomicBoolean _destroyed = new AtomicBoolean(false); + + /** + * Create new instance of SimpleExtension. + * @param bundle bundle + */ + public SimpleExtension(Bundle bundle) { + _bundle = bundle; + _bundleContext = bundle.getBundleContext(); + } + + /** + * Whether the extension has been destroyed. + * @return true if the extension has been destroyed, false otherwise. + */ + public boolean isDestroyed() { + synchronized (getLock()) { + return _destroyed.get(); + } + } + + /** + * Retrieves the bundle for this extension. + * @return bundle + */ + public Bundle getBundle() { + return _bundle; + } + + /** + * Retrieves the bundle context for this extension. + * @return bundle context + */ + public BundleContext getBundleContext() { + return _bundleContext; + } + + @Override + public void start() throws Exception { + synchronized (getLock()) { + if (_destroyed.get()) { + return; + } + if (_bundle.getState() != Bundle.ACTIVE) { + return; + } + if (_bundle.getBundleContext() != _bundleContext) { + return; + } + doStart(); + } + } + + @Override + public void destroy() throws Exception { + synchronized (getLock()) { + _destroyed.set(true); + } + doDestroy(); + } + + protected Object getLock() { + return this; + } + + protected abstract void doStart() throws Exception; + + protected abstract void doDestroy() throws Exception; + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ComponentExtension.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ComponentExtension.java new file mode 100644 index 000000000..e09925e63 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ComponentExtension.java @@ -0,0 +1,219 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.ServiceRegistration; +import org.osgi.service.cm.ConfigurationAdmin; +import org.osgi.util.tracker.ServiceTracker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.switchyard.config.Configuration; +import org.switchyard.config.Configurations; +import org.switchyard.deploy.Component; +import org.switchyard.deploy.osgi.base.SimpleExtension; + +/** + * ComponentExtension. + */ +public class ComponentExtension extends SimpleExtension { + + /** + * Location of component descriptor. + */ + public static final String META_INF_COMPONENT = "META-INF/services/org.switchyard.deploy.Component"; + /** + * List of activation types. + */ + public static final String SWITCHYARD_TYPES = "switchyard.types"; + + private final Logger _logger = LoggerFactory.getLogger(SwitchYardExtender.class); + + private final SwitchYardExtender _extender; + private List> _registrations = new ArrayList>(); + private final ServiceTracker _configTracker; + private ConfigurationAdmin _configAdmin; + /** + * Create a new instance of ComponentExtension. + * @param extender extender + * @param bundle component bundle + */ + public ComponentExtension(SwitchYardExtender extender, Bundle bundle) { + super(bundle); + _extender = extender; + _configTracker = new ServiceTracker( + bundle.getBundleContext(), ConfigurationAdmin.class, null); + _configTracker.open(); + } + + @Override + protected void doStart() throws Exception { + _configAdmin = _configTracker.waitForService(0); + URL url = getBundle().getEntry(META_INF_COMPONENT); + List classNames = parse(Component.class, url); + for (String className : classNames) { + Component component = initializeComponent(className); + Dictionary props = new Hashtable(); + props.put(SWITCHYARD_TYPES, component.getActivationTypes()); + ServiceRegistration reg = getBundleContext().registerService(Component.class, component, props); + _registrations.add(reg); + } + } + + @Override + protected void doDestroy() throws Exception { + for (ServiceRegistration reg : _registrations) { + reg.unregister(); + } + _configTracker.close(); + } + + private Component initializeComponent(String className) throws Exception { + Class clazz = (Class) getBundle().loadClass(className); + Component component = clazz.newInstance(); + + // load configuration for a component - SY components all use the same package + // naming conventions so grab the config name from the package name. For custom + // components (non-SY), use the name of the component returned from Component.getName(). + String configName = className.contains("org.switchyard.component") && className.indexOf(".deploy") > 0 + ? className.substring(0, className.indexOf(".deploy")) + : component.getName(); + Configuration config = loadConfiguration(configName); + + // invoke the component's init method with config loaded from config admin - the + // destroy() method is called in ComponentRegistryImpl.unregisterComponent() + component.init(config); + return component; + } + + private Configuration loadConfiguration(String configName) throws Exception { + Configuration syConfig = Configurations.newConfiguration(); + org.osgi.service.cm.Configuration osgiConfig = _configAdmin.getConfiguration(configName, null); + + Dictionary props = osgiConfig.getProperties(); + if (props != null) { + Enumeration keys = props.keys(); + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + Configuration config = Configurations.newConfiguration(key); + config.setValue((String)props.get(key)); + syConfig.addChild(config); + } + } + return syConfig; + } + + // Parse a single line from the given configuration file, adding the name + // on the line to the names list. + // + // Parse the content of the given URL as a provider-configuration file. + // + // @param service + // The service type for which providers are being sought; + // used to construct error detail strings + // + // @param u + // The URL naming the configuration file to be parsed + // + // @return A (possibly empty) iterator that will yield the provider-class + // names in the given configuration file that are not yet members + // of the returned set + // + // @throws ServiceConfigurationError + // If an I/O error occurs while reading from the given URL, or + // if a configuration-file format error is detected + // + private List parse(Class service, URL u) + { + InputStream in = null; + BufferedReader r = null; + ArrayList names = new ArrayList(); + try { + in = u.openStream(); + r = new BufferedReader(new InputStreamReader(in, "utf-8")); + int lc = 1; + while ((lc = parseLine(service, u, r, lc, names)) >= 0); + } catch (IOException x) { + fail(service, "Error reading configuration file", x); + } finally { + try { + if (r != null) { + r.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException y) { + fail(service, "Error closing configuration file", y); + } + } + return names; + } + + private int parseLine(Class service, URL u, BufferedReader r, int lc, List names) throws IOException + { + String ln = r.readLine(); + if (ln == null) { + return -1; + } + int ci = ln.indexOf('#'); + if (ci >= 0) { + ln = ln.substring(0, ci); + } + ln = ln.trim(); + int n = ln.length(); + if (n != 0) { + if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0)) { + fail(service, u, lc, "Illegal configuration-file syntax"); + } + int cp = ln.codePointAt(0); + if (!Character.isJavaIdentifierStart(cp)) { + fail(service, u, lc, "Illegal provider-class name: " + ln); + } + for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) { + cp = ln.codePointAt(i); + if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) { + fail(service, u, lc, "Illegal provider-class name: " + ln); + } + } + if (!names.contains(ln)) { + names.add(ln); + } + } + return lc + 1; + } + + private static void fail(Class service, String msg, Throwable cause) { + throw new IllegalStateException(service.getName() + ": " + msg, cause); + } + + private static void fail(Class service, String msg) { + throw new IllegalStateException(service.getName() + ": " + msg); + } + + private static void fail(Class service, URL u, int line, String msg) { + fail(service, u + ":" + line + ": " + msg); + } +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ComponentRegistryImpl.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ComponentRegistryImpl.java new file mode 100644 index 000000000..ea5ca1965 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ComponentRegistryImpl.java @@ -0,0 +1,119 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.util.tracker.ServiceTracker; +import org.osgi.util.tracker.ServiceTrackerCustomizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.switchyard.deploy.Component; +import org.switchyard.deploy.osgi.ComponentRegistry; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * ComponentRegistryImpl. + */ +public class ComponentRegistryImpl implements ComponentRegistry, ServiceTrackerCustomizer { + + private static final Logger LOGGER = LoggerFactory.getLogger(NamespaceHandlerRegistryImpl.class); + + // The bundle context is thread safe + private final BundleContext _bundleContext; + + // The service tracker is thread safe + private final ServiceTracker _tracker; + + // List of listeners + private final List _listeners = new CopyOnWriteArrayList(); + + // List of components + private final List _components = new CopyOnWriteArrayList(); + + /** + * Create a new ComponentRegistryImpl. + * @param bundleContext bundleContext + */ + public ComponentRegistryImpl(BundleContext bundleContext) { + _bundleContext = bundleContext; + _tracker = new ServiceTracker(bundleContext, Component.class, this); + _tracker.open(); + } + + @Override + public Component getComponent(String type) { + for (Component component : _components) { + if (component.getActivationTypes().contains(type)) { + return component; + } + } + return null; + } + + @Override + public void addListener(Listener listener) { + _listeners.add(listener); + } + + @Override + public void removeListener(Listener listener) { + _listeners.remove(listener); + } + + @Override + public Component addingService(ServiceReference reference) { + Component component = _bundleContext.getService(reference); + registerComponent(component); + return component; + } + + @Override + public void modifiedService(ServiceReference reference, Component component) { + unregisterComponent(component); + registerComponent(component); + } + + @Override + public void removedService(ServiceReference reference, Component component) { + unregisterComponent(component); + } + + @Override + public void destroy() { + _tracker.close(); + } + + private void registerComponent(Component component) { + _components.add(component); + for (Listener listener : _listeners) { + for (String type : component.getActivationTypes()) { + listener.componentRegistered(type); + } + } + } + + private void unregisterComponent(Component component) { + for (Listener listener : _listeners) { + for (String type : component.getActivationTypes()) { + listener.componentUnregistered(type); + } + } + component.destroy(); + _components.remove(component); + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ConfigurationExtension.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ConfigurationExtension.java new file mode 100644 index 000000000..08236fc3f --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ConfigurationExtension.java @@ -0,0 +1,76 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.osgi.internal; + +import org.osgi.framework.Bundle; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.switchyard.common.io.pull.PropertiesPuller; +import org.switchyard.config.model.Descriptor; +import org.switchyard.deploy.osgi.NamespaceHandler; +import org.switchyard.deploy.osgi.base.SimpleExtension; + +import java.net.URL; +import java.util.Dictionary; +import java.util.Hashtable; +import java.util.Properties; + +/** + * ConfigurationExtension. + */ +public class ConfigurationExtension extends SimpleExtension { + + private final Logger _logger = LoggerFactory.getLogger(SwitchYardExtender.class); + + private final SwitchYardExtender _extender; + private SimpleNamespaceHandler _handler; + private ServiceRegistration _registration; + + /** + * Create a new instance of ConfigurationExtension. + * @param extender SY extender + * @param bundle configuration bundle + */ + public ConfigurationExtension(SwitchYardExtender extender, Bundle bundle) { + super(bundle); + _extender = extender; + } + + @Override + protected void doStart() throws Exception { + URL configUrl = getBundle().getEntry(Descriptor.DEFAULT_PROPERTIES); + Properties properties = new PropertiesPuller().pull(configUrl); + _handler = new SimpleNamespaceHandler(getBundle(), properties); + _logger.info("Registering namespace handler for " + _handler.getNamespaces()); + if (_registration == null) { + Dictionary props = new Hashtable(); + props.put(NamespaceHandler.NAMESPACES, _handler.getNamespaces()); + _registration = getBundleContext().registerService(NamespaceHandler.class, _handler, props); + } + } + + @Override + protected void doDestroy() throws Exception { + if (_handler != null) { + _logger.info("Unregistering namespace handler for " + _handler.getNamespaces()); + if (_registration != null) { + _registration.unregister(); + _registration = null; + } + } + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ExecutorServiceWrapper.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ExecutorServiceWrapper.java new file mode 100644 index 000000000..4036311c6 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ExecutorServiceWrapper.java @@ -0,0 +1,134 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * ExecutorServiceWrapper. + */ +public class ExecutorServiceWrapper extends AbstractExecutorService implements Runnable { + + private final ExecutorService _delegate; + private final ConcurrentLinkedQueue _queue = new ConcurrentLinkedQueue(); + private final AtomicBoolean _triggered = new AtomicBoolean(); + private final AtomicBoolean _shutdown = new AtomicBoolean(); + private Thread _runningThread; + + /** + * Create a new instance of ExecutorServiceWrapper. + * @param delegate ExecutorService delegate + */ + public ExecutorServiceWrapper(ExecutorService delegate) { + this._delegate = delegate; + } + + @Override + public void shutdown() { + _shutdown.set(true); + } + + @Override + public List shutdownNow() { + List pending = new ArrayList(); + if (_shutdown.compareAndSet(false, true)) { + Runnable runnable; + while ((runnable = _queue.poll()) != null) { + pending.add(runnable); + } + } + return pending; + } + + @Override + public boolean isShutdown() { + return _shutdown.get(); + } + + @Override + public boolean isTerminated() { + return _delegate.isTerminated() || isShutdown() && _queue.isEmpty() && !_triggered.get(); + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + long millis = unit.toMillis(timeout); + if (millis > 0) { + long max = System.currentTimeMillis() + millis; + synchronized (_triggered) { + while (System.currentTimeMillis() < max) { + if (isTerminated()) { + return true; + } else { + _triggered.wait(millis); + } + } + } + } + return isTerminated(); + } + + @Override + public void execute(Runnable command) { + if (isShutdown()) { + throw new RejectedExecutionException("Executor has been shut down"); + } + _queue.add(command); + triggerExecution(); + } + + protected void triggerExecution() { + if (_triggered.compareAndSet(false, true)) { + _delegate.execute(this); + } + } + + @Override + public void run() { + try { + Runnable runnable; + synchronized (_triggered) { + _runningThread = Thread.currentThread(); + } + while (true) { + runnable = _queue.poll(); + if (runnable == null) { + return; + } + try { + runnable.run(); + } catch (Throwable e) { + Thread thread = Thread.currentThread(); + thread.getUncaughtExceptionHandler().uncaughtException(thread, e); + } + } + } finally { + synchronized (_triggered) { + _runningThread = null; + _triggered.set(false); + _triggered.notifyAll(); + } + if (!isShutdown() && !_queue.isEmpty()) { + triggerExecution(); + } + } + } +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/NamespaceHandlerRegistryImpl.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/NamespaceHandlerRegistryImpl.java new file mode 100644 index 000000000..850f97b8f --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/NamespaceHandlerRegistryImpl.java @@ -0,0 +1,706 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.lang.ref.Reference; +import java.lang.ref.SoftReference; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.AbstractMap; +import java.util.AbstractSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CopyOnWriteArraySet; +import javax.xml.XMLConstants; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.util.tracker.ServiceTracker; +import org.osgi.util.tracker.ServiceTrackerCustomizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.switchyard.deploy.osgi.NamespaceHandler; +import org.switchyard.deploy.osgi.NamespaceHandlerRegistry; +import org.switchyard.deploy.osgi.NamespaceHandlerSet; +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSResourceResolver; +import org.xml.sax.SAXException; + +/** + * Default implementation of the NamespaceHandlerRegistry. + * + * This registry will track NamespaceHandler objects in the OSGi registry and make + * them available, calling listeners when handlers are registered or unregistered. + * + */ +public class NamespaceHandlerRegistryImpl implements NamespaceHandlerRegistry, ServiceTrackerCustomizer { + + private static final Logger LOGGER = LoggerFactory.getLogger(NamespaceHandlerRegistryImpl.class); + + // The bundle context is thread safe + private final BundleContext _bundleContext; + + // The service tracker is thread safe + private final ServiceTracker _tracker; + + // The handlers map is concurrent + private final ConcurrentHashMap> _handlers = + new ConcurrentHashMap>(); + + // Access to the LRU schemas map is synchronized on itself + private final LRUMap, Reference> _schemas = + new LRUMap, Reference>(10); + + // Access to this factory is synchronized on itself + private final SchemaFactory _schemaFactory = + SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + + // Access to this variable is not synchronized. The list itself is concurrent + private final CopyOnWriteArrayList _sets = + new CopyOnWriteArrayList(); + + /** + * Create new instance of NamespaceHandlerRegistryImpl. + * @param bundleContext bundleContext + */ + public NamespaceHandlerRegistryImpl(BundleContext bundleContext) { + _bundleContext = bundleContext; + _tracker = new ServiceTracker(bundleContext, NamespaceHandler.class.getName(), this); + _tracker.open(); + } + + @Override + public Object addingService(ServiceReference reference) { + LOGGER.debug("Adding NamespaceHandler " + reference.toString()); + NamespaceHandler handler = (NamespaceHandler) _bundleContext.getService(reference); + if (handler != null) { + try { + Map props = new HashMap(); + for (String name : reference.getPropertyKeys()) { + props.put(name, reference.getProperty(name)); + } + registerHandler(handler, props); + } catch (Exception e) { + LOGGER.warn("Error registering NamespaceHandler", e); + } + } else { + LOGGER.warn("Error resolving NamespaceHandler, null Service obtained from tracked ServiceReference {} for bundle {}, ver {}", + new Object[] { reference.toString(), reference.getBundle().getSymbolicName(), reference.getBundle().getVersion() }); + } + return handler; + } + + @Override + public void modifiedService(ServiceReference reference, Object service) { + removedService(reference, service); + addingService(reference); + } + + @Override + public void removedService(ServiceReference reference, Object service) { + try { + LOGGER.debug("Removing NamespaceHandler " + reference.toString()); + NamespaceHandler handler = (NamespaceHandler) service; + Map props = new HashMap(); + for (String name : reference.getPropertyKeys()) { + props.put(name, reference.getProperty(name)); + } + unregisterHandler(handler, props); + } catch (Exception e) { + LOGGER.warn("Error unregistering NamespaceHandler", e); + } + } + + public void registerHandler(NamespaceHandler handler, Map properties) { + List namespaces = getNamespaces(properties); + for (URI uri : namespaces) { + CopyOnWriteArraySet h = _handlers.putIfAbsent(uri, new CopyOnWriteArraySet()); + if (h == null) { + h = _handlers.get(uri); + } + if (h.add(handler)) { + for (NamespaceHandlerSetImpl s : _sets) { + s.registerHandler(uri, handler); + } + } + } + } + + public void unregisterHandler(NamespaceHandler handler, Map properties) { + List namespaces = getNamespaces(properties); + for (URI uri : namespaces) { + CopyOnWriteArraySet h = _handlers.get(uri); + if (!h.remove(handler)) { + continue; + } + for (NamespaceHandlerSetImpl s : _sets) { + s.unregisterHandler(uri, handler); + } + } + removeSchemasFor(handler); + } + + private static List getNamespaces(Map properties) { + Object ns = properties != null ? properties.get(NamespaceHandler.NAMESPACES) : null; + if (ns == null) { + throw new IllegalArgumentException("NamespaceHandler service does not have an associated " + + NamespaceHandler.NAMESPACES + " property defined"); + } else if (ns instanceof URI[]) { + return Arrays.asList((URI[]) ns); + } else if (ns instanceof URI) { + return Collections.singletonList((URI) ns); + } else if (ns instanceof String) { + return Collections.singletonList(URI.create((String) ns)); + } else if (ns instanceof String[]) { + String[] strings = (String[]) ns; + List namespaces = new ArrayList(strings.length); + for (String string : strings) { + namespaces.add(URI.create(string)); + } + return namespaces; + } else if (ns instanceof Collection) { + Collection col = (Collection) ns; + List namespaces = new ArrayList(col.size()); + for (Object o : col) { + namespaces.add(toURI(o)); + } + return namespaces; + } else if (ns instanceof Object[]) { + Object[] array = (Object[]) ns; + List namespaces = new ArrayList(array.length); + for (Object o : array) { + namespaces.add(toURI(o)); + } + return namespaces; + } else { + throw new IllegalArgumentException("NamespaceHandler service has an associated " + + NamespaceHandler.NAMESPACES + " property defined which can not be converted to an array of URI"); + } + } + + private static URI toURI(Object o) { + if (o instanceof URI) { + return (URI) o; + } else if (o instanceof String) { + return URI.create((String) o); + } else { + throw new IllegalArgumentException("NamespaceHandler service has an associated " + + NamespaceHandler.NAMESPACES + " property defined which can not be converted to an array of URI"); + } + } + + public NamespaceHandlerSet getNamespaceHandlers(Set uris, Bundle bundle) { + NamespaceHandlerSetImpl s = new NamespaceHandlerSetImpl(uris, bundle); + _sets.add(s); + return s; + } + + public void destroy() { + _tracker.close(); + } + + private Schema getSchema(Map handlers, + final Bundle bundle, + final Properties schemaMap) throws IOException, SAXException { + if (schemaMap != null && !schemaMap.isEmpty()) { + return createSchema(handlers, bundle, schemaMap); + } + // Find a schema that can handle all the requested namespaces + // If it contains additional namespaces, it should not be a problem since + // they won't be used at all + Schema schema = getExistingSchema(handlers); + if (schema == null) { + // Create schema + schema = createSchema(handlers, bundle, schemaMap); + cacheSchema(handlers, schema); + } + return schema; + } + + private Schema getExistingSchema(Map handlers) { + synchronized (_schemas) { + for (Map key : _schemas.keySet()) { + boolean found = true; + for (URI uri : handlers.keySet()) { + if (!handlers.get(uri).equals(key.get(uri))) { + found = false; + break; + } + } + if (found) { + return _schemas.get(key).get(); + } + } + return null; + } + } + + private void removeSchemasFor(NamespaceHandler handler) { + synchronized (_schemas) { + List> keys = new ArrayList>(); + for (Map key : _schemas.keySet()) { + if (key.values().contains(handler)) { + keys.add(key); + } + } + for (Map key : keys) { + _schemas.remove(key); + } + } + } + + private void cacheSchema(Map handlers, Schema schema) { + synchronized (_schemas) { + // Remove schemas that are fully included + for (Iterator> iterator = _schemas.keySet().iterator(); iterator.hasNext();) { + Map key = iterator.next(); + boolean found = true; + for (URI uri : key.keySet()) { + if (!key.get(uri).equals(handlers.get(uri))) { + found = false; + break; + } + } + if (found) { + iterator.remove(); + break; + } + } + // Add our new schema + _schemas.put(handlers, new SoftReference(schema)); + } + } + + private Schema createSchema(Map handlers, + Bundle bundle, + Properties schemaMap) throws IOException, SAXException { + final List schemaSources = new ArrayList(); + try { + // Create a schema for all namespaces known at this point + // It will speed things as it can be reused for all other deployments + for (URI ns : handlers.keySet()) { + URL url = handlers.get(ns).getSchemaLocation(ns.toString()); + if (url == null) { + LOGGER.warn("No URL is defined for schema " + ns + ". This schema will not be validated"); + } else { + schemaSources.add(new StreamSource(url.openStream(), url.toExternalForm())); + } + } + for (Object ns : schemaMap.values()) { + URL url = bundle.getResource(ns.toString()); + if (url == null) { + LOGGER.warn("No URL is defined for schema " + ns + ". This schema will not be validated"); + } else { + schemaSources.add(new StreamSource(url.openStream(), url.toExternalForm())); + } + } + synchronized (_schemaFactory) { + _schemaFactory.setResourceResolver(new BundleResourceResolver(schemaMap, bundle, schemaSources)); + return _schemaFactory.newSchema(schemaSources.toArray(new Source[schemaSources.size()])); + } + } finally { + for (StreamSource s : schemaSources) { + closeQuietly(s.getInputStream()); + } + } + } + + private static void closeQuietly(Closeable closeable) { + try { + if (closeable != null) { + closeable.close(); + } + } catch (IOException e) { + // Ignore + } + } + + private class BundleResourceResolver implements LSResourceResolver { + private final Properties _schemaMap; + private final Bundle _bundle; + private final List _schemaSources; + + public BundleResourceResolver(Properties schemaMap, Bundle bundle, List schemaSources) { + _schemaMap = schemaMap; + _bundle = bundle; + _schemaSources = schemaSources; + } + + public LSInput resolveResource(String type, + final String namespaceURI, + final String publicId, + String systemId, String baseURI) { + String loc = null; + if (namespaceURI != null) { + loc = _schemaMap.getProperty(namespaceURI); + } + if (loc == null && publicId != null) { + loc = _schemaMap.getProperty(publicId); + } + if (loc == null && systemId != null) { + loc = _schemaMap.getProperty(systemId); + } + if (loc != null) { + URL url = _bundle.getResource(loc); + if (url != null) { + try { + StreamSource source + = new StreamSource(url.openStream(), url.toExternalForm()); + _schemaSources.add(source); + return new SourceLSInput(source, publicId, url); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + URI uri = URI.create(namespaceURI); + Set hs = NamespaceHandlerRegistryImpl.this._handlers.get(uri); + if (hs == null) { + return null; + } + for (NamespaceHandler h : hs) { + URL url = h.getSchemaLocation(namespaceURI); + if (url != null) { + // handling include-relative-path case + if (systemId != null && !systemId.matches("^[a-z][-+.0-9a-z]*:.*")) { + try { + url = new URL(url, systemId); + } catch (Exception e) { + // ignore and use the given systemId + } + } + try { + final StreamSource source = new StreamSource(url.openStream(), url.toExternalForm()); + _schemaSources.add(source); + return new SourceLSInput(source, publicId, url); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + return null; + } + } + + private class SourceLSInput implements LSInput { + private final StreamSource _source; + private final URL _systemId; + private final String _publicId; + + public SourceLSInput(StreamSource source, String publicId, URL systemId) { + _source = source; + _publicId = publicId; + _systemId = systemId; + } + + public Reader getCharacterStream() { + return null; + } + + public void setCharacterStream(Reader characterStream) { + } + + public InputStream getByteStream() { + return _source.getInputStream(); + } + + public void setByteStream(InputStream byteStream) { + } + + public String getStringData() { + return null; + } + + public void setStringData(String stringData) { + } + + public String getSystemId() { + return _systemId.toExternalForm(); + } + + public void setSystemId(String systemId) { + } + + public String getPublicId() { + return _publicId; + } + + public void setPublicId(String publicId) { + } + + public String getBaseURI() { + return null; + } + + public void setBaseURI(String baseURI) { + } + + public String getEncoding() { + return null; + } + + public void setEncoding(String encoding) { + } + + public boolean getCertifiedText() { + return false; + } + + public void setCertifiedText(boolean certifiedText) { + } + } + + protected class NamespaceHandlerSetImpl implements NamespaceHandlerSet { + + private final List _listeners; + private final Bundle _bundle; + private final Set _namespaces; + private final Map _nsHandlers; + private final Properties _schemaMap = new Properties(); + private Schema _schema; + + public NamespaceHandlerSetImpl(Set namespaces, Bundle bundle) { + _listeners = new CopyOnWriteArrayList(); + _namespaces = namespaces; + _bundle = bundle; + _nsHandlers = new HashMap(); + for (URI ns : namespaces) { + findCompatibleNamespaceHandler(ns); + } + URL url = bundle.getResource("OSGI-INF/switchyard/schema.map"); + if (url != null) { + InputStream ins = null; + try { + ins = url.openStream(); + _schemaMap.load(ins); + } catch (IOException ex) { + ex.printStackTrace(); + //ignore + } finally { + closeQuietly(ins); + } + } + for (Object ns : _schemaMap.keySet()) { + try { + this._namespaces.remove(new URI(ns.toString())); + } catch (URISyntaxException e) { + //ignore + } + } + } + + public boolean isComplete() { + return _nsHandlers.size() == _namespaces.size(); + } + + public Set getNamespaces() { + return _namespaces; + } + + public NamespaceHandler getNamespaceHandler(URI namespace) { + return _nsHandlers.get(namespace); + } + + public Schema getSchema() throws SAXException, IOException { + if (!isComplete()) { + throw new IllegalStateException("NamespaceHandlerSet is not complete"); + } + if (_schema == null) { + _schema = NamespaceHandlerRegistryImpl.this.getSchema(_nsHandlers, _bundle, _schemaMap); + } + return _schema; + } + + public void addListener(Listener listener) { + _listeners.add(listener); + } + + public void removeListener(Listener listener) { + _listeners.remove(listener); + } + + public void destroy() { + NamespaceHandlerRegistryImpl.this._sets.remove(this); + } + + public void registerHandler(URI uri, NamespaceHandler handler) { + if (_namespaces.contains(uri) && _nsHandlers.get(uri) == null) { + if (findCompatibleNamespaceHandler(uri) != null) { + for (Listener listener : _listeners) { + try { + listener.namespaceHandlerRegistered(uri); + } catch (Throwable t) { + LOGGER.debug("Unexpected exception when notifying a NamespaceHandler listener", t); + } + } + } + } + } + + public void unregisterHandler(URI uri, NamespaceHandler handler) { + if (_nsHandlers.get(uri) == handler) { + _nsHandlers.remove(uri); + for (Listener listener : _listeners) { + try { + listener.namespaceHandlerUnregistered(uri); + } catch (Throwable t) { + LOGGER.debug("Unexpected exception when notifying a NamespaceHandler listener", t); + } + } + } + } + + private NamespaceHandler findCompatibleNamespaceHandler(URI ns) { + Set candidates = NamespaceHandlerRegistryImpl.this._handlers.get(ns); + if (candidates != null) { + for (NamespaceHandler h : candidates) { + Set classes = h.getManagedClasses(); + boolean compat = true; + if (classes != null) { + Set allClasses = new HashSet(); + for (Class cl : classes) { + for (Class c = cl; c != null; c = c.getSuperclass()) { + allClasses.add(c); + for (Class i : c.getInterfaces()) { + allClasses.add(i); + } + } + } + for (Class cl : allClasses) { + Class clb; + try { + clb = _bundle.loadClass(cl.getName()); + if (clb != cl) { + compat = false; + break; + } + } catch (ClassNotFoundException e) { + // Ignore + } catch (NoClassDefFoundError e) { + // Ignore + } + } + } + if (compat) { + _nsHandlers.put(ns, h); + return h; + } + } + } + return null; + } + } + + public static class LRUMap extends AbstractMap { + + private final int bound; + private final LinkedList> entries = new LinkedList>(); + + private static class LRUEntry implements Entry { + private final K key; + private final V value; + + private LRUEntry(K key, V value) { + this.key = key; + this.value = value; + } + + public K getKey() { + return key; + } + + public V getValue() { + return value; + } + + public V setValue(V value) { + throw new UnsupportedOperationException(); + } + } + + private LRUMap(int bound) { + this.bound = bound; + } + + public V get(Object key) { + if (key == null) { + throw new NullPointerException(); + } + for (Entry e : entries) { + if (e.getKey().equals(key)) { + entries.remove(e); + entries.addFirst(e); + return e.getValue(); + } + } + return null; + } + + public V put(K key, V value) { + if (key == null) { + throw new NullPointerException(); + } + V old = null; + for (Entry e : entries) { + if (e.getKey().equals(key)) { + entries.remove(e); + old = e.getValue(); + break; + } + } + if (value != null) { + entries.addFirst(new LRUEntry(key, value)); + while (entries.size() > bound) { + entries.removeLast(); + } + } + return old; + } + + public Set> entrySet() { + return new AbstractSet>() { + public Iterator> iterator() { + return entries.iterator(); + } + + public int size() { + return entries.size(); + } + }; + } + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/OsgiDomainManager.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/OsgiDomainManager.java new file mode 100644 index 000000000..cfe8fe757 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/OsgiDomainManager.java @@ -0,0 +1,73 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.osgi.framework.BundleContext; +import org.switchyard.ServiceDomain; +import org.switchyard.bus.camel.CamelExchangeBus; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.internal.DomainImpl; +import org.switchyard.internal.transform.BaseTransformerRegistry; +import org.switchyard.internal.validate.BaseValidatorRegistry; +import org.switchyard.security.service.ServiceDomainSecurity; +import org.switchyard.transform.TransformerRegistry; +import org.switchyard.validate.ValidatorRegistry; + +/** + */ +public class OsgiDomainManager extends ServiceDomainManager { + + @SuppressWarnings("unused") + private final SwitchYardExtender _extender; + + public OsgiDomainManager(SwitchYardExtender extender) { + _extender = extender; + } + + public ServiceDomain createDomain(BundleContext bundleContext, QName domainName, SwitchYardModel switchyardConfig) { + TransformerRegistry transformerRegistry = new BaseTransformerRegistry(); + ValidatorRegistry validatorRegistry = new BaseValidatorRegistry(); + + OsgiSwitchYardCamelContextImpl camelContext = new OsgiSwitchYardCamelContextImpl(bundleContext); + CamelExchangeBus bus = new CamelExchangeBus(camelContext); + + ServiceDomainSecurity serviceSecurities = getServiceDomainSecurity(switchyardConfig); + + DomainImpl domain = new DomainImpl( + domainName, getRegistry(), bus, transformerRegistry, + validatorRegistry, getEventManager(), serviceSecurities); + camelContext.setServiceDomain(domain); + + /*if (switchyardConfig != null) { + domain.getHandlers().addAll(getDomainHandlers(switchyardConfig.getDomain())); + }*/ + + // set properties on the domain + Map properties = getDomainProperties(switchyardConfig); + for (Map.Entry property : properties.entrySet()) { + domain.setProperty(property.getKey(), property.getValue()); + } + + // now that all resources and properties are set, init the domain + domain.init(); + + return domain; + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/OsgiSwitchYardCamelContextImpl.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/OsgiSwitchYardCamelContextImpl.java new file mode 100644 index 000000000..8c529ec77 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/OsgiSwitchYardCamelContextImpl.java @@ -0,0 +1,58 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import org.apache.camel.TypeConverter; +import org.apache.camel.core.osgi.OsgiCamelContextHelper; +import org.apache.camel.core.osgi.OsgiFactoryFinderResolver; +import org.apache.camel.core.osgi.OsgiTypeConverter; +import org.apache.camel.core.osgi.utils.BundleContextUtils; +import org.apache.camel.impl.CompositeRegistry; +import org.apache.camel.spi.FactoryFinder; +import org.osgi.framework.BundleContext; +import org.switchyard.common.camel.SwitchYardCamelContextImpl; + +/** + * OsgiSwitchYardCamelContextImpl. + */ +public class OsgiSwitchYardCamelContextImpl extends SwitchYardCamelContextImpl { + + private final BundleContext _bundleContext; + + /** + * Create a new instance of OsgiSwitchYardCamelContextImpl. + * @param bundleContext bundleContext + */ + public OsgiSwitchYardCamelContextImpl(BundleContext bundleContext) { + _bundleContext = bundleContext; + OsgiCamelContextHelper.osgiUpdate(this, bundleContext); + } + + @Override + protected CompositeRegistry createRegistry() { + return (CompositeRegistry) OsgiCamelContextHelper.wrapRegistry(this, super.createRegistry(), _bundleContext); + } + + @Override + protected TypeConverter createTypeConverter() { + // CAMEL-3614: make sure we use a bundle context which imports org.apache.camel.impl.converter package + BundleContext ctx = BundleContextUtils.getBundleContext(getClass()); + if (ctx == null) { + ctx = _bundleContext; + } + FactoryFinder finder = new OsgiFactoryFinderResolver(_bundleContext).resolveDefaultFactoryFinder(getClassResolver()); + return new OsgiTypeConverter(ctx, getInjector(), finder); + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ProviderRegistryImpl.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ProviderRegistryImpl.java new file mode 100644 index 000000000..a38ec0e8c --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/ProviderRegistryImpl.java @@ -0,0 +1,348 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.ServiceReference; +import org.osgi.util.tracker.BundleTracker; +import org.osgi.util.tracker.BundleTrackerCustomizer; +import org.switchyard.common.util.ProviderRegistry; + +/** + * ProviderRegistryImpl. + */ +public class ProviderRegistryImpl implements ProviderRegistry.Registry, BundleTrackerCustomizer { + + public static final long DEFAULT_TIMEOUT = 0l; + public static final String TIMEOUT = "org.switchyard.providers.timeout"; + + private Map>> _factories; + + private ReadWriteLock _lock = new ReentrantReadWriteLock(); + private final BundleContext _bundleContext; + private final BundleTracker _tracker; + + private ConcurrentMap>> allFactories = new ConcurrentHashMap>>(); + + /** + * Create a new instance of ProviderRegistryImpl. + * @param bundleContext bundleContext + */ + public ProviderRegistryImpl(BundleContext bundleContext) { + _bundleContext = bundleContext; + _tracker = new BundleTracker(bundleContext, Bundle.ACTIVE, this); + _tracker.open(); + } + + @Override + public T getProvider(Class clazz) { + try { + T provider = null; + // Attempt to resolve via META-INF/services first + Class pvdClass = locate(clazz); + if (pvdClass != null) { + provider = pvdClass.newInstance(); + } else { + // Not found in META-INF/services, try OSGi Service Registry + ServiceReference ref = _bundleContext.getServiceReference(clazz); + if (ref != null) { + provider = _bundleContext.getService(ref); + } + } + return provider; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public List getProviders(Class clazz) { + try { + List providers = new ArrayList(); + List> pvds = locateAll(clazz); + for (Class pvd : pvds) { + providers.add(pvd.newInstance()); + } + return providers; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public void destroy() { + _tracker.close(); + } + + @Override + public Bundle addingBundle(Bundle bundle, BundleEvent event) { + register(bundle); + return bundle; + } + + @Override + public void modifiedBundle(Bundle bundle, BundleEvent event, Bundle object) { + } + + @Override + public void removedBundle(Bundle bundle, BundleEvent event, Bundle object) { + unregister(bundle.getBundleId()); + } + + public void register(String id, Callable factory) { + _lock.writeLock().lock(); + try { + if (_factories == null) { + _factories = new HashMap>>(); + } + List> l = _factories.get(id); + if (l == null) { + l = new ArrayList>(); + _factories.put(id, l); + } + l.add(0, factory); + synchronized (_lock) { + _lock.notifyAll(); + } + } finally { + _lock.writeLock().unlock(); + } + } + + + public void unregister(String id, Callable factory) { + _lock.writeLock().lock(); + try { + if (_factories != null) { + List> l = _factories.get(id); + if (l != null) { + l.remove(factory); + } + } + } finally { + _lock.writeLock().unlock(); + } + } + + public Class locate(Class factoryId) { + return locate(factoryId, factoryId.getName()); + } + + private static long getTimeout() { + long timeout = DEFAULT_TIMEOUT; + try { + String prop = System.getProperty(TIMEOUT); + if (prop != null) { + timeout = Long.parseLong(prop); + } + } catch (Throwable t) { } + return timeout; + } + + public Class locate(Class factoryClass, String factoryId) { + long timeout = getTimeout(); + if (timeout <= 0) { + return doLocate(factoryClass, factoryId); + } + long t0 = System.currentTimeMillis(); + long t1 = t0; + while (t1 - t0 < timeout) { + Class impl = doLocate(factoryClass, factoryId); + if (impl != null) { + return impl; + } + synchronized (_lock) { + try { + _lock.wait(timeout - (t1 - t0)); + } catch (InterruptedException e) { + return null; + } + } + t1 = System.currentTimeMillis(); + } + return null; + } + + private Class doLocate(Class factoryClass, String factoryId) { + _lock.readLock().lock(); + try { + if (_factories != null) { + List> l = _factories.get(factoryId); + if (l != null && !l.isEmpty()) { + // look up the System property first + String factoryClassName = System.getProperty(factoryId); + try { + for (Callable i : l) { + Class c = null; + try { + c = i.call(); + } catch (Exception ex) { + // do nothing here + } + if (c != null && factoryClass == c.getClassLoader().loadClass(factoryClass.getName()) + && (factoryClassName == null || c.getName().equals(factoryClassName))) + { + return c; + } + } + } catch (Exception ex) { + // do nothing here + } + } + } + return null; + } finally { + _lock.readLock().unlock(); + } + } + + public List> locateAll(Class factoryId) { + return locateAll(factoryId, factoryId.getName()); + } + + public List> locateAll(Class factoryClass, String factoryId) { + _lock.readLock().lock(); + try { + List> classes = new ArrayList>(); + if (_factories != null) { + List> l = _factories.get(factoryId); + if (l != null) { + for (Callable i : l) { + try { + Class c = i.call(); + if (c != null && factoryClass.isAssignableFrom(c)) { + classes.add(c); + } + } catch (Exception e) { + } + } + } + } + return classes; + } finally { + _lock.readLock().unlock(); + } + } + + protected void register(final Bundle bundle) { + Map> map = allFactories.get(bundle.getBundleId()); + Enumeration e = bundle.findEntries("META-INF/services/", "*", false); + if (e != null) { + while (e.hasMoreElements()) { + final URL u = e.nextElement(); + final String url = u.toString(); + if (url.endsWith("/")) { + continue; + } + final String factoryId = url.substring(url.lastIndexOf("/") + 1); + if (map == null) { + map = new HashMap>(); + allFactories.put(bundle.getBundleId(), map); + } + map.put(factoryId, new BundleFactoryLoader(factoryId, u, bundle)); + } + } + if (map != null) { + for (Map.Entry> entry : map.entrySet()) { + register(entry.getKey(), entry.getValue()); + } + } + } + + protected void unregister(long bundleId) { + Map> map = allFactories.remove(bundleId); + if (map != null) { + for (Map.Entry> entry : map.entrySet()) { + unregister(entry.getKey(), entry.getValue()); + } + } + } + + private class BundleFactoryLoader implements Callable { + private final String factoryId; + private final URL u; + private final Bundle bundle; + private volatile Class clazz; + + public BundleFactoryLoader(String factoryId, URL u, Bundle bundle) { + this.factoryId = factoryId; + this.u = u; + this.bundle = bundle; + } + + public Class call() throws Exception { + try { + if (clazz == null){ + synchronized (this) { + if (clazz == null){ + BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream(), "UTF-8")); + try { + String factoryClassName = br.readLine(); + while (factoryClassName != null) { + factoryClassName = factoryClassName.trim(); + if (factoryClassName.charAt(0) != '#') { + clazz = bundle.loadClass(factoryClassName); + return clazz; + } + factoryClassName = br.readLine(); + } + } finally { + br.close(); + } + } + } + } + return clazz; + } catch (Exception e) { + throw e; + } catch (Error e) { + throw e; + } + } + + @Override + public String toString() { + return u.toString(); + } + + @Override + public int hashCode() { + return u.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof BundleFactoryLoader) { + return u.equals(((BundleFactoryLoader) obj).u); + } else { + return false; + } + } + } +} \ No newline at end of file diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SimpleNamespaceHandler.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SimpleNamespaceHandler.java new file mode 100644 index 000000000..1efeb0370 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SimpleNamespaceHandler.java @@ -0,0 +1,115 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.net.URL; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.osgi.framework.Bundle; +import org.switchyard.common.type.reflect.Construction; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Marshaller; +import org.switchyard.deploy.osgi.NamespaceHandler; + +/** + * SimpleNamespaceHandler. + */ +public class SimpleNamespaceHandler implements NamespaceHandler { + + private final Bundle _bundle; + private final Properties _properties; + + public SimpleNamespaceHandler(Bundle bundle, Properties properties) { + _bundle = bundle; + _properties = properties; + } + + @Override + public URL getSchemaLocation(String namespace) { + String prefix = getPrefix(namespace); + if (prefix == null) { + return null; + } + String location = _properties.getProperty(prefix + ".location"); + String schema = _properties.getProperty(prefix + ".schema"); + return _bundle.getResource(location + schema); + } + + @Override + public Marshaller createMarshaller(String namespace, Descriptor desc) { + try { + Class clazz = getMarshallerClass(namespace); + if (clazz != null) { + return Construction.construct(clazz, new Class[]{Descriptor.class}, new Object[]{desc}); + } + return null; + } catch (Exception e) { + throw new IllegalStateException("Unable to create marshaller", e); + } + } + + @Override + public Set getManagedClasses() { + Set classes = new HashSet(); + for (String namespace : getNamespaces()) { + Class clazz = getMarshallerClass(namespace); + if (clazz != null) { + classes.add(clazz); + } + } + return classes; + } + + Class getMarshallerClass(String namespace) { + String prefix = getPrefix(namespace); + if (prefix == null) { + return null; + } + String className = _properties.getProperty(prefix + ".marshaller"); + if (className != null) { + try { + return (Class) _bundle.loadClass(className); + } catch (Exception e) { + throw new IllegalStateException("Unable to load marshaller", e); + } + } + return null; + } + + String getPrefix(String namespace) { + for (String key : _properties.stringPropertyNames()) { + if (key.endsWith(".namespace")) { + if (namespace.equals(_properties.getProperty(key))) { + return key.substring(0, key.length() - ".namespace".length()); + } + } + } + return null; + } + + List getNamespaces() { + List namespaces = new ArrayList(); + for (String key : _properties.stringPropertyNames()) { + if (key.endsWith(".namespace")) { + namespaces.add(_properties.getProperty(key)); + } + } + return namespaces; + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardContainerImpl.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardContainerImpl.java new file mode 100644 index 000000000..1265b9d69 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardContainerImpl.java @@ -0,0 +1,605 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Dictionary; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.xml.XMLConstants; +import javax.xml.validation.Schema; + +import org.osgi.framework.Bundle; +import org.osgi.framework.Constants; +import org.osgi.framework.Filter; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.osgi.framework.ServiceRegistration; +import org.osgi.framework.wiring.BundleWire; +import org.osgi.framework.wiring.BundleWiring; +import org.osgi.service.cm.ConfigurationAdmin; +import org.osgi.util.tracker.ServiceTracker; +import org.osgi.util.tracker.ServiceTrackerCustomizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.switchyard.ServiceDomain; +import org.switchyard.common.io.pull.ElementPuller; +import org.switchyard.common.property.CompoundPropertyResolver; +import org.switchyard.common.property.PropertyResolver; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.config.model.Marshaller; +import org.switchyard.config.model.ModelPuller; +import org.switchyard.config.model.composite.BindingModel; +import org.switchyard.config.model.composite.ComponentImplementationModel; +import org.switchyard.config.model.composite.ComponentModel; +import org.switchyard.config.model.composite.CompositeReferenceModel; +import org.switchyard.config.model.composite.CompositeServiceModel; +import org.switchyard.config.model.switchyard.SwitchYardModel; +import org.switchyard.config.model.transform.TransformsModel; +import org.switchyard.deploy.Activator; +import org.switchyard.deploy.Component; +import org.switchyard.deploy.internal.Deployment; +import org.switchyard.deploy.osgi.ComponentRegistry; +import org.switchyard.deploy.osgi.NamespaceHandler; +import org.switchyard.deploy.osgi.NamespaceHandlerSet; +import org.switchyard.deploy.osgi.SwitchYardContainer; +import org.switchyard.deploy.osgi.SwitchYardEvent; +import org.switchyard.deploy.osgi.base.SimpleExtension; +import org.switchyard.transform.internal.DuplicateTransformerException; +import org.switchyard.transform.internal.TransformerRegistryLoader; +import org.switchyard.transform.osgi.internal.TransformSource; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * SwitchYardContainerImpl. + */ +public class SwitchYardContainerImpl extends SimpleExtension + implements NamespaceHandlerSet.Listener, ComponentRegistry.Listener, Runnable, SwitchYardContainer { + + public static final String SWITCHYARD_DEPLOYMENT_BUNDLE = "switchyard.deployment.bundle"; + public static final String CONTAINER_SYMBOLIC_NAME_PROPERTY = "switchyard.container.symbolicname"; + public static final String CONTAINER_VERSION_PROPERTY = "switchyard.container.version"; + + private static final Logger logger = LoggerFactory.getLogger(SwitchYardExtender.class); + + public enum State { + Unknown, + WaitForCdi, + WaitForNamespaceHandlers, + WaitForComponents, + Created, + Failed, + } + + + private final SwitchYardExtender _extender; + private final Bundle _extenderBundle; + private State _state = State.Unknown; + private Element _xml; + private SwitchYardModel _model; + private Set _namespaces; + private NamespaceHandlerSet _nhs; + private Set _types; + private ServiceDomain _domain; + private Deployment _deployment; + private final AtomicBoolean _scheduled = new AtomicBoolean(); + private final AtomicBoolean _destroyed = new AtomicBoolean(false); + private final ExecutorService _executors; + private ServiceRegistration _registration; + private ServiceTracker _cdiContainerTracker; + private Object _cdiContainer; + + public SwitchYardContainerImpl(SwitchYardExtender extender, Bundle bundle, ExecutorService executor) { + super(bundle); + _extender = extender; + _extenderBundle = extender.getBundleContext().getBundle(); + _executors = executor != null ? new ExecutorServiceWrapper(executor) : null; + } + + @Override + protected Object getLock() { + return _scheduled; + } + + public void schedule() { + if (_scheduled.compareAndSet(false, true) && !_destroyed.get()) { + _executors.submit(this); + } + } + + public void run() { + _scheduled.set(false); + synchronized (_scheduled) { + doStart(); + } + } + + @Override + protected void doStart() { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(_bundle.adapt(BundleWiring.class).getClassLoader()); + for (;;) { + if (_destroyed.get()) { + return; + } + if (_bundle.getState() != Bundle.ACTIVE && _bundle.getState() != Bundle.STARTING) { + return; + } + if (_bundle.getBundleContext() != _bundleContext) { + return; + } + logger.debug("Running switchyard container for bundle {} in state {}", _bundle.getSymbolicName(), _state); + switch (_state) { + case Unknown: { + dispatch(SwitchYardEvent.CREATING); + boolean needsCdi = false; + List wires = _bundle.adapt(BundleWiring.class).getRequiredWires("osgi.extender"); + for (BundleWire wire : wires) { + String filterStr = wire.getRequirement().getDirectives().get("filter"); + Filter filter = FrameworkUtil.createFilter(filterStr); + Dictionary props = new Hashtable(); + props.put("osgi.extender", "pax.cdi"); + needsCdi = filter.match(props); + } + if (needsCdi) { + String filter = "(&(objectClass=org.ops4j.pax.cdi.spi.CdiContainer)(bundleId=" + _bundle.getBundleId() + "))"; + _cdiContainerTracker = new ServiceTracker(_bundleContext, FrameworkUtil.createFilter(filter), new ServiceTrackerCustomizer() { + @Override + public Object addingService(ServiceReference reference) { + synchronized (_scheduled) { + _cdiContainer = _bundleContext.getService(reference); + } + schedule(); + return _cdiContainer; + } + @Override + public void modifiedService(ServiceReference reference, Object service) { + } + @Override + public void removedService(ServiceReference reference, Object service) { + _bundleContext.ungetService(reference); + enterGracePeriod(); + } + }); + _cdiContainerTracker.open(); + } + _state = State.WaitForCdi; + break; + } + case WaitForCdi: { + if (_cdiContainerTracker != null) { + if (_cdiContainer == null) { + String filter = "(&(objectClass=org.ops4j.pax.cdi.spi.CdiContainer)(bundleId=" + _bundle.getBundleId() + "))"; + dispatch(SwitchYardEvent.GRACE_PERIOD, Collections.singleton(filter)); + return; + } + } + if (_nhs == null) { + URL configUrl = getBundle().getEntry(SwitchYardExtender.SWITCHYARD_XML); + if (configUrl == null) { + configUrl = getBundle().getEntry(SwitchYardExtender.WEBINF_SWITCHYARD_XML); + } + InputStream configStream = configUrl.openStream(); + try { + _xml = new ElementPuller().pull(configStream); + } finally { + configStream.close(); + } + _namespaces = findNamespaces(new HashSet(), _xml); + _nhs = _extender.getNamespaceHandlerRegistry().getNamespaceHandlers(_namespaces, getBundle()); + _nhs.addListener(this); + } + _state = State.WaitForNamespaceHandlers; + break; + } + case WaitForNamespaceHandlers: { + List missing = new ArrayList(); + List missingURIs = new ArrayList(); + for (URI ns : _namespaces) { + if (_nhs.getNamespaceHandler(ns) == null) { + missing.add("(&(" + Constants.OBJECTCLASS + "=" + NamespaceHandler.class.getName() + ")(" + NamespaceHandler.NAMESPACES + "=" + ns + "))"); + missingURIs.add(ns); + dispatch(SwitchYardEvent.GRACE_PERIOD, missing); + } + } + if (missing.size() > 0) { + logger.info("Bundle {} is waiting for namespace handlers {}", getBundle().getSymbolicName(), missingURIs); + return; + } + _model = new ModelPuller(new OsgiDescriptor(_nhs)).pull(_xml); + OsgiPropertyResolver.set(_model, _bundle); + _types = new HashSet(); + if (_model.getComposite() != null) { + for (CompositeReferenceModel reference : _model.getComposite().getReferences()) { + for (BindingModel binding : reference.getBindings()) { + _types.add(binding.getType()); + } + } + for (ComponentModel component : _model.getComposite().getComponents()) { + ComponentImplementationModel impl = component.getImplementation(); + if (impl == null) { + throw new IllegalStateException("Component implementation should not be null"); + } + _types.add(impl.getType()); + } + for (CompositeServiceModel service : _model.getComposite().getServices()) { + for (BindingModel binding : service.getBindings()) { + _types.add(binding.getType()); + } + } + } else { + logger.info("A composite element is missing from the switchyard.xml"); + } + _extender.getComponentRegistry().addListener(this); + _state = State.WaitForComponents; + break; + } + case WaitForComponents: { + List components = new ArrayList(); + List missingTypes = new ArrayList(); + for (String type : _types) { + Component component = _extender.getComponentRegistry().getComponent(type); + if (component == null) { + missingTypes.add(type); + } else { + components.add(component); + } + } + if (!missingTypes.isEmpty()) { + logger.info("Bundle {} is waiting for components {}", getBundle().getSymbolicName(), missingTypes); + dispatch(SwitchYardEvent.GRACE_PERIOD, missingTypes); + return; + } + + ClassLoader oldTccl = Thread.currentThread().getContextClassLoader(); + ClassLoader newTccl = oldTccl; + if (_cdiContainer != null) { + try { + Method method = _cdiContainer.getClass().getMethod("getContextClassLoader"); + newTccl = (ClassLoader) method.invoke(_cdiContainer); + } catch (Throwable t) { + // Ignore + } + } + try { + Thread.currentThread().setContextClassLoader(newTccl); + _domain = _extender.getDomainManager().createDomain(getBundleContext(), _model.getQName(), _model); + _domain.setProperty(SWITCHYARD_DEPLOYMENT_BUNDLE, getBundle()); + + registerOOTBTransformers(); + + List activators = new ArrayList(); + for (Component component : components) { + activators.add(component.createActivator(_domain)); + } + _deployment = new Deployment(_model); + _deployment.init(_domain, activators); + _deployment.start(); + } finally { + Thread.currentThread().setContextClassLoader(oldTccl); + } + // Register the BlueprintContainer in the OSGi registry + int bs = _bundle.getState(); + if (_registration == null && (bs == Bundle.ACTIVE || bs == Bundle.STARTING)) { + Dictionary props = new Hashtable(); + props.put(CONTAINER_SYMBOLIC_NAME_PROPERTY, _bundle.getSymbolicName()); + props.put(CONTAINER_VERSION_PROPERTY, _bundle.getVersion()); + _registration = _bundleContext.registerService(SwitchYardContainer.class, this, props); + } + dispatch(SwitchYardEvent.CREATED); + _state = State.Created; + break; + } + case Created: + case Failed: + return; + } + } + } catch (Throwable t) { + try { + _state = State.Failed; + logger.error("Unable to start switchyard for bundle " + getBundle().getSymbolicName(), t); + dispatch(SwitchYardEvent.FAILURE, t); + destroyDeployment(); + } catch (RuntimeException re) { + logger.debug("Tidying up components failed. ", re); + throw re; + } + } finally { + Thread.currentThread().setContextClassLoader(tccl); + } + } + + @Override + protected void doDestroy() throws Exception { + dispatch(SwitchYardEvent.DESTROYING); + _executors.shutdownNow(); + try { + if (_registration != null) { + _registration.unregister(); + _registration = null; + } + } catch (Throwable t) { + logger.debug("Error unregistering Switchyard container", t); + } + if (_cdiContainerTracker != null) { + _cdiContainerTracker.close(); + _cdiContainerTracker = null; + } + if (_nhs != null) { + _nhs.removeListener(this); + _nhs.destroy(); + _nhs = null; + } + try { + _executors.awaitTermination(5 * 60, TimeUnit.SECONDS); + } catch (InterruptedException e) { + logger.debug("Interrupted waiting for executor to shut down"); + } + destroyDeployment(); + dispatch(SwitchYardEvent.DESTROYED); + logger.debug("Switchyard container destroyed: {}", _bundleContext); + } + + private void dispatch(int type) { + dispatch(new SwitchYardEvent(type, getBundle(), _extenderBundle)); + } + + private void dispatch(int type, Collection deps) { + String[] depsArray = deps.toArray(new String[deps.size()]); + dispatch(new SwitchYardEvent(type, getBundle(), _extenderBundle, depsArray)); + } + + private void dispatch(int type, Throwable t) { + dispatch(new SwitchYardEvent(type, getBundle(), _extenderBundle, t)); + } + + private void dispatch(SwitchYardEvent event) { + _extender.getEventDispatcher().switchyardEvent(event); + } + + @Override + public void namespaceHandlerRegistered(URI uri) { + if (_nhs.isComplete()) { + schedule(); + } + } + + @Override + public void namespaceHandlerUnregistered(URI uri) { + if (!_nhs.isComplete()) { + enterGracePeriod(); + } + } + + @Override + public void componentRegistered(String type) { + if (_types != null && _types.contains(type)) { + schedule(); + } + } + + @Override + public void componentUnregistered(String type) { + if (_types != null && _types.contains(type)) { + enterGracePeriod(); + } + } + + private void destroyDeployment() { + _extender.getComponentRegistry().removeListener(this); + if (_deployment != null) { + _deployment.stop(); + _deployment.destroy(); + _deployment = null; + } + if (_domain != null) { + _domain.destroy(); + _domain = null; + } + } + + private void enterGracePeriod() { + synchronized (_scheduled) { + if (_destroyed.get()) { + return; + } + try { + destroyDeployment(); + } catch (Exception e) { + logger.error("Error while stopping switchyard", e); + } + _cdiContainer = null; + _state = State.WaitForCdi; + schedule(); + } + } + + private Set findNamespaces(Set namespaces, Node node) { + if (node instanceof Element || node instanceof Attr) { + String ns = node.getNamespaceURI(); + if (ns != null && !isIgnorableAttributeNamespace(ns)) { + namespaces.add(URI.create(ns)); + } + } + NamedNodeMap nnm = node.getAttributes(); + if (nnm != null) { + for (int i = 0; i< nnm.getLength(); i++) { + findNamespaces(namespaces, nnm.item(i)); + } + } + NodeList nl = node.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + findNamespaces(namespaces, nl.item(i)); + } + return namespaces; + } + + private boolean isIgnorableAttributeNamespace(String ns) { + return XMLConstants.RELAXNG_NS_URI.equals(ns) + || XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI.equals(ns) + || XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(ns) + || XMLConstants.W3C_XPATH_DATATYPE_NS_URI.equals(ns) + || XMLConstants.W3C_XPATH_DATATYPE_NS_URI.equals(ns) + || XMLConstants.XML_DTD_NS_URI.equals(ns) + || XMLConstants.XML_NS_URI.equals(ns) + || XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(ns); + } + + /** + * OSGi container code needs to register these outside of + * TransformerRegistryLoader.registerOOTBTransformers() due to the fact that + * descriptors cannot be parsed directly from the class path. + */ + private void registerOOTBTransformers() throws Exception { + Collection> refs = + _bundleContext.getServiceReferences(TransformSource.class, null); + + // Find all SY bundles which contain transformer definitions + for (final ServiceReference ref : refs) { + // Create a customized transformer loader which loads classes via the bundle + TransformerRegistryLoader loader = + new TransformerRegistryLoader(_domain.getTransformerRegistry()) { + @Override + protected Class getClass(String className) { + Class clazz = null; + try { + clazz = ref.getBundle().loadClass(className); + } catch (ClassNotFoundException ex) { + logger.warn("Failed to load transformer class " + className + + " from bundle " + ref.getBundle().getSymbolicName()); + } + return clazz; + } + }; + TransformSource trs = _bundleContext.getService(ref); + InputStream tStream = null; + + // parse and register the transformer definitions + try { + tStream = trs.getTransformsURL().openStream(); + Element tConfig = new ElementPuller().pull(tStream); + Set tNamespaces = findNamespaces(new HashSet(), tConfig); + NamespaceHandlerSet tHandlers = _extender.getNamespaceHandlerRegistry() + .getNamespaceHandlers(tNamespaces, getBundle()); + TransformsModel tm = new ModelPuller( + new OsgiDescriptor(tHandlers)).pull(tConfig); + + loader.registerTransformers(tm, false); + } catch (final DuplicateTransformerException e) { + // duplicate OOTB transformers are not an error - log for visibility + logger.debug(e.getMessage()); + } catch (Exception ex) { + logger.warn("Failed to load transformers from bundle: " + + ref.getBundle().getSymbolicName(), ex); + } finally { + if (tStream != null) { + tStream.close(); + } + _bundleContext.ungetService(ref); + } + } + } + + /** + * OSGi wrapper for Descriptor which loads marshallers and schema based on + * registered namespace handlers. + */ + private class OsgiDescriptor extends Descriptor { + + private NamespaceHandlerSet _namespaceHandlers; + + /** + * Create a new OSGi wrapper Descriptor. + * @param namespaceHandlers namespace handlers to use in descriptor + */ + OsgiDescriptor(NamespaceHandlerSet namespaceHandlers) { + super(); + _namespaceHandlers = namespaceHandlers; + } + + @Override + public synchronized Schema getSchema(Set namespaces) { + try { + return _namespaceHandlers.getSchema(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public synchronized Marshaller getMarshaller(String namespace) { + return _namespaceHandlers.getNamespaceHandler(URI.create(namespace)).createMarshaller(namespace, this); + } + + @Override + public boolean equals(Object obj) { + return super.equals(obj); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + }; + + private static final class OsgiPropertyResolver implements PropertyResolver { + + private org.osgi.service.cm.Configuration _wrapped; + + private OsgiPropertyResolver(org.osgi.service.cm.Configuration wrapped) { + _wrapped = wrapped; + } + + /** + * {@inheritDoc} + */ + @Override + public Object resolveProperty(String key) { + return _wrapped.getProperties() != null ? _wrapped.getProperties().get(key) : null; + } + + private static void set(SwitchYardModel switchyardModel, Bundle bundle) throws Exception { + ServiceReference configurationAdminReference = bundle.getBundleContext().getServiceReference(ConfigurationAdmin.class.getName()); + ConfigurationAdmin configAdmin = (ConfigurationAdmin) bundle.getBundleContext().getService(configurationAdminReference); + org.osgi.service.cm.Configuration osgiConfig = configAdmin.getConfiguration(bundle.getSymbolicName()); + if(osgiConfig != null) { + Configuration config = switchyardModel.getModelConfiguration(); + config.setPropertyResolver(CompoundPropertyResolver.compact(config.getPropertyResolver(), new OsgiPropertyResolver(osgiConfig))); + } + } + } + +} + + diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardEventDispatcher.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardEventDispatcher.java new file mode 100644 index 000000000..a7d8a7173 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardEventDispatcher.java @@ -0,0 +1,280 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.service.event.Event; +import org.osgi.service.event.EventAdmin; +import org.osgi.util.tracker.ServiceTracker; +import org.osgi.util.tracker.ServiceTrackerCustomizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.switchyard.deploy.osgi.EventConstants; +import org.switchyard.deploy.osgi.SwitchYardEvent; +import org.switchyard.deploy.osgi.SwitchYardListener; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Dictionary; +import java.util.Hashtable; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * SwitchYardEventDispatcher. + */ +public class SwitchYardEventDispatcher implements SwitchYardListener { + + private static final Logger LOGGER = LoggerFactory.getLogger(SwitchYardEventDispatcher.class); + + private final Set _listeners = new CopyOnWriteArraySet(); + private final Map _states = new ConcurrentHashMap(); + private final ExecutorService _executor; + private final ExecutorService _sharedExecutor; + private final EventAdminListener _eventAdminListener; + private final ServiceTracker _containerListenerTracker; + + SwitchYardEventDispatcher(final BundleContext bundleContext, ExecutorService sharedExecutor) { + + assert bundleContext != null; + assert sharedExecutor != null; + + _executor = Executors.newSingleThreadExecutor(new SwitchYardThreadFactory("Switchyard Event Dispatcher")); + + _sharedExecutor = sharedExecutor; + + EventAdminListener listener = null; + try { + getClass().getClassLoader().loadClass("org.osgi.service.event.EventAdmin"); + listener = new EventAdminListener(bundleContext); + } catch (Throwable t) { + // Ignore, if the EventAdmin package is not available, just don't use it + LOGGER.debug("EventAdmin package is not available, just don't use it"); + } + _eventAdminListener = listener; + + _containerListenerTracker = new ServiceTracker(bundleContext, SwitchYardListener.class.getName(), new ServiceTrackerCustomizer() { + public SwitchYardListener addingService(ServiceReference reference) { + SwitchYardListener listener = bundleContext.getService(reference); + synchronized (_listeners) { + sendInitialEvents(listener); + _listeners.add(listener); + } + return listener; + } + + public void modifiedService(ServiceReference reference, SwitchYardListener service) { + } + + public void removedService(ServiceReference reference, SwitchYardListener service) { + _listeners.remove(service); + bundleContext.ungetService(reference); + } + }); + _containerListenerTracker.open(); + } + + private void sendInitialEvents(SwitchYardListener listener) { + for (Map.Entry entry : _states.entrySet()) { + try { + callListener(listener, new SwitchYardEvent(entry.getValue(), true)); + } catch (RejectedExecutionException ree) { + LOGGER.warn("Executor shut down", ree); + break; + } + } + } + + public void switchyardEvent(final SwitchYardEvent event) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Sending switchyard container event {} for bundle {}", toString(event), event.getBundle().getSymbolicName()); + } + + synchronized (_listeners) { + callListeners(event); + _states.put(event.getBundle(), event); + } + + if (_eventAdminListener != null) { + try { + _sharedExecutor.submit(new Runnable() { + public void run() { + _eventAdminListener.switchyardEvent(event); + } + }); + } catch (RejectedExecutionException ree) { + LOGGER.warn("Executor shut down", ree); + } + } + } + + @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) + private static String toString(SwitchYardEvent event) { + return "SwitchyardEvent[type=" + getEventType(event.getType()) + + (event.getDependencies() != null ? ", dependencies=" + Arrays.asList(event.getDependencies()) : "") + + (event.getCause() != null ? ", exception=" + event.getCause().getMessage() : "") + + "]"; + } + + private static String getEventType(int type) { + switch (type) { + case SwitchYardEvent.CREATING: + return "CREATING"; + case SwitchYardEvent.CREATED: + return "CREATED"; + case SwitchYardEvent.DESTROYING: + return "DESTROYING"; + case SwitchYardEvent.DESTROYED: + return "DESTROYED"; + case SwitchYardEvent.FAILURE: + return "FAILURE"; + case SwitchYardEvent.GRACE_PERIOD: + return "GRACE_PERIOD"; + default: + return "UNKNOWN"; + } + } + + private void callListeners(SwitchYardEvent event) { + for (final SwitchYardListener listener : _listeners) { + try { + callListener(listener, event); + } catch (RejectedExecutionException ree) { + LOGGER.warn("Executor shut down", ree); + break; + } + } + } + + private void callListener(final SwitchYardListener listener, final SwitchYardEvent event) throws RejectedExecutionException { + try { + _executor.invokeAny(Collections.>singleton(new Callable() { + public Void call() throws Exception { + listener.switchyardEvent(event); + return null; + } + }), 60L, TimeUnit.SECONDS); + } catch (InterruptedException ie) { + LOGGER.warn("Thread interrupted", ie); + Thread.currentThread().interrupt(); + } catch (TimeoutException te) { + LOGGER.warn("Listener timed out, will be ignored", te); + _listeners.remove(listener); + } catch (ExecutionException ee) { + LOGGER.warn("Listener caused an exception, will be ignored", ee); + _listeners.remove(listener); + } + } + + void destroy() { + _executor.shutdown(); + // wait for the queued tasks to execute + try { + _executor.awaitTermination(60, TimeUnit.SECONDS); + } catch (InterruptedException e) { + // ignore + } + _containerListenerTracker.close(); + // clean up the EventAdmin tracker if we're using that + if (_eventAdminListener != null) { + _eventAdminListener.destroy(); + } + } + + public void removeSwitchyardBundle(Bundle bundle) { + _states.remove(bundle); + } + + private static class EventAdminListener implements SwitchYardListener { + + private final ServiceTracker tracker; + + EventAdminListener(BundleContext context) { + tracker = new ServiceTracker(context, EventAdmin.class.getName(), null); + tracker.open(); + } + + @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) + public void switchyardEvent(SwitchYardEvent event) { + EventAdmin eventAdmin = (EventAdmin) tracker.getService(); + if (eventAdmin == null) { + return; + } + + Dictionary props = new Hashtable(); + props.put(EventConstants.TYPE, event.getType()); + props.put(EventConstants.EVENT, event); + props.put(EventConstants.TIMESTAMP, event.getTimestamp()); + props.put(EventConstants.BUNDLE, event.getBundle()); + props.put(EventConstants.BUNDLE_SYMBOLICNAME, event.getBundle().getSymbolicName()); + props.put(EventConstants.BUNDLE_ID, event.getBundle().getBundleId()); + props.put(EventConstants.BUNDLE_VERSION, event.getBundle().getVersion()); + props.put(EventConstants.EXTENDER_BUNDLE, event.getExtenderBundle()); + props.put(EventConstants.EXTENDER_BUNDLE_ID, event.getExtenderBundle().getBundleId()); + props.put(EventConstants.EXTENDER_BUNDLE_SYMBOLICNAME, event.getExtenderBundle().getSymbolicName()); + props.put(EventConstants.EXTENDER_BUNDLE_VERSION, event.getExtenderBundle().getVersion()); + + if (event.getCause() != null) { + props.put(EventConstants.CAUSE, event.getCause()); + } + if (event.getDependencies() != null) { + props.put(EventConstants.DEPENDENCIES, event.getDependencies()); + } + String topic; + switch (event.getType()) { + case SwitchYardEvent.CREATING: + topic = EventConstants.TOPIC_CREATING; + break; + case SwitchYardEvent.CREATED: + topic = EventConstants.TOPIC_CREATED; + break; + case SwitchYardEvent.DESTROYING: + topic = EventConstants.TOPIC_DESTROYING; + break; + case SwitchYardEvent.DESTROYED: + topic = EventConstants.TOPIC_DESTROYED; + break; + case SwitchYardEvent.FAILURE: + topic = EventConstants.TOPIC_FAILURE; + break; + case SwitchYardEvent.GRACE_PERIOD: + topic = EventConstants.TOPIC_GRACE_PERIOD; + break; + default: + throw new IllegalStateException("Unknown switchyard event type: " + event.getType()); + } + eventAdmin.postEvent(new Event(topic, props)); + } + + /** + * Perform cleanup at Switchyard extender shutdown. + */ + public void destroy() { + tracker.close(); + } + + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardExtender.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardExtender.java new file mode 100644 index 000000000..04b6cfb11 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardExtender.java @@ -0,0 +1,180 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.osgi.framework.Bundle; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.switchyard.ServiceDomain; +import org.switchyard.admin.SwitchYard; +import org.switchyard.admin.base.SwitchYardBuilder; +import org.switchyard.common.util.ProviderRegistry; +import org.switchyard.config.Configuration; +import org.switchyard.config.model.Descriptor; +import org.switchyard.deploy.ServiceDomainManager; +import org.switchyard.deploy.osgi.ComponentRegistry; +import org.switchyard.deploy.osgi.NamespaceHandlerRegistry; +import org.switchyard.deploy.osgi.SwitchYardListener; +import org.switchyard.deploy.osgi.base.AbstractExtender; +import org.switchyard.deploy.osgi.base.CompoundExtension; +import org.switchyard.deploy.osgi.base.Extension; + +/** + * SwitchYardExtender. + */ +public class SwitchYardExtender extends AbstractExtender { + + public static final String SWITCHYARD_XML = "META-INF/switchyard.xml"; + public static final String WEBINF_SWITCHYARD_XML = "WEB-INF/switchyard.xml"; + + private final Logger _logger = LoggerFactory.getLogger(SwitchYardExtender.class); + + private NamespaceHandlerRegistry _namespaceHandlerRegistry; + + private ComponentRegistry _componentRegistry; + + private ProviderRegistryImpl _providerRegistry; + + private OsgiDomainManager _domainManager = new OsgiDomainManager(this); + + private SwitchYardEventDispatcher _eventDispatcher; + + private Runnable _management; + + @Override + protected void doStart() throws Exception { + try { + _management = createManagement(_domainManager); + } catch (NoClassDefFoundError e) { + _logger.warn("Management support disabled (package not available)", e); + } + _eventDispatcher = new SwitchYardEventDispatcher(getBundleContext(), getExecutors()); + _namespaceHandlerRegistry = new NamespaceHandlerRegistryImpl(getBundleContext()); + _componentRegistry = new ComponentRegistryImpl(getBundleContext()); + _providerRegistry = new ProviderRegistryImpl(getBundleContext()); + ProviderRegistry.setRegistry(_providerRegistry); + super.doStart(); + } + + @Override + protected void doStop() throws Exception { + super.doStop(); + if (_management != null) { + _management.run(); + _management = null; + } + + ProviderRegistry.setRegistry(null); + _providerRegistry.destroy(); + _componentRegistry.destroy(); + _namespaceHandlerRegistry.destroy(); + _eventDispatcher.destroy(); + } + + protected ExecutorService createExecutor() { + return Executors.newScheduledThreadPool(3, new SwitchYardThreadFactory("Switchyard Extender")); + } + + public NamespaceHandlerRegistry getNamespaceHandlerRegistry() { + return _namespaceHandlerRegistry; + } + + public ComponentRegistry getComponentRegistry() { + return _componentRegistry; + } + + public OsgiDomainManager getDomainManager() { + return _domainManager; + } + + public SwitchYardListener getEventDispatcher() { + return _eventDispatcher; + } + + @Override + protected Extension doCreateExtension(Bundle bundle) throws Exception { + // Check bundle compatibility + if (!checkCompatible(bundle, ServiceDomain.class, Configuration.class)) { + return null; + } + // Check switchyard extensions + List extensions = new ArrayList(); + URL swCfg = bundle.getEntry(Descriptor.DEFAULT_PROPERTIES); + if (swCfg != null) { + extensions.add(new ConfigurationExtension(this, bundle)); + } + URL swCmp = bundle.getEntry(ComponentExtension.META_INF_COMPONENT); + if (swCmp != null) { + extensions.add(new ComponentExtension(this, bundle)); + } + URL swXml = bundle.getEntry(SWITCHYARD_XML); + if (swXml == null) { + swXml = bundle.getEntry(WEBINF_SWITCHYARD_XML); + } + if (swXml != null) { + extensions.add(new SwitchYardContainerImpl(this, bundle, getExecutors())); + } + return extensions.isEmpty() ? null : new CompoundExtension(bundle, extensions); + } + + private boolean checkCompatible(Bundle bundle, Class... classes) { + for (Class clazz : classes) { + try { + Class loaded = bundle.loadClass(clazz.getName()); + if (loaded != null && loaded != clazz) { + return false; + } + } catch (Throwable t) { + // ignore if the class can' be loaded + } + } + return true; + } + + @Override + protected void debug(Bundle bundle, String msg) { + _logger.debug("Switchyard extender for bundle " + bundle + ": " + msg); + } + + @Override + protected void warn(Bundle bundle, String msg, Throwable t) { + _logger.warn("Switchyard extender for bundle " + bundle + ": " + msg, t); + } + + @Override + protected void error(String msg, Throwable t) { + _logger.debug("Switchyard extender: " + msg, t); + } + + private Runnable createManagement(ServiceDomainManager manager) { + final SwitchYardBuilder builder = new SwitchYardBuilder(); + builder.init(manager); + final ServiceRegistration reg = getBundleContext().registerService(SwitchYard.class, + builder.getSwitchYard(), null); + return new Runnable() { + @Override + public void run() { + reg.unregister(); + builder.destroy(); + } + }; + } +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardThreadFactory.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardThreadFactory.java new file mode 100644 index 000000000..af8db6990 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/SwitchYardThreadFactory.java @@ -0,0 +1,45 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.deploy.osgi.internal; + +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * SwitchYardThreadFactory. + */ +public class SwitchYardThreadFactory implements ThreadFactory { + + private final ThreadFactory _factory = Executors.defaultThreadFactory(); + private final AtomicInteger _count = new AtomicInteger(); + private final String _name; + + /** + * Create a new instance of SwitchYardThreadFactory. + * @param name + */ + public SwitchYardThreadFactory(String name) { + _name = name; + } + + @Override + public Thread newThread(Runnable r) { + final Thread t = _factory.newThread(r); + t.setName(_name + ": " + _count.incrementAndGet()); + t.setDaemon(true); + return t; + } + +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/soap/AddressingInterceptor.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/soap/AddressingInterceptor.java new file mode 100644 index 000000000..63712f78b --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/soap/AddressingInterceptor.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.osgi.internal.soap; + +import javax.xml.ws.handler.MessageContext.Scope; + +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.jaxws.context.WrappedMessageContext; +import org.apache.cxf.jaxws.interceptors.WebFaultOutInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.ws.addressing.AddressingProperties; +import org.apache.cxf.ws.addressing.AttributedURIType; +import org.apache.cxf.ws.addressing.ContextUtils; +import org.apache.cxf.ws.addressing.EndpointReferenceType; +import org.apache.cxf.ws.addressing.RelatesToType; +import org.apache.cxf.ws.addressing.soap.MAPCodec; +import org.switchyard.Context; +import org.switchyard.component.soap.util.SOAPUtil; + +/** + * Outbound Addressing handler. + * + * @author Magesh Kumar B (C) 2013 Red Hat Inc. + */ +public class AddressingInterceptor extends AbstractSoapInterceptor { + + /** + * Default Constructor. + */ + public AddressingInterceptor() { + super(Phase.PRE_PROTOCOL); + addAfter(WebFaultOutInterceptor.class.getName()); + addBefore(MAPCodec.class.getName()); + } + + /** + * {@inheritDoc} + */ + @Override + public void handleMessage(SoapMessage message) throws Fault { + if (ContextUtils.isOutbound(message)) { + AddressingProperties maps = ContextUtils.retrieveMAPs(message, false, true, false); + WrappedMessageContext soapContext = new WrappedMessageContext(message, Scope.APPLICATION); + if (soapContext.containsKey(SOAPUtil.SWITCHYARD_CONTEXT)) { + Context context = (Context)soapContext.get(SOAPUtil.SWITCHYARD_CONTEXT); + + String property = (String)context.getPropertyValue(SOAPUtil.WSA_ACTION_STR); + AttributedURIType uri = null; + EndpointReferenceType ref = null; + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + maps.setAction(uri); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_FROM_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + ref = new EndpointReferenceType(); + ref.setAddress(uri); + maps.setFrom(ref); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_TO_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + ref = new EndpointReferenceType(); + ref.setAddress(uri); + maps.setTo(ref); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_FAULTTO_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + ref = new EndpointReferenceType(); + ref.setAddress(uri); + maps.setFaultTo(ref); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_REPLYTO_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + ref = new EndpointReferenceType(); + ref.setAddress(uri); + maps.setReplyTo(ref); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_RELATESTO_STR); + if (property != null) { + RelatesToType relatesTo = new RelatesToType(); + relatesTo.setValue(property); + maps.setRelatesTo(relatesTo); + } + property = (String)context.getPropertyValue(SOAPUtil.WSA_MESSAGEID_STR); + if (property != null) { + uri = new AttributedURIType(); + uri.setValue(property); + maps.setMessageID(uri); + } + } + } + } +} diff --git a/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/soap/OsgiEndpointPublisher.java b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/soap/OsgiEndpointPublisher.java new file mode 100644 index 000000000..a91406b92 --- /dev/null +++ b/release/karaf/deploy/src/main/java/org/switchyard/deploy/osgi/internal/soap/OsgiEndpointPublisher.java @@ -0,0 +1,61 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.deploy.osgi.internal.soap; + +import java.net.MalformedURLException; + +import javax.xml.ws.WebServiceFeature; + +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.message.Message; +import org.switchyard.ServiceDomain; +import org.switchyard.component.common.Endpoint; +import org.switchyard.component.soap.InboundHandler; +import org.switchyard.component.soap.WebServicePublishException; +import org.switchyard.component.soap.config.model.SOAPBindingModel; +import org.switchyard.component.soap.endpoint.AbstractEndpointPublisher; +import org.switchyard.component.soap.endpoint.CXFJettyEndpoint; + +/** + * Handles publishing of Webservice Endpoints on CXF implementations. + * + */ +public class OsgiEndpointPublisher extends AbstractEndpointPublisher { + /** + * {@inheritDoc} + */ + public synchronized Endpoint publish(ServiceDomain domain, final SOAPBindingModel config, final String bindingId, final InboundHandler handler, WebServiceFeature... features) { + CXFJettyEndpoint wsEndpoint = null; + try { + initialize(config); + + String publishUrl = "/" + getContextPath(); + + wsEndpoint = new CXFJettyEndpoint(bindingId, handler, new AddressingInterceptor(), features); + wsEndpoint.getEndpoint().setWsdlURL(getWsdlLocation()); + wsEndpoint.getEndpoint().setServiceName(config.getPort().getServiceQName()); + wsEndpoint.publish(publishUrl); + } catch (MalformedURLException e) { + throw new WebServicePublishException(e); + } + return wsEndpoint; + } + + @Override + public Interceptor createAddressingInterceptor() { + return new AddressingInterceptor(); + } + +} diff --git a/release/karaf/deploy/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/release/karaf/deploy/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 000000000..698fc8c7c --- /dev/null +++ b/release/karaf/deploy/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/release/karaf/features/pom.xml b/release/karaf/features/pom.xml new file mode 100644 index 000000000..51a9449f3 --- /dev/null +++ b/release/karaf/features/pom.xml @@ -0,0 +1,114 @@ + + + + 4.0.0 + + org.switchyard.karaf + switchyard-karaf-parent + 2.1.0-SNAPSHOT + + switchyard + pom + SwitchYard: Karaf Features + Feature descriptions for running Switchyard on Karaf + http://switchyard.org + + + 1.9.2 + 1.0.0 + 1.1.1 + 1.0.1 + 1.1.1 + 1.1 + 1.1.1 + 1.2 + 1.0 + 1.1 + 4.2.4 + 4.2.5 + 2.1.15 + 3.3_2 + 1.7_3 + 5.2_4 + 1.4_3 + 2.2.6_1 + 1.3.9_2 + 1.6.2_6 + 2.7.1_8 + 2.7.1_5 + 1.2_5 + 2.2.0 + 3.18 + 0.9.0.M3 + 1.4.5.Final + 0.8.0 + + [5.9,6.0) + [2.14,3) + [3,4) + [4.2,4.3) + [3.2,4) + + + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-resources-plugin + + + filter + generate-resources + + resources + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + attach-artifacts + package + + attach-artifact + + + + + target/classes/features-karaf.xml + xml + features + + + target/classes/features.xml + xml + core-features + + + + + + + + + diff --git a/release/karaf/features/src/main/resources/features-karaf.xml b/release/karaf/features/src/main/resources/features-karaf.xml new file mode 100644 index 000000000..dc3a9b543 --- /dev/null +++ b/release/karaf/features/src/main/resources/features-karaf.xml @@ -0,0 +1,9 @@ + + + + mvn:org.switchyard.karaf/switchyard/${project.version}/xml/core-features + mvn:org.apache.camel.karaf/apache-camel/${version.org.apache.camel}/xml/features + mvn:org.apache.cxf.karaf/apache-cxf/${version.org.apache.cxf}/xml/features + mvn:org.apache.activemq/activemq-karaf/${version.org.apache.activemq}/xml/features + + diff --git a/release/karaf/features/src/main/resources/features.xml b/release/karaf/features/src/main/resources/features.xml new file mode 100644 index 000000000..a39dbd96b --- /dev/null +++ b/release/karaf/features/src/main/resources/features.xml @@ -0,0 +1,756 @@ + + + + mvn:org.ops4j.pax.cdi/pax-cdi-features/${version.org.ops4j.pax.cdi}/xml/features + mvn:org.drools/drools-karaf-features/${version.org.drools}/xml/features + mvn:org.milyn/milyn-smooks-all/${version.org.milyn}/xml/features + + + + + eventadmin + http + camel-core + camel-spring + switchyard-internal-core + mvn:org.switchyard.karaf/switchyard-karaf-deploy/${project.version} + mvn:org.switchyard.karaf/switchyard-karaf-commands/${project.version} + + + + switchyard-cdi + mvn:org.apache.geronimo.specs/geronimo-servlet_3.0_spec/${version.org.apache.geronimo.specs.geronimo-servlet_3.0_spec} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.xmlresolver/${version.org.apache.servicemix.bundles.xmlresolver} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.jaxb-impl/${version.org.apache.servicemix.bundles.jaxb-impl} + mvn:org.jboss.logging/jboss-logging/${version.org.jboss.logging.jboss-logging} + mvn:org.switchyard/switchyard-api/${project.version} + mvn:org.switchyard/switchyard-common/${project.version} + mvn:org.switchyard/switchyard-common-camel/${project.version} + mvn:org.switchyard/switchyard-common-cdi/${project.version} + mvn:org.switchyard/switchyard-security/${project.version} + mvn:org.switchyard/switchyard-security-karaf/${project.version} + mvn:org.switchyard/switchyard-config/${project.version} + mvn:org.switchyard/switchyard-serial/${project.version} + mvn:org.switchyard/switchyard-serial-jackson/${project.version} + mvn:org.switchyard/switchyard-runtime/${project.version} + mvn:org.switchyard/switchyard-extensions-java/${project.version} + mvn:org.switchyard/switchyard-extensions-wsdl/${project.version} + mvn:org.switchyard/switchyard-bus-camel/${project.version} + mvn:org.switchyard/switchyard-validate/${project.version} + mvn:org.switchyard/switchyard-admin/${project.version} + mvn:org.switchyard/switchyard-deploy/${project.version} + mvn:org.codehaus.jackson/jackson-core-asl/${version.org.codehaus.jackson} + mvn:org.codehaus.jackson/jackson-mapper-asl/${version.org.codehaus.jackson} + dozer + smooks + mvn:org.switchyard/switchyard-transform/${project.version} + + + + mvn:commons-collections/commons-collections/${version.commons-collections} + mvn:commons-beanutils/commons-beanutils/${version.commons-beanutils} + mvn:org.apache.commons/commons-lang3/${version.org.apache.commons.lang3} + wrap:mvn:net.sf.dozer/dozer/${version.net.sf.dozer} + + + + mvn:org.apache.geronimo.specs/geronimo-annotation_1.0_spec/${version.org.apache.geronimo.specs.geronimo-annotation_1.0_spec} + mvn:org.apache.geronimo.specs/geronimo-jpa_2.0_spec/${version.org.apache.geronimo.specs.geronimo-jpa_2.0_spec} + mvn:org.apache.geronimo.specs/geronimo-servlet_2.5_spec/${version.org.apache.geronimo.specs.geronimo-servlet_2.5_spec} + spring-tx + mvn:org.apache.geronimo.specs/geronimo-el_1.0_spec/${version.org.apache.geronimo.specs.geronimo-el_1.0_spec} + mvn:org.apache.geronimo.specs/geronimo-jta_1.1_spec/${version.org.apache.geronimo.specs.geronimo-jta_1.1_spec} + spring-jdbc + mvn:commons-lang/commons-lang/${version.commons-lang} + mvn:commons-collections/commons-collections/${version.commons-collections} + mvn:commons-pool/commons-pool/${version.commons-pool} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.commons-dbcp/${version.org.apache.servicemix.bundles.commons-dbcp} + mvn:org.apache.geronimo.specs/geronimo-jms_1.1_spec/${version.org.apache.geronimo.specs.geronimo-jms_1.1_spec} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.asm/${version.org.apache.servicemix.bundles.asm} + hibernate + spring-orm + camel-core + mvn:org.apache.camel/camel-jpa/${version.org.apache.camel} + + + + + + switchyard-jms + camel-amqp + mvn:org.switchyard.components/switchyard-component-camel-amqp/${project.version} + + + + switchyard-camel + camel-atom + mvn:org.switchyard.components/switchyard-component-camel-atom/${project.version} + + + + switchyard + mvn:org.switchyard.components/switchyard-component-common/${project.version} + mvn:org.switchyard.components/switchyard-component-bean/${project.version} + + + + jndi + switchyard + mvn:org.switchyard.components/switchyard-component-common/${project.version} + + + mvn:com.h2database/h2/${version.com.h2database} + + + camel-spring + + wrap:mvn:org.jboss.jbossts.jts/jbossjts-jacorb/${version.org.jboss.jbossts.xts} + wrap:mvn:org.jboss.jbossts.xts/jbossxts/${version.org.jboss.jbossts.xts} + wrap:mvn:org.jboss.jbossts/jbosstxbridge/${version.org.jboss.jbossts.xts} + + wrap:mvn:org.jboss.marshalling/jboss-marshalling/${version.org.jboss.marshalling} + wrap:mvn:org.jboss.marshalling/jboss-marshalling-river/${version.org.jboss.marshalling} + wrap:mvn:org.jboss/staxmapper/${version.org.jboss.staxmapper} + mvn:org.jgroups/jgroups/${version.org.jgroups} + mvn:org.infinispan/infinispan-core/${version.org.infinispan} + + hibernate + wrap:mvn:net.sourceforge.saxon/saxonhe/${version.net.sourceforge.saxon}$Export-Package=*;-noimport:=true;version="${version.net.sourceforge.saxon}" + mvn:commons-collections/commons-collections/${version.commons-collections} + mvn:commons-lang/commons-lang/${version.commons-lang} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.bcel/${version.org.apache.servicemix.bundles.bcel} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.xalan/${version.org.apache.servicemix.bundles.xalan} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.xalan-serializer/${version.org.apache.servicemix.bundles.xalan-serializer} + wrap:mvn:org.apache.xmlbeans/xmlbeans/${version.org.apache.xmlbeans} + mvn:org.codehaus.jettison/jettison/${version.org.codehaus.jettison} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.batik/${version.org.apache.servicemix.bundles.batik} + mvn:commons-codec/commons-codec/${version.commons-codec} + wrap:mvn:xml-apis/xml-apis-ext/${version.xml-apis} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.wsdl4j/${version.org.apache.servicemix.bundles.wsdl4j} + + mvn:org.overlord/overlord-commons-services/${version.overlord-commons} + + mvn:org.switchyard.karaf/switchyard-karaf-bpel/${project.version} + mvn:org.switchyard.karaf/switchyard-karaf-bpel/${project.version}/properties/riftsaw + + + + pax-cdi-1.2-weld + deltaspike-core + mvn:org.apache.camel/camel-cdi/${version.org.apache.camel} + + + + jndi + hibernate + switchyard + drools-decisiontable + jbpm + wrap:mvn:org.eclipse.aether/aether-api/${version.org.eclipse.aether.aether-api} + wrap:mvn:org.jbpm/jbpm-executor/${version.org.jbpm}$DynamicImport-Package=org.hibernate.*,javassist.* + wrap:mvn:org.jbpm/jbpm-workitems/${version.org.jbpm} + wrap:mvn:org.kie/kie-ci/${version.org.kie} + wrap:mvn:org.kie.remote/kie-remote-client/${version.org.kie} + wrap:mvn:org.kie.remote/kie-remote-common/${version.org.kie} + wrap:mvn:org.kie.remote/kie-remote-jaxb/${version.org.kie} + mvn:org.switchyard.components/switchyard-component-common/${project.version} + mvn:org.switchyard.components/switchyard-component-common-knowledge/${project.version} + + + + switchyard-common-knowledge + mvn:org.switchyard.components/switchyard-component-rules/${project.version} + + + + switchyard-common-knowledge + mvn:org.switchyard.components/switchyard-component-bpm/${project.version} + + + + switchyard + mvn:org.switchyard.components/switchyard-component-common/${project.version} + mvn:org.switchyard.components/switchyard-component-common-camel/${project.version} + mvn:org.switchyard.components/switchyard-component-camel-switchyard/${project.version} + mvn:org.switchyard.components/switchyard-component-camel-core/${project.version} + mvn:org.switchyard.components/switchyard-component-camel/${project.version} + + + + switchyard-camel + camel-cxf + mvn:org.switchyard.components/switchyard-component-camel-cxf/${project.version} + + + + switchyard-camel + mvn:org.switchyard.components/switchyard-component-camel-file/${project.version} + + + + switchyard-camel + camel-ftp + mvn:org.switchyard.components/switchyard-component-camel-ftp/${project.version} + + + + switchyard + switchyard-internal-http + + + + jetty + mvn:org.apache.httpcomponents/httpcore-osgi/${version.org.apache.httpcomponents.httpcore} + mvn:org.apache.httpcomponents/httpclient-osgi/${version.org.apache.httpcomponents.httpclient} + mvn:org.switchyard.components/switchyard-component-http/${project.version} + + + + switchyard-camel + camel-jms + mvn:org.switchyard.components/switchyard-component-camel-jms/${project.version} + + + + switchyard-camel + switchyard-camel-jpa-hibernate + mvn:org.switchyard.components/switchyard-component-camel-jpa/${project.version} + + + + switchyard-camel + camel-mail + mvn:org.switchyard.components/switchyard-component-camel-mail/${project.version} + + + + switchyard-camel + camel-mqtt + mvn:org.switchyard.components/switchyard-component-camel-mqtt/${project.version} + + + + switchyard-camel + camel-netty + mvn:org.switchyard.components/switchyard-component-camel-netty/${project.version} + + + + switchyard-camel + camel-quartz + mvn:org.switchyard.components/switchyard-component-camel-quartz/${project.version} + + + + switchyard-camel + camel-rss + mvn:org.switchyard.components/switchyard-component-camel-atom/${project.version} + mvn:org.switchyard.components/switchyard-component-camel-rss/${project.version} + + + + switchyard + switchyard-internal-rest + + + + mvn:org.apache.servicemix.specs/org.apache.servicemix.specs.jsr311-api-1.1.1/${version.org.apache.servicemix.specs.jsr311-api-1.1.1} + wrap:mvn:org.jboss.resteasy/resteasy-jaxrs/${version.org.jboss.resteasy} + wrap:mvn:org.jboss.resteasy/resteasy-jaxb-provider/${version.org.jboss.resteasy} + mvn:org.apache.httpcomponents/httpcore-osgi/${version.org.apache.httpcomponents.httpcore} + mvn:org.apache.httpcomponents/httpclient-osgi/${version.org.apache.httpcomponents.httpclient} + mvn:commons-io/commons-io/${version.commons-io} + wrap:mvn:org.scannotation/scannotation/${version.org.scannotation} + mvn:org.switchyard.components/switchyard-component-common/${project.version} + mvn:org.switchyard.components/switchyard-component-resteasy/${project.version} + + + + switchyard + switchyard-internal-sca + + + + wrap:mvn:org.jboss.marshalling/jboss-marshalling/${version.org.jboss.marshalling} + wrap:mvn:org.jboss.marshalling/jboss-marshalling-river/${version.org.jboss.marshalling} + mvn:org.jboss.marshalling/jboss-marshalling-osgi/${version.org.jboss.marshalling.jboss-marshalling-osgi} + wrap:mvn:org.jboss/staxmapper/${version.org.jboss.staxmapper} + mvn:org.jgroups/jgroups/${version.org.jgroups} + mvn:org.infinispan/infinispan-core/${version.org.infinispan} + wrap:mvn:org.jboss.jbossts.jts/jbossjts-jacorb/${version.org.jboss.jbossts.xts} + wrap:mvn:org.jboss.jbossts.xts/jbossxts/${version.org.jboss.jbossts.xts} + wrap:mvn:org.jboss.jbossts/jbosstxbridge/${version.org.jboss.jbossts.xts} + mvn:org.switchyard.components/switchyard-component-common/${project.version} + mvn:org.switchyard/switchyard-remote/${project.version} + mvn:org.switchyard.components/switchyard-component-sca/${project.version} + mvn:org.switchyard.components/switchyard-component-sca/${project.version}/properties/sca + mvn:org.switchyard.components/switchyard-component-sca/${project.version}/xml/infinispan-switchyard + + + + switchyard-camel + camel-sql + mvn:org.switchyard.components/switchyard-component-camel-sql/${project.version} + + + + switchyard + switchyard-internal-soap + + + + cxf-jaxws + cxf-http + cxf-ws-addr + cxf-specs + cxf-http-jetty + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.wsdl4j/${version.org.apache.servicemix.bundles.wsdl4j} + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.saaj-impl/${version.org.apache.servicemix.bundles.saaj-impl} + mvn:org.switchyard.components/switchyard-component-common/${project.version} + mvn:org.switchyard.components/switchyard-component-soap/${project.version} + + + + switchyard-camel + mvn:org.fusesource/camel-sap/${version.camelsap} + mvn:org.switchyard.components/switchyard-component-camel-sap/${project.version} + + + + + + switchyard-bpel + switchyard-jms + activemq-broker-noweb + mvn:org.switchyard.quickstarts/switchyard-bpel-jms-binding/${project.version} + + + + switchyard-bpel + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-bpel-loan-approval/${project.version} + + + + switchyard-bpel + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-bpel-say-hello/${project.version} + + + + switchyard-bpel + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-bpel-simple-correlation/${project.version} + + + + switchyard-bean + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-bean-service/${project.version} + + + + switchyard-bean + switchyard-soap + switchyard-bpm + mvn:org.switchyard.quickstarts/switchyard-bpm-service/${project.version} + + + + switchyard-amqp + switchyard-bean + mvn:org.switchyard.quickstarts/switchyard-camel-amqp-binding/${project.version} + + + + switchyard-atom + switchyard-bean + mvn:org.switchyard.quickstarts/switchyard-camel-atom-binding/${project.version} + + + + switchyard-bean + switchyard-file + mvn:org.switchyard.quickstarts/switchyard-camel-file-binding/${project.version} + + + + switchyard-bean + switchyard-file + camel-bindy + mvn:org.switchyard.quickstarts/switchyard-camel-bindy/${project.version} + + + + switchyard-bean + switchyard-camel-cxf + mvn:org.switchyard.quickstarts/switchyard-camel-cxf-binding/${project.version} + + + + switchyard-bean + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-camel-bus-cdi/${project.version} + + + + switchyard-ftp + switchyard-bean + + storefile = etc/ftpclient.jks + hostsfile = etc/known_hosts_sftp + keyfile = etc/id_sftp_rsa + + mvn:org.switchyard.quickstarts/switchyard-camel-ftp-binding/${project.version} + + + + switchyard-bean + switchyard-camel + camel-hl7 + camel-mina2 + mvn:org.switchyard.quickstarts/switchyard-camel-hl7/${project.version} + + + + switchyard-camel + switchyard-http + camel-jaxb + mvn:org.switchyard.quickstarts/switchyard-camel-jaxb/${project.version} + + + + switchyard-bean + switchyard-jms + activemq-broker-noweb + mvn:org.switchyard.quickstarts/switchyard-camel-jms-binding/${project.version} + + + + + jndi + transaction + jpa + switchyard-bean + switchyard-jpa + switchyard-quartz + + aries.transaction.recoverable = true + aries.transaction.timeout = 600 + aries.transaction.howl.maxLogFiles = 2 + aries.transaction.howl.maxBlocksPerFile = 512 + aries.transaction.howl.bufferSizeKBytes = 4 + + mvn:com.h2database/h2/${version.com.h2database} + mvn:org.switchyard.quickstarts/switchyard-camel-jpa-binding/${project.version} + + + + switchyard-bean + switchyard-mail + mvn:org.switchyard.quickstarts/switchyard-camel-mail-binding/${project.version} + + + + switchyard-bean + switchyard-mqtt + activemq-broker-noweb + mvn:org.switchyard.quickstarts/switchyard-camel-mqtt-binding/${project.version} + + + + switchyard-bean + switchyard-netty + mvn:org.switchyard.quickstarts/switchyard-camel-netty-binding/${project.version} + + + + switchyard-bean + switchyard-quartz + mvn:org.switchyard.quickstarts/switchyard-camel-quartz-binding/${project.version} + + + + switchyard-bean + switchyard-rss + mvn:org.switchyard.quickstarts/switchyard-camel-rss-binding/${project.version} + + + + switchyard-camel + camel-script + camel-script-javascript + camel-ognl + camel-mvel + switchyard-sca + mvn:org.switchyard.quickstarts/switchyard-camel-service/${project.version} + + + + switchyard-bean + switchyard-rules + switchyard-sca + mvn:org.switchyard.quickstarts/switchyard-remote-invoker/${project.version} + + + + switchyard-bean + switchyard-sca + mvn:org.switchyard.quickstarts.demos/switchyard-demo-cluster-dealer/${project.version} + + + + switchyard-rules + switchyard-sca + mvn:org.switchyard.quickstarts.demos/switchyard-demo-cluster-credit/${project.version} + + + + switchyard-bean + switchyard-camel + switchyard-soap + camel-saxon + mvn:org.switchyard.quickstarts/switchyard-camel-saxon/${project.version} + + + + switchyard-bean + switchyard-camel + switchyard-rules + switchyard-sca + mvn:org.switchyard.quickstarts/switchyard-rules-camel-cbr/${project.version} + + + + switchyard-bean + switchyard-soap + switchyard-rules + mvn:org.switchyard.quickstarts/switchyard-rules-interview/${project.version} + + + + switchyard-bean + switchyard-soap + switchyard-rules + mvn:org.switchyard.quickstarts/switchyard-rules-interview-container/${project.version} + + + + switchyard-bean + switchyard-soap + switchyard-rules + mvn:org.switchyard.quickstarts/switchyard-rules-interview-dtable/${project.version} + + + + + switchyard-bean + switchyard-camel + switchyard-soap + cxf + + org.switchyard.component.soap.client.port=8181/cxf + org.switchyard.component.soap.standalone.port=8181/cxf + + mvn:org.switchyard.quickstarts/switchyard-camel-soap-proxy-reverse/${project.version} + mvn:org.switchyard.quickstarts/switchyard-camel-soap-proxy/${project.version} + + + + jndi + switchyard-bean + switchyard-quartz + switchyard-sql + mvn:com.h2database/h2/${version.com.h2database} + + org.switchyard.quickstarts.camel.sql.datasourceName=osgi:service/jboss/myDS + + mvn:org.switchyard.quickstarts/switchyard-camel-sql-binding/${project.version} + + + + switchyard-soap + switchyard-bean + switchyard-camel + switchyard-file + switchyard-http + + org.switchyard.component.soap.client.port=8181/cxf + org.switchyard.component.soap.standalone.port=8181 + org.switchyard.component.http.standalone.port=8181 + + mvn:org.switchyard.quickstarts/switchyard-soap-addressing/${project.version} + + + + switchyard-soap + switchyard-bean + switchyard-camel + + org.switchyard.component.soap.client.port=8181/cxf + org.switchyard.component.soap.standalone.port=8181 + + mvn:org.switchyard.quickstarts/switchyard-soap-attachment/${project.version} + + + + switchyard-soap + switchyard-bean + switchyard-camel + + org.switchyard.component.soap.client.port=8181/cxf + org.switchyard.component.soap.standalone.port=8181 + + mvn:org.switchyard.quickstarts/switchyard-soap-binding-rpc/${project.version} + + + + switchyard-soap + switchyard-bean + switchyard-camel + + org.switchyard.component.soap.client.port=8181/cxf + org.switchyard.component.soap.standalone.port=8181 + + mvn:org.switchyard.quickstarts/switchyard-soap-mtom/${project.version} + + + + switchyard-bean + switchyard-rest + + org.switchyard.component.resteasy.standalone.port=8181 + + mvn:org.switchyard.quickstarts/switchyard-rest-binding/${project.version} + + + + switchyard-bean + switchyard-sca + mvn:org.switchyard.quickstarts/switchyard-transform-dozer/${project.version} + + + + switchyard-bean + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-transform-jaxb/${project.version} + + + + switchyard-bean + switchyard-sca + mvn:org.switchyard.quickstarts/switchyard-transform-json/${project.version} + + + + switchyard-bean + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-transform-smooks/${project.version} + + + + switchyard-bean + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-transform-xslt/${project.version} + + + + switchyard-bean + switchyard-soap + mvn:org.switchyard.quickstarts/switchyard-validate-xml/${project.version} + + + + switchyard-bean + switchyard-camel + switchyard-sap + mvn:org.switchyard.quickstarts/switchyard-camel-sap-binding/${project.version} + + + + switchyard-bean + switchyard-http + + org.switchyard.component.http.standalone.port=8181 + + mvn:org.switchyard.quickstarts/switchyard-http-binding/${project.version} + + + + switchyard-soap + switchyard-bpm + switchyard-rules + mvn:org.switchyard.quickstarts.demos/switchyard-demo-library/${project.version} + + + + switchyard-soap + switchyard-bean + switchyard-camel + mvn:org.switchyard.quickstarts.demos/switchyard-demo-policy-security-basic/${project.version} + + + + switchyard-soap + switchyard-bean + switchyard-camel + mvn:org.switchyard.quickstarts.demos/switchyard-demo-policy-security-cert/${project.version} + + + + + + jndi + transaction + + aries.transaction.recoverable = true + aries.transaction.timeout = 600 + aries.transaction.howl.maxLogFiles = 2 + aries.transaction.howl.maxBlocksPerFile = 512 + aries.transaction.howl.bufferSizeKBytes = 4 + + switchyard-bean + switchyard-jms + activemq-broker-noweb + mvn:org.switchyard.quickstarts.demos/switchyard-demo-policy-transaction/${project.version} + + + + + + switchyard-bean + switchyard-soap + switchyard-bpm + + + + + pax-cdi-1.2-web-weld + + + mvn:com.h2database/h2/${version.com.h2database} + + + mvn:commons-collections/commons-collections/${version.commons-collections} + mvn:commons-codec/commons-codec/${version.commons-codec} + mvn:commons-beanutils/commons-beanutils/${version.commons-beanutils} + mvn:commons-digester/commons-digester/${version.commons-digester} + mvn:org.apache.myfaces.core/myfaces-bundle/${version.org.apache.myfaces.core.myfaces-bundle} + mvn:org.apache.geronimo.specs/geronimo-validation_1.0_spec/${version.org.apache.geronimo.specs.geronimo-validation_1.0_spec} + + mvn:org.switchyard.quickstarts.demos/switchyard-demo-helpdesk/${project.version}/war + + + diff --git a/release/karaf/pom.xml b/release/karaf/pom.xml new file mode 100644 index 000000000..20bd7a096 --- /dev/null +++ b/release/karaf/pom.xml @@ -0,0 +1,153 @@ + + + + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + org.switchyard.karaf + switchyard-karaf-parent + pom + SwitchYard: Karaf + SwitchYard Karaf + + + 3.0.2 + 5.9.0 + + + deploy + commands + bpel + features + tests + + + + + org.apache.maven.plugins + maven-deploy-plugin + + false + + + + + + + + org.apache.cxf + cxf-core + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-bindings-coloc + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-bindings-object + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-bindings-soap + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-bindings-xml + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-databinding-jaxb + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-frontend-jaxws + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-frontend-simple + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-transports-http + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-transports-http-jetty + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-transports-local + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-ws-addr + ${version.org.apache.cxf} + + + org.apache.cxf + cxf-rt-ws-policy + ${version.org.apache.cxf} + + + org.apache.ftpserver + ftplet-api + 1.0.6 + test + + + org.apache.sshd + sshd-core + 0.9.0 + + + org.apache.sshd + sshd-sftp + 0.9.0 + + + com.jcraft + jsch + 0.1.51 + + + org.bouncycastle + bcpg-jdk15on + 1.49 + test + + + org.bouncycastle + bcpkix-jdk15on + 1.49 + test + + + + diff --git a/release/karaf/tests/pom.xml b/release/karaf/tests/pom.xml new file mode 100644 index 000000000..18698e6f5 --- /dev/null +++ b/release/karaf/tests/pom.xml @@ -0,0 +1,316 @@ + + + + + org.switchyard.karaf + switchyard-karaf-parent + 2.1.0-SNAPSHOT + + 4.0.0 + switchyard-karaf-tests + jar + SwitchYard: Karaf Tests + SwitchYard Karaf Tests + + + org.switchyard.karaf + switchyard-karaf-deploy + test + + + org.ops4j.pax.exam + pax-exam + test + + + org.ops4j.pax.exam + pax-exam-junit4 + test + + + org.ops4j.pax.exam + pax-exam-container-karaf + test + + + org.apache.karaf + apache-karaf + tar.gz + test + + + org.jboss.spec.javax.jms + jboss-jms-api_1.1_spec + test + + + org.apache.activemq + activemq-client + test + + + org.switchyard.components + switchyard-component-test-mixin-http + test + + + org.switchyard + switchyard-remote + test + + + org.switchyard.karaf + switchyard + xml + features + test + + + org.switchyard.quickstarts + switchyard-camel-cxf-binding + test + + + org.switchyard.quickstarts + switchyard-remote-invoker + test + + + org.switchyard.quickstarts + switchyard-transform-dozer + test + + + org.fusesource.mqtt-client + mqtt-client + test + + + org.apache.activemq + activemq-broker + test + + + org.apache.activemq + activemq-mqtt + test + + + org.apache.ftpserver + ftpserver-core + test + + + org.apache.ftpserver + ftplet-api + test + + + commons-io + commons-io + test + + + org.apache.sshd + sshd-core + + + org.apache.sshd + sshd-sftp + + + com.jcraft + jsch + + + org.bouncycastle + bcpg-jdk15on + test + + + org.bouncycastle + bcpkix-jdk15on + test + + + + + + org.apache.servicemix.tooling + depends-maven-plugin + + + generate-depends-file + + generate-depends-file + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + true + + + **/*Test*.java + + + **/Abstract*.java + **/*$* + **/ClusterDemoQuickstartTest.java + + **/CamelSAPBindingQuickstartTest.java + + + + + + org.apache.karaf.tooling + features-maven-plugin + 2.4.0 + + + add-features-to-repo + generate-resources + + add-features-to-repo + + + ${version.org.apache.karaf} + + mvn:org.apache.karaf.assemblies.features/spring/${version.org.apache.karaf}/xml/features + mvn:org.switchyard.karaf/switchyard/${project.version}/xml/features + + + switchyard + switchyard-amqp + switchyard-atom + switchyard-bpel + switchyard-bean + switchyard-bpm + switchyard-cdi + switchyard-camel + switchyard-file + switchyard-ftp + switchyard-jms + switchyard-jpa + switchyard-mail + switchyard-mqtt + switchyard-netty + switchyard-quartz + switchyard-rules + switchyard-rss + switchyard-sql + switchyard-soap + switchyard-sap + camel-bindy + camel-hl7 + camel-mina2 + camel-jaxb + camel-saxon + activemq-broker + + target/dependencies/apache-karaf-${version.org.apache.karaf}/system + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack + generate-resources + + unpack + + + + + org.apache.karaf + apache-karaf + tar.gz + target/dependencies + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + bin + generate-test-resources + + single + + + + src/main/assembly/bin.xml + + ${project.artifactId} + gnu + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + + springsource.release + Spring Release Repository + https://repository.jboss.org/nexus/content/repositories/springsource-obr-releases/ + default + + true + never + + + false + never + + + + springsource.external + Spring External Repository + https://repository.jboss.org/nexus/content/repositories/springsource-obr-external/ + default + + true + never + + + false + never + + + + diff --git a/release/karaf/tests/src/main/assembly/bin.xml b/release/karaf/tests/src/main/assembly/bin.xml new file mode 100644 index 000000000..10c1cc2ab --- /dev/null +++ b/release/karaf/tests/src/main/assembly/bin.xml @@ -0,0 +1,39 @@ + + + + bin + + + tar.gz + + + + + + target/dependencies/apache-karaf-${version.org.apache.karaf} + / + + bin/** + + + + + + target/dependencies/apache-karaf-${version.org.apache.karaf} + / + + bin/admin + bin/karaf + bin/start + bin/stop + + 0755 + + + target/dependencies/features-repo + /system + + + + diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/AbstractQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/AbstractQuickstartTest.java new file mode 100644 index 000000000..ba7070cfb --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/AbstractQuickstartTest.java @@ -0,0 +1,187 @@ +package org.switchyard.karaf.test.quickstarts; + +import static java.util.concurrent.TimeUnit.HOURS; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.MINUTES; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.ops4j.pax.exam.CoreOptions.composite; +import static org.ops4j.pax.exam.CoreOptions.maven; +import static org.ops4j.pax.exam.CoreOptions.options; +import static org.ops4j.pax.exam.CoreOptions.systemProperty; +import static org.ops4j.pax.exam.CoreOptions.vmOptions; +import static org.ops4j.pax.exam.CoreOptions.when; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFileExtend; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.features; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.logLevel; +import static org.switchyard.karaf.test.quickstarts.PhaseListener.Phase.ADD_TESTS; +import static org.switchyard.karaf.test.quickstarts.PhaseListener.Phase.BUILD_PROBE; +import static org.switchyard.karaf.test.quickstarts.PhaseListener.Phase.CREATE_CONTAINER; +import static org.switchyard.karaf.test.quickstarts.PhaseListener.Phase.CREATE_PROBE; +import static org.switchyard.karaf.test.quickstarts.PhaseListener.Phase.CREATE_SYSTEM; +import static org.switchyard.karaf.test.quickstarts.PhaseListener.Phase.EXECUTE_PROBE; +import static org.switchyard.karaf.test.quickstarts.PhaseListener.Phase.INSTALL_PROBE; +import static org.switchyard.karaf.test.quickstarts.PhaseListener.Phase.START_CONTAINER; + +import java.io.File; + +import org.junit.AfterClass; +import org.junit.Test; +import org.ops4j.pax.exam.ExamSystem; +import org.ops4j.pax.exam.MavenUtils; +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.TestAddress; +import org.ops4j.pax.exam.TestContainer; +import org.ops4j.pax.exam.TestProbeBuilder; +import org.ops4j.pax.exam.TestProbeProvider; +import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel; +import org.ops4j.pax.exam.spi.PaxExamRuntime; +import org.osgi.framework.Constants; +import org.switchyard.karaf.test.quickstarts.PhaseListener.Phase; + +public abstract class AbstractQuickstartTest { + protected static ExamSystem system; + protected static TestContainer testContainer; + private static TestProbeProvider testProbe; + + @AfterClass + public static void after() throws Exception { + if (testContainer != null) { + final TestContainer tc = testContainer; + testContainer = null; + tc.stop(); + } + } + + @Test + public void testDeployment() throws Exception { + /* + * Do nothing. Deployment is tested when the test container is started. + * This method simply prevents errors for "No runnable methods" for + * those test cases that don't actually exercise the deployment. + */ + } + + protected static void startTestContainer(String featureName, String bundleName) throws Exception { + startTestContainer(featureName, bundleName, null); + } + + protected static void startTestContainer(String featureName, String bundleName, Option[] additionalOptions) throws Exception { + startTestContainer(featureName, bundleName, additionalOptions, null); + } + + protected static void startTestContainer(String featureName, String bundleName, Option[] additionalOptions, Class probeClass) throws Exception { + startTestContainer(featureName, bundleName, additionalOptions, probeClass, null); + } + + protected static void startTestContainer(String featureName, String bundleName, Option[] additionalOptions, Class probeClass, PhaseListener phaseListener) throws Exception { + if (probeClass == null) { + probeClass = DeploymentProbe.class; + } + long time = System.currentTimeMillis(); + system = PaxExamRuntime.createTestSystem(mergeOptions(config(featureName, bundleName), additionalOptions)); + time = post(phaseListener, CREATE_SYSTEM, time); + testContainer = PaxExamRuntime.createContainer(system); + time = post(phaseListener, CREATE_CONTAINER, time); + testContainer.start(); + time = post(phaseListener, START_CONTAINER, time); + try { + // install the probe + TestProbeBuilder probeBuilder = system.createProbe(); + time = post(phaseListener, CREATE_PROBE, time); + probeBuilder.setHeader(Constants.DYNAMICIMPORT_PACKAGE, "*,org.apache.felix.service.*;status=provisional"); + probeBuilder.addTests(probeClass, probeClass.getMethods()); + time = post(phaseListener, ADD_TESTS, time); + testProbe = probeBuilder.build(); + time = post(phaseListener, BUILD_PROBE, time); + testContainer.installProbe(testProbe.getStream()); + time = post(phaseListener, INSTALL_PROBE, time); + // wait for SwitchYard application activation + executeProbe("testBundleActivation"); + time = post(phaseListener, EXECUTE_PROBE, time); + } catch (Exception e) { + // cleanup + after(); + throw e; + } + } + + private static long post(PhaseListener phaseListener, Phase phase, long time) throws Exception { + long duration = System.currentTimeMillis() - time; + System.out.println(String.format("Phase %s took %sh:%sm:%ss:%sms", phase.name(), + MILLISECONDS.toHours(duration), + MILLISECONDS.toMinutes(duration) - HOURS.toMinutes(MILLISECONDS.toHours(duration)), + MILLISECONDS.toSeconds(duration) - MINUTES.toSeconds(MILLISECONDS.toMinutes(duration)), + MILLISECONDS.toMillis(duration) - SECONDS.toMillis(MILLISECONDS.toSeconds(duration)))); + if (phaseListener != null) { + String plp = phaseListener.getClass().getName() + ".post(" + phase.name() + ")"; + System.out.println(plp + " executing..."); + phaseListener.post(phase); + System.out.println(plp + " done."); + } + return System.currentTimeMillis(); + } + + protected static void executeProbe(String operation) throws Exception { + final String testOperation = "." + operation; + for (TestAddress test : testProbe.getTests()) { + if (test.caption().endsWith(testOperation)) { + testContainer.call(test); + break; + } + } + } + + private static Option[] config(String featureName, String bundleName) throws Exception { + final String localMavenRepo = System.getProperty("maven.repo.local", ""); + return options( + // karafDistributionConfiguration().frameworkUrl(maven().groupId("org.apache.karaf").artifactId("apache-karaf").type("tar.gz").versionAsInProject()) + karafDistributionConfiguration() + .frameworkUrl(new File("target/switchyard-karaf-tests-bin.tar.gz").toURI().toURL().toString()) + .karafVersion(MavenUtils.getArtifactVersion("org.apache.karaf", "apache-karaf")) + .name("Apache Karaf").unpackDirectory(new File("target/karaf/" + featureName)) + .useDeployFolder(false), + //keepRuntimeFolder(), // this could leave behind lots of cruft + logLevel(LogLevel.INFO), + configureConsole().ignoreLocalConsole().ignoreRemoteShell(), + editConfigurationFileExtend("etc/config.properties", "org.osgi.framework.system.packages.extra", + "sun.misc"), + editConfigurationFilePut("etc/org.ops4j.pax.logging.cfg", "log4j.logger.org.switchyard", "DEBUG"), + editConfigurationFilePut("etc/org.ops4j.pax.logging.cfg", "log4j.logger.org.ops4j.pax.exam", "DEBUG"), + editConfigurationFilePut("etc/org.ops4j.pax.logging.cfg", "log4j.appender.out.file", + "${karaf.home}/../test.log"), + editConfigurationFilePut("etc/system.properties", "org.switchyard.component.http.standalone.port", + "8181"), + editConfigurationFilePut("etc/system.properties", "org.switchyard.component.soap.client.port", + "8181/cxf"), + editConfigurationFilePut("etc/system.properties", "org.switchyard.component.soap.standalone.port", + "8181"), + editConfigurationFilePut("etc/system.properties", "org.switchyard.component.camel.ftps.storefile", + "../../../test-classes/quickstarts/camel-ftp-binding/ftpclient.jks"), + editConfigurationFilePut("etc/system.properties", "org.switchyard.component.camel.sftp.knownhosts", + "../../../test-classes/quickstarts/camel-ftp-binding/known_hosts_sftp"), + editConfigurationFilePut("etc/system.properties", "org.switchyard.component.camel.sftp.keyfile", + "../../../test-classes/quickstarts/camel-ftp-binding/id_sftp_rsa"), + editConfigurationFilePut( + "etc/org.ops4j.pax.url.mvn.cfg", + "org.ops4j.pax.url.mvn.repositories", + "https://repository.jboss.org/nexus/content/groups/public@id=jboss-public-repository-group,http://repo1.maven.org/maven2@id=central, http://svn.apache.org/repos/asf/servicemix/m2-repo@id=servicemix, http://repository.springsource.com/maven/bundles/release@id=springsource.release, http://repository.springsource.com/maven/bundles/external@id=springsource.external, https://repository.jboss.org/nexus/content/repositories/snapshots@snapshots@noreleases@id=jboss-snapshot, https://repository.jboss.org/nexus/content/repositories/fs-releases@id=fusesource.release"), + features(maven().groupId("org.switchyard.karaf").artifactId("switchyard").type("xml").classifier("features").versionAsInProject().getURL(), featureName), + systemProperty(DeploymentProbe.BUNDLE_NAME_KEY).value(bundleName), + vmOptions("-Xmx1G", "-XX:MaxPermSize=256M"), + when(localMavenRepo.length() > 0).useOptions(systemProperty("org.ops4j.pax.url.mvn.localRepository").value(localMavenRepo))); + } + + private static Option[] mergeOptions(Option[] defaultOptions, Option[] additionalOptions) { + if (additionalOptions != null) { + return options(composite(defaultOptions), composite(additionalOptions)); + } + return defaultOptions; + } + + protected String getSoapClientPort() { + return System.getProperty("org.switchyard.component.soap.client.port", "8181/cxf"); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BPMServiceQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BPMServiceQuickstartTest.java new file mode 100644 index 000000000..9f90b713a --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BPMServiceQuickstartTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.custommonkey.xmlunit.XMLAssert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class BPMServiceQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.bpm.service"; + private static String featureName = "switchyard-quickstart-bpm-service"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Override + @Test + public void testDeployment() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String port = getSoapClientPort(); + String response = httpMixIn.postString("http://localhost:" + port + "/swydws/ProcessOrder", request); + XMLAssert.assertXpathEvaluatesTo(String.valueOf(true), "//accepted", response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String request = "" + + " " + + " " + + " " + + " test1" + + " cowbell" + + " 30" + + " " + + " " + + ""; + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BeanServiceQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BeanServiceQuickstartTest.java new file mode 100644 index 000000000..f8846e69e --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BeanServiceQuickstartTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import java.io.InputStreamReader; +import java.io.StringReader; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class BeanServiceQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.bean.service"; + private static String featureName = "switchyard-quickstart-bean-service"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testOrders() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String port = getSoapClientPort(); + String wsdl = httpMixIn.sendString("http://localhost:" + port + "/quickstart-bean/OrderService?wsdl", "", HTTPMixIn.HTTP_GET); + XMLAssert.assertXMLEqual(new InputStreamReader(Classes.getResourceAsStream("quickstarts/bean-service/OrderService.wsdl")), new StringReader(wsdl)); + String response = httpMixIn.postString("http://localhost:" + port + "/quickstart-bean/OrderService", SOAP_REQUEST); + XMLAssert.assertXpathEvaluatesTo("PO-19838-XYZ", "//orderAck/orderId", response); + XMLAssert.assertXpathEvaluatesTo("true", "//orderAck/accepted", response); + XMLAssert.assertXpathEvaluatesTo("Order Accepted [intercepted]", "//orderAck/status", response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " \n" + + " \n" + + " \n" + + " PO-19838-XYZ\n" + + " BUTTER\n" + + " 200\n" + + " \n" + + " \n" + + " \n" + + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceJmsBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceJmsBindingQuickstartTest.java new file mode 100644 index 000000000..d03e49a30 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceJmsBindingQuickstartTest.java @@ -0,0 +1,78 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.Message; +import javax.jms.MessageConsumer; +import javax.jms.MessageProducer; +import javax.jms.Session; +import javax.jms.TextMessage; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.test.SwitchYardTestKit; + +public class BpelServiceJmsBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.bpel.jms.binding"; + private static String featureName = "switchyard-quickstart-bpel-jms-binding"; + + private static final String AMQ_USER = "karaf"; + private static final String AMQ_PASSWD = "karaf"; + private static final String AMQ_BROKER_URL = "tcp://localhost:61616"; + + private static final String REQUEST_QUEUE = "HelloRequestQueue"; + private static final String REPLY_QUEUE = "HelloReplyQueue"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Override + @Test + public void testDeployment() throws Exception { + ConnectionFactory cf = new ActiveMQConnectionFactory(AMQ_USER, AMQ_PASSWD, AMQ_BROKER_URL); + Connection conn = cf.createConnection(); + + try { + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = session.createProducer(session.createQueue(REQUEST_QUEUE)); + final MessageConsumer consumer = session.createConsumer(session.createQueue(REPLY_QUEUE)); + conn.start(); + + producer.send(session.createObjectMessage(INPUT)); + + Message message = consumer.receive(3000); + String reply = ((TextMessage)message).getText(); + SwitchYardTestKit.compareXMLToString(reply, EXPECTED_REPLY); + } finally { + conn.close(); + } + } + + private static final String INPUT = "" + + "Tomo" + + ""; + + private static final String EXPECTED_REPLY = "" + + "Hello Tomo" + + ""; + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceLoanApprovalQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceLoanApprovalQuickstartTest.java new file mode 100644 index 000000000..2127a056e --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceLoanApprovalQuickstartTest.java @@ -0,0 +1,114 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.custommonkey.xmlunit.NamespaceContext; +import org.custommonkey.xmlunit.SimpleNamespaceContext; +import org.custommonkey.xmlunit.XMLUnit; +import org.custommonkey.xmlunit.XpathEngine; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.w3c.dom.NodeList; + +public class BpelServiceLoanApprovalQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.bpel.loan.approval"; + private static String featureName = "switchyard-quickstart-bpel-loan-approval"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testLoanRequestAccepted() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String port = System.getProperty("org.switchyard.component.soap.standalone.port", "8181/cxf"); + String response = httpMixIn.postString("http://localhost:" + port + "/loanService/loanService", SOAP_REQUEST_1); + + org.w3c.dom.Document d = XMLUnit.buildControlDocument(response); + java.util.HashMap m = new java.util.HashMap(); + m.put("tns", "http://example.com/loan-approval/loanService/"); + NamespaceContext ctx = new SimpleNamespaceContext(m); + XpathEngine engine = XMLUnit.newXpathEngine(); + engine.setNamespaceContext(ctx); + + NodeList l = engine.getMatchingNodes("//tns:accept", d); + assertEquals(1, l.getLength()); + assertEquals(org.w3c.dom.Node.ELEMENT_NODE, l.item(0).getNodeType()); + + if (!l.item(0).getTextContent().equals("yes")) { + fail("Expecting 'yes'"); + } + } finally { + httpMixIn.uninitialize(); + } + } + + @Test + public void testLoanRequestUnableToHandle() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:" + getSoapClientPort() + "/loanService/loanService", SOAP_REQUEST_2); + + org.w3c.dom.Document d = XMLUnit.buildControlDocument(response); + java.util.HashMap m = new java.util.HashMap(); + //m.put("tns", "http://example.com/loan-approval/loanService/"); + NamespaceContext ctx = new SimpleNamespaceContext(m); + XpathEngine engine = XMLUnit.newXpathEngine(); + engine.setNamespaceContext(ctx); + + NodeList l = engine.getMatchingNodes("//faultcode", d); + assertEquals(1, l.getLength()); + assertEquals(org.w3c.dom.Node.ELEMENT_NODE, l.item(0).getNodeType()); + + if (!l.item(0).getTextContent().endsWith(":unableToHandleRequest")) { + fail("Expecting 'unableToHandleRequest' fault code"); + } + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST_1 = "\n" + + " \n" + + " \n" + + " \n" + + " Fred\n" + + " Bloggs\n" + + " 100\n" + + " \n" + + " \n" + + ""; + + private static final String SOAP_REQUEST_2 = "\n" + + " \n" + + " \n" + + " \n" + + " Fred\n" + + " Bloggs\n" + + " 11000\n" + + " \n" + + " \n" + + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceSayHelloQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceSayHelloQuickstartTest.java new file mode 100644 index 000000000..e6cc618df --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelServiceSayHelloQuickstartTest.java @@ -0,0 +1,75 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.custommonkey.xmlunit.NamespaceContext; +import org.custommonkey.xmlunit.SimpleNamespaceContext; +import org.custommonkey.xmlunit.XMLUnit; +import org.custommonkey.xmlunit.XpathEngine; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.w3c.dom.NodeList; + +public class BpelServiceSayHelloQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.bpel.say.hello"; + private static String featureName = "switchyard-quickstart-bpel-say-hello"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Override + @Test + public void testDeployment() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:" + getSoapClientPort() + "/SayHelloService/SayHelloService", SOAP_REQUEST); + + org.w3c.dom.Document d = XMLUnit.buildControlDocument(response); + java.util.HashMap m = new java.util.HashMap(); + m.put("tns", "http://www.jboss.org/bpel/examples"); + NamespaceContext ctx = new SimpleNamespaceContext(m); + XpathEngine engine = XMLUnit.newXpathEngine(); + engine.setNamespaceContext(ctx); + + NodeList l = engine.getMatchingNodes("//tns:result", d); + assertEquals(1, l.getLength()); + assertEquals(org.w3c.dom.Node.ELEMENT_NODE, l.item(0).getNodeType()); + + if (!l.item(0).getTextContent().equals("Hello Fred")) { + fail("Expecting 'Hello Fred'"); + } + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " \n" + + " \n" + + " \n" + + " Fred\n" + + " \n" + + " \n" + + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelSimpleCorrelationQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelSimpleCorrelationQuickstartTest.java new file mode 100644 index 000000000..1bee43355 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/BpelSimpleCorrelationQuickstartTest.java @@ -0,0 +1,81 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual + * contributors by the @authors tag. See the copyright.txt in the + * distribution for a full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import java.util.Collections; + +import org.custommonkey.xmlunit.SimpleNamespaceContext; +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class BpelSimpleCorrelationQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.bpel.simple.correlation"; + private static String featureName = "switchyard-quickstart-bpel-simple-correlation"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Override + @Test + public void testDeployment() throws Exception { + HTTPMixIn soapMixIn = new HTTPMixIn(); + soapMixIn.initialize(); + + try { + String url = "http://localhost:" + getSoapClientPort() + "/HelloGoodbyeService/HelloGoodbyeService"; + String response = soapMixIn.postString(url, HELLO_REQUEST); + XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(Collections.singletonMap("ns", "http://www.jboss.org/bpel/examples/simple_correlation/"))); + XMLAssert.assertXpathEvaluatesTo("1", "//ns:sessionId/ns:id", response); + XMLAssert.assertXpathEvaluatesTo("BPEL, Hello World!", "//ns:parameter", response); + + response = soapMixIn.postString(url, GOODBYE_REQUEST); + XMLAssert.assertXpathEvaluatesTo("1", "//ns:sessionId/ns:id", response); + XMLAssert.assertXpathEvaluatesTo("BPEL, Goodbye World!", "//ns:parameter", response); + } finally { + soapMixIn.uninitialize(); + } + } + + private static final String HELLO_REQUEST = "" + + " " + + " " + + " " + + " " + + " 1" + + " " + + " BPEL" + + " " + + " " + + ""; + + private static final String GOODBYE_REQUEST = "" + + " " + + " " + + " " + + " " + + " 1" + + " " + + " BPEL" + + " " + + " " + + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelAMQPBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelAMQPBindingQuickstartTest.java new file mode 100644 index 000000000..e4334d9b4 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelAMQPBindingQuickstartTest.java @@ -0,0 +1,13 @@ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class CamelAMQPBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.amqp.binding"; + private static String featureName = "switchyard-quickstart-camel-amqp-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelAtomBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelAtomBindingQuickstartTest.java new file mode 100644 index 000000000..3139cafea --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelAtomBindingQuickstartTest.java @@ -0,0 +1,13 @@ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class CamelAtomBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.atom.binding"; + private static String featureName = "switchyard-quickstart-camel-atom-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindingQuickstartProbe.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindingQuickstartProbe.java new file mode 100644 index 000000000..41001af85 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindingQuickstartProbe.java @@ -0,0 +1,33 @@ +package org.switchyard.karaf.test.quickstarts; + +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertTrue; + +import java.io.File; + +import org.junit.Test; +import org.switchyard.common.io.Files; + +public class CamelBindingQuickstartProbe extends DeploymentProbe { + + private static String SOURCE_FILE = "../../../test-classes/quickstarts/camel-file-binding/test.txt"; + private static String DEST_FILE = "target/input/test.txt"; + + public CamelBindingQuickstartProbe() { + } + + @Test + public void testFeatures() throws Exception { + File srcFile = new File(SOURCE_FILE); + assertTrue(srcFile.exists()); + File destFile = new File(DEST_FILE); + Files.copy(srcFile, destFile); + assertTrue(destFile.exists()); + // Wait a spell so that the file component polls and picks up the file + while (destFile.exists()) { + Thread.sleep(50); + } + // File should have been picked up + assertFalse(destFile.exists()); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindingQuickstartTest.java new file mode 100644 index 000000000..8d479ce6e --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindingQuickstartTest.java @@ -0,0 +1,19 @@ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class CamelBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.file.binding"; + private static String featureName = "switchyard-quickstart-camel-file-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName, null, CamelBindingQuickstartProbe.class); + } + + @Test + public void testFeatures() throws Exception { + executeProbe("testFeatures"); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindyQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindyQuickstartTest.java new file mode 100644 index 000000000..ca04d7495 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelBindyQuickstartTest.java @@ -0,0 +1,13 @@ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class CamelBindyQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.bindy"; + private static String featureName = "switchyard-quickstart-camel-bindy"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelCDIBusQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelCDIBusQuickstartTest.java new file mode 100644 index 000000000..7b66ebee0 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelCDIBusQuickstartTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import java.util.HashMap; +import java.util.Map; + +import org.custommonkey.xmlunit.SimpleNamespaceContext; +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +/** + * Test deployment of bus extension done by custom cdi beans. + */ +public class CamelCDIBusQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.bus.cdi"; + private static String featureName = "switchyard-quickstart-camel-bus-cdi"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testOrders() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String response = httpMixIn.postString("http://localhost:" + getSoapClientPort() + "/quickstart-cdi-bus/OrderService", SOAP_REQUEST); + + Map namespaces = new HashMap(); + namespaces.put("ns", "urn:switchyard-quickstart:cdi-bus:1.0"); + XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces)); + + XMLAssert.assertXpathEvaluatesTo("PO-19838-XYZ", "//ns:orderAck/orderId", response); + XMLAssert.assertXpathEvaluatesTo("true", "//ns:orderAck/accepted", response); + XMLAssert.assertXpathEvaluatesTo("Order Accepted", "//ns:orderAck/status", response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " " + + " \n" + + " \n" + + " PO-19838-XYZ\n" + + " BUTTER\n" + + " 200\n" + + " \n" + + " \n" + + ""; + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelCxfQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelCxfQuickstartTest.java new file mode 100644 index 000000000..a948262de --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelCxfQuickstartTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +/** + * Test deployment of Camel Cxf. + */ +public class CamelCxfQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.cxf.binding"; + private static String featureName = "switchyard-quickstart-camel-cxf-binding"; + + private HTTPMixIn _httpMixIn = new HTTPMixIn(); + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Ignore("Sporadic failures with JAXBMarshalling") @Test + public void cxfBinding() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:8082/camel-cxf/order/OrderService", REQUEST); + Assert.assertTrue(response.contains("Order Boeing with quantity 10 accepted.")); + } finally { + httpMixIn.uninitialize(); + } + } + + private static String REQUEST = "" + + " " + + " " + + " Boeing" + + " 10" + + " " + + " " + + ""; + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelFTPBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelFTPBindingQuickstartTest.java new file mode 100644 index 000000000..fcda777cf --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelFTPBindingQuickstartTest.java @@ -0,0 +1,241 @@ +package org.switchyard.karaf.test.quickstarts; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertFalse; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertTrue; + +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.Logger; +import com.jcraft.jsch.Session; +import com.jcraft.jsch.UIKeyboardInteractive; +import com.jcraft.jsch.UserInfo; + +import java.io.File; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Arrays; + +import org.apache.commons.io.FileUtils; +import org.apache.ftpserver.FtpServer; +import org.apache.ftpserver.FtpServerFactory; +//import org.apache.ftpserver.filesystem.nativefs.NativeFileSystemFactory; +import org.apache.ftpserver.ftplet.FtpException; +import org.apache.ftpserver.ftplet.UserManager; +import org.apache.ftpserver.listener.Listener; +import org.apache.ftpserver.listener.ListenerFactory; +import org.apache.ftpserver.ssl.SslConfigurationFactory; +import org.apache.ftpserver.usermanager.ClearTextPasswordEncryptor; +import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory; + +import org.apache.sshd.SshServer; +import org.apache.sshd.common.keyprovider.FileKeyPairProvider; +import org.apache.sshd.common.NamedFactory; +import org.apache.sshd.server.Command; +import org.apache.sshd.server.PasswordAuthenticator; +import org.apache.sshd.server.command.ScpCommandFactory; +import org.apache.sshd.server.session.ServerSession; +import org.apache.sshd.sftp.subsystem.SftpSubsystem; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class CamelFTPBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.ftp.binding"; + private static String featureName = "switchyard-quickstart-camel-ftp-binding"; + + private static FtpServer ftpServer; + private static SshServer sshd; + + @BeforeClass + public static void before() throws Exception { + + sshd = SshServer.setUpDefaultServer(); + sshd.setPort(2220); + sshd.setKeyPairProvider(createTestKeyPairProvider("target/test-classes/quickstarts/camel-ftp-binding/hostkey.pem")); + sshd.setSubsystemFactories(Arrays.>asList(new SftpSubsystem.Factory())); + sshd.setCommandFactory(new ScpCommandFactory()); + sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator()); + //sshd.setFileSystemFactory(new org.apache.sshd.common.file.nativefs.NativeFileSystemFactory()); + + sshd.start(); + + FtpServerFactory serverFactory = new FtpServerFactory(); + ListenerFactory listenerFactory = new ListenerFactory(); + listenerFactory.setPort(2222); + serverFactory.addListener("default", listenerFactory.createListener()); + + ListenerFactory sslListenerFactory = new ListenerFactory(); + sslListenerFactory.setPort(2221); + SslConfigurationFactory ssl = new SslConfigurationFactory(); + ssl.setKeystoreFile(getFile("target/test-classes/quickstarts/camel-ftp-binding/ftpserver.jks")); + ssl.setKeystorePassword("password"); + sslListenerFactory.setSslConfiguration(ssl.createSslConfiguration()); + sslListenerFactory.setImplicitSsl(false); // Setting it to true will not read the file + serverFactory.addListener("ssl", sslListenerFactory.createListener()); + + PropertiesUserManagerFactory managerFactory = new PropertiesUserManagerFactory(); + managerFactory.setPasswordEncryptor(new ClearTextPasswordEncryptor()); + managerFactory.setFile(getFile("target/test-classes/quickstarts/camel-ftp-binding/ftp-users.properties")); + UserManager createUserManager = managerFactory.createUserManager(); + serverFactory.setUserManager(createUserManager); + + // This doesn't work due to class method signature mismatch + //NativeFileSystemFactory fileSystemFactory = new NativeFileSystemFactory(); + //fileSystemFactory.setCreateHome(true); + //serverFactory.setFileSystem(fileSystemFactory); + + File file = new File("target/ftp/ftps"); + file.mkdirs(); + file = new File("target/ftp/sftp"); + file.mkdirs(); + + JSch sch = new JSch(); + Session session = sch.getSession("camel", "localhost", 2220); + session.setUserInfo(new SimpleUserInfo("isMyFriend")); + session.connect(); + ChannelSftp c = (ChannelSftp) session.openChannel("sftp"); + c.connect(); + System.out.println("Home: " + c.getHome()); + c.chmod(777, "."); + c.chmod(777, "target"); + c.chmod(777, "target/ftp"); + c.chmod(777, "target/ftp/sftp"); + c.disconnect(); + session.disconnect(); + + ftpServer = serverFactory.createServer(); + ftpServer.start(); + startTestContainer(featureName, bundleName); + } + + @AfterClass + public static void shutDown() throws Exception { + if (ftpServer != null) { + ftpServer.stop(); + } + if (sshd != null) { + sshd.stop(); + } + } + + @Test + public void testFeatures() throws Exception { + + // Ftp + File srcFile = new File("target/ftp", "test.txt"); + FileUtils.write(srcFile, "The Phantom"); + for (int i = 0; i < 20; i++) { + Thread.sleep(500); + if (!srcFile.exists()) { + break; + } + } + // File should have been picked up + assertFalse(srcFile.exists()); + File destFile = new File("target/ftp/done", "test.txt"); + assertTrue(destFile.exists()); + + // Ftps + srcFile = new File("target/ftp/ftps", "ftps-test.txt"); + FileUtils.write(srcFile, "The Ghost Who Walks"); + for (int i = 0; i < 20; i++) { + Thread.sleep(500); + if (!srcFile.exists()) { + break; + } + } + // File should have been picked up + assertFalse(srcFile.exists()); + destFile = new File("target/ftp/ftps/done", "ftps-test.txt"); + assertTrue(destFile.exists()); + + // Sftp + srcFile = new File("target/ftp/sftp", "sftp-test.txt"); + FileUtils.write(srcFile, "Christopher Walker"); + for (int i = 0; i < 20; i++) { + Thread.sleep(500); + if (!srcFile.exists()) { + break; + } + } + // File should have been picked up + assertFalse(srcFile.exists()); + destFile = new File("target/ftp/sftp/done", "sftp-test.txt"); + assertTrue(destFile.exists()); + + } + + public static FileKeyPairProvider createTestKeyPairProvider(String resource) { + return new FileKeyPairProvider(new String[] { getFile("target/test-classes/quickstarts/camel-ftp-binding/hostkey.pem").toString() }); + } + + public static int getFreePort() throws Exception { + ServerSocket s = new ServerSocket(0); + try { + return s.getLocalPort(); + } finally { + s.close(); + } + } + + private static File getFile(String resource) { + /*URL url = CamelFTPBindingQuickstartTest.class.getClassLoader().getResource(resource); + File f; + try { + f = new File(url.toURI()); + } catch(URISyntaxException e) { + f = new File(url.getPath()); + } + return f;*/ + File f = new File(resource); + return f; + } + + public static class BogusPasswordAuthenticator implements PasswordAuthenticator { + + public boolean authenticate(String username, String password, ServerSession session) { + return ((username != null) && (password != null) && username.equals("camel") && password.equals("isMyFriend")); + } + } + + public static class SimpleUserInfo implements UserInfo, UIKeyboardInteractive { + + private final String password; + + public SimpleUserInfo(String password) { + this.password = password; + } + + public String getPassphrase() { + return null; + } + + public String getPassword() { + return password; + } + + public boolean promptPassword(String message) { + return true; + } + + public boolean promptPassphrase(String message) { + return false; + } + + public boolean promptYesNo(String message) { + return true; + } + + public void showMessage(String message) { + } + + public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) { + return new String[] { password }; + } + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJAXBQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJAXBQuickstartTest.java new file mode 100644 index 000000000..415e02560 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJAXBQuickstartTest.java @@ -0,0 +1,13 @@ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class CamelJAXBQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.jaxb"; + private static String featureName = "switchyard-quickstart-camel-jaxb"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJMSBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJMSBindingQuickstartTest.java new file mode 100644 index 000000000..d1c2a31d3 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJMSBindingQuickstartTest.java @@ -0,0 +1,48 @@ +package org.switchyard.karaf.test.quickstarts; + +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut; + +import javax.jms.Connection; +import javax.jms.ConnectionFactory; +import javax.jms.Message; +import javax.jms.MessageProducer; +import javax.jms.Session; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.junit.BeforeClass; +import org.junit.Test; +import org.ops4j.pax.exam.CoreOptions; + +public class CamelJMSBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.jms.binding"; + private static String featureName = "switchyard-quickstart-camel-jms-binding"; + + private static final String AMQ_USER = "karaf"; + private static final String AMQ_PASSWD = "karaf"; + private static final String AMQ_BROKER_URL = "tcp://localhost:61616"; + + private static final String QUEUE_NAME = "GreetingServiceQueue"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName, + CoreOptions.options( + editConfigurationFilePut("etc/org.ops4j.pax.logging.cfg", "log4j.logger.org.apache.activemq", + "DEBUG")), DeploymentProbe.class); + } + + @Test + public void testDeployment() throws Exception { + ConnectionFactory cf = new ActiveMQConnectionFactory(AMQ_USER, AMQ_PASSWD, AMQ_BROKER_URL); + Connection conn = cf.createConnection(); + + try { + Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); + final MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); + Message message = session.createTextMessage("Captain Crunch"); + producer.send(message); + } finally { + conn.close(); + } + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJPABindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJPABindingQuickstartTest.java new file mode 100644 index 000000000..91eca6fe5 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelJPABindingQuickstartTest.java @@ -0,0 +1,19 @@ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; +import org.junit.Ignore; + +/** + * JPA quickstart needs to be built specifically for Karaf. The problem lies + * with the JNDI name used to lookup the datasource in the persistence.xml. + */ +@Ignore +public class CamelJPABindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.jpa.binding"; + private static String featureName = "switchyard-quickstart-camel-jpa-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelMQTTBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelMQTTBindingQuickstartTest.java new file mode 100644 index 000000000..ee0f79c5f --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelMQTTBindingQuickstartTest.java @@ -0,0 +1,72 @@ +package org.switchyard.karaf.test.quickstarts; + +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.editConfigurationFilePut; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.replaceConfigurationFile; + +import java.io.File; +import java.net.URL; +import java.util.concurrent.TimeUnit; + +import org.fusesource.mqtt.client.BlockingConnection; +import org.fusesource.mqtt.client.MQTT; +import org.fusesource.mqtt.client.Message; +import org.fusesource.mqtt.client.QoS; +import org.fusesource.mqtt.client.Topic; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.ops4j.pax.exam.CoreOptions; +import org.switchyard.common.type.Classes; + +@Ignore("Disable for now due to https://issues.jboss.org/browse/SWITCHYARD-2220") +public class CamelMQTTBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.mqtt.binding"; + private static String featureName = "switchyard-quickstart-camel-mqtt-binding"; + + private static final String TOPIC_INPUT = "camel/mqtt/test/input"; + private static final String TOPIC_OUTPUT = "camel/mqtt/test/output"; + private static final String MESSAGE_INPUT = "SquarePants"; + private static final String MESSAGE_OUTPUT = "Hello there " + MESSAGE_INPUT + " :-) "; + private static final String USER_NAME = "karaf"; + private static final String PASSWORD = "karaf"; + + @BeforeClass + public static void before() throws Exception { + URL activemqXml = Classes.getResource("activemq.xml"); + startTestContainer(featureName, bundleName, + CoreOptions.options( + editConfigurationFilePut("etc/org.ops4j.pax.logging.cfg", "log4j.logger.org.apache.activemq", + "DEBUG"), + replaceConfigurationFile("etc/activemq.xml", new File(activemqXml.toURI()))), DeploymentProbe.class); + } + + @Test + public void testDeployment() throws Exception { + BlockingConnection publishConnection = null; + BlockingConnection subscribeConnection = null; + try { + Topic outputTopic = new Topic(TOPIC_OUTPUT, QoS.AT_LEAST_ONCE); + MQTT mqtt = new MQTT(); + mqtt.setUserName(USER_NAME); + mqtt.setPassword(PASSWORD); + subscribeConnection = mqtt.blockingConnection(); + subscribeConnection.connect(); + subscribeConnection.subscribe(new Topic[]{outputTopic}); + + publishConnection = mqtt.blockingConnection(); + publishConnection.connect(); + publishConnection.publish(TOPIC_INPUT, MESSAGE_INPUT.getBytes(), QoS.AT_LEAST_ONCE, false); + + Message message = subscribeConnection.receive(1000, TimeUnit.MILLISECONDS); + Assert.assertNotNull("No output message from " + TOPIC_OUTPUT, message); + Assert.assertEquals(MESSAGE_OUTPUT, new String(message.getPayload())); + Assert.assertNull("More than one message received from " + TOPIC_OUTPUT, + subscribeConnection.receive(1000, TimeUnit.MILLISECONDS)); + } finally { + if (publishConnection != null) { + publishConnection.disconnect(); + } + } + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelMailBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelMailBindingQuickstartTest.java new file mode 100644 index 000000000..496052857 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelMailBindingQuickstartTest.java @@ -0,0 +1,13 @@ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class CamelMailBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.mail.binding"; + private static String featureName = "switchyard-quickstart-camel-mail-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelNettyBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelNettyBindingQuickstartTest.java new file mode 100644 index 000000000..7e0aa96e1 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelNettyBindingQuickstartTest.java @@ -0,0 +1,72 @@ +package org.switchyard.karaf.test.quickstarts; + +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.net.Socket; +import java.security.KeyStore; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManagerFactory; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.common.io.Files; + +public class CamelNettyBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.netty.binding"; + private static String featureName = "switchyard-quickstart-camel-netty-binding"; + + private static String SRC_DIR = "target/test-classes/quickstarts/camel-netty-binding"; + private static String DEST_DIR_0 = "target/karaf/" + featureName; + private static String DEST_DIR_2 = "quickstarts/camel-netty-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName, null, null, new PhaseListener() { + // TODO: Look into using KarafDistributionOption.replaceConfigurationFile(String,File) instead of using a PhaseListener. + @Override + public void post(Phase phase) throws Exception { + if (Phase.START_CONTAINER.equals(phase)) { + copy("users.jks", "roles.properties"); + } + } + private void copy(String... names) throws Exception { + for (String name : names) { + File srcFile = new File(SRC_DIR, name); + File destDir0 = new File(DEST_DIR_0); + if (destDir0.exists()) { + for (File destDir1 : destDir0.listFiles()) { + if (destDir1.isDirectory()) { + File destFile = new File(new File(destDir1, DEST_DIR_2), name); + Files.copy(srcFile, destFile); + } + } + } + } + } + }); + } + + @Override + @Test + public void testDeployment() throws Exception { + KeyStore keystore = KeyStore.getInstance("JKS"); + keystore.load(new FileInputStream(new File(SRC_DIR, "users.jks")), "changeit".toCharArray()); + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(keystore); + SSLContext context = SSLContext.getInstance("TLS"); + KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keystore, "changeit".toCharArray()); + context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); + SSLSocketFactory sf = context.getSocketFactory(); + Socket clientSocket = sf.createSocket("localhost", 3939); + DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream()); + outputStream.write(getClass().getName().getBytes()); + outputStream.flush(); + Thread.sleep(1000); + clientSocket.close(); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelQuartzBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelQuartzBindingQuickstartTest.java new file mode 100644 index 000000000..e17a1d972 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelQuartzBindingQuickstartTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class CamelQuartzBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.quartz.binding"; + private static String featureName = "switchyard-quickstart-camel-quartz-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelRSSBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelRSSBindingQuickstartTest.java new file mode 100644 index 000000000..43039417a --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelRSSBindingQuickstartTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class CamelRSSBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.rss.binding"; + private static String featureName = "switchyard-quickstart-camel-rss-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSAPBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSAPBindingQuickstartTest.java new file mode 100644 index 000000000..f4d309785 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSAPBindingQuickstartTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class CamelSAPBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.sap.binding"; + private static String featureName = "switchyard-quickstart-camel-sap-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSQLBindingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSQLBindingQuickstartTest.java new file mode 100644 index 000000000..1dbc00c7d --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSQLBindingQuickstartTest.java @@ -0,0 +1,16 @@ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; +import org.ops4j.pax.exam.CoreOptions; + +public class CamelSQLBindingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.sql.binding"; + private static String featureName = "switchyard-quickstart-camel-sql-binding"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName, CoreOptions.options(CoreOptions.systemProperty( + "org.switchyard.quickstarts.camel.sql.datasourceName").value("osgi:service/jboss/myDS")), + DeploymentProbe.class); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSaxonQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSaxonQuickstartTest.java new file mode 100644 index 000000000..694b92103 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/CamelSaxonQuickstartTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class CamelSaxonQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.camel.saxon"; + private static String featureName = "switchyard-quickstart-camel-saxon"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testGreeting() throws Exception { + HTTPMixIn soapMixIn = new HTTPMixIn(); + soapMixIn.initialize(); + + try { + String url = "http://localhost:" + getSoapClientPort() + "/quickstart-camel-saxon/GreetingService"; + int status = soapMixIn.sendStringAndGetStatus(url, SOAP_REQUEST, HTTPMixIn.HTTP_POST); + Assert.assertEquals("Unexpected status.", 202, status); + } finally { + soapMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = +"" + +" " + +" " + +" Garfield" + +" " + +""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/ClusterDemoQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/ClusterDemoQuickstartTest.java new file mode 100644 index 000000000..d4988df1a --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/ClusterDemoQuickstartTest.java @@ -0,0 +1,87 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import static java.lang.System.out; +import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.features; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.ops4j.pax.exam.CoreOptions; +import org.switchyard.quickstarts.remoteinvoker.Application; +import org.switchyard.quickstarts.remoteinvoker.Car; +import org.switchyard.quickstarts.remoteinvoker.Deal; +import org.switchyard.quickstarts.remoteinvoker.Offer; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; + +public class ClusterDemoQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.demos.switchyard.demo.cluster.dealer"; + private static String featureName = "switchyard-demo-cluster-dealer"; + private static String[] extraFeatures = {"switchyard-demo-cluster-credit"}; + + private static final QName SERVICE = new QName( + "urn:switchyard-quickstart-demo-cluster-dealer:1.0", + "Dealer"); + private static final String URL = "http://localhost:8181/switchyard-remote"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName, + CoreOptions.options(features( + "mvn:org.switchyard.karaf/switchyard/2.0.0.Final/xml/features", + extraFeatures))); + } + + @Test + public void testOffer() throws Exception { + + // Create a new remote client invoker + RemoteInvoker invoker = new HttpInvoker(URL); + + // Create request payload + Offer offer = createOffer(true); + + // Create the request message + RemoteMessage message = new RemoteMessage(); + message.setService(SERVICE).setOperation("offer").setContent(offer); + + // Invoke the service + RemoteMessage reply = invoker.invoke(message); + if (reply.isFault()) { + Assert.fail("Invocation returned fault: " + reply.getContent()); + } + Deal deal = (Deal)reply.getContent(); + Assert.assertTrue(deal.isAccepted()); + } + + public static Offer createOffer(boolean acceptable) { + Application app = new Application(); + app.setName("John Smith"); + app.setCreditScore(acceptable ? 700 : 300); + Car car = new Car(); + car.setPrice(18000); + car.setVehicleId("Honda"); + Offer offer = new Offer(); + offer.setApplication(app); + offer.setCar(car); + offer.setAmount(17000); + + return offer; + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/DeploymentProbe.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/DeploymentProbe.java new file mode 100644 index 000000000..de4b79c1b --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/DeploymentProbe.java @@ -0,0 +1,69 @@ +package org.switchyard.karaf.test.quickstarts; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import javax.inject.Inject; + +import org.junit.Assert; +import org.junit.Test; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.switchyard.deploy.osgi.SwitchYardEvent; +import org.switchyard.deploy.osgi.SwitchYardListener; + +public class DeploymentProbe { + public static final String BUNDLE_NAME_KEY = "org.switchyard.karaf.test.bundleName"; + + public DeploymentProbe() { + } + + @Inject + private BundleContext _bundleContext; + private boolean _activated; + + @Test + public void testBundleActivation() { + Assert.assertNotNull(_bundleContext); + String bundleName = System.getProperty(BUNDLE_NAME_KEY); + Bundle bundle = null; + for (Bundle aux : _bundleContext.getBundles()) { + if (bundleName.equals(aux.getSymbolicName())) { + bundle = aux; + break; + } + } + Assert.assertNotNull(bundle); + Assert.assertEquals("Bundle ACTIVE", Bundle.ACTIVE, bundle.getState()); + + // Wait for SwitchYard application activation + final CountDownLatch latch = new CountDownLatch(1); + final long bundleId = bundle.getBundleId(); + final SwitchYardListener listener = new SwitchYardListener() { + @Override + public void switchyardEvent(SwitchYardEvent event) { + if (bundleId == event.getBundle().getBundleId()) { + switch (event.getType()) { + case SwitchYardEvent.CREATED: + _activated = true; + // fall through + case SwitchYardEvent.FAILURE: + latch.countDown(); + break; + default: + break; + } + } + } + }; + final ServiceRegistration registration = _bundleContext.registerService( + SwitchYardListener.class, listener, null); + try { + latch.await(120000, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + } + registration.unregister(); + Assert.assertTrue("SwitchYard bundle activation failed", _activated); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/PhaseListener.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/PhaseListener.java new file mode 100644 index 000000000..fcc1a8243 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/PhaseListener.java @@ -0,0 +1,18 @@ +package org.switchyard.karaf.test.quickstarts; + +public interface PhaseListener { + + public static enum Phase { + CREATE_SYSTEM, + CREATE_CONTAINER, + START_CONTAINER, + CREATE_PROBE, + ADD_TESTS, + BUILD_PROBE, + INSTALL_PROBE, + EXECUTE_PROBE; + } + + public void post(Phase phase) throws Exception; + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RemoteInvokerQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RemoteInvokerQuickstartTest.java new file mode 100644 index 000000000..03730808a --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RemoteInvokerQuickstartTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.quickstarts.remoteinvoker.Application; +import org.switchyard.quickstarts.remoteinvoker.Car; +import org.switchyard.quickstarts.remoteinvoker.Deal; +import org.switchyard.quickstarts.remoteinvoker.Offer; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; + +public class RemoteInvokerQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.remote.invoker"; + private static String featureName = "switchyard-quickstart-remote-invoker"; + + private static final QName SERVICE = new QName("urn:com.example.switchyard:switchyard-quickstart-remote-invoker:1.0", "Dealer"); + private static final String URL = "http://localhost:8181/switchyard-remote"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testOffer() throws Exception { + + RemoteInvoker invoker = new HttpInvoker(URL); + Application app = new Application(); + app.setName("Magesh"); + app.setCreditScore(812); + Car car = new Car(); + car.setPrice(9600); + Offer offer = new Offer(); + offer.setApplication(app); + offer.setCar(car); + offer.setAmount(9000); + + RemoteMessage message = new RemoteMessage(); + message.setService(SERVICE) + .setOperation("offer") + .setContent(offer); + + // Invoke the service + RemoteMessage reply = invoker.invoke(message); + Deal deal = (Deal)reply.getContent(); + Assert.assertTrue(deal.isAccepted()); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesCamelCBRQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesCamelCBRQuickstartTest.java new file mode 100644 index 000000000..3b882cbc6 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesCamelCBRQuickstartTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class RulesCamelCBRQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.rules.camel.cbr"; + private static String featureName = "switchyard-quickstart-rules-camel-cbr"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewContainerQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewContainerQuickstartTest.java new file mode 100644 index 000000000..783a148e6 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewContainerQuickstartTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class RulesInterviewContainerQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.rules.interview.container"; + private static String featureName = "switchyard-quickstart-rules-interview-container"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testVerifyPass() throws Exception { + RulesInterviewQuickstartTest.doTestVerify("rules-interview-container", getSoapClientPort(), true); + } + + @Test + public void testVerifyFail() throws Exception { + RulesInterviewQuickstartTest.doTestVerify("rules-interview-container", getSoapClientPort(), false); + } + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewDTableQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewDTableQuickstartTest.java new file mode 100644 index 000000000..39ca3a8b7 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewDTableQuickstartTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class RulesInterviewDTableQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.rules.interview.dtable"; + private static String featureName = "switchyard-quickstart-rules-interview-dtable"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testVerifyPass() throws Exception { + RulesInterviewQuickstartTest.doTestVerify("rules-interview-dtable", getSoapClientPort(), true); + } + + @Test + public void testVerifyFail() throws Exception { + RulesInterviewQuickstartTest.doTestVerify("rules-interview-dtable", getSoapClientPort(), false); + } + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewQuickstartTest.java new file mode 100644 index 000000000..a08b2c9f9 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/RulesInterviewQuickstartTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.custommonkey.xmlunit.XMLAssert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class RulesInterviewQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.rules.interview"; + private static String featureName = "switchyard-quickstart-rules-interview"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testVerifyPass() throws Exception { + doTestVerify("rules-interview", getSoapClientPort(), true); + } + + @Test + public void testVerifyFail() throws Exception { + doTestVerify("rules-interview", getSoapClientPort(), false); + } + + static final void doTestVerify(String context, String port, boolean pass) throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String request = getSoapRequest(context, pass); + String response = httpMixIn.postString("http://localhost:" + port + "/" + context + "/Interview", request); + XMLAssert.assertXpathEvaluatesTo(String.valueOf(pass), "//return", response); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String getSoapRequest(String context, boolean pass) { + return + "" + + "" + + "" + + "" + + "" + + "" + (pass ? 20 : 16) + "" + + "" + (pass ? "Twenty" : "Sixteen") + "" + + "" + + "" + + "" + + ""; + } + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapAddressingQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapAddressingQuickstartTest.java new file mode 100644 index 000000000..9fbca59a3 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapAddressingQuickstartTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.BeforeClass; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class SoapAddressingQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.soap.addressing"; + private static String featureName = "switchyard-quickstart-soap-addressing"; + private static String SWITCHYARD_WEB_SERVICE = "http://localhost:8181/cxf/soap-addressing/order/OrderService"; + + private HTTPMixIn _httpMixIn = new HTTPMixIn(); + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void addressingError() throws Exception { + _httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String response = _httpMixIn.postString(SWITCHYARD_WEB_SERVICE, REQUEST); + Assert.assertTrue(response.contains("MessageAddressingHeaderRequired")); + Assert.assertTrue(response.contains("A required header representing a Message Addressing Property is not present")); + } finally { + _httpMixIn.uninitialize(); + } + } + + @Test + public void addressingReplyTo() throws Exception { + _httpMixIn.initialize(); + try { + File testFile = new File("/tmp/test.txt"); + if (testFile.exists()) { + testFile.delete(); + } + String response = _httpMixIn.postString(SWITCHYARD_WEB_SERVICE, REQUEST2); + Assert.assertTrue(response, response.contains("urn:switchyard-quickstart:soap-addressing:1.0:OrderService:orderResponse")); + Assert.assertTrue(response, response.contains("uuid:3d3fcbbb-fd43-4118-b40e-62577894f39a")); + Assert.assertTrue(response, response.contains("Thank you for your order. You should hear back from our WarehouseService shortly!")); + // Wait for the actual response from WarehouseService + int timeout = 0; + while (!testFile.exists()) { + Thread.sleep(100); + timeout += 100; + if (timeout == 15000) { + break; + } + } + System.out.println("...................." + testFile.exists()); + BufferedReader stream = new BufferedReader(new FileReader(testFile)); + String text = stream.readLine(); + stream.close(); + Assert.assertEquals("Order Boeing with quantity 10 accepted.", text); + } finally { + _httpMixIn.uninitialize(); + } + } + + private static String REQUEST = "" + + " " + + " " + + " Boeing" + + " 10" + + " " + + " " + + ""; + + private static String REQUEST2 = "" + + " " + + " uuid:3d3fcbbb-fd43-4118-b40e-62577894f39a" + + " urn:switchyard-quickstart:soap-addressing:1.0:OrderService:orderRequest" + + " " + + " " + + " " + + " Boeing" + + " 10" + + " " + + " " + + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapAttachmentQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapAttachmentQuickstartTest.java new file mode 100644 index 000000000..bec27dc55 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapAttachmentQuickstartTest.java @@ -0,0 +1,118 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map; +import java.util.Iterator; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.jws.WebService; +import javax.xml.namespace.QName; +import javax.xml.soap.AttachmentPart; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPBodyElement; +import javax.xml.soap.SOAPConnection; +import javax.xml.soap.SOAPConnectionFactory; +import javax.xml.soap.SOAPConstants; +import javax.xml.soap.SOAPElement; +import javax.xml.soap.SOAPMessage; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.BeforeClass; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class SoapAttachmentQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.soap.attachment"; + private static String featureName = "switchyard-quickstart-soap-attachment"; + private static String SWITCHYARD_WEB_SERVICE = "http://localhost:8181/cxf/soap-attachment/ImageServiceService"; + + private HTTPMixIn _httpMixIn = new HTTPMixIn(); + + static int size = 13000000; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + + @Test + public void imageService() throws Exception { + SOAPMessage response = sendMessage(); + Assert.assertTrue(response.getAttachments().hasNext()); + } + + public SOAPMessage sendMessage() throws Exception { + SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); + + SOAPConnection connection = conFactory.createConnection(); + MessageFactory msgFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); + SOAPMessage msg = msgFactory.createMessage(); + SOAPBodyElement bodyElement = msg.getSOAPBody().addBodyElement(new QName("urn:switchyard-quickstart:soap-attachment:1.0", "echoImage")); + bodyElement.addTextNode("cid:switchyard.png"); + + // CXF does not set content-type. + msg.getMimeHeaders().addHeader("Content-Type", "multipart/related; type=\"text/xml\"; start=\"\""); + msg.getSOAPPart().setContentId(""); + + AttachmentPart ap = msg.createAttachmentPart(); + ap.setDataHandler(new DataHandler(new StreamDataSource())); + ap.setContentId(""); + msg.addAttachmentPart(ap); + + return connection.call(msg, new URL(SWITCHYARD_WEB_SERVICE)); + } + + private static class StreamDataSource implements DataSource { + + public InputStream getInputStream() throws IOException { + return new InputStream() { + int count; + + @Override + public int read() throws IOException { + if (count < size) { + count++; + return 'M'; + } else { + return -1; + } + } + }; + } + + public OutputStream getOutputStream() throws IOException { + return null; + } + + public String getContentType() { + return "image/png"; + } + + public String getName() { + return "junk"; + } + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapBindingRpcQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapBindingRpcQuickstartTest.java new file mode 100644 index 000000000..d624dd92a --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapBindingRpcQuickstartTest.java @@ -0,0 +1,80 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.BeforeClass; +import org.junit.Assert; +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class SoapBindingRpcQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.soap.binding.rpc"; + private static String featureName = "switchyard-quickstart-soap-binding-rpc"; + private static String SWITCHYARD_WEB_SERVICE = "http://localhost:8181/cxf/soap-binding-rpc/HelloWorldWSService"; + + private HTTPMixIn _httpMixIn = new HTTPMixIn(); + + static int size = 13000000; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void helloWorldService() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + XMLUnit.setIgnoreWhitespace(true); + String replyMsg = httpMixIn.postString(SWITCHYARD_WEB_SERVICE, REQUEST); + XMLAssert.assertXMLEqual(RESPONSE, replyMsg); + int status = httpMixIn.sendStringAndGetStatus(SWITCHYARD_WEB_SERVICE, REQUEST2, HTTPMixIn.HTTP_POST); + Assert.assertEquals(500, status); + } finally { + httpMixIn.uninitialize(); + } + } + + private static String REQUEST = "" + + " " + + " " + + " SwitchYard" + + " English" + + " " + + " " + + ""; + + private static String REQUEST2 = "" + + " " + + " " + + " 500" + + " English" + + " " + + " " + + ""; + + private static String RESPONSE = "" + + "" + + " " + + " " + + " Hello World Greeting for 'SwitchYard' in English on a Sunday!" + + " " + + " " + + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapMtomQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapMtomQuickstartTest.java new file mode 100644 index 000000000..00b83db64 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/SoapMtomQuickstartTest.java @@ -0,0 +1,99 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.soap.AttachmentPart; +import javax.xml.soap.MessageFactory; +import javax.xml.soap.SOAPBodyElement; +import javax.xml.soap.SOAPConnection; +import javax.xml.soap.SOAPConnectionFactory; +import javax.xml.soap.SOAPConstants; +import javax.xml.soap.SOAPMessage; + +import org.custommonkey.xmlunit.XMLAssert; +import org.custommonkey.xmlunit.XMLUnit; +import org.junit.BeforeClass; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.switchyard.common.type.Classes; +import org.switchyard.common.xml.XMLHelper; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +@Ignore +public class SoapMtomQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.mtom"; + private static String featureName = "switchyard-quickstart-soap-mtom"; + private static String SWITCHYARD_WEB_SERVICE = "http://localhost:8181/cxf/soap-mtom/ImageServiceService"; + + private HTTPMixIn _httpMixIn = new HTTPMixIn(); + + static int size = 13000000; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + //@Ignore + @Test + public void imageService() throws Exception { + SOAPMessage response = sendMessage(); + XMLAssert.assertXMLEqual(RESPONSE, XMLHelper.toString(response.getSOAPPart().getDocumentElement())); + Assert.assertTrue(response.getAttachments().hasNext()); + AttachmentPart attachment = (AttachmentPart)response.getAttachments().next(); + Assert.assertNotNull(attachment); + Assert.assertEquals("image/jpeg", attachment.getContentType()); + /* this assertion appears to be platform-dependent + Assert.assertEquals(16384, attachment.getSize()); + */ + } + + public SOAPMessage sendMessage() throws Exception { + SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance(); + + SOAPConnection connection = conFactory.createConnection(); + MessageFactory msgFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL); + SOAPMessage msg = msgFactory.createMessage(); + SOAPBodyElement bodyElement = msg.getSOAPBody().addBodyElement(new QName("urn:switchyard-quickstart:soap-mtom:1.0", "image")); + bodyElement.setTextContent(imageData); + + return connection.call(msg, new URL(SWITCHYARD_WEB_SERVICE)); + } + + private static String imageData = "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwg" + + "JC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyM" + + "jIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAQABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAA" + + "AAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRV" + + "S0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJi" + + "pKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8Q" + + "AHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhc" + + "RMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN" + + "0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6" + + "Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDFs0162zJdeLvEepNFcxW0ywahLFDDKTyrsWLlSeAwC5wcHPTRbxbrd3r" + + "994UfVbiJA8trDdwXEwkRo8hX3b9zcrzk89z1qjDoXi6W5i1nStG1KC8uI83dnc28iLIQRvB3/LsLYwpbdgAjkcJP4" + + "I8S2fjE6yul3osBdi4JaFpZQrNkrtjBLMMkZAxxngVtotjHV77n/9k="; + + private static String RESPONSE = "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformDozerQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformDozerQuickstartTest.java new file mode 100644 index 000000000..b97d568f8 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformDozerQuickstartTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import javax.xml.namespace.QName; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.quickstarts.transform.dozer.Order; +import org.switchyard.quickstarts.transform.dozer.OrderAck; +import org.switchyard.remote.RemoteInvoker; +import org.switchyard.remote.RemoteMessage; +import org.switchyard.remote.http.HttpInvoker; + +public class TransformDozerQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.transform.dozer"; + private static String featureName = "switchyard-quickstart-transform-dozer"; + + private static final QName SERVICE = new QName( "urn:switchyard-quickstart:transform-dozer:0.1.0", "OrderService"); + private static final String URL = "http://localhost:8181/switchyard-remote"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + //Require RemoteInvoker + @Test + public void testDeployment() throws Exception { + RemoteInvoker invoker = new HttpInvoker(URL); + + // Create request payload + Order order = new Order(); + order.setItem("Turkey"); + order.setQuantity(1); + + // Create the request message + RemoteMessage message = new RemoteMessage(); + message.setService(SERVICE).setOperation("submitOrder").setContent(order); + + // Invoke the service + RemoteMessage reply = invoker.invoke(message); + System.out.println(">>>>> " + reply.getContent().toString()); + OrderAck orderAck = (OrderAck) reply.getContent(); + Assert.assertEquals(true, orderAck.isAccepted()); + Assert.assertEquals("Order Accepted", orderAck.getStatusDescription()); + Assert.assertEquals("PO-19838-XYZ", orderAck.getOrderId()); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformJAXBQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformJAXBQuickstartTest.java new file mode 100644 index 000000000..c50a58502 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformJAXBQuickstartTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class TransformJAXBQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.transform.jaxb"; + private static String featureName = "switchyard-quickstart-transform-jaxb"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformJSONQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformJSONQuickstartTest.java new file mode 100644 index 000000000..4a1145fc6 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformJSONQuickstartTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class TransformJSONQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.transform.json"; + private static String featureName = "switchyard-quickstart-transform-json"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformSmooksQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformSmooksQuickstartTest.java new file mode 100644 index 000000000..161d8c1b1 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformSmooksQuickstartTest.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +/** + * Smooks integration needs to be patched up. + */ +@Ignore +public class TransformSmooksQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.transform.smooks"; + private static String featureName = "switchyard-quickstart-transform-smooks"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testGreeting() throws Exception { + HTTPMixIn soapMixIn = new HTTPMixIn(); + soapMixIn.initialize(); + + try { + String url = "http://localhost:" + getSoapClientPort() + "/quickstart-transform-smooks/OrderService"; + soapMixIn.postStringAndTestXML(url, SOAP_REQUEST, SOAP_RESPONSE); + } finally { + soapMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = +"" + +" " + +" " + +" " + +" PO-19838-XYZ" + +" BUTTER" + +" 200" + +" " + +" " + +""; + + private static final String SOAP_RESPONSE = +"" + +" " + +" " + +" " + +" PO-19838-XYZ" + +" true" + +" Order Accepted" + +" " + +" " + +""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformXSLTQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformXSLTQuickstartTest.java new file mode 100644 index 000000000..62e3250ee --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/TransformXSLTQuickstartTest.java @@ -0,0 +1,26 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.BeforeClass; + +public class TransformXSLTQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.transform.xslt"; + private static String featureName = "switchyard-quickstart-transform-xslt"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/ValidateXMLQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/ValidateXMLQuickstartTest.java new file mode 100644 index 000000000..3fe49b6de --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/ValidateXMLQuickstartTest.java @@ -0,0 +1,53 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.component.test.mixins.http.HTTPMixIn; + +public class ValidateXMLQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.switchyard.validate.xml"; + private static String featureName = "switchyard-quickstart-validate-xml"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Test + public void testOrders() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + + httpMixIn.initialize(); + try { + String response = httpMixIn.postString("http://localhost:" + getSoapClientPort() + "/quickstart-validate-xml/OrderService", SOAP_REQUEST); + Assert.assertTrue(response.contains("Invalid content was found starting with element 'invalid-element'. No child element is expected at this point.")); + } finally { + httpMixIn.uninitialize(); + } + } + + private static final String SOAP_REQUEST = "\n" + + " \n" + + " \n" + + " PO-19838-XYZ\n" + + " BUTTER\n" + + " 200\n" + + " This element is not allowed by XML Schema.\n" + + " \n" + + " \n" + + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/HelpdeskDemoQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/HelpdeskDemoQuickstartTest.java new file mode 100644 index 000000000..200189c7b --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/HelpdeskDemoQuickstartTest.java @@ -0,0 +1,60 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts.demo; + +import org.custommonkey.xmlunit.XMLAssert; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.karaf.test.quickstarts.AbstractQuickstartTest; + +/** + * Requires some fixes in jBPM to get the basic bpm stuff working. Needs more + * work to get the webapp stuff working. + */ +@Ignore +public class HelpdeskDemoQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.demos.switchyard.demo.helpdesk"; + private static String featureName = "switchyard-demo-helpdesk"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Override + public void testDeployment() throws Exception { + final String ticketId = "TCKT-" + System.currentTimeMillis(); + final String soapRequest = REQUEST.replaceAll("TICKET_ID", ticketId); + final HTTPMixIn http = new HTTPMixIn(); + http.initialize(); + try { + String port = getSoapClientPort(); + String response = http.postString("http://localhost:" + port + "/HelpDeskService/HelpDeskService", soapRequest); + XMLAssert.assertXpathEvaluatesTo(ticketId, "//ticketAck/id", response); + } finally { + http.uninitialize(); + } + } + + private static final String REQUEST = "" + + " " + + " " + + " " + + " " + + " TICKET_ID" + + " " + + " " + + " " + ""; +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/LibraryDemoQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/LibraryDemoQuickstartTest.java new file mode 100644 index 000000000..451f7a4c6 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/LibraryDemoQuickstartTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts.demo; + +import org.custommonkey.xmlunit.XMLAssert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.switchyard.common.io.pull.StringPuller; +import org.switchyard.component.test.mixins.http.HTTPMixIn; +import org.switchyard.karaf.test.quickstarts.AbstractQuickstartTest; + +public class LibraryDemoQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.demos.switchyard.demo.library"; + private static String featureName = "switchyard-demo-library"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } + + @Override + @Test + public void testDeployment() throws Exception { + HTTPMixIn httpMixIn = new HTTPMixIn(); + httpMixIn.initialize(); + try { + String port = getSoapClientPort(); + suggestion(httpMixIn, port, 1); + loan(httpMixIn, port, 2); + loan(httpMixIn, port, 3); + loan(httpMixIn, port, 4); + loan(httpMixIn, port, 5); + suggestion(httpMixIn, port, 6); + loan(httpMixIn, port, 7); + loan(httpMixIn, port, 8); + loan(httpMixIn, port, 9); + } finally { + httpMixIn.uninitialize(); + } + } + + private void suggestion(HTTPMixIn httpMixIn, String port, int interaction) throws Exception { + String actual = httpMixIn.postString("http://localhost:" + port + "/suggestion/SuggestionService", xml("request", interaction)); + String expected = xml("response", interaction); + XMLAssert.assertXMLEqual(expected, actual); + } + + private void loan(HTTPMixIn httpMixIn, String port, int interaction) throws Exception { + String actual = httpMixIn.postString("http://localhost:" + port + "/loan/LoanService", xml("request", interaction)); + String expected = xml("response", interaction); + XMLAssert.assertXMLEqual(expected, actual); + } + + private String xml(String direction, int interaction) throws Exception { + return new StringPuller().pull("quickstarts/demos/library/soap-" + direction + "-" + interaction + ".xml", getClass()); + } + +} diff --git a/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/PolicyTransactionDemoQuickstartTest.java b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/PolicyTransactionDemoQuickstartTest.java new file mode 100644 index 000000000..a7e9c6836 --- /dev/null +++ b/release/karaf/tests/src/test/java/org/switchyard/karaf/test/quickstarts/demo/PolicyTransactionDemoQuickstartTest.java @@ -0,0 +1,27 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.switchyard.karaf.test.quickstarts.demo; + +import org.junit.BeforeClass; +import org.switchyard.karaf.test.quickstarts.AbstractQuickstartTest; + +public class PolicyTransactionDemoQuickstartTest extends AbstractQuickstartTest { + private static String bundleName = "org.switchyard.quickstarts.demos.switchyard.demo.policy.transaction"; + private static String featureName = "switchyard-demo-policy-transaction"; + + @BeforeClass + public static void before() throws Exception { + startTestContainer(featureName, bundleName); + } +} diff --git a/release/karaf/tests/src/test/resources/activemq.xml b/release/karaf/tests/src/test/resources/activemq.xml new file mode 100644 index 000000000..20b88e0df --- /dev/null +++ b/release/karaf/tests/src/test/resources/activemq.xml @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/bean-service/OrderService.wsdl b/release/karaf/tests/src/test/resources/quickstarts/bean-service/OrderService.wsdl new file mode 100644 index 000000000..dd51ecfb2 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/bean-service/OrderService.wsdl @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-file-binding/test.txt b/release/karaf/tests/src/test/resources/quickstarts/camel-file-binding/test.txt new file mode 100644 index 000000000..cac5c47ea --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/camel-file-binding/test.txt @@ -0,0 +1 @@ +Captain Crunch \ No newline at end of file diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftp-users.properties b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftp-users.properties new file mode 100644 index 000000000..0b38cdc8a --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftp-users.properties @@ -0,0 +1,26 @@ +# +# JBoss, Home of Professional Open Source +# Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual +# contributors by the @authors tag. See the copyright.txt in the +# distribution for a full listing of individual contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +ftpserver.user.camel.userpassword=isMyFriend +ftpserver.user.camel.homedirectory=./target/ftp +ftpserver.user.camel.enableflag=true +ftpserver.user.camel.writepermission=true +ftpserver.user.camel.maxloginnumber=0 +ftpserver.user.camel.maxloginperip=0 +ftpserver.user.camel.idletime=0 +ftpserver.user.camel.uploadrate=0 +ftpserver.user.camel.downloadrate=0 \ No newline at end of file diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftpclient.jks b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftpclient.jks new file mode 100644 index 000000000..87385283c Binary files /dev/null and b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftpclient.jks differ diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftpserver.jks b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftpserver.jks new file mode 100644 index 000000000..7348c6e97 Binary files /dev/null and b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/ftpserver.jks differ diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/hostkey.pem b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/hostkey.pem new file mode 100644 index 000000000..18d68acb7 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/hostkey.pem @@ -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. + +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQDdfIWeSV4o68dRrKSzFd/Bk51E65UTmmSrmW0O1ohtzi6HzsDP +jXgCtlTt3FqTcfFfI92IlTr4JWqC9UK1QT1ZTeng0MkPQmv68hDANHbt5CpETZHj +W5q4OOgWhVvj5IyOC2NZHtKlJBkdsMAa15ouOOJLzBvAvbqOR/yUROsEiQIDAQAB +AoGBANG3JDW6NoP8rF/zXoeLgLCj+tfVUPSczhGFVrQkAk4mWfyRkhN0WlwHFOec +K89MpkV1ij/XPVzU4MNbQ2yod1KiDylzvweYv+EaEhASCmYNs6LS03punml42SL9 +97tOmWfVJXxlQoLiY6jHPU97vTc65k8gL+gmmrpchsW0aqmZAkEA/c8zfmKvY37T +cxcLLwzwsqqH7g2KZGTf9aRmx2ebdW+QKviJJhbdluDgl1TNNFj5vCLznFDRHiqJ +wq0wkZ39cwJBAN9l5v3kdXj21UrurNPdlV0n2GZBt2vblooQC37XHF97r2zM7Ou+ +Lg6MyfJClyguhWL9dxnGbf3btQ0l3KDstxMCQCRaiEqjAfIjWVATzeNIXDWLHXso +b1kf5cA+cwY+vdKdTy4IeUR+Y/DXdvPWDqpf0C11aCVMohdLCn5a5ikFUycCQDhV +K/BuAallJNfmY7JxN87r00fF3ojWMJnT/fIYMFFrkQrwifXQWTDWE76BSDibsosJ +u1TGksnm8zrDh2UVC/0CQFrHTiSl/3DHvWAbOJawGKg46cnlDcAhSyV8Frs8/dlP +7YGG3eqkw++lsghqmFO6mRUTKsBmiiB2wgLGhL5pyYY= +-----END RSA PRIVATE KEY----- diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/id_sftp_rsa b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/id_sftp_rsa new file mode 100644 index 000000000..a7590c309 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/id_sftp_rsa @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: DES-EDE3-CBC,67F4157B476BB411 + +aJrktM58FIfn3J3DD+fpJv3BsmQURJ1KjBOZUQESFLYDcp5rMzVg1r6Lnz3pgb4H +cTzTVGwanwviK/y5brQaZuUnXCPc6Wbw7JCJc8FZs1cYCD5SX1D4NF+EDRVJ1c67 +l7bHGTMDYdEHaW01ITRyKc6v2TBVl78sa3rjcrC+u1PYuaB1tpexQUuBzpnFtE08 +s1FbGfEPrUSVlSpbRoH4I4GjP1qFgDlnUjdo24dJCWWXAadKoe4RSmiRMKskd6ca +GpSIwhst6mSe4bl9iSA/Ioapcj/jmCtrd1uEFEXHrGF0OzevgWCC40aby5bVxQzA +GfalQrRxnMXLijhzxnSvi2xG+MM+HQz+QqcpM18qx3LXVOId/dvNeHNZaRgDdHas +k1Cz6M19y9Fo0JZLcX7l5Dh33kbaFdwkf0ikwMThQGo+u8p02E6RiMwkyJxjfj6g +PY54TaXBZXr1kQBWvbI6oWtZ2+22UkgzUndAObGwVEczyL7geHBUaO15RX5ppRFC +6rkym3vbFUXibxNkQAhUvAtvuPNVHWMcQ1DLAnYzwdZsvb+FiqJcwqjp/A6yGE9Z +AbtCF+SF8Dtle14xdPkjrNw+iB/gaGSsE2+E7OteHETohU+NOK81CokWmwqqJBIe +3mskcWVJ5PNa51A9zjkDKc2pFrWITvnvtVRWUQEB+orS57xbGvreiFtnmcruR/3w +CuuEPORqbMsr3q30ThkYvFQdrcG8UMgxVdLMywGAnOvRSQoO6TVFamwY1dOseXq0 +NnrTlQnant6y66hit0FFUBv6bS1HDd4dooiYyxT/9ufVg89cTm6WLjgydSy+7wjp +DZ1Fny7GP00ci4SoSm2IQjks0tfVb8F5IFwdlGoWTMPfnoEmaIX/0a9Zxmnv4dp5 +v2hBB3sQJR2lvHVTWCQJCHuYD0ykv4JxGIxWVsUl/IzEezuueDfBMDdctD6xSFc7 +sz5gGIsnoBMbKZkPDlRsijeaNMDUaZkvL0xZ1fNaxLU0xo+FzHLjUoQ7BJWRFKyG +7x05CbGbj5AI60Rb25X4xbWS9l+IAkKTThskCTehmJ4SKKk7SSOGf0/Vl3gWJE2W +mWMRsHT2FBKhUN9JyQsLLDx08NK+/ibqRPVJ9Ay2ssXrlkWvaV7YCAToV8SEl9ob +FvIiCfTpyzK9JOHcE0qHKshXEIl6xEB4ZqOJgW/wiAWi5KlveUIdhIa04xI6buqW +nsHFc59GareKOfLjmSlpo6wg9Aa0Bp30WzWo+n/wKimY6eByabErTyRC1JBWqw9e +KBZCq+TWefOqxfnDdix0xU2W1k+dOlV1CaBc9jhl0DwWTGAio2cubJD/nmIlVGsd +Snawqz18K4O4drgewlEIBbqZWfrYvqr3e8Di/Hk+9wTwygR+xzM0RehkOsUHj/YH +9S7+4E9NeNQsM7JxKGlmye4zHFWMz2Pt9WfrG+CblzQweKSMmNSmv3Q4oM/zutqK ++NTn+KKXikUInYnAKGhmsNwcFkJiQv9FgF9P21T91xvAK4e2898KbIkhwfmSRD7b +zqPo54l/LTl54q4n8wmUtfV/n4Q2WqPn00CljqmpX4T84I6wE4mAWQ== +-----END RSA PRIVATE KEY----- diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/id_sftp_rsa.pub b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/id_sftp_rsa.pub new file mode 100644 index 000000000..4677aea5c --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/id_sftp_rsa.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAwQYFtN28KKGDSOSf/n1T/F0jhdh8HepZVDd7TH364tGNr2cft3GJcBQ7RJwkcwyvDqjGMrMSJEJ+i2DzRJlbgtG6x0hMxRvKQYIktdIyViXbwPn27dBfbolZS0hgRbZlN6utva6JhecUQLnErMt6MgJ1mOhqf5s1JyTnFfMN5yeH5v7hP0VkI+0lsFY00aHulgBoQVPyVgg8hIbLZMN8+4LzGpNXXcOkOwXLzFuVEWxNHg1gLRH4YjdbWNZTj0Km+bpAH65FqIHftze8m9NOSG+3Q9OAPwcMPPpeWFHZT8sCOQlgRsUc/bKMq5sE1bEABrk0d1rkkKlQdaMv/yST+Q== Magesh@JBOSSESB diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/known_hosts_sftp b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/known_hosts_sftp new file mode 100644 index 000000000..c23b8c179 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/camel-ftp-binding/known_hosts_sftp @@ -0,0 +1 @@ +[localhost]:2220 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDdfIWeSV4o68dRrKSzFd/Bk51E65UTmmSrmW0O1ohtzi6HzsDPjXgCtlTt3FqTcfFfI92IlTr4JWqC9UK1QT1ZTeng0MkPQmv68hDANHbt5CpETZHjW5q4OOgWhVvj5IyOC2NZHtKlJBkdsMAa15ouOOJLzBvAvbqOR/yUROsEiQ== diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-netty-binding/roles.properties b/release/karaf/tests/src/test/resources/quickstarts/camel-netty-binding/roles.properties new file mode 100644 index 000000000..c1ac57264 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/camel-netty-binding/roles.properties @@ -0,0 +1,18 @@ +# +# JBoss, Home of Professional Open Source +# Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual +# contributors by the @authors tag. See the copyright.txt in the +# distribution for a full listing of individual contributors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +kermit=friend diff --git a/release/karaf/tests/src/test/resources/quickstarts/camel-netty-binding/users.jks b/release/karaf/tests/src/test/resources/quickstarts/camel-netty-binding/users.jks new file mode 100644 index 000000000..551002663 Binary files /dev/null and b/release/karaf/tests/src/test/resources/quickstarts/camel-netty-binding/users.jks differ diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-1.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-1.xml new file mode 100644 index 000000000..5874f277a --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-1.xml @@ -0,0 +1,3 @@ + + Zombie + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-2.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-2.xml new file mode 100644 index 000000000..af3ca2956 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-2.xml @@ -0,0 +1,3 @@ + + 978-0-307-35193-7 + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-3.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-3.xml new file mode 100644 index 000000000..af3ca2956 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-3.xml @@ -0,0 +1,3 @@ + + 978-0-307-35193-7 + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-4.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-4.xml new file mode 100644 index 000000000..7a9086141 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-4.xml @@ -0,0 +1,8 @@ +1 + + 1 + + 978-0-307-35193-7 + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-5.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-5.xml new file mode 100644 index 000000000..af3ca2956 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-5.xml @@ -0,0 +1,3 @@ + + 978-0-307-35193-7 + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-6.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-6.xml new file mode 100644 index 000000000..5874f277a --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-6.xml @@ -0,0 +1,3 @@ + + Zombie + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-7.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-7.xml new file mode 100644 index 000000000..c547c239f --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-7.xml @@ -0,0 +1,3 @@ + + 978-1-4000-5-80-2 + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-8.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-8.xml new file mode 100644 index 000000000..156402e7b --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-8.xml @@ -0,0 +1,8 @@ +3 + + 3 + + 978-0-307-35193-7 + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-9.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-9.xml new file mode 100644 index 000000000..23749b87e --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-request-9.xml @@ -0,0 +1,8 @@ +4 + + 4 + + 978-1-4000-5-80-2 + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-1.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-1.xml new file mode 100644 index 000000000..883df89df --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-1.xml @@ -0,0 +1,9 @@ + + + + 978-0-307-35193-7 + World War Z + An Oral History of the Zombie War + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-2.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-2.xml new file mode 100644 index 000000000..909a9e052 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-2.xml @@ -0,0 +1,12 @@ +1 + + 1 + true + Happy reading! Remaining copies: 0 + + 978-0-307-35193-7 + World War Z + An Oral History of the Zombie War + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-3.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-3.xml new file mode 100644 index 000000000..2532f1210 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-3.xml @@ -0,0 +1,7 @@ +2 + + 2 + false + Book has no copies available. + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-4.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-4.xml new file mode 100644 index 000000000..f565d7cf2 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-4.xml @@ -0,0 +1,3 @@ +1 + true + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-5.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-5.xml new file mode 100644 index 000000000..03d64005b --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-5.xml @@ -0,0 +1,12 @@ +3 + + 3 + true + Happy reading! Remaining copies: 0 + + 978-0-307-35193-7 + World War Z + An Oral History of the Zombie War + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-6.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-6.xml new file mode 100644 index 000000000..3dc78d93c --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-6.xml @@ -0,0 +1,9 @@ + + + + 978-1-4000-5-80-2 + The Zombie Survival Guide + Complete Protection from the Living Dead + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-7.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-7.xml new file mode 100644 index 000000000..6292ed484 --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-7.xml @@ -0,0 +1,12 @@ +4 + + 4 + true + Happy reading! Remaining copies: 5 + + 978-1-4000-5-80-2 + The Zombie Survival Guide + Complete Protection from the Living Dead + + + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-8.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-8.xml new file mode 100644 index 000000000..67d8932ea --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-8.xml @@ -0,0 +1,3 @@ +3 + true + diff --git a/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-9.xml b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-9.xml new file mode 100644 index 000000000..4f3e1ffdb --- /dev/null +++ b/release/karaf/tests/src/test/resources/quickstarts/demos/library/soap-response-9.xml @@ -0,0 +1,3 @@ +4 + true + diff --git a/release/pom.xml b/release/pom.xml new file mode 100644 index 000000000..f88615fd5 --- /dev/null +++ b/release/pom.xml @@ -0,0 +1,120 @@ + + + + + org.switchyard + switchyard-parent + 2.1.0-SNAPSHOT + .. + + 4.0.0 + switchyard-release + pom + SwitchYard: Distribution + SwitchYard Distribution + + 2.0 + + + scm:git:https://github.com/jboss-switchyard/release.git + scm:git:ssh://git@github.com:jboss-switchyard/release.git + http://github.com/jboss-switchyard/release + + + testutil + distribution + tools/dist + admin/rhq + installer + + + + jboss-public-repository-group + JBoss Public Maven Repository Group + https://repository.jboss.org/nexus/content/groups/public/ + default + + true + never + + + true + always + + + + jboss-deprecated-repository + Deprecated JBoss Repository + https://repository.jboss.org/nexus/content/repositories/deprecated/ + + true + never + + + false + never + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + + + eap + + true + + + jboss-as7 + + + + wildfly + + false + + + jboss-as7 + + + + karaf + + true + + + karaf + + + + openshift + + false + + + jboss-as7 + + + + diff --git a/release/testutil/pom.xml b/release/testutil/pom.xml new file mode 100644 index 000000000..864a4df1a --- /dev/null +++ b/release/testutil/pom.xml @@ -0,0 +1,86 @@ + + + + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../pom.xml + + 4.0.0 + switchyard-release-testutil + jar + SwitchYard: Release Distribution Tests Utilities + SwitchYard Release Distribution Test Utilities + + + org.switchyard + switchyard-remote + + + org.switchyard + switchyard-test + + + org.switchyard.components + switchyard-component-test-mixin-http + + + org.switchyard.components + switchyard-component-test-mixin-hornetq + + + org.jboss.shrinkwrap + shrinkwrap-impl-base + + + org.jboss.shrinkwrap + shrinkwrap-api + + + org.jboss.shrinkwrap + shrinkwrap-spi + + + + + org.jboss.shrinkwrap + shrinkwrap-api + + + org.jboss.shrinkwrap + shrinkwrap-spi + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-impl-maven + + + junit + junit + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + diff --git a/release/testutil/src/main/java/org/switchyard/test/ArquillianUtil.java b/release/testutil/src/main/java/org/switchyard/test/ArquillianUtil.java new file mode 100644 index 000000000..573003906 --- /dev/null +++ b/release/testutil/src/main/java/org/switchyard/test/ArquillianUtil.java @@ -0,0 +1,96 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; + +/** + * Arquillian Test utilities. + * + * @author Magesh Kumar B (C) 2011 Red Hat Inc. + * @author tom.fennelly@gmail.com + */ +public abstract class ArquillianUtil { + + public static final String QS_GID = "org.switchyard.quickstarts"; + public static final String QS_DEMO_GID = "org.switchyard.quickstarts.demos"; + + /** + * Create a SwitchYard Quickstart Demo Deployment. + *

+ * Uses "org.switchyard.quickstarts.demos" as the groupId and gets the SwitchYard + * version from the mandatory SWITCHYARD_VERSION env property. + * + * @param artifactId Maven artifactId. + * @return The Maven artifact archive. + */ + public static JavaArchive createJarDemoDeployment(String artifactId) { + return ShrinkwrapUtil.getSwitchYardJavaArchive(QS_DEMO_GID, artifactId); + } + + /** + * Create a SwitchYard Quickstart Deployment. + *

+ * Uses "org.switchyard.quickstarts" as the groupId and gets the SwitchYard + * version from the mandatory SWITCHYARD_VERSION env property. + * + * @param artifactId Maven artifactId. + * @return The Maven artifact archive. + */ + public static JavaArchive createJarQSDeployment(String artifactId) { + return ShrinkwrapUtil.getSwitchYardJavaArchive(QS_GID, artifactId); + } + + /** + * Create a SwitchYard Quickstart Demo Deployment. + *

+ * Uses "org.switchyard.quickstarts.demos" as the groupId and gets the SwitchYard + * version from the mandatory SWITCHYARD_VERSION env property. + * + * @param artifactId Maven artifactId. + * @return The Maven artifact archive. + */ + public static WebArchive createWarDemoDeployment(String artifactId) { + return ShrinkwrapUtil.getSwitchYardWebArchive(QS_DEMO_GID, artifactId); + } + + /** + * Create a SwitchYard Quickstart Deployment. + *

+ * Uses "org.switchyard.quickstarts" as the groupId and gets the SwitchYard + * version from the mandatory SWITCHYARD_VERSION env property. + * + * @param artifactId Maven artifactId. + * @return The Maven artifact archive. + */ + public static WebArchive createWarQSDeployment(String artifactId) { + return ShrinkwrapUtil.getSwitchYardWebArchive(QS_GID, artifactId); + } + + /** + * Create a SwitchYard Quickstart Deployment. + *

+ * Uses "org.switchyard.quickstarts" as the groupId and gets the SwitchYard + * version from the mandatory SWITCHYARD_VERSION env property. + * + * @param artifactId Maven artifactId. + * @return The Maven artifact archive. + */ + public static EnterpriseArchive createEarQSDeployment(String artifactId) { + return ShrinkwrapUtil.getSwitchYardEarArchive(QS_GID, artifactId); + } +} diff --git a/release/testutil/src/main/java/org/switchyard/test/ShrinkwrapUtil.java b/release/testutil/src/main/java/org/switchyard/test/ShrinkwrapUtil.java new file mode 100644 index 000000000..d312c4005 --- /dev/null +++ b/release/testutil/src/main/java/org/switchyard/test/ShrinkwrapUtil.java @@ -0,0 +1,193 @@ +/* + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.switchyard.test; + +import java.io.File; +import java.io.IOException; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; + +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.importer.ZipImporter; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; +import org.junit.Assert; + +/** + * Shrinkwrap utilities. + * + * @author tom.fennelly@gmail.com + */ +public final class ShrinkwrapUtil { + + /** + * Current SwitchYard version test Environment variable. + */ + public static final String SWITCHYARD_VERSION = "SWITCHYARD_VERSION"; + + private static final String LOCAL_MAVEN_REPO = + System.getProperty("maven.repo.local") != null + ? System.getProperty("maven.repo.local") + : (System.getProperty("user.home") + File.separatorChar + ".m2" + File.separatorChar + "repository"); + + private ShrinkwrapUtil() { + } + + /** + * Get a SwitchYard maven Java Artifact Archive. + *

+ * Gets the SwitchYard version from the mandatory {@link #SWITCHYARD_VERSION} env property. + * + * @param groupId Maven groupId + * @param artifactId Maven artifactId. + * @return The Maven artifact archive. + */ + public static JavaArchive getSwitchYardJavaArchive(String groupId, String artifactId) { + return getJavaArchive(groupId, artifactId, getSwitchYardVersion()); + } + + /** + * Get a maven Java Artifact Archive. + * + * @param groupId Maven groupId + * @param artifactId Maven artifactId. + * @param version Artifact version. + * @return The Maven artifact archive. + */ + public static JavaArchive getJavaArchive(String groupId, String artifactId, String version) { + return getArchive(groupId, artifactId, version, JavaArchive.class, "jar"); + } + + /** + * Get a SwitchYard maven Web Artifact Archive. + *

+ * Gets the SwitchYard version from the mandatory {@link #SWITCHYARD_VERSION} env property. + * + * @param groupId Maven groupId + * @param artifactId Maven artifactId. + * @return The Maven artifact archive. + */ + public static WebArchive getSwitchYardWebArchive(String groupId, String artifactId) { + return getWebArchive(groupId, artifactId, getSwitchYardVersion()); + } + + /** + * Get a maven Web Artifact Archive. + * + * @param groupId Maven groupId + * @param artifactId Maven artifactId. + * @param version Artifact version. + * @return The Maven artifact archive. + */ + public static WebArchive getWebArchive(String groupId, String artifactId, String version) { + return getArchive(groupId, artifactId, version, WebArchive.class, "war"); + } + + /** + * Get a SwitchYard maven Enterprise Artifact Archive. + *

+ * Gets the SwitchYard version from the mandatory {@link #SWITCHYARD_VERSION} env property. + * + * @param groupId Maven groupId + * @param artifactId Maven artifactId. + * @return The Maven artifact archive. + */ + public static EnterpriseArchive getSwitchYardEarArchive(String groupId, String artifactId) { + return getEarArchive(groupId, artifactId, getSwitchYardVersion()); + } + + /** + * Get a maven Enterprise Artifact Archive. + * + * @param groupId Maven groupId + * @param artifactId Maven artifactId. + * @param version Artifact version. + * @return The Maven artifact archive. + */ + public static EnterpriseArchive getEarArchive(String groupId, String artifactId, String version) { + return getArchive(groupId, artifactId, version, EnterpriseArchive.class, "ear"); + } + + /** + * Get a maven Artifact Archive. + * + * @param groupId Maven groupId + * @param artifactId Maven artifactId. + * @param version Artifact version. + * @param archiveType The artifact type. + * @param fileExtension The artifact file extension. + * @return The Maven artifact archive. + * + * @param Archive type. + */ + public static A getArchive(String groupId, String artifactId, String version, Class archiveType, String fileExtension) { + Assert.assertNotNull("'groupId' argument is null.", groupId); + Assert.assertNotNull("'artifactId' argument is null.", artifactId); + Assert.assertNotNull("'version' argument is null.", version); + + File artifactFile = new File(LOCAL_MAVEN_REPO, + groupId.replace(".", "/") + + "/" + artifactId + + "/" + version + + "/" + artifactId + "-" + version + "." + fileExtension); + + if (!artifactFile.isFile()) { + String artifact = groupId + ":" + artifactId + ":" + version; + Assert.fail("Failed to resolve artifact '" + artifact + "'. The artifact must be declared as a dependency in your POM, thereby making it available in your local repository."); + } + + A archive = ShrinkWrap.create(ZipImporter.class, artifactFile.getName()).importFrom(convert(artifactFile)).as(archiveType); + + return archive; + } + + + + /** + * Get the SwitchYard version being tested. + *

+ * Gets the SwitchYard version from the mandatory {@link #SWITCHYARD_VERSION} env property. + * + * @return The SwitchYard version being tested. + */ + public static String getSwitchYardVersion() { + String version = System.getenv(SWITCHYARD_VERSION); + + if (version == null) { + Assert.fail("Test Environment variable '" + SWITCHYARD_VERSION + "' is not configured. " + + "\n\t\t- If running the test in your IDE, set this Environment variable (in the test Run/Debug Configuration) to the current version of SwitchYard (maven artifact version)." + + "\n\t\t- If running the tests through Maven, make sure that the surefire plugin sets this Environment variable to the current version of SwitchYard (maven artifact version)."); + } + version = version.trim(); + if (version.length() == 0) { + Assert.fail("Test Environment variable '" + SWITCHYARD_VERSION + "' not configured. If running the test in your IDE, set this Environment variable to the current version od SwitchYard."); + } + + return version; + } + + // converts a file to a ZIP file + private static ZipFile convert(File file) { + try { + return new ZipFile(file); + } catch (ZipException e) { + throw new RuntimeException("Unable to treat dependency artifact \"" + file.getAbsolutePath() + "\" as a ZIP file", e); + } catch (IOException e) { + throw new RuntimeException("Unable to access artifact file at \"" + file.getAbsolutePath() + "\".", e); + } + } +} diff --git a/release/tools/dist/assembly.xml b/release/tools/dist/assembly.xml new file mode 100644 index 000000000..dde331e36 --- /dev/null +++ b/release/tools/dist/assembly.xml @@ -0,0 +1,58 @@ + + + + SwitchyardTools + false + + zip + + + + + src/main/resources + ${tools.root.dir} + + + + + + false + + org.switchyard.console:switchyard-console-application + + ${tools.root.dir} + switchyard-console-application.war + + + false + + org.riftsaw.console:switchyard-bpel-console-server + + ${tools.root.dir} + switchyard-bpel-console-server.war + + + false + + org.riftsaw.console:switchyard-bpel-console + + true + ${tools.root.dir}/switchyard-bpel-console.war + + + + diff --git a/release/tools/dist/pom.xml b/release/tools/dist/pom.xml new file mode 100644 index 000000000..7b813c186 --- /dev/null +++ b/release/tools/dist/pom.xml @@ -0,0 +1,79 @@ + + + + + org.switchyard + switchyard-release + 2.1.0-SNAPSHOT + ../../pom.xml + + 4.0.0 + switchyard-tools-dist + pom + SwitchYard: Tools Distribution + SwitchYard Tools Distribution + + ${project.build.directory}/bundle + switchyard-tools-${version.distro} + + + + org.switchyard.console + switchyard-console-application + resources + + + org.riftsaw.console + switchyard-bpel-console-server + war + + + org.riftsaw.console + switchyard-bpel-console + war + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + make-assembly + generate-test-resources + + single + + + false + switchyard-tools + + ${basedir}/assembly.xml + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + diff --git a/release/tools/dist/src/main/resources/configuration/bpel-console.properties b/release/tools/dist/src/main/resources/configuration/bpel-console.properties new file mode 100644 index 000000000..0f65c757d --- /dev/null +++ b/release/tools/dist/src/main/resources/configuration/bpel-console.properties @@ -0,0 +1,9 @@ +bpel-console.rest-proxy.proxy-url=http://localhost:8080/bpel-console-server/rs/ +bpel-console.rest-proxy.authentication.provider=org.jboss.bpm.console.server.RestProxySAMLBearerTokenAuthProvider +bpel-console.rest-proxy.authentication.saml.issuer=/bpel-console +bpel-console.rest-proxy.authentication.saml.service=/bpel-console-server +bpel-console.rest-proxy.authentication.saml.sign-assertions=true +bpel-console.rest-proxy.authentication.saml.keystore=${sys:jboss.server.config.dir}/overlord-saml.keystore +bpel-console.rest-proxy.authentication.saml.keystore-password=samlkeystore77 +bpel-console.rest-proxy.authentication.saml.key-alias=overlord +bpel-console.rest-proxy.authentication.saml.key-password=overlord99 diff --git a/remote-invoker/pom.xml b/remote-invoker/pom.xml deleted file mode 100644 index e73935558..000000000 --- a/remote-invoker/pom.xml +++ /dev/null @@ -1,264 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-remote-invoker - 2.0.0.Final - bundle - SwitchYard Quickstart: remote-invoker - Quickstart : Remote Invoker - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.remote.invoker - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-rules - - - org.switchyard.components - switchyard-component-sca - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.remoteinvoker.RemoteClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.sca.client.port - 8181 - - - - - - - - - wildfly - - 9990 - - - - diff --git a/rest-binding/pom.xml b/rest-binding/pom.xml deleted file mode 100644 index 658b5d55b..000000000 --- a/rest-binding/pom.xml +++ /dev/null @@ -1,280 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-rest-binding - 2.0.0.Final - bundle - SwitchYard Quickstart: rest-binding - Quickstart : RESTEasy Binding - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.rest.binding - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-resteasy - - - org.jboss.as - jboss-as-jaxrs - - - org.jboss.resteasy - resteasy-jaxrs - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-netty - test - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - java - test - org.switchyard.quickstarts.rest.binding.RESTEasyBindingClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.resteasy.client.port - 8181 - - - - - - - - - wildfly - - 9990 - - - - diff --git a/rules-camel-cbr/pom.xml b/rules-camel-cbr/pom.xml deleted file mode 100644 index b9504bfe0..000000000 --- a/rules-camel-cbr/pom.xml +++ /dev/null @@ -1,268 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-rules-camel-cbr - 2.0.0.Final - bundle - SwitchYard Quickstart: rules-camel-cbr - Quickstart : Rules+Camel Content-Based Router - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.rules.camel.cbr - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-rules - - - org.switchyard.components - switchyard-component-sca - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.rules.camel.cbr.RulesCamelCBRClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.sca.client.port - 8181 - - - - - - - - - wildfly - - 9990 - - - - diff --git a/rules-interview-container/pom.xml b/rules-interview-container/pom.xml deleted file mode 100644 index 8ee91e173..000000000 --- a/rules-interview-container/pom.xml +++ /dev/null @@ -1,265 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-rules-interview-container - 2.0.0.Final - bundle - SwitchYard Quickstart: rules-interview-container - Quickstart : Rules Interview (Container) - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.rules.interview.container - true - 9999 - 1.6 - 1.6 - 1.3.1 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-rules - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard.components - switchyard-component-soap - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.rules.interview.RulesInterviewClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/rules-interview-dtable/pom.xml b/rules-interview-dtable/pom.xml deleted file mode 100644 index a2d2185a4..000000000 --- a/rules-interview-dtable/pom.xml +++ /dev/null @@ -1,265 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-rules-interview-dtable - 2.0.0.Final - bundle - SwitchYard Quickstart: rules-interview-dtable - Quickstart : Rules Interview (Decision Table) - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.rules.interview.dtable - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-rules - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard.components - switchyard-component-soap - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.rules.interview.RulesInterviewClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/rules-interview/pom.xml b/rules-interview/pom.xml deleted file mode 100644 index 11790a74e..000000000 --- a/rules-interview/pom.xml +++ /dev/null @@ -1,279 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-rules-interview - 2.0.0.Final - bundle - SwitchYard Quickstart: rules-interview - Quickstart : Rules Interview - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - jboss-public-repository - JBoss Public Maven Repository - http://repository.jboss.org/nexus/content/groups/public - - - - - jboss-public-repository - JBoss Public Maven Repository - http://repository.jboss.org/nexus/content/groups/public - - - - - ${project.groupId}.switchyard.rules.interview - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-rules - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.switchyard - switchyard-transform - - - org.switchyard - switchyard-validate - - - org.switchyard.components - switchyard-component-soap - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.rules.interview.RulesInterviewClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/soap-addressing/pom.xml b/soap-addressing/pom.xml deleted file mode 100644 index 7b4514562..000000000 --- a/soap-addressing/pom.xml +++ /dev/null @@ -1,261 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-soap-addressing - 2.0.0.Final - bundle - SwitchYard Quickstart: soap-addressing - Quickstart : SOAP with WS-Addressing - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.soap.addressing - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-camel-file - - - org.switchyard.components - switchyard-component-http - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.soap.addressing.SoapAddressingClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/soap-attachment/pom.xml b/soap-attachment/pom.xml deleted file mode 100644 index 1bafc3d52..000000000 --- a/soap-attachment/pom.xml +++ /dev/null @@ -1,236 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-soap-attachment - 2.0.0.Final - bundle - SwitchYard Quickstart: soap-attachment - Quickstart : SOAP with Attachments - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.soap.attachment - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.soap.attachment.SoapAttachmentClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/soap-binding-rpc/pom.xml b/soap-binding-rpc/pom.xml deleted file mode 100644 index 582ae95aa..000000000 --- a/soap-binding-rpc/pom.xml +++ /dev/null @@ -1,257 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-soap-binding-rpc - 2.0.0.Final - bundle - SwitchYard Quickstart: soap-binding-rpc - Quickstart : SOAP Binding RPC/Lit - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.soap.binding.rpc - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.soap.binding.rpc.SoapBindingClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/soap-mtom/pom.xml b/soap-mtom/pom.xml deleted file mode 100644 index e29eff734..000000000 --- a/soap-mtom/pom.xml +++ /dev/null @@ -1,253 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-soap-mtom - 2.0.0.Final - bundle - SwitchYard Quickstart: soap-mtom - Quickstart : SOAP with MTOM - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.soap.mtom - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard.components - switchyard-component-camel - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.soap.mtom.SoapMtomClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/testutil/pom.xml b/testutil/pom.xml deleted file mode 100644 index 83830ea25..000000000 --- a/testutil/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - 4.0.0 - - org.switchyard.quickstarts - switchyard-quickstart-parent - 2.0.0.Final - .. - - org.switchyard.quickstarts - switchyard-quickstart-testutil - jar - SwitchYard Quickstart: testutil - Testutil for SwitchYard Quickstarts - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - jboss-public-repository-group - JBoss Public Maven Repository Group - https://repository.jboss.org/nexus/content/groups/public/ - default - - true - never - - - true - never - - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - 1.6 - 1.6 - - - - org.jboss.as - jboss-as-cli - - - org.jboss.as - jboss-as-protocol - - - org.jboss.logging - jboss-logging - - - - diff --git a/transform-dozer/pom.xml b/transform-dozer/pom.xml deleted file mode 100644 index b14b14850..000000000 --- a/transform-dozer/pom.xml +++ /dev/null @@ -1,273 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-transform-dozer - 2.0.0.Final - bundle - SwitchYard Quickstart: transform-dozer - Quickstart : Dozer Transformation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.transform.dozer - 1.6 - 1.6 - true - 9999 - - org.dozer.util, - * - - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - org.switchyard.components - switchyard-component-sca - - - org.switchyard - switchyard-validate - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.transform.dozer.DozerTransformationClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.sca.client.port - 8181 - - - - - - - - - wildfly - - 9990 - - - - diff --git a/transform-jaxb/pom.xml b/transform-jaxb/pom.xml deleted file mode 100644 index d6965df30..000000000 --- a/transform-jaxb/pom.xml +++ /dev/null @@ -1,262 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-transform-jaxb - 2.0.0.Final - bundle - SwitchYard Quickstart: transform-jaxb - Quickstart : JAXB Transformation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.transform.jaxb - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - org.apache.httpcomponents - httpclient - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.transform.jaxb.JAXBClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/transform-json/pom.xml b/transform-json/pom.xml deleted file mode 100644 index be0efb357..000000000 --- a/transform-json/pom.xml +++ /dev/null @@ -1,270 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-transform-json - 2.0.0.Final - bundle - SwitchYard Quickstart: transform-json - Quickstart : JSON Transformation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.transform.json - 1.6 - 1.6 - true - 9999 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - org.switchyard.components - switchyard-component-sca - - - org.switchyard - switchyard-validate - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.transform.json.JsonTransformationClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.sca.client.port - 8181 - - - - - - - - - wildfly - - 9990 - - - - diff --git a/transform-smooks/pom.xml b/transform-smooks/pom.xml deleted file mode 100644 index 4952bbf1f..000000000 --- a/transform-smooks/pom.xml +++ /dev/null @@ -1,271 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-transform-smooks - 2.0.0.Final - bundle - SwitchYard Quickstart: transform-smooks - Quickstart : Smooks Transformation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.transform.smooks - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard - switchyard-transform - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - org.switchyard.components - switchyard-component-test-mixin-smooks - test - - - junit - junit - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - org.switchyard.transform.config.model.TransformSwitchYardScanner - - - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.transform.smooks.ServiceTransformationClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/transform-xslt/pom.xml b/transform-xslt/pom.xml deleted file mode 100644 index b0af049e9..000000000 --- a/transform-xslt/pom.xml +++ /dev/null @@ -1,262 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-transform-xslt - 2.0.0.Final - bundle - SwitchYard Quickstart: transform-xslt - Quickstart : XSLT Transformation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.transform.xslt - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - org.apache.httpcomponents - httpclient - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.transform.xslt.XSLTClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - - diff --git a/validate-xml/pom.xml b/validate-xml/pom.xml deleted file mode 100644 index bc33f2b1a..000000000 --- a/validate-xml/pom.xml +++ /dev/null @@ -1,262 +0,0 @@ - - - - 4.0.0 - org.switchyard.quickstarts - switchyard-validate-xml - 2.0.0.Final - bundle - SwitchYard Quickstart: validate-xml - Quickstart : XML Message Validation - http://switchyard.org - - JBoss by Red Hat - http://jboss.org - - - - SwitchYard committers - - - - scm:git:https://github.com/jboss-switchyard/quickstarts.git - scm:git:ssh://git@github.com:jboss-switchyard/quickstarts.git - http://github.com/jboss-switchyard/quickstarts - - - - Apache License, Version 2.0 - repo - http://www.apache.org/licenses/LICENSE-2.0.html - - - - - ${project.groupId}.switchyard.validate.xml - true - 9999 - 1.6 - 1.6 - * - - org.ops4j.pax.cdi.extension; filter:="(extension=switchyard-component-bean)", - org.ops4j.pax.cdi.extension; filter:="(extension=deltaspike-core-api)", - osgi.extender; filter:="(osgi.extender=pax.cdi)" - - - org.switchyard,org.switchyard.* - - 1.3.1 - 2.4.0 - 1.0.2.Final - - - - - org.switchyard - switchyard-bom - ${project.version} - import - pom - - - - - - org.switchyard - switchyard-api - - - org.switchyard.components - switchyard-component-bean - - - org.switchyard.components - switchyard-component-soap - - - org.switchyard - switchyard-test - test - - - org.switchyard.components - switchyard-component-test-mixin-cdi - test - - - org.switchyard.components - switchyard-component-test-mixin-http - test - - - junit - junit - test - - - org.apache.httpcomponents - httpclient - test - - - - ${project.artifactId} - - - org.switchyard - switchyard-plugin - ${project.version} - - - - configure - - - - - - org.apache.felix - maven-bundle-plugin - ${version.felix.maven} - true - - false - - ${bundle.symbolic.name} - ${switchyard.osgi.dynamic} - !* - ${switchyard.osgi.import} - {maven-resources}, META-INF/switchyard.xml=target/classes/META-INF/switchyard.xml - ${switchyard.osgi.require.capability} - - - - ${project.artifactId} - ${project.groupId} - ${project.version} - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${version.enforcer.maven} - - - enforce-versions - - enforce - - clean - - - - 1.7 - - - - - - - - org.wildfly.plugins - wildfly-maven-plugin - ${version.wildfly.maven} - - - deploy - install - - deploy-only - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - undeploy - clean - - undeploy - - - ${project.build.finalName}.jar - ${deploy.skip} - - - - - - org.codehaus.mojo - exec-maven-plugin - - test - org.switchyard.quickstarts.validate.xml.ValidationClient - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.1 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - deploy - - false - - - - karaf - - - - org.codehaus.mojo - exec-maven-plugin - - - - org.switchyard.component.soap.client.port - 8181/cxf - - - - - - - - - wildfly - - 9990 - - - -